popen.c 14 KB

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