utmpupdate.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. * Copyright (c) 2020-2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Assertions.h>
  7. #include <AK/ByteBuffer.h>
  8. #include <AK/JsonObject.h>
  9. #include <AK/JsonValue.h>
  10. #include <LibCore/ArgsParser.h>
  11. #include <LibCore/DateTime.h>
  12. #include <LibCore/File.h>
  13. #include <LibCore/System.h>
  14. #include <LibMain/Main.h>
  15. #include <unistd.h>
  16. ErrorOr<int> serenity_main(Main::Arguments arguments)
  17. {
  18. TRY(Core::System::pledge("stdio wpath cpath"));
  19. TRY(Core::System::unveil("/var/run/utmp", "rwc"));
  20. TRY(Core::System::unveil(nullptr, nullptr));
  21. pid_t pid = 0;
  22. bool flag_create = false;
  23. bool flag_delete = false;
  24. StringView tty_name;
  25. StringView from;
  26. Core::ArgsParser args_parser;
  27. args_parser.add_option(flag_create, "Create entry", "create", 'c');
  28. args_parser.add_option(flag_delete, "Delete entry", "delete", 'd');
  29. args_parser.add_option(pid, "PID", "PID", 'p', "PID");
  30. args_parser.add_option(from, "From", "from", 'f', "From");
  31. args_parser.add_positional_argument(tty_name, "TTY name", "tty");
  32. args_parser.parse(arguments);
  33. if (flag_create && flag_delete) {
  34. warnln("-c and -d are mutually exclusive");
  35. return 1;
  36. }
  37. dbgln("Updating utmp from UID={} GID={} EGID={} PID={}", getuid(), getgid(), getegid(), pid);
  38. auto file = TRY(Core::File::open("/var/run/utmp"sv, Core::File::OpenMode::ReadWrite));
  39. auto file_contents = TRY(file->read_until_eof());
  40. auto previous_json = TRY(JsonValue::from_string(file_contents));
  41. JsonObject json;
  42. if (!file_contents.is_empty()) {
  43. if (!previous_json.is_object()) {
  44. dbgln("Error: Could not parse JSON");
  45. } else {
  46. json = previous_json.as_object();
  47. }
  48. }
  49. if (flag_create) {
  50. JsonObject entry;
  51. entry.set("pid", pid);
  52. entry.set("uid", getuid());
  53. entry.set("from", from);
  54. entry.set("login_at", time(nullptr));
  55. json.set(tty_name, move(entry));
  56. } else {
  57. VERIFY(flag_delete);
  58. dbgln("Removing {} from utmp", tty_name);
  59. json.remove(tty_name);
  60. }
  61. TRY(file->seek(0, SeekMode::SetPosition));
  62. TRY(file->truncate(0));
  63. TRY(file->write_until_depleted(json.to_byte_string()));
  64. return 0;
  65. }