popen.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #include "../libnetdata.h"
  3. // ----------------------------------------------------------------------------
  4. // popen with tracking
  5. static pthread_mutex_t netdata_popen_tracking_mutex = NETDATA_MUTEX_INITIALIZER;
  6. struct netdata_popen {
  7. pid_t pid;
  8. bool reaped;
  9. siginfo_t infop;
  10. int waitid_ret;
  11. struct netdata_popen *next;
  12. struct netdata_popen *prev;
  13. };
  14. static struct netdata_popen *netdata_popen_root = NULL;
  15. // myp_add_lock takes the lock if we're tracking.
  16. static void netdata_popen_tracking_lock(void) {
  17. netdata_mutex_lock(&netdata_popen_tracking_mutex);
  18. }
  19. // myp_add_unlock release the lock if we're tracking.
  20. static void netdata_popen_tracking_unlock(void) {
  21. netdata_mutex_unlock(&netdata_popen_tracking_mutex);
  22. }
  23. // myp_add_locked adds pid if we're tracking.
  24. // myp_add_lock must have been called previously.
  25. static void netdata_popen_tracking_add_pid_unsafe(pid_t pid) {
  26. struct netdata_popen *mp;
  27. mp = callocz(1, sizeof(struct netdata_popen));
  28. mp->pid = pid;
  29. DOUBLE_LINKED_LIST_PREPEND_ITEM_UNSAFE(netdata_popen_root, mp, prev, next);
  30. }
  31. // myp_del deletes pid if we're tracking.
  32. static void netdata_popen_tracking_del_pid(pid_t pid) {
  33. struct netdata_popen *mp;
  34. netdata_popen_tracking_lock();
  35. DOUBLE_LINKED_LIST_FOREACH_FORWARD(netdata_popen_root, mp, prev, next) {
  36. if(unlikely(mp->pid == pid))
  37. break;
  38. }
  39. if(mp) {
  40. DOUBLE_LINKED_LIST_REMOVE_ITEM_UNSAFE(netdata_popen_root, mp, prev, next);
  41. freez(mp);
  42. }
  43. else
  44. netdata_log_error("POPEN: Cannot find pid %d.", pid);
  45. netdata_popen_tracking_unlock();
  46. }
  47. // myp_free cleans up any resources allocated for process
  48. // tracking.
  49. void netdata_popen_tracking_cleanup(void) {
  50. netdata_popen_tracking_lock();
  51. while(netdata_popen_root) {
  52. struct netdata_popen *mp = netdata_popen_root;
  53. DOUBLE_LINKED_LIST_REMOVE_ITEM_UNSAFE(netdata_popen_root, mp, prev, next);
  54. freez(mp);
  55. }
  56. netdata_popen_tracking_unlock();
  57. }
  58. int netdata_waitid(idtype_t idtype, id_t id, siginfo_t *infop, int options) {
  59. struct netdata_popen *mp = NULL;
  60. if(idtype == P_PID && id != 0) {
  61. // the caller is asking to waitid() for a specific child pid
  62. netdata_popen_tracking_lock();
  63. DOUBLE_LINKED_LIST_FOREACH_FORWARD(netdata_popen_root, mp, prev, next) {
  64. if(unlikely(mp->pid == (pid_t)id))
  65. break;
  66. }
  67. if(!mp)
  68. netdata_popen_tracking_unlock();
  69. }
  70. int ret;
  71. if(mp && mp->reaped) {
  72. // we have already reaped this child
  73. ret = mp->waitid_ret;
  74. *infop = mp->infop;
  75. }
  76. else {
  77. // we haven't reaped this child yet
  78. ret = waitid(idtype, id, infop, options);
  79. if(mp && !mp->reaped) {
  80. mp->reaped = true;
  81. mp->infop = *infop;
  82. mp->waitid_ret = ret;
  83. }
  84. }
  85. if(mp)
  86. netdata_popen_tracking_unlock();
  87. return ret;
  88. }
  89. // ----------------------------------------------------------------------------
  90. // helpers
  91. static inline void convert_argv_to_string(char *dst, size_t size, const char *spawn_argv[]) {
  92. int i;
  93. for(i = 0; spawn_argv[i] ;i++) {
  94. if(i == 0) snprintfz(dst, size, "%s", spawn_argv[i]);
  95. else {
  96. size_t len = strlen(dst);
  97. snprintfz(&dst[len], size - len, " '%s'", spawn_argv[i]);
  98. }
  99. }
  100. }
  101. // ----------------------------------------------------------------------------
  102. // the core of netdata popen
  103. /*
  104. * Returns -1 on failure, 0 on success. When POPEN_FLAG_CREATE_PIPE is set, on success set the FILE *fp pointer.
  105. */
  106. #define PIPE_READ 0
  107. #define PIPE_WRITE 1
  108. static int popene_internal(volatile pid_t *pidptr, char **env, uint8_t flags, FILE **fpp_child_stdin, FILE **fpp_child_stdout, const char *command, const char *spawn_argv[]) {
  109. // create a string to be logged about the command we are running
  110. char command_to_be_logged[2048];
  111. convert_argv_to_string(command_to_be_logged, sizeof(command_to_be_logged), spawn_argv);
  112. // netdata_log_info("custom_popene() running command: %s", command_to_be_logged);
  113. int ret = 0; // success by default
  114. int attr_rc = 1; // failure by default
  115. FILE *fp_child_stdin = NULL, *fp_child_stdout = NULL;
  116. int pipefd_stdin[2] = { -1, -1 };
  117. int pipefd_stdout[2] = { -1, -1 };
  118. pid_t pid;
  119. posix_spawnattr_t attr;
  120. posix_spawn_file_actions_t fa;
  121. unsigned int fds_to_exclude_from_closing = OPEN_FD_EXCLUDE_STDERR;
  122. if(posix_spawn_file_actions_init(&fa)) {
  123. netdata_log_error("POPEN: posix_spawn_file_actions_init() failed.");
  124. ret = -1;
  125. goto set_return_values_and_return;
  126. }
  127. if(fpp_child_stdin) {
  128. if (pipe(pipefd_stdin) == -1) {
  129. netdata_log_error("POPEN: stdin pipe() failed");
  130. ret = -1;
  131. goto cleanup_and_return;
  132. }
  133. if ((fp_child_stdin = fdopen(pipefd_stdin[PIPE_WRITE], "w")) == NULL) {
  134. netdata_log_error("POPEN: fdopen() stdin failed");
  135. ret = -1;
  136. goto cleanup_and_return;
  137. }
  138. if(posix_spawn_file_actions_adddup2(&fa, pipefd_stdin[PIPE_READ], STDIN_FILENO)) {
  139. netdata_log_error("POPEN: posix_spawn_file_actions_adddup2() on stdin failed.");
  140. ret = -1;
  141. goto cleanup_and_return;
  142. }
  143. }
  144. else {
  145. if (posix_spawn_file_actions_addopen(&fa, STDIN_FILENO, "/dev/null", O_RDONLY, 0)) {
  146. netdata_log_error("POPEN: posix_spawn_file_actions_addopen() on stdin to /dev/null failed.");
  147. // this is not a fatal error
  148. fds_to_exclude_from_closing |= OPEN_FD_EXCLUDE_STDIN;
  149. }
  150. }
  151. if (fpp_child_stdout) {
  152. if (pipe(pipefd_stdout) == -1) {
  153. netdata_log_error("POPEN: stdout pipe() failed");
  154. ret = -1;
  155. goto cleanup_and_return;
  156. }
  157. if ((fp_child_stdout = fdopen(pipefd_stdout[PIPE_READ], "r")) == NULL) {
  158. netdata_log_error("POPEN: fdopen() stdout failed");
  159. ret = -1;
  160. goto cleanup_and_return;
  161. }
  162. if(posix_spawn_file_actions_adddup2(&fa, pipefd_stdout[PIPE_WRITE], STDOUT_FILENO)) {
  163. netdata_log_error("POPEN: posix_spawn_file_actions_adddup2() on stdout failed.");
  164. ret = -1;
  165. goto cleanup_and_return;
  166. }
  167. }
  168. else {
  169. if (posix_spawn_file_actions_addopen(&fa, STDOUT_FILENO, "/dev/null", O_WRONLY, 0)) {
  170. netdata_log_error("POPEN: posix_spawn_file_actions_addopen() on stdout to /dev/null failed.");
  171. // this is not a fatal error
  172. fds_to_exclude_from_closing |= OPEN_FD_EXCLUDE_STDOUT;
  173. }
  174. }
  175. if(flags & POPEN_FLAG_CLOSE_FD) {
  176. // Mark all files to be closed by the exec() stage of posix_spawn()
  177. for_each_open_fd(OPEN_FD_ACTION_FD_CLOEXEC, fds_to_exclude_from_closing);
  178. }
  179. attr_rc = posix_spawnattr_init(&attr);
  180. if(attr_rc) {
  181. // failed
  182. netdata_log_error("POPEN: posix_spawnattr_init() failed.");
  183. }
  184. else {
  185. // success
  186. // reset all signals in the child
  187. if (posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETSIGMASK | POSIX_SPAWN_SETSIGDEF))
  188. netdata_log_error("POPEN: posix_spawnattr_setflags() failed.");
  189. sigset_t mask;
  190. sigemptyset(&mask);
  191. if (posix_spawnattr_setsigmask(&attr, &mask))
  192. netdata_log_error("POPEN: posix_spawnattr_setsigmask() failed.");
  193. }
  194. // Take the lock while we fork to ensure we don't race with SIGCHLD
  195. // delivery on a process which exits quickly.
  196. netdata_popen_tracking_lock();
  197. if (!posix_spawn(&pid, command, &fa, &attr, (char * const*)spawn_argv, env)) {
  198. // success
  199. *pidptr = pid;
  200. netdata_popen_tracking_add_pid_unsafe(pid);
  201. netdata_popen_tracking_unlock();
  202. }
  203. else {
  204. // failure
  205. netdata_popen_tracking_unlock();
  206. netdata_log_error("POPEN: failed to spawn command: \"%s\" from parent pid %d.", command_to_be_logged, getpid());
  207. ret = -1;
  208. goto cleanup_and_return;
  209. }
  210. // the normal cleanup will run
  211. // but ret == 0 at this point
  212. cleanup_and_return:
  213. if(!attr_rc) {
  214. // posix_spawnattr_init() succeeded
  215. if (posix_spawnattr_destroy(&attr))
  216. netdata_log_error("POPEN: posix_spawnattr_destroy() failed");
  217. }
  218. if (posix_spawn_file_actions_destroy(&fa))
  219. netdata_log_error("POPEN: posix_spawn_file_actions_destroy() failed");
  220. // the child end - close it
  221. if(pipefd_stdin[PIPE_READ] != -1)
  222. close(pipefd_stdin[PIPE_READ]);
  223. // our end
  224. if(ret == -1 || !fpp_child_stdin) {
  225. if (fp_child_stdin)
  226. fclose(fp_child_stdin);
  227. else if (pipefd_stdin[PIPE_WRITE] != -1)
  228. close(pipefd_stdin[PIPE_WRITE]);
  229. fp_child_stdin = NULL;
  230. }
  231. // the child end - close it
  232. if (pipefd_stdout[PIPE_WRITE] != -1)
  233. close(pipefd_stdout[PIPE_WRITE]);
  234. // our end
  235. if (ret == -1 || !fpp_child_stdout) {
  236. if (fp_child_stdout)
  237. fclose(fp_child_stdout);
  238. else if (pipefd_stdout[PIPE_READ] != -1)
  239. close(pipefd_stdout[PIPE_READ]);
  240. fp_child_stdout = NULL;
  241. }
  242. set_return_values_and_return:
  243. if(fpp_child_stdin)
  244. *fpp_child_stdin = fp_child_stdin;
  245. if(fpp_child_stdout)
  246. *fpp_child_stdout = fp_child_stdout;
  247. return ret;
  248. }
  249. int netdata_popene_variadic_internal_dont_use_directly(volatile pid_t *pidptr, char **env, uint8_t flags, FILE **fpp_child_input, FILE **fpp_child_output, const char *command, ...) {
  250. // convert the variable list arguments into what posix_spawn() needs
  251. // all arguments are expected strings
  252. va_list args;
  253. int args_count;
  254. // count the number variable parameters
  255. // the variable parameters are expected NULL terminated
  256. {
  257. const char *s;
  258. va_start(args, command);
  259. args_count = 0;
  260. while ((s = va_arg(args, const char *))) args_count++;
  261. va_end(args);
  262. }
  263. // create a string pointer array as needed by posix_spawn()
  264. // variable array in the stack
  265. const char *spawn_argv[args_count + 1];
  266. {
  267. const char *s;
  268. va_start(args, command);
  269. int i;
  270. for (i = 0; i < args_count; i++) {
  271. s = va_arg(args, const char *);
  272. spawn_argv[i] = s;
  273. }
  274. spawn_argv[args_count] = NULL;
  275. va_end(args);
  276. }
  277. return popene_internal(pidptr, env, flags, fpp_child_input, fpp_child_output, command, spawn_argv);
  278. }
  279. // See man environ
  280. extern char **environ;
  281. FILE *netdata_popen(const char *command, volatile pid_t *pidptr, FILE **fpp_child_input) {
  282. FILE *fp_child_output = NULL;
  283. const char *spawn_argv[] = {
  284. "sh",
  285. "-c",
  286. command,
  287. NULL
  288. };
  289. (void)popene_internal(pidptr, environ, POPEN_FLAG_CLOSE_FD, fpp_child_input, &fp_child_output, "/bin/sh", spawn_argv);
  290. return fp_child_output;
  291. }
  292. FILE *netdata_popene(const char *command, volatile pid_t *pidptr, char **env, FILE **fpp_child_input) {
  293. FILE *fp_child_output = NULL;
  294. const char *spawn_argv[] = {
  295. "sh",
  296. "-c",
  297. command,
  298. NULL
  299. };
  300. (void)popene_internal(pidptr, env, POPEN_FLAG_CLOSE_FD, fpp_child_input, &fp_child_output, "/bin/sh", spawn_argv);
  301. return fp_child_output;
  302. }
  303. // returns 0 on success, -1 on failure
  304. int netdata_spawn(const char *command, volatile pid_t *pidptr) {
  305. const char *spawn_argv[] = {
  306. "sh",
  307. "-c",
  308. command,
  309. NULL
  310. };
  311. return popene_internal(pidptr, environ, POPEN_FLAG_NONE, NULL, NULL, "/bin/sh", spawn_argv);
  312. }
  313. int netdata_pclose(FILE *fp_child_input, FILE *fp_child_output, pid_t pid) {
  314. int ret;
  315. siginfo_t info;
  316. netdata_log_debug(D_EXIT, "Request to netdata_pclose() on pid %d", pid);
  317. if (fp_child_input)
  318. fclose(fp_child_input);
  319. if (fp_child_output)
  320. fclose(fp_child_output);
  321. errno = 0;
  322. ret = netdata_waitid(P_PID, (id_t) pid, &info, WEXITED);
  323. netdata_popen_tracking_del_pid(pid);
  324. if (ret != -1) {
  325. switch (info.si_code) {
  326. case CLD_EXITED:
  327. if(info.si_status)
  328. netdata_log_error("child pid %d exited with code %d.", info.si_pid, info.si_status);
  329. return(info.si_status);
  330. case CLD_KILLED:
  331. if(info.si_status == SIGTERM) {
  332. netdata_log_info("child pid %d killed by SIGTERM", info.si_pid);
  333. return(0);
  334. }
  335. else if(info.si_status == SIGPIPE) {
  336. netdata_log_info("child pid %d killed by SIGPIPE.", info.si_pid);
  337. return(0);
  338. }
  339. else {
  340. netdata_log_error("child pid %d killed by signal %d.", info.si_pid, info.si_status);
  341. return(-1);
  342. }
  343. case CLD_DUMPED:
  344. netdata_log_error("child pid %d core dumped by signal %d.", info.si_pid, info.si_status);
  345. return(-2);
  346. case CLD_STOPPED:
  347. netdata_log_error("child pid %d stopped by signal %d.", info.si_pid, info.si_status);
  348. return(0);
  349. case CLD_TRAPPED:
  350. netdata_log_error("child pid %d trapped by signal %d.", info.si_pid, info.si_status);
  351. return(-4);
  352. case CLD_CONTINUED:
  353. netdata_log_error("child pid %d continued by signal %d.", info.si_pid, info.si_status);
  354. return(0);
  355. default:
  356. netdata_log_error("child pid %d gave us a SIGCHLD with code %d and status %d.", info.si_pid, info.si_code, info.si_status);
  357. return(-5);
  358. }
  359. }
  360. else
  361. netdata_log_error("Cannot waitid() for pid %d", pid);
  362. return 0;
  363. }