Serenity Operating System
1/*
2 * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
3 *
4 * SPDX-License-Identifier: BSD-2-Clause
5 */
6
7#include <AK/JsonObject.h>
8#include <AK/JsonValue.h>
9#include <LibCore/DateTime.h>
10#include <LibCore/File.h>
11#include <LibCore/ProcessStatisticsReader.h>
12#include <LibCore/System.h>
13#include <LibMain/Main.h>
14#include <pwd.h>
15#include <sys/stat.h>
16#include <time.h>
17
18ErrorOr<int> serenity_main(Main::Arguments)
19{
20 TRY(Core::System::pledge("stdio rpath"));
21 TRY(Core::System::unveil("/dev", "r"));
22 TRY(Core::System::unveil("/etc/passwd", "r"));
23 TRY(Core::System::unveil("/etc/timezone", "r"));
24 TRY(Core::System::unveil("/var/run/utmp", "r"));
25 TRY(Core::System::unveil("/sys/kernel/processes", "r"));
26 TRY(Core::System::unveil(nullptr, nullptr));
27
28 auto file = TRY(Core::File::open("/var/run/utmp"sv, Core::File::OpenMode::Read));
29 auto file_contents = TRY(file->read_until_eof());
30 auto json = TRY(JsonValue::from_string(file_contents));
31 if (!json.is_object()) {
32 warnln("Error: Could not parse /var/run/utmp");
33 return 1;
34 }
35
36 auto process_statistics = TRY(Core::ProcessStatisticsReader::get_all());
37
38 auto now = time(nullptr);
39
40 outln("\033[1m{:10} {:12} {:16} {:6} {}\033[0m", "USER", "TTY", "LOGIN@", "IDLE", "WHAT");
41 json.as_object().for_each_member([&](auto& tty, auto& value) {
42 const JsonObject& entry = value.as_object();
43 auto uid = entry.get_u32("uid"sv).value_or(0);
44 [[maybe_unused]] auto pid = entry.get_i32("pid"sv).value_or(0);
45
46 auto login_time = Core::DateTime::from_timestamp(entry.get_integer<time_t>("login_at"sv).value_or(0));
47 auto login_at = login_time.to_deprecated_string("%b%d %H:%M:%S"sv);
48
49 auto* pw = getpwuid(uid);
50 DeprecatedString username;
51 if (pw)
52 username = pw->pw_name;
53 else
54 username = DeprecatedString::number(uid);
55
56 StringBuilder builder;
57 DeprecatedString idle_string = "n/a";
58 struct stat st;
59 if (stat(tty.characters(), &st) == 0) {
60 auto idle_time = now - st.st_mtime;
61 if (idle_time >= 0) {
62 builder.appendff("{}s", idle_time);
63 idle_string = builder.to_deprecated_string();
64 }
65 }
66
67 DeprecatedString what = "n/a";
68
69 for (auto& process : process_statistics.processes) {
70 if (process.tty == tty && process.pid == process.pgid)
71 what = process.name;
72 }
73
74 outln("{:10} {:12} {:16} {:6} {}", username, tty, login_at, idle_string, what);
75 });
76 return 0;
77}