Command.cpp 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. /*
  2. * Copyright (c) 2020, Itamar S. <itamar8910@gmail.com>
  3. * Copyright (c) 2022, David Tuin <davidot@serenityos.org>
  4. * Copyright (c) 2023, Shannon Booth <shannon@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include "Command.h"
  9. #include <AK/Format.h>
  10. #include <AK/ScopeGuard.h>
  11. #include <LibCore/File.h>
  12. #include <LibCore/System.h>
  13. #include <fcntl.h>
  14. #include <stdio.h>
  15. #include <sys/wait.h>
  16. #include <unistd.h>
  17. namespace Core {
  18. ErrorOr<OwnPtr<Command>> Command::create(StringView command, char const* const arguments[])
  19. {
  20. auto stdin_fds = TRY(Core::System::pipe2(O_CLOEXEC));
  21. auto stdout_fds = TRY(Core::System::pipe2(O_CLOEXEC));
  22. auto stderr_fds = TRY(Core::System::pipe2(O_CLOEXEC));
  23. posix_spawn_file_actions_t file_actions;
  24. posix_spawn_file_actions_init(&file_actions);
  25. posix_spawn_file_actions_adddup2(&file_actions, stdin_fds[0], STDIN_FILENO);
  26. posix_spawn_file_actions_adddup2(&file_actions, stdout_fds[1], STDOUT_FILENO);
  27. posix_spawn_file_actions_adddup2(&file_actions, stderr_fds[1], STDERR_FILENO);
  28. auto pid = TRY(Core::System::posix_spawnp(command, &file_actions, nullptr, const_cast<char**>(arguments), System::environment()));
  29. posix_spawn_file_actions_destroy(&file_actions);
  30. ArmedScopeGuard runner_kill { [&pid] { kill(pid, SIGKILL); } };
  31. TRY(Core::System::close(stdin_fds[0]));
  32. TRY(Core::System::close(stdout_fds[1]));
  33. TRY(Core::System::close(stderr_fds[1]));
  34. auto stdin_file = TRY(Core::File::adopt_fd(stdin_fds[1], Core::File::OpenMode::Write));
  35. auto stdout_file = TRY(Core::File::adopt_fd(stdout_fds[0], Core::File::OpenMode::Read));
  36. auto stderr_file = TRY(Core::File::adopt_fd(stderr_fds[0], Core::File::OpenMode::Read));
  37. runner_kill.disarm();
  38. return make<Command>(pid, move(stdin_file), move(stdout_file), move(stderr_file));
  39. }
  40. Command::Command(pid_t pid, NonnullOwnPtr<Core::File> stdin_file, NonnullOwnPtr<Core::File> stdout_file, NonnullOwnPtr<Core::File> stderr_file)
  41. : m_pid(pid)
  42. , m_stdin(move(stdin_file))
  43. , m_stdout(move(stdout_file))
  44. , m_stderr(move(stderr_file))
  45. {
  46. }
  47. ErrorOr<void> Command::write(StringView input)
  48. {
  49. TRY(m_stdin->write_until_depleted(input.bytes()));
  50. m_stdin->close();
  51. return {};
  52. }
  53. ErrorOr<void> Command::write_lines(Span<ByteString> lines)
  54. {
  55. // It's possible the process dies before we can write everything to the
  56. // stdin. So make sure that we don't crash but just stop writing.
  57. struct sigaction action_handler { };
  58. action_handler.sa_handler = SIG_IGN;
  59. struct sigaction old_action_handler;
  60. TRY(Core::System::sigaction(SIGPIPE, &action_handler, &old_action_handler));
  61. auto close_stdin = ScopeGuard([this, &old_action_handler] {
  62. // Ensure that the input stream ends here, whether we were able to write all lines or not
  63. m_stdin->close();
  64. // It's not really a problem if this signal failed
  65. if (sigaction(SIGPIPE, &old_action_handler, nullptr) < 0)
  66. perror("sigaction");
  67. });
  68. for (ByteString const& line : lines)
  69. TRY(m_stdin->write_until_depleted(ByteString::formatted("{}\n", line).bytes()));
  70. return {};
  71. }
  72. ErrorOr<Command::ProcessOutputs> Command::read_all()
  73. {
  74. return ProcessOutputs { TRY(m_stdout->read_until_eof()), TRY(m_stderr->read_until_eof()) };
  75. }
  76. ErrorOr<Command::ProcessResult> Command::status(int options)
  77. {
  78. if (m_pid == -1)
  79. return ProcessResult::Unknown;
  80. m_stdin->close();
  81. auto wait_result = TRY(Core::System::waitpid(m_pid, options));
  82. if (wait_result.pid == 0) {
  83. // Attempt to kill it, since it has not finished yet somehow
  84. return ProcessResult::Running;
  85. }
  86. m_pid = -1;
  87. if (WIFSIGNALED(wait_result.status) && WTERMSIG(wait_result.status) == SIGALRM)
  88. return ProcessResult::FailedFromTimeout;
  89. if (WIFEXITED(wait_result.status) && WEXITSTATUS(wait_result.status) == 0)
  90. return ProcessResult::DoneWithZeroExitCode;
  91. return ProcessResult::Failed;
  92. }
  93. // Only supported in serenity mode because we use `posix_spawn_file_actions_addchdir`
  94. #ifdef AK_OS_SERENITY
  95. ErrorOr<CommandResult> command(ByteString const& command_string, Optional<LexicalPath> chdir)
  96. {
  97. auto parts = command_string.split(' ');
  98. if (parts.is_empty())
  99. return Error::from_string_literal("empty command");
  100. auto program = parts[0];
  101. parts.remove(0);
  102. return command(program, parts, chdir);
  103. }
  104. ErrorOr<CommandResult> command(ByteString const& program, Vector<ByteString> const& arguments, Optional<LexicalPath> chdir)
  105. {
  106. int stdout_pipe[2] = {};
  107. int stderr_pipe[2] = {};
  108. if (pipe2(stdout_pipe, O_CLOEXEC)) {
  109. return Error::from_errno(errno);
  110. }
  111. if (pipe2(stderr_pipe, O_CLOEXEC)) {
  112. perror("pipe2");
  113. return Error::from_errno(errno);
  114. }
  115. auto close_pipes = ScopeGuard([stderr_pipe, stdout_pipe] {
  116. // The write-ends of these pipes are closed manually
  117. close(stdout_pipe[0]);
  118. close(stderr_pipe[0]);
  119. });
  120. Vector<char const*> parts = { program.characters() };
  121. for (auto const& part : arguments) {
  122. parts.append(part.characters());
  123. }
  124. parts.append(nullptr);
  125. char const** argv = parts.data();
  126. posix_spawn_file_actions_t action;
  127. posix_spawn_file_actions_init(&action);
  128. if (chdir.has_value()) {
  129. posix_spawn_file_actions_addchdir(&action, chdir.value().string().characters());
  130. }
  131. posix_spawn_file_actions_adddup2(&action, stdout_pipe[1], STDOUT_FILENO);
  132. posix_spawn_file_actions_adddup2(&action, stderr_pipe[1], STDERR_FILENO);
  133. pid_t pid;
  134. if ((errno = posix_spawnp(&pid, program.characters(), &action, nullptr, const_cast<char**>(argv), environ))) {
  135. perror("posix_spawn");
  136. VERIFY_NOT_REACHED();
  137. }
  138. // close the write-ends so reading wouldn't block
  139. close(stdout_pipe[1]);
  140. close(stderr_pipe[1]);
  141. auto read_all_from_pipe = [](int pipe[2]) -> ErrorOr<ByteBuffer> {
  142. auto result_file_or_error = Core::File::adopt_fd(pipe[0], Core::File::OpenMode::Read, Core::File::ShouldCloseFileDescriptor::Yes);
  143. auto result_file = TRY(result_file_or_error);
  144. return result_file->read_until_eof();
  145. };
  146. auto output = TRY(read_all_from_pipe(stdout_pipe));
  147. auto error = TRY(read_all_from_pipe(stderr_pipe));
  148. int wstatus { 0 };
  149. waitpid(pid, &wstatus, 0);
  150. posix_spawn_file_actions_destroy(&action);
  151. int exit_code = WEXITSTATUS(wstatus);
  152. if (exit_code != 0) {
  153. # ifdef DBG_FAILED_COMMANDS
  154. dbgln("command failed. stderr: {}", );
  155. # endif
  156. }
  157. return CommandResult { WEXITSTATUS(wstatus), output, error };
  158. }
  159. #endif
  160. }