lsof.cpp 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. /*
  2. * Copyright (c) 2020, Maciej Zygmanowski <sppmacd@pm.me>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/ByteBuffer.h>
  7. #include <AK/GenericLexer.h>
  8. #include <AK/JsonArray.h>
  9. #include <AK/JsonObject.h>
  10. #include <AK/JsonParser.h>
  11. #include <AK/JsonValue.h>
  12. #include <AK/String.h>
  13. #include <AK/Vector.h>
  14. #include <LibCore/ArgsParser.h>
  15. #include <LibCore/File.h>
  16. #include <LibCore/ProcessStatisticsReader.h>
  17. #include <ctype.h>
  18. #include <stdio.h>
  19. struct OpenFile {
  20. int fd;
  21. int pid;
  22. String type;
  23. String name;
  24. String state;
  25. String full_name;
  26. };
  27. static bool parse_name(StringView name, OpenFile& file)
  28. {
  29. GenericLexer lexer(name);
  30. auto component1 = lexer.consume_until(':');
  31. if (lexer.tell_remaining() == 0) {
  32. file.name = component1;
  33. return true;
  34. } else {
  35. file.type = component1;
  36. auto component2 = lexer.consume_while([](char c) { return isprint(c) && c != '('; });
  37. lexer.ignore_while(isspace);
  38. file.name = component2;
  39. if (lexer.tell_remaining() == 0) {
  40. return true;
  41. } else {
  42. if (!lexer.consume_specific('(')) {
  43. dbgln("parse_name: expected (");
  44. return false;
  45. }
  46. auto component3 = lexer.consume_until(')');
  47. if (lexer.tell_remaining() != 0) {
  48. dbgln("parse_name: expected EOF");
  49. return false;
  50. }
  51. file.state = component3;
  52. return true;
  53. }
  54. }
  55. }
  56. static Vector<OpenFile> get_open_files_by_pid(pid_t pid)
  57. {
  58. auto file = Core::File::open(String::formatted("/proc/{}/fds", pid), Core::OpenMode::ReadOnly);
  59. if (file.is_error()) {
  60. outln("lsof: PID {}: {}", pid, file.error());
  61. return Vector<OpenFile>();
  62. }
  63. auto data = file.value()->read_all();
  64. JsonParser parser(data);
  65. auto result = parser.parse();
  66. if (!result.has_value()) {
  67. VERIFY_NOT_REACHED();
  68. }
  69. Vector<OpenFile> files;
  70. result.value().as_array().for_each([pid, &files](const JsonValue& object) {
  71. OpenFile open_file;
  72. open_file.pid = pid;
  73. open_file.fd = object.as_object().get("fd").to_int();
  74. String name = object.as_object().get("absolute_path").to_string();
  75. VERIFY(parse_name(name, open_file));
  76. open_file.full_name = name;
  77. files.append(open_file);
  78. });
  79. return files;
  80. }
  81. static void display_entry(const OpenFile& file, const Core::ProcessStatistics& statistics)
  82. {
  83. outln("{:28} {:>4} {:>4} {:10} {:>4} {}", statistics.name, file.pid, statistics.pgid, statistics.username, file.fd, file.full_name);
  84. }
  85. int main(int argc, char* argv[])
  86. {
  87. if (pledge("stdio rpath proc", nullptr) < 0) {
  88. perror("pledge");
  89. return 1;
  90. }
  91. if (unveil("/proc", "r") < 0) {
  92. perror("unveil /proc");
  93. return 1;
  94. }
  95. // needed by ProcessStatisticsReader::get_all()
  96. if (unveil("/etc/passwd", "r") < 0) {
  97. perror("unveil /etc/passwd");
  98. return 1;
  99. }
  100. unveil(nullptr, nullptr);
  101. bool arg_all_processes { false };
  102. int arg_fd { -1 };
  103. const char* arg_uid { nullptr };
  104. int arg_uid_int = -1;
  105. int arg_pgid { -1 };
  106. pid_t arg_pid { -1 };
  107. const char* arg_filename { nullptr };
  108. if (argc == 1)
  109. arg_all_processes = true;
  110. else {
  111. Core::ArgsParser parser;
  112. parser.set_general_help("List open files of a processes. This can mean actual files in the file system, sockets, pipes, etc.");
  113. parser.add_option(arg_pid, "Select by PID", nullptr, 'p', "pid");
  114. parser.add_option(arg_fd, "Select by file descriptor", nullptr, 'd', "fd");
  115. parser.add_option(arg_uid, "Select by login/UID", nullptr, 'u', "login/UID");
  116. parser.add_option(arg_pgid, "Select by process group ID", nullptr, 'g', "PGID");
  117. parser.add_positional_argument(arg_filename, "Filename", "filename", Core::ArgsParser::Required::No);
  118. parser.parse(argc, argv);
  119. }
  120. {
  121. // try convert UID to int
  122. auto arg = String(arg_uid).to_int();
  123. if (arg.has_value())
  124. arg_uid_int = arg.value();
  125. }
  126. outln("{:28} {:>4} {:>4} {:10} {:>4} {}", "COMMAND", "PID", "PGID", "USER", "FD", "NAME");
  127. auto all_processes = Core::ProcessStatisticsReader::get_all();
  128. if (!all_processes.has_value())
  129. return 1;
  130. if (arg_pid == -1) {
  131. for (auto& process : all_processes.value().processes) {
  132. if (process.pid == 0)
  133. continue;
  134. auto open_files = get_open_files_by_pid(process.pid);
  135. if (open_files.is_empty())
  136. continue;
  137. for (auto& file : open_files) {
  138. if ((arg_all_processes)
  139. || (arg_fd != -1 && file.fd == arg_fd)
  140. || (arg_uid_int != -1 && (int)process.uid == arg_uid_int)
  141. || (arg_uid != nullptr && process.username == arg_uid)
  142. || (arg_pgid != -1 && (int)process.pgid == arg_pgid)
  143. || (arg_filename != nullptr && file.name == arg_filename))
  144. display_entry(file, process);
  145. }
  146. }
  147. } else {
  148. auto open_files = get_open_files_by_pid(arg_pid);
  149. if (open_files.is_empty())
  150. return 0;
  151. for (auto& file : open_files) {
  152. display_entry(file, *all_processes->processes.find_if([&](auto& entry) { return entry.pid == arg_pid; }));
  153. }
  154. }
  155. return 0;
  156. }