From 8e489b451aee793dfb45f01d7cc4d13fd96040a9 Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Sun, 6 Sep 2020 16:16:10 +0200 Subject: [PATCH] Userland: Add a simple 'w' program that shows current terminal sessions This fetches information from /var/run/utmp and shows the interactive sessions in a little list. More things can be added here to make it more interesting. :^) --- Userland/w.cpp | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 Userland/w.cpp diff --git a/Userland/w.cpp b/Userland/w.cpp new file mode 100644 index 0000000000..e71147a28d --- /dev/null +++ b/Userland/w.cpp @@ -0,0 +1,62 @@ +#include +#include +#include +#include +#include + +int main() +{ + if (pledge("stdio rpath", nullptr) < 0) { + perror("pledge"); + return 1; + } + + if (unveil("/etc/passwd", "r") < 0) { + perror("unveil"); + return 1; + } + + if (unveil("/var/run/utmp", "r") < 0) { + perror("unveil"); + return 1; + } + + unveil(nullptr, nullptr); + + auto file_or_error = Core::File::open("/var/run/utmp", Core::IODevice::ReadOnly); + if (file_or_error.is_error()) { + warn() << "Error: " << file_or_error.error(); + return 1; + } + auto& file = *file_or_error.value(); + auto json = JsonValue::from_string(file.read_all()); + if (!json.has_value() || !json.value().is_object()) { + warn() << "Error: Could not parse /var/run/utmp"; + return 1; + } + + printf("%-10s %-12s %-16s %-16s\n", + "USER", "TTY", "FROM", "LOGIN@"); + json.value().as_object().for_each_member([&](auto& tty, auto& value) { + const JsonObject& entry = value.as_object(); + auto uid = entry.get("uid").to_u32(); + auto pid = entry.get("pid").to_i32(); + (void)pid; + auto from = entry.get("from").to_string(); + auto login_at = entry.get("login_at").to_string(); + + auto* pw = getpwuid(uid); + String username; + if (pw) + username = pw->pw_name; + else + username = String::number(uid); + + printf("%-10s %-12s %-16s %-16s\n", + username.characters(), + tty.characters(), + from.characters(), + login_at.characters()); + }); + return 0; +}