Bitcoin Core 30.99.0
P2P Digital Currency
subprocess.h
Go to the documentation of this file.
1// Based on the https://github.com/arun11299/cpp-subprocess project.
2
36#ifndef BITCOIN_UTIL_SUBPROCESS_H
37#define BITCOIN_UTIL_SUBPROCESS_H
38
39#include <util/syserror.h>
40
41#include <algorithm>
42#include <cassert>
43#include <csignal>
44#include <cstdio>
45#include <cstdlib>
46#include <cstring>
47#include <exception>
48#include <future>
49#include <initializer_list>
50#include <iostream>
51#include <locale>
52#include <map>
53#include <memory>
54#include <sstream>
55#include <string>
56#include <vector>
57
58#if (defined _MSC_VER) || (defined __MINGW32__)
59 #define __USING_WINDOWS__
60#endif
61
62#ifdef __USING_WINDOWS__
63 #include <codecvt>
64#endif
65
66extern "C" {
67#ifdef __USING_WINDOWS__
68 #include <windows.h>
69 #include <io.h>
70 #include <cwchar>
71#else
72 #include <sys/wait.h>
73 #include <unistd.h>
74#endif
75 #include <csignal>
76 #include <fcntl.h>
77 #include <sys/types.h>
78}
79
80// The Microsoft C++ compiler issues deprecation warnings
81// for the standard POSIX function names.
82// Its preferred implementations have a leading underscore.
83// See: https://learn.microsoft.com/en-us/cpp/c-runtime-library/compatibility.
84#if (defined _MSC_VER)
85 #define subprocess_close _close
86 #define subprocess_fileno _fileno
87 #define subprocess_open _open
88 #define subprocess_write _write
89#else
90 #define subprocess_close close
91 #define subprocess_fileno fileno
92 #define subprocess_open open
93 #define subprocess_write write
94#endif
95
119namespace subprocess {
120
121// Max buffer size allocated on stack for read error
122// from pipe
123static const size_t SP_MAX_ERR_BUF_SIZ = 1024;
124
125// Default buffer capacity for OutBuffer and ErrBuffer.
126// If the data exceeds this capacity, the buffer size is grown
127// by 1.5 times its previous capacity
128static const size_t DEFAULT_BUF_CAP_BYTES = 8192;
129
130
131/*-----------------------------------------------
132 * EXCEPTION CLASSES
133 *-----------------------------------------------
134 */
135
143class CalledProcessError: public std::runtime_error
144{
145public:
147 CalledProcessError(const std::string& error_msg, int retcode):
148 std::runtime_error(error_msg), retcode(retcode)
149 {}
150};
151
152
163class OSError: public std::runtime_error
164{
165public:
166 OSError(const std::string& err_msg, int err_code):
167 std::runtime_error(err_msg + ": " + SysErrorString(err_code))
168 {}
169};
170
171//--------------------------------------------------------------------
172namespace util
173{
174#ifdef __USING_WINDOWS__
175 inline void quote_argument(const std::wstring &argument, std::wstring &command_line,
176 bool force)
177 {
178 //
179 // Unless we're told otherwise, don't quote unless we actually
180 // need to do so --- hopefully avoid problems if programs won't
181 // parse quotes properly
182 //
183
184 if (force == false && argument.empty() == false &&
185 argument.find_first_of(L" \t\n\v") == argument.npos) {
186 command_line.append(argument);
187 }
188 else {
189 command_line.push_back(L'"');
190
191 for (auto it = argument.begin();; ++it) {
192 unsigned number_backslashes = 0;
193
194 while (it != argument.end() && *it == L'\\') {
195 ++it;
196 ++number_backslashes;
197 }
198
199 if (it == argument.end()) {
200
201 //
202 // Escape all backslashes, but let the terminating
203 // double quotation mark we add below be interpreted
204 // as a metacharacter.
205 //
206
207 command_line.append(number_backslashes * 2, L'\\');
208 break;
209 }
210 else if (*it == L'"') {
211
212 //
213 // Escape all backslashes and the following
214 // double quotation mark.
215 //
216
217 command_line.append(number_backslashes * 2 + 1, L'\\');
218 command_line.push_back(*it);
219 }
220 else {
221
222 //
223 // Backslashes aren't special here.
224 //
225
226 command_line.append(number_backslashes, L'\\');
227 command_line.push_back(*it);
228 }
229 }
230
231 command_line.push_back(L'"');
232 }
233 }
234
235 inline std::string get_last_error(DWORD errorMessageID)
236 {
237 if (errorMessageID == 0)
238 return std::string();
239
240 LPSTR messageBuffer = nullptr;
241 size_t size = FormatMessageA(
242 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
243 FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
244 NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
245 (LPSTR)&messageBuffer, 0, NULL);
246
247 std::string message(messageBuffer, size);
248
249 LocalFree(messageBuffer);
250
251 return message;
252 }
253
254 inline FILE *file_from_handle(HANDLE h, const char *mode)
255 {
256 int md;
257 if (!mode) {
258 throw OSError("invalid_mode", 0);
259 }
260
261 if (mode[0] == 'w') {
262 md = _O_WRONLY;
263 }
264 else if (mode[0] == 'r') {
265 md = _O_RDONLY;
266 }
267 else {
268 throw OSError("file_from_handle", 0);
269 }
270
271 int os_fhandle = _open_osfhandle((intptr_t)h, md);
272 if (os_fhandle == -1) {
273 CloseHandle(h);
274 throw OSError("_open_osfhandle", 0);
275 }
276
277 FILE *fp = _fdopen(os_fhandle, mode);
278 if (fp == 0) {
279 subprocess_close(os_fhandle);
280 throw OSError("_fdopen", 0);
281 }
282
283 return fp;
284 }
285
286 inline void configure_pipe(HANDLE* read_handle, HANDLE* write_handle, HANDLE* child_handle)
287 {
288 SECURITY_ATTRIBUTES saAttr;
289
290 // Set the bInheritHandle flag so pipe handles are inherited.
291 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
292 saAttr.bInheritHandle = TRUE;
293 saAttr.lpSecurityDescriptor = NULL;
294
295 // Create a pipe for the child process's STDIN.
296 if (!CreatePipe(read_handle, write_handle, &saAttr,0))
297 throw OSError("CreatePipe", 0);
298
299 // Ensure the write handle to the pipe for STDIN is not inherited.
300 if (!SetHandleInformation(*child_handle, HANDLE_FLAG_INHERIT, 0))
301 throw OSError("SetHandleInformation", 0);
302 }
303#endif
304
314 static inline std::vector<std::string>
315 split(const std::string& str, const std::string& delims=" \t")
316 {
317 std::vector<std::string> res;
318 size_t init = 0;
319
320 while (true) {
321 auto pos = str.find_first_of(delims, init);
322 if (pos == std::string::npos) {
323 res.emplace_back(str.substr(init, str.length()));
324 break;
325 }
326 res.emplace_back(str.substr(init, pos - init));
327 pos++;
328 init = pos;
329 }
330
331 return res;
332 }
333
334
335#ifndef __USING_WINDOWS__
345 static inline
346 void set_clo_on_exec(int fd, bool set = true)
347 {
348 int flags = fcntl(fd, F_GETFD, 0);
349 if (flags == -1) {
350 throw OSError("fcntl F_GETFD failed", errno);
351 }
352 if (set) flags |= FD_CLOEXEC;
353 else flags &= ~FD_CLOEXEC;
354 if (fcntl(fd, F_SETFD, flags) == -1) {
355 throw OSError("fcntl F_SETFD failed", errno);
356 }
357 }
358
359
369 static inline
370 std::pair<int, int> pipe_cloexec() noexcept(false)
371 {
372 int pipe_fds[2];
373 int res = pipe(pipe_fds);
374 if (res) {
375 throw OSError("pipe failure", errno);
376 }
377
378 set_clo_on_exec(pipe_fds[0]);
379 set_clo_on_exec(pipe_fds[1]);
380
381 return std::make_pair(pipe_fds[0], pipe_fds[1]);
382 }
383#endif
384
385
397 static inline
398 int write_n(int fd, const char* buf, size_t length)
399 {
400 size_t nwritten = 0;
401 while (nwritten < length) {
402 int written = subprocess_write(fd, buf + nwritten, length - nwritten);
403 if (written == -1) return -1;
404 nwritten += written;
405 }
406 return nwritten;
407 }
408
409
424 static inline
425 int read_atmost_n(FILE* fp, char* buf, size_t read_upto)
426 {
427#ifdef __USING_WINDOWS__
428 return (int)fread(buf, 1, read_upto, fp);
429#else
430 int fd = subprocess_fileno(fp);
431 int rbytes = 0;
432 int eintr_cnter = 0;
433
434 while (1) {
435 int read_bytes = read(fd, buf + rbytes, read_upto - rbytes);
436 if (read_bytes == -1) {
437 if (errno == EINTR) {
438 if (eintr_cnter >= 50) return -1;
439 eintr_cnter++;
440 continue;
441 }
442 return -1;
443 }
444 if (read_bytes == 0) return rbytes;
445
446 rbytes += read_bytes;
447 }
448 return rbytes;
449#endif
450 }
451
452
466 static inline int read_all(FILE* fp, std::vector<char>& buf)
467 {
468 auto buffer = buf.data();
469 int total_bytes_read = 0;
470 int fill_sz = buf.size();
471
472 while (1) {
473 const int rd_bytes = read_atmost_n(fp, buffer, fill_sz);
474
475 if (rd_bytes == -1) { // Read finished
476 if (total_bytes_read == 0) return -1;
477 break;
478
479 } else if (rd_bytes == fill_sz) { // Buffer full
480 const auto orig_sz = buf.size();
481 const auto new_sz = orig_sz * 2;
482 buf.resize(new_sz);
483 fill_sz = new_sz - orig_sz;
484
485 //update the buffer pointer
486 buffer = buf.data();
487 total_bytes_read += rd_bytes;
488 buffer += total_bytes_read;
489
490 } else { // Partial data ? Continue reading
491 total_bytes_read += rd_bytes;
492 fill_sz -= rd_bytes;
493 break;
494 }
495 }
496 buf.erase(buf.begin()+total_bytes_read, buf.end()); // remove extra nulls
497 return total_bytes_read;
498 }
499
500#ifndef __USING_WINDOWS__
514 static inline
515 std::pair<int, int> wait_for_child_exit(int pid)
516 {
517 int status = 0;
518 int ret = -1;
519 while (1) {
520 ret = waitpid(pid, &status, 0);
521 if (ret == -1) break;
522 if (ret == 0) continue;
523 return std::make_pair(ret, status);
524 }
525
526 return std::make_pair(ret, status);
527 }
528#endif
529
530} // end namespace util
531
532
533
534/* -------------------------------
535 * Popen Arguments
536 * -------------------------------
537 */
538
543{
544 string_arg(const char* arg): arg_value(arg) {}
545 string_arg(std::string&& arg): arg_value(std::move(arg)) {}
546 string_arg(const std::string& arg): arg_value(arg) {}
547 std::string arg_value;
548};
549
559{
560 template <typename T>
561 executable(T&& arg): string_arg(std::forward<T>(arg)) {}
562};
563
567enum IOTYPE {
571};
572
573//TODO: A common base/interface for below stream structures ??
574
586struct input
587{
588 // For an already existing file descriptor.
589 explicit input(int fd): rd_ch_(fd) {}
590
591 // FILE pointer.
592 explicit input (FILE* fp):input(subprocess_fileno(fp)) { assert(fp); }
593
594 explicit input(const char* filename) {
595 int fd = subprocess_open(filename, O_RDONLY);
596 if (fd == -1) throw OSError("File not found: ", errno);
597 rd_ch_ = fd;
598 }
599 explicit input(IOTYPE typ) {
600 assert (typ == PIPE && "STDOUT/STDERR not allowed");
601#ifndef __USING_WINDOWS__
602 std::tie(rd_ch_, wr_ch_) = util::pipe_cloexec();
603#endif
604 }
605
606 int rd_ch_ = -1;
607 int wr_ch_ = -1;
608};
609
610
621struct output
622{
623 explicit output(int fd): wr_ch_(fd) {}
624
625 explicit output (FILE* fp):output(subprocess_fileno(fp)) { assert(fp); }
626
627 explicit output(const char* filename) {
628 int fd = subprocess_open(filename, O_APPEND | O_CREAT | O_RDWR, 0640);
629 if (fd == -1) throw OSError("File not found: ", errno);
630 wr_ch_ = fd;
631 }
632 explicit output(IOTYPE typ) {
633 assert (typ == PIPE && "STDOUT/STDERR not allowed");
634#ifndef __USING_WINDOWS__
635 std::tie(rd_ch_, wr_ch_) = util::pipe_cloexec();
636#endif
637 }
638
639 int rd_ch_ = -1;
640 int wr_ch_ = -1;
641};
642
643
652struct error
653{
654 explicit error(int fd): wr_ch_(fd) {}
655
656 explicit error(FILE* fp):error(subprocess_fileno(fp)) { assert(fp); }
657
658 explicit error(const char* filename) {
659 int fd = subprocess_open(filename, O_APPEND | O_CREAT | O_RDWR, 0640);
660 if (fd == -1) throw OSError("File not found: ", errno);
661 wr_ch_ = fd;
662 }
663 explicit error(IOTYPE typ) {
664 assert ((typ == PIPE || typ == STDOUT) && "STDERR not allowed");
665 if (typ == PIPE) {
666#ifndef __USING_WINDOWS__
667 std::tie(rd_ch_, wr_ch_) = util::pipe_cloexec();
668#endif
669 } else {
670 // Need to defer it till we have checked all arguments
671 deferred_ = true;
672 }
673 }
674
675 bool deferred_ = false;
676 int rd_ch_ = -1;
677 int wr_ch_ = -1;
678};
679
680// ~~~~ End Popen Args ~~~~
681
682
695{
696public:
697 Buffer() = default;
698 explicit Buffer(size_t cap) { buf.resize(cap); }
699 void add_cap(size_t cap) { buf.resize(cap); }
700
701public:
702 std::vector<char> buf;
703 size_t length = 0;
704};
705
706// Buffer for storing output written to output fd
708// Buffer for storing output written to error fd
710
711
712// Fwd Decl.
713class Popen;
714
715/*---------------------------------------------------
716 * DETAIL NAMESPACE
717 *---------------------------------------------------
718 */
719
720namespace detail {
729{
731
732 void set_option(executable&& exe);
733 void set_option(input&& inp);
734 void set_option(output&& out);
735 void set_option(error&& err);
736
737private:
738 Popen* popen_ = nullptr;
739};
740
741#ifndef __USING_WINDOWS__
747class Child
748{
749public:
750 Child(Popen* p, int err_wr_pipe):
751 parent_(p),
752 err_wr_pipe_(err_wr_pipe)
753 {}
754
755 void execute_child();
756
757private:
758 // Lets call it parent even though
759 // technically a bit incorrect
760 Popen* parent_ = nullptr;
761 int err_wr_pipe_ = -1;
762};
763#endif
764
765// Fwd Decl.
766class Streams;
767
775{
776public:
777 Communication(Streams* stream): stream_(stream)
778 {}
779 Communication(const Communication&) = delete;
783public:
784 int send(const char* msg, size_t length);
785 int send(const std::vector<char>& msg);
786
787 std::pair<OutBuffer, ErrBuffer> communicate(const char* msg, size_t length);
788 std::pair<OutBuffer, ErrBuffer> communicate(const std::vector<char>& msg)
789 { return communicate(msg.data(), msg.size()); }
790
791 void set_out_buf_cap(size_t cap) { out_buf_cap_ = cap; }
792 void set_err_buf_cap(size_t cap) { err_buf_cap_ = cap; }
793
794private:
795 std::pair<OutBuffer, ErrBuffer> communicate_threaded(
796 const char* msg, size_t length);
797
798private:
802};
803
804
805
816{
817public:
818 Streams():comm_(this) {}
819 Streams(const Streams&) = delete;
820 Streams& operator=(const Streams&) = delete;
821 Streams(Streams&&) = default;
822 Streams& operator=(Streams&&) = default;
823
824public:
825 void setup_comm_channels();
826
828 {
829 if (write_to_child_ != -1 && read_from_parent_ != -1) {
831 }
832 if (write_to_parent_ != -1 && read_from_child_ != -1) {
834 }
835 if (err_write_ != -1 && err_read_ != -1) {
837 }
838 }
839
841 {
845 }
846
848 {
852 }
853
854 FILE* input() { return input_.get(); }
855 FILE* output() { return output_.get(); }
856 FILE* error() { return error_.get(); }
857
858 void input(FILE* fp) { input_.reset(fp, fclose); }
859 void output(FILE* fp) { output_.reset(fp, fclose); }
860 void error(FILE* fp) { error_.reset(fp, fclose); }
861
862 void set_out_buf_cap(size_t cap) { comm_.set_out_buf_cap(cap); }
863 void set_err_buf_cap(size_t cap) { comm_.set_err_buf_cap(cap); }
864
865public: /* Communication forwarding API's */
866 int send(const char* msg, size_t length)
867 { return comm_.send(msg, length); }
868
869 int send(const std::vector<char>& msg)
870 { return comm_.send(msg); }
871
872 std::pair<OutBuffer, ErrBuffer> communicate(const char* msg, size_t length)
873 { return comm_.communicate(msg, length); }
874
875 std::pair<OutBuffer, ErrBuffer> communicate(const std::vector<char>& msg)
876 { return comm_.communicate(msg); }
877
878
879public:// Yes they are public
880
881 std::shared_ptr<FILE> input_ = nullptr;
882 std::shared_ptr<FILE> output_ = nullptr;
883 std::shared_ptr<FILE> error_ = nullptr;
884
885#ifdef __USING_WINDOWS__
886 HANDLE g_hChildStd_IN_Rd = nullptr;
887 HANDLE g_hChildStd_IN_Wr = nullptr;
888 HANDLE g_hChildStd_OUT_Rd = nullptr;
889 HANDLE g_hChildStd_OUT_Wr = nullptr;
890 HANDLE g_hChildStd_ERR_Rd = nullptr;
891 HANDLE g_hChildStd_ERR_Wr = nullptr;
892#endif
893
894 // Pipes for communicating with child
895
896 // Emulates stdin
897 int write_to_child_ = -1; // Parent owned descriptor
898 int read_from_parent_ = -1; // Child owned descriptor
899
900 // Emulates stdout
901 int write_to_parent_ = -1; // Child owned descriptor
902 int read_from_child_ = -1; // Parent owned descriptor
903
904 // Emulates stderr
905 int err_write_ = -1; // Write error to parent (Child owned)
906 int err_read_ = -1; // Read error from child (Parent owned)
907
908private:
910};
911
912} // end namespace detail
913
914
915
931class Popen
932{
933public:
935#ifndef __USING_WINDOWS__
936 friend class detail::Child;
937#endif
938
939 template <typename... Args>
940 Popen(std::initializer_list<const char*> cmd_args, Args&& ...args)
941 {
942 vargs_.insert(vargs_.end(), cmd_args.begin(), cmd_args.end());
943 init_args(std::forward<Args>(args)...);
944
945 // Setup the communication channels of the Popen class
947
949 }
950
951 template <typename... Args>
952 Popen(std::vector<std::string> vargs_, Args &&... args) : vargs_(vargs_)
953 {
954 init_args(std::forward<Args>(args)...);
955
956 // Setup the communication channels of the Popen class
958
960 }
961
962 int retcode() const noexcept { return retcode_; }
963
964 int wait() noexcept(false);
965
966 void set_out_buf_cap(size_t cap) { stream_.set_out_buf_cap(cap); }
967
968 void set_err_buf_cap(size_t cap) { stream_.set_err_buf_cap(cap); }
969
970 int send(const char* msg, size_t length)
971 { return stream_.send(msg, length); }
972
973 int send(const std::string& msg)
974 { return send(msg.c_str(), msg.size()); }
975
976 int send(const std::vector<char>& msg)
977 { return stream_.send(msg); }
978
979 std::pair<OutBuffer, ErrBuffer> communicate(const char* msg, size_t length)
980 {
981 auto res = stream_.communicate(msg, length);
982 retcode_ = wait();
983 return res;
984 }
985
986 std::pair<OutBuffer, ErrBuffer> communicate(const std::string& msg)
987 {
988 return communicate(msg.c_str(), msg.size());
989 }
990
991 std::pair<OutBuffer, ErrBuffer> communicate(const std::vector<char>& msg)
992 {
993 auto res = stream_.communicate(msg);
994 retcode_ = wait();
995 return res;
996 }
997
998 std::pair<OutBuffer, ErrBuffer> communicate()
999 {
1000 return communicate(nullptr, 0);
1001 }
1002
1003private:
1004 template <typename F, typename... Args>
1005 void init_args(F&& farg, Args&&... args);
1006 void init_args();
1007 void populate_c_argv();
1008 void execute_process() noexcept(false);
1009
1010private:
1011 detail::Streams stream_;
1012
1013#ifdef __USING_WINDOWS__
1014 HANDLE process_handle_;
1015 std::future<void> cleanup_future_;
1016#else
1017 // Pid of the child process
1018 int child_pid_ = -1;
1019#endif
1020
1021 std::string exe_name_;
1022
1023 // Command provided as sequence
1024 std::vector<std::string> vargs_;
1025 std::vector<char*> cargv_;
1026
1027 int retcode_ = -1;
1028};
1029
1030inline void Popen::init_args() {
1032}
1033
1034template <typename F, typename... Args>
1035inline void Popen::init_args(F&& farg, Args&&... args)
1036{
1037 detail::ArgumentDeducer argd(this);
1038 argd.set_option(std::forward<F>(farg));
1039 init_args(std::forward<Args>(args)...);
1040}
1041
1043{
1044 cargv_.clear();
1045 cargv_.reserve(vargs_.size() + 1);
1046 for (auto& arg : vargs_) cargv_.push_back(&arg[0]);
1047 cargv_.push_back(nullptr);
1048}
1049
1050inline int Popen::wait() noexcept(false)
1051{
1052#ifdef __USING_WINDOWS__
1053 int ret = WaitForSingleObject(process_handle_, INFINITE);
1054
1055 // WaitForSingleObject with INFINITE should only return when process has signaled
1056 if (ret != WAIT_OBJECT_0) {
1057 throw OSError("Unexpected return code from WaitForSingleObject", 0);
1058 }
1059
1060 DWORD dretcode_;
1061
1062 if (FALSE == GetExitCodeProcess(process_handle_, &dretcode_))
1063 throw OSError("Failed during call to GetExitCodeProcess", 0);
1064
1065 CloseHandle(process_handle_);
1066
1067 return (int)dretcode_;
1068#else
1069 int ret, status;
1070 std::tie(ret, status) = util::wait_for_child_exit(child_pid_);
1071 if (ret == -1) {
1072 if (errno != ECHILD) throw OSError("waitpid failed", errno);
1073 return 0;
1074 }
1075 if (WIFEXITED(status)) return WEXITSTATUS(status);
1076 if (WIFSIGNALED(status)) return WTERMSIG(status);
1077 else return 255;
1078
1079 return 0;
1080#endif
1081}
1082
1083inline void Popen::execute_process() noexcept(false)
1084{
1085#ifdef __USING_WINDOWS__
1086 if (exe_name_.length()) {
1087 this->vargs_.insert(this->vargs_.begin(), this->exe_name_);
1088 this->populate_c_argv();
1089 }
1090 this->exe_name_ = vargs_[0];
1091
1092 std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
1093 std::wstring argument;
1094 std::wstring command_line;
1095 bool first_arg = true;
1096
1097 for (auto arg : this->vargs_) {
1098 if (!first_arg) {
1099 command_line += L" ";
1100 } else {
1101 first_arg = false;
1102 }
1103 argument = converter.from_bytes(arg);
1104 util::quote_argument(argument, command_line, false);
1105 }
1106
1107 // CreateProcessW can modify szCmdLine so we allocate needed memory
1108 wchar_t *szCmdline = new wchar_t[command_line.size() + 1];
1109 wcscpy_s(szCmdline, command_line.size() + 1, command_line.c_str());
1110 PROCESS_INFORMATION piProcInfo;
1111 STARTUPINFOW siStartInfo;
1112 BOOL bSuccess = FALSE;
1113 DWORD creation_flags = CREATE_UNICODE_ENVIRONMENT | CREATE_NO_WINDOW;
1114
1115 // Set up members of the PROCESS_INFORMATION structure.
1116 ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION));
1117
1118 // Set up members of the STARTUPINFOW structure.
1119 // This structure specifies the STDIN and STDOUT handles for redirection.
1120
1121 ZeroMemory(&siStartInfo, sizeof(STARTUPINFOW));
1122 siStartInfo.cb = sizeof(STARTUPINFOW);
1123
1124 siStartInfo.hStdError = this->stream_.g_hChildStd_ERR_Wr;
1125 siStartInfo.hStdOutput = this->stream_.g_hChildStd_OUT_Wr;
1126 siStartInfo.hStdInput = this->stream_.g_hChildStd_IN_Rd;
1127
1128 siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
1129
1130 // Create the child process.
1131 bSuccess = CreateProcessW(NULL,
1132 szCmdline, // command line
1133 NULL, // process security attributes
1134 NULL, // primary thread security attributes
1135 TRUE, // handles are inherited
1136 creation_flags, // creation flags
1137 NULL, // use parent's environment
1138 NULL, // use parent's current directory
1139 &siStartInfo, // STARTUPINFOW pointer
1140 &piProcInfo); // receives PROCESS_INFORMATION
1141
1142 // If an error occurs, exit the application.
1143 if (!bSuccess) {
1144 DWORD errorMessageID = ::GetLastError();
1145 throw CalledProcessError("CreateProcess failed: " + util::get_last_error(errorMessageID), errorMessageID);
1146 }
1147
1148 CloseHandle(piProcInfo.hThread);
1149
1150 /*
1151 TODO: use common apis to close linux handles
1152 */
1153
1154 this->process_handle_ = piProcInfo.hProcess;
1155
1156 this->cleanup_future_ = std::async(std::launch::async, [this] {
1157 WaitForSingleObject(this->process_handle_, INFINITE);
1158
1159 CloseHandle(this->stream_.g_hChildStd_ERR_Wr);
1160 CloseHandle(this->stream_.g_hChildStd_OUT_Wr);
1161 CloseHandle(this->stream_.g_hChildStd_IN_Rd);
1162 });
1163
1164/*
1165 NOTE: In the linux version, there is a check to make sure that the process
1166 has been started. Here, we do nothing because CreateProcess will throw
1167 if we fail to create the process.
1168*/
1169
1170
1171#else
1172
1173 int err_rd_pipe, err_wr_pipe;
1174 std::tie(err_rd_pipe, err_wr_pipe) = util::pipe_cloexec();
1175
1176 if (exe_name_.length()) {
1177 vargs_.insert(vargs_.begin(), exe_name_);
1179 }
1180 exe_name_ = vargs_[0];
1181
1182 child_pid_ = fork();
1183
1184 if (child_pid_ < 0) {
1185 subprocess_close(err_rd_pipe);
1186 subprocess_close(err_wr_pipe);
1187 throw OSError("fork failed", errno);
1188 }
1189
1190 if (child_pid_ == 0)
1191 {
1192 // Close descriptors belonging to parent
1194
1195 //Close the read end of the error pipe
1196 subprocess_close(err_rd_pipe);
1197
1198 detail::Child chld(this, err_wr_pipe);
1199 chld.execute_child();
1200 }
1201 else
1202 {
1203 subprocess_close(err_wr_pipe);// close child side of pipe, else get stuck in read below
1204
1206
1207 try {
1208 char err_buf[SP_MAX_ERR_BUF_SIZ] = {0,};
1209
1210 FILE* err_fp = fdopen(err_rd_pipe, "r");
1211 if (!err_fp) {
1212 subprocess_close(err_rd_pipe);
1213 throw OSError("fdopen failed", errno);
1214 }
1215 int read_bytes = util::read_atmost_n(err_fp, err_buf, SP_MAX_ERR_BUF_SIZ);
1216 fclose(err_fp);
1217
1218 if (read_bytes || strlen(err_buf)) {
1219 // Call waitpid to reap the child process
1220 // waitpid suspends the calling process until the
1221 // child terminates.
1222 int retcode = wait();
1223
1224 // Throw whatever information we have about child failure
1225 throw CalledProcessError(err_buf, retcode);
1226 }
1227 } catch (std::exception& exp) {
1229 throw;
1230 }
1231
1232 }
1233#endif
1234}
1235
1236namespace detail {
1237
1239 popen_->exe_name_ = std::move(exe.arg_value);
1240 }
1241
1243 if (inp.rd_ch_ != -1) popen_->stream_.read_from_parent_ = inp.rd_ch_;
1244 if (inp.wr_ch_ != -1) popen_->stream_.write_to_child_ = inp.wr_ch_;
1245 }
1246
1248 if (out.wr_ch_ != -1) popen_->stream_.write_to_parent_ = out.wr_ch_;
1249 if (out.rd_ch_ != -1) popen_->stream_.read_from_child_ = out.rd_ch_;
1250 }
1251
1253 if (err.deferred_) {
1256 } else {
1257 throw std::runtime_error("Set output before redirecting error to output");
1258 }
1259 }
1260 if (err.wr_ch_ != -1) popen_->stream_.err_write_ = err.wr_ch_;
1261 if (err.rd_ch_ != -1) popen_->stream_.err_read_ = err.rd_ch_;
1262 }
1263
1264
1265#ifndef __USING_WINDOWS__
1266 inline void Child::execute_child() {
1267 int sys_ret = -1;
1268 auto& stream = parent_->stream_;
1269
1270 try {
1271 if (stream.write_to_parent_ == 0)
1272 stream.write_to_parent_ = dup(stream.write_to_parent_);
1273
1274 if (stream.err_write_ == 0 || stream.err_write_ == 1)
1275 stream.err_write_ = dup(stream.err_write_);
1276
1277 // Make the child owned descriptors as the
1278 // stdin, stdout and stderr for the child process
1279 auto _dup2_ = [](int fd, int to_fd) {
1280 if (fd == to_fd) {
1281 // dup2 syscall does not reset the
1282 // CLOEXEC flag if the descriptors
1283 // provided to it are same.
1284 // But, we need to reset the CLOEXEC
1285 // flag as the provided descriptors
1286 // are now going to be the standard
1287 // input, output and error
1288 util::set_clo_on_exec(fd, false);
1289 } else if(fd != -1) {
1290 int res = dup2(fd, to_fd);
1291 if (res == -1) throw OSError("dup2 failed", errno);
1292 }
1293 };
1294
1295 // Create the standard streams
1296 _dup2_(stream.read_from_parent_, 0); // Input stream
1297 _dup2_(stream.write_to_parent_, 1); // Output stream
1298 _dup2_(stream.err_write_, 2); // Error stream
1299
1300 // Close the duped descriptors
1301 if (stream.read_from_parent_ != -1 && stream.read_from_parent_ > 2)
1302 subprocess_close(stream.read_from_parent_);
1303
1304 if (stream.write_to_parent_ != -1 && stream.write_to_parent_ > 2)
1305 subprocess_close(stream.write_to_parent_);
1306
1307 if (stream.err_write_ != -1 && stream.err_write_ > 2)
1308 subprocess_close(stream.err_write_);
1309
1310 // Replace the current image with the executable
1311 sys_ret = execvp(parent_->exe_name_.c_str(), parent_->cargv_.data());
1312
1313 if (sys_ret == -1) throw OSError("execve failed", errno);
1314
1315 } catch (const OSError& exp) {
1316 // Just write the exception message
1317 // TODO: Give back stack trace ?
1318 std::string err_msg(exp.what());
1319 //ATTN: Can we do something on error here ?
1320 util::write_n(err_wr_pipe_, err_msg.c_str(), err_msg.length());
1321 }
1322
1323 // Calling application would not get this
1324 // exit failure
1325 _exit (EXIT_FAILURE);
1326 }
1327#endif
1328
1329
1331 {
1332#ifdef __USING_WINDOWS__
1333 util::configure_pipe(&this->g_hChildStd_IN_Rd, &this->g_hChildStd_IN_Wr, &this->g_hChildStd_IN_Wr);
1334 this->input(util::file_from_handle(this->g_hChildStd_IN_Wr, "w"));
1335 this->write_to_child_ = subprocess_fileno(this->input());
1336
1337 util::configure_pipe(&this->g_hChildStd_OUT_Rd, &this->g_hChildStd_OUT_Wr, &this->g_hChildStd_OUT_Rd);
1338 this->output(util::file_from_handle(this->g_hChildStd_OUT_Rd, "r"));
1339 this->read_from_child_ = subprocess_fileno(this->output());
1340
1341 util::configure_pipe(&this->g_hChildStd_ERR_Rd, &this->g_hChildStd_ERR_Wr, &this->g_hChildStd_ERR_Rd);
1342 this->error(util::file_from_handle(this->g_hChildStd_ERR_Rd, "r"));
1343 this->err_read_ = subprocess_fileno(this->error());
1344#else
1345
1346 if (write_to_child_ != -1) input(fdopen(write_to_child_, "wb"));
1347 if (read_from_child_ != -1) output(fdopen(read_from_child_, "rb"));
1348 if (err_read_ != -1) error(fdopen(err_read_, "rb"));
1349
1350 auto handles = {input(), output(), error()};
1351
1352 for (auto& h : handles) {
1353 if (h == nullptr) continue;
1354 setvbuf(h, nullptr, _IONBF, BUFSIZ);
1355 }
1356 #endif
1357 }
1358
1359 inline int Communication::send(const char* msg, size_t length)
1360 {
1361 if (stream_->input() == nullptr) return -1;
1362 return std::fwrite(msg, sizeof(char), length, stream_->input());
1363 }
1364
1365 inline int Communication::send(const std::vector<char>& msg)
1366 {
1367 return send(msg.data(), msg.size());
1368 }
1369
1370 inline std::pair<OutBuffer, ErrBuffer>
1371 Communication::communicate(const char* msg, size_t length)
1372 {
1373 // Optimization from subprocess.py
1374 // If we are using one pipe, or no pipe
1375 // at all, using select() or threads is unnecessary.
1376 auto hndls = {stream_->input(), stream_->output(), stream_->error()};
1377 int count = std::count(std::begin(hndls), std::end(hndls), nullptr);
1378 const int len_conv = length;
1379
1380 if (count >= 2) {
1381 OutBuffer obuf;
1382 ErrBuffer ebuf;
1383 if (stream_->input()) {
1384 if (msg) {
1385 int wbytes = std::fwrite(msg, sizeof(char), length, stream_->input());
1386 if (wbytes < len_conv) {
1387 if (errno != EPIPE && errno != EINVAL) {
1388 throw OSError("fwrite error", errno);
1389 }
1390 }
1391 }
1392 // Close the input stream
1393 stream_->input_.reset();
1394 } else if (stream_->output()) {
1395 // Read till EOF
1396 // ATTN: This could be blocking, if the process
1397 // at the other end screws up, we get screwed as well
1398 obuf.add_cap(out_buf_cap_);
1399
1400 int rbytes = util::read_all(
1401 stream_->output(),
1402 obuf.buf);
1403
1404 if (rbytes == -1) {
1405 throw OSError("read to obuf failed", errno);
1406 }
1407
1408 obuf.length = rbytes;
1409 // Close the output stream
1410 stream_->output_.reset();
1411
1412 } else if (stream_->error()) {
1413 // Same screwness applies here as well
1414 ebuf.add_cap(err_buf_cap_);
1415
1416 int rbytes = util::read_atmost_n(
1417 stream_->error(),
1418 ebuf.buf.data(),
1419 ebuf.buf.size());
1420
1421 if (rbytes == -1) {
1422 throw OSError("read to ebuf failed", errno);
1423 }
1424
1425 ebuf.length = rbytes;
1426 // Close the error stream
1427 stream_->error_.reset();
1428 }
1429 return std::make_pair(std::move(obuf), std::move(ebuf));
1430 }
1431
1432 return communicate_threaded(msg, length);
1433 }
1434
1435
1436 inline std::pair<OutBuffer, ErrBuffer>
1437 Communication::communicate_threaded(const char* msg, size_t length)
1438 {
1439 OutBuffer obuf;
1440 ErrBuffer ebuf;
1441 std::future<int> out_fut, err_fut;
1442 const int length_conv = length;
1443
1444 if (stream_->output()) {
1445 obuf.add_cap(out_buf_cap_);
1446
1447 out_fut = std::async(std::launch::async,
1448 [&obuf, this] {
1449 return util::read_all(this->stream_->output(), obuf.buf);
1450 });
1451 }
1452 if (stream_->error()) {
1453 ebuf.add_cap(err_buf_cap_);
1454
1455 err_fut = std::async(std::launch::async,
1456 [&ebuf, this] {
1457 return util::read_all(this->stream_->error(), ebuf.buf);
1458 });
1459 }
1460 if (stream_->input()) {
1461 if (msg) {
1462 int wbytes = std::fwrite(msg, sizeof(char), length, stream_->input());
1463 if (wbytes < length_conv) {
1464 if (errno != EPIPE && errno != EINVAL) {
1465 throw OSError("fwrite error", errno);
1466 }
1467 }
1468 }
1469 stream_->input_.reset();
1470 }
1471
1472 if (out_fut.valid()) {
1473 int res = out_fut.get();
1474 if (res != -1) obuf.length = res;
1475 else obuf.length = 0;
1476 }
1477 if (err_fut.valid()) {
1478 int res = err_fut.get();
1479 if (res != -1) ebuf.length = res;
1480 else ebuf.length = 0;
1481 }
1482
1483 return std::make_pair(std::move(obuf), std::move(ebuf));
1484 }
1485
1486} // end namespace detail
1487
1488}
1489
1490#endif // BITCOIN_UTIL_SUBPROCESS_H
int ret
int flags
Definition: bitcoin-tx.cpp:529
ArgsManager & args
Definition: bitcoind.cpp:277
Buffer(size_t cap)
Definition: subprocess.h:698
void add_cap(size_t cap)
Definition: subprocess.h:699
std::vector< char > buf
Definition: subprocess.h:702
CalledProcessError(const std::string &error_msg, int retcode)
Definition: subprocess.h:147
OSError(const std::string &err_msg, int err_code)
Definition: subprocess.h:166
std::pair< OutBuffer, ErrBuffer > communicate(const char *msg, size_t length)
Definition: subprocess.h:979
void populate_c_argv()
Definition: subprocess.h:1042
detail::Streams stream_
Definition: subprocess.h:1011
std::pair< OutBuffer, ErrBuffer > communicate(const std::string &msg)
Definition: subprocess.h:986
void set_out_buf_cap(size_t cap)
Definition: subprocess.h:966
Popen(std::initializer_list< const char * > cmd_args, Args &&...args)
Definition: subprocess.h:940
std::vector< char * > cargv_
Definition: subprocess.h:1025
Popen(std::vector< std::string > vargs_, Args &&... args)
Definition: subprocess.h:952
void execute_process() noexcept(false)
Definition: subprocess.h:1083
std::vector< std::string > vargs_
Definition: subprocess.h:1024
std::string exe_name_
Definition: subprocess.h:1021
int send(const std::vector< char > &msg)
Definition: subprocess.h:976
int send(const std::string &msg)
Definition: subprocess.h:973
std::pair< OutBuffer, ErrBuffer > communicate()
Definition: subprocess.h:998
std::pair< OutBuffer, ErrBuffer > communicate(const std::vector< char > &msg)
Definition: subprocess.h:991
int retcode() const noexcept
Definition: subprocess.h:962
int wait() noexcept(false)
Definition: subprocess.h:1050
void set_err_buf_cap(size_t cap)
Definition: subprocess.h:968
int send(const char *msg, size_t length)
Definition: subprocess.h:970
Child(Popen *p, int err_wr_pipe)
Definition: subprocess.h:750
void set_err_buf_cap(size_t cap)
Definition: subprocess.h:792
Communication(Communication &&)=default
void set_out_buf_cap(size_t cap)
Definition: subprocess.h:791
int send(const char *msg, size_t length)
Definition: subprocess.h:1359
std::pair< OutBuffer, ErrBuffer > communicate(const char *msg, size_t length)
Definition: subprocess.h:1371
std::pair< OutBuffer, ErrBuffer > communicate_threaded(const char *msg, size_t length)
Definition: subprocess.h:1437
Communication & operator=(const Communication &)=delete
Communication(const Communication &)=delete
Communication & operator=(Communication &&)=default
std::pair< OutBuffer, ErrBuffer > communicate(const std::vector< char > &msg)
Definition: subprocess.h:788
std::pair< OutBuffer, ErrBuffer > communicate(const std::vector< char > &msg)
Definition: subprocess.h:875
int send(const std::vector< char > &msg)
Definition: subprocess.h:869
void set_out_buf_cap(size_t cap)
Definition: subprocess.h:862
Streams(Streams &&)=default
std::pair< OutBuffer, ErrBuffer > communicate(const char *msg, size_t length)
Definition: subprocess.h:872
void set_err_buf_cap(size_t cap)
Definition: subprocess.h:863
std::shared_ptr< FILE > output_
Definition: subprocess.h:882
std::shared_ptr< FILE > error_
Definition: subprocess.h:883
Streams & operator=(const Streams &)=delete
int send(const char *msg, size_t length)
Definition: subprocess.h:866
Streams(const Streams &)=delete
Streams & operator=(Streams &&)=default
std::shared_ptr< FILE > input_
Definition: subprocess.h:881
#define T(expected, seed, data)
static int read_all(FILE *fp, std::vector< char > &buf)
Definition: subprocess.h:466
static int read_atmost_n(FILE *fp, char *buf, size_t read_upto)
Definition: subprocess.h:425
static void set_clo_on_exec(int fd, bool set=true)
Definition: subprocess.h:346
static std::vector< std::string > split(const std::string &str, const std::string &delims=" \t")
Definition: subprocess.h:315
static std::pair< int, int > wait_for_child_exit(int pid)
Definition: subprocess.h:515
static std::pair< int, int > pipe_cloexec() noexcept(false)
Definition: subprocess.h:370
static int write_n(int fd, const char *buf, size_t length)
Definition: subprocess.h:398
static const size_t SP_MAX_ERR_BUF_SIZ
Definition: subprocess.h:123
static const size_t DEFAULT_BUF_CAP_BYTES
Definition: subprocess.h:128
void set_option(executable &&exe)
Definition: subprocess.h:1238
error(FILE *fp)
Definition: subprocess.h:656
error(IOTYPE typ)
Definition: subprocess.h:663
error(const char *filename)
Definition: subprocess.h:658
input(const char *filename)
Definition: subprocess.h:594
input(IOTYPE typ)
Definition: subprocess.h:599
input(FILE *fp)
Definition: subprocess.h:592
output(IOTYPE typ)
Definition: subprocess.h:632
output(const char *filename)
Definition: subprocess.h:627
output(FILE *fp)
Definition: subprocess.h:625
std::string arg_value
Definition: subprocess.h:547
string_arg(const char *arg)
Definition: subprocess.h:544
string_arg(std::string &&arg)
Definition: subprocess.h:545
string_arg(const std::string &arg)
Definition: subprocess.h:546
#define subprocess_close
Definition: subprocess.h:90
#define subprocess_write
Definition: subprocess.h:93
#define subprocess_fileno
Definition: subprocess.h:91
#define subprocess_open
Definition: subprocess.h:92
std::string SysErrorString(int err)
Return system error string from errno value.
Definition: syserror.cpp:17
static int count
assert(!tx.IsCoinBase())