#include #include #include #ifdef _WIN32 namespace Void::Process { Void::Result::Result run(const std::filesystem::path&, std::vector, std::string_view, std::chrono::milliseconds) { return Void::Result::fail("Process::run: not implemented on Windows"); } Void::Result::Result run_streaming(const std::filesystem::path&, std::vector, const StreamCallbacks&, std::string_view, std::chrono::milliseconds) { return Void::Result::fail( "Process::run_streaming: not implemented on Windows"); } Void::Result::Result shell(std::string_view, std::chrono::milliseconds) { return Void::Result::fail("Process::shell: not implemented on Windows"); } Void::Result::Result reexec(const std::filesystem::path&, const std::vector&) { return Void::Result::fail("Process::reexec: not implemented on Windows"); } } // namespace Void::Process #else // POSIX #include #include #include #include #include #include #include #include namespace Void::Process { namespace { // Read into buf until EAGAIN (no more data right now) or EOF. // Returns true on EOF, false on EAGAIN. bool drain(int fd, std::string& buf) { char tmp[4096]; for (;;) { ssize_t n = ::read(fd, tmp, sizeof(tmp)); if (n > 0) { buf.append(tmp, static_cast(n)); } else if (n == 0) { return true; // EOF } else { if (errno == EINTR) { continue; } // EAGAIN / EWOULDBLOCK: no data right now return false; } } } void set_nonblock(int fd) { int flags = ::fcntl(fd, F_GETFL, 0); if (flags >= 0) { ::fcntl(fd, F_SETFL, flags | O_NONBLOCK); } } // Close an fd if it is >= 0, then set it to -1. void safe_close(int& fd) { if (fd >= 0) { ::close(fd); fd = -1; } } // Emit newly-completed lines from `buf` (from offset `off`), advancing // `off`. When `flush` is set, any trailing partial line is emitted too. void emit_lines(const std::string& buf, std::size_t& off, const std::function& fn, bool flush) { if (!fn) { off = buf.size(); return; } std::size_t nl; while ((nl = buf.find('\n', off)) != std::string::npos) { std::size_t len = nl - off; if (len > 0 && buf[off + len - 1] == '\r') { --len; // strip CR of a CRLF } fn(std::string_view{buf.data() + off, len}); off = nl + 1; } if (flush && off < buf.size()) { fn(std::string_view{buf.data() + off, buf.size() - off}); off = buf.size(); } } } // namespace namespace { Void::Result::Result run_impl(const std::filesystem::path& executable, std::vector args, std::string_view stdin_data, std::chrono::milliseconds timeout, const StreamCallbacks* cb) { // [0] = read end, [1] = write end int stdin_pipe[2] = {-1, -1}; int stdout_pipe[2] = {-1, -1}; int stderr_pipe[2] = {-1, -1}; if (::pipe(stdin_pipe) != 0 || ::pipe(stdout_pipe) != 0 || ::pipe(stderr_pipe) != 0) { safe_close(stdin_pipe[0]); safe_close(stdin_pipe[1]); safe_close(stdout_pipe[0]); safe_close(stdout_pipe[1]); safe_close(stderr_pipe[0]); safe_close(stderr_pipe[1]); return Void::Result::fail(std::format( "Process::run: pipe() failed: {}", std::strerror(errno))); } Void::Log::debug("Process", "run: '{}'", executable.string()); std::vector argv; argv.push_back(executable.c_str()); for (const auto& a : args) { argv.push_back(a.c_str()); } argv.push_back(nullptr); pid_t pid = ::fork(); if (pid < 0) { safe_close(stdin_pipe[0]); safe_close(stdin_pipe[1]); safe_close(stdout_pipe[0]); safe_close(stdout_pipe[1]); safe_close(stderr_pipe[0]); safe_close(stderr_pipe[1]); return Void::Result::fail(std::format( "Process::run: fork() failed: {}", std::strerror(errno))); } if (pid == 0) { // Child process ::dup2(stdin_pipe[0], STDIN_FILENO); ::dup2(stdout_pipe[1], STDOUT_FILENO); ::dup2(stderr_pipe[1], STDERR_FILENO); ::close(stdin_pipe[0]); ::close(stdin_pipe[1]); ::close(stdout_pipe[0]); ::close(stdout_pipe[1]); ::close(stderr_pipe[0]); ::close(stderr_pipe[1]); ::execvp( executable.c_str(), // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) const_cast(argv.data())); // execvp only returns on error; 127 is the POSIX convention ::_exit(127); } // Parent: close child-side ends safe_close(stdin_pipe[0]); safe_close(stdout_pipe[1]); safe_close(stderr_pipe[1]); // Write stdin and close immediately so the child sees EOF if (!stdin_data.empty()) { const char* p = stdin_data.data(); std::size_t remaining = stdin_data.size(); while (remaining > 0) { ssize_t n = ::write(stdin_pipe[1], p, remaining); if (n < 0) { if (errno == EINTR) { continue; } break; // child likely closed stdin; ignore } p += static_cast(n); remaining -= static_cast(n); } } safe_close(stdin_pipe[1]); set_nonblock(stdout_pipe[0]); set_nonblock(stderr_pipe[0]); Output output; bool out_done = false; bool err_done = false; std::size_t out_emitted = 0; std::size_t err_emitted = 0; const bool has_timeout = timeout.count() > 0; const auto deadline = std::chrono::steady_clock::now() + (has_timeout ? timeout : std::chrono::milliseconds{30'000}); while (!out_done || !err_done) { struct pollfd pfds[2]; int nfds = 0; if (!out_done) { pfds[nfds++] = {stdout_pipe[0], POLLIN, 0}; } if (!err_done) { pfds[nfds++] = {stderr_pipe[0], POLLIN, 0}; } auto left_ms = std::chrono::duration_cast( deadline - std::chrono::steady_clock::now()) .count(); if (left_ms <= 0) { ::kill(pid, SIGTERM); break; } int ret = ::poll(pfds, static_cast(nfds), static_cast(left_ms)); if (ret < 0) { if (errno == EINTR) { continue; } break; } if (ret == 0) { // Wall-clock timeout expired ::kill(pid, SIGTERM); break; } for (int i = 0; i < nfds; ++i) { if ((pfds[i].revents & (POLLIN | POLLHUP | POLLERR)) == 0) { continue; } const bool is_out = (pfds[i].fd == stdout_pipe[0]); bool& done = is_out ? out_done : err_done; std::string& buf = is_out ? output.out : output.err; bool eof = drain(pfds[i].fd, buf); if (cb) { emit_lines(buf, is_out ? out_emitted : err_emitted, is_out ? cb->on_stdout : cb->on_stderr, /*flush=*/false); } // POLLHUP means the write end was closed; no more data will // arrive if (eof || (pfds[i].revents & (POLLHUP | POLLERR))) { done = true; } } } if (cb) { emit_lines(output.out, out_emitted, cb->on_stdout, /*flush=*/true); emit_lines(output.err, err_emitted, cb->on_stderr, /*flush=*/true); } safe_close(stdout_pipe[0]); safe_close(stderr_pipe[0]); int status = 0; ::waitpid(pid, &status, 0); output.exit_code = WIFEXITED(status) ? WEXITSTATUS(status) : -1; Void::Log::debug("Process", "run: '{}' exited {}", executable.string(), output.exit_code); return Void::Result::ok(std::move(output)); } } // namespace Void::Result::Result run(const std::filesystem::path& executable, std::vector args, std::string_view stdin_data, std::chrono::milliseconds timeout) { return run_impl(executable, std::move(args), stdin_data, timeout, nullptr); } Void::Result::Result run_streaming( const std::filesystem::path& executable, std::vector args, const StreamCallbacks& callbacks, std::string_view stdin_data, std::chrono::milliseconds timeout) { return run_impl(executable, std::move(args), stdin_data, timeout, &callbacks); } Void::Result::Result shell(std::string_view command, std::chrono::milliseconds timeout) { return run("/bin/sh", {"-c", std::string{command}}, {}, timeout); } Void::Result::Result reexec(const std::filesystem::path& executable, const std::vector& arguments) { if (executable.empty()) { return Void::Result::fail("Process::reexec: executable is empty"); } std::vector owned; owned.reserve(arguments.size() + 1); owned.push_back(executable.string()); owned.insert(owned.end(), arguments.begin(), arguments.end()); std::vector argv; argv.reserve(owned.size() + 1); for (auto& argument : owned) { argv.push_back(argument.data()); } argv.push_back(nullptr); ::execv(executable.c_str(), argv.data()); return Void::Result::fail(std::format( "Process::reexec: execv '{}' failed: {}", executable.string(), std::strerror(errno))); } } // namespace Void::Process #endif // _WIN32