Command.cpp 6.6 KB

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