popen.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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_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_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_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. int stdin_fd_to_exclude_from_closing = -1;
  129. int stdout_fd_to_exclude_from_closing = -1;
  130. if(posix_spawn_file_actions_init(&fa)) {
  131. error("POPEN: posix_spawn_file_actions_init() failed.");
  132. ret = -1;
  133. goto set_return_values_and_return;
  134. }
  135. if(fpp_child_stdin) {
  136. if (pipe(pipefd_stdin) == -1) {
  137. error("POPEN: stdin pipe() failed");
  138. ret = -1;
  139. goto cleanup_and_return;
  140. }
  141. if ((fp_child_stdin = fdopen(pipefd_stdin[PIPE_WRITE], "w")) == NULL) {
  142. error("POPEN: fdopen() stdin failed");
  143. ret = -1;
  144. goto cleanup_and_return;
  145. }
  146. if(posix_spawn_file_actions_adddup2(&fa, pipefd_stdin[PIPE_READ], STDIN_FILENO)) {
  147. error("POPEN: posix_spawn_file_actions_adddup2() on stdin failed.");
  148. ret = -1;
  149. goto cleanup_and_return;
  150. }
  151. }
  152. else {
  153. if (posix_spawn_file_actions_addopen(&fa, STDIN_FILENO, "/dev/null", O_RDONLY, 0)) {
  154. error("POPEN: posix_spawn_file_actions_addopen() on stdin to /dev/null failed.");
  155. // this is not a fatal error
  156. stdin_fd_to_exclude_from_closing = STDIN_FILENO;
  157. }
  158. }
  159. if (fpp_child_stdout) {
  160. if (pipe(pipefd_stdout) == -1) {
  161. error("POPEN: stdout pipe() failed");
  162. ret = -1;
  163. goto cleanup_and_return;
  164. }
  165. if ((fp_child_stdout = fdopen(pipefd_stdout[PIPE_READ], "r")) == NULL) {
  166. error("POPEN: fdopen() stdout failed");
  167. ret = -1;
  168. goto cleanup_and_return;
  169. }
  170. if(posix_spawn_file_actions_adddup2(&fa, pipefd_stdout[PIPE_WRITE], STDOUT_FILENO)) {
  171. error("POPEN: posix_spawn_file_actions_adddup2() on stdout failed.");
  172. ret = -1;
  173. goto cleanup_and_return;
  174. }
  175. }
  176. else {
  177. if (posix_spawn_file_actions_addopen(&fa, STDOUT_FILENO, "/dev/null", O_WRONLY, 0)) {
  178. error("POPEN: posix_spawn_file_actions_addopen() on stdout to /dev/null failed.");
  179. // this is not a fatal error
  180. stdout_fd_to_exclude_from_closing = STDOUT_FILENO;
  181. }
  182. }
  183. if(flags & POPEN_FLAG_CLOSE_FD) {
  184. // Mark all files to be closed by the exec() stage of posix_spawn()
  185. for(int i = (int)(sysconf(_SC_OPEN_MAX) - 1); i >= 0; i--) {
  186. if(likely(i != STDERR_FILENO && i != stdin_fd_to_exclude_from_closing && i != stdout_fd_to_exclude_from_closing))
  187. (void)fcntl(i, F_SETFD, FD_CLOEXEC);
  188. }
  189. }
  190. attr_rc = posix_spawnattr_init(&attr);
  191. if(attr_rc) {
  192. // failed
  193. error("POPEN: posix_spawnattr_init() failed.");
  194. }
  195. else {
  196. // success
  197. // reset all signals in the child
  198. if (posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETSIGMASK | POSIX_SPAWN_SETSIGDEF))
  199. error("POPEN: posix_spawnattr_setflags() failed.");
  200. sigset_t mask;
  201. sigemptyset(&mask);
  202. if (posix_spawnattr_setsigmask(&attr, &mask))
  203. error("POPEN: posix_spawnattr_setsigmask() failed.");
  204. }
  205. // Take the lock while we fork to ensure we don't race with SIGCHLD
  206. // delivery on a process which exits quickly.
  207. netdata_popen_tracking_lock();
  208. if (!posix_spawn(&pid, command, &fa, &attr, (char * const*)spawn_argv, env)) {
  209. // success
  210. *pidptr = pid;
  211. netdata_popen_tracking_add_pid_unsafe(pid);
  212. netdata_popen_tracking_unlock();
  213. }
  214. else {
  215. // failure
  216. netdata_popen_tracking_unlock();
  217. error("POPEN: failed to spawn command: \"%s\" from parent pid %d.", command_to_be_logged, getpid());
  218. ret = -1;
  219. goto cleanup_and_return;
  220. }
  221. // the normal cleanup will run
  222. // but ret == 0 at this point
  223. cleanup_and_return:
  224. if(!attr_rc) {
  225. // posix_spawnattr_init() succeeded
  226. if (posix_spawnattr_destroy(&attr))
  227. error("POPEN: posix_spawnattr_destroy() failed");
  228. }
  229. if (posix_spawn_file_actions_destroy(&fa))
  230. error("POPEN: posix_spawn_file_actions_destroy() failed");
  231. // the child end - close it
  232. if(pipefd_stdin[PIPE_READ] != -1)
  233. close(pipefd_stdin[PIPE_READ]);
  234. // our end
  235. if(ret == -1 || !fpp_child_stdin) {
  236. if (fp_child_stdin)
  237. fclose(fp_child_stdin);
  238. else if (pipefd_stdin[PIPE_WRITE] != -1)
  239. close(pipefd_stdin[PIPE_WRITE]);
  240. fp_child_stdin = NULL;
  241. }
  242. // the child end - close it
  243. if (pipefd_stdout[PIPE_WRITE] != -1)
  244. close(pipefd_stdout[PIPE_WRITE]);
  245. // our end
  246. if (ret == -1 || !fpp_child_stdout) {
  247. if (fp_child_stdout)
  248. fclose(fp_child_stdout);
  249. else if (pipefd_stdout[PIPE_READ] != -1)
  250. close(pipefd_stdout[PIPE_READ]);
  251. fp_child_stdout = NULL;
  252. }
  253. set_return_values_and_return:
  254. if(fpp_child_stdin)
  255. *fpp_child_stdin = fp_child_stdin;
  256. if(fpp_child_stdout)
  257. *fpp_child_stdout = fp_child_stdout;
  258. return ret;
  259. }
  260. 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, ...) {
  261. // convert the variable list arguments into what posix_spawn() needs
  262. // all arguments are expected strings
  263. va_list args;
  264. int args_count;
  265. // count the number variable parameters
  266. // the variable parameters are expected NULL terminated
  267. {
  268. const char *s;
  269. va_start(args, command);
  270. args_count = 0;
  271. while ((s = va_arg(args, const char *))) args_count++;
  272. va_end(args);
  273. }
  274. // create a string pointer array as needed by posix_spawn()
  275. // variable array in the stack
  276. const char *spawn_argv[args_count + 1];
  277. {
  278. const char *s;
  279. va_start(args, command);
  280. int i;
  281. for (i = 0; i < args_count; i++) {
  282. s = va_arg(args, const char *);
  283. spawn_argv[i] = s;
  284. }
  285. spawn_argv[args_count] = NULL;
  286. va_end(args);
  287. }
  288. return popene_internal(pidptr, env, flags, fpp_child_input, fpp_child_output, command, spawn_argv);
  289. }
  290. // See man environ
  291. extern char **environ;
  292. FILE *netdata_popen(const char *command, volatile pid_t *pidptr, 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, environ, POPEN_FLAG_CLOSE_FD, fpp_child_input, &fp_child_output, "/bin/sh", spawn_argv);
  301. return fp_child_output;
  302. }
  303. FILE *netdata_popene(const char *command, volatile pid_t *pidptr, char **env, FILE **fpp_child_input) {
  304. FILE *fp_child_output = NULL;
  305. const char *spawn_argv[] = {
  306. "sh",
  307. "-c",
  308. command,
  309. NULL
  310. };
  311. (void)popene_internal(pidptr, env, POPEN_FLAG_CLOSE_FD, fpp_child_input, &fp_child_output, "/bin/sh", spawn_argv);
  312. return fp_child_output;
  313. }
  314. // returns 0 on success, -1 on failure
  315. int netdata_spawn(const char *command, volatile pid_t *pidptr) {
  316. const char *spawn_argv[] = {
  317. "sh",
  318. "-c",
  319. command,
  320. NULL
  321. };
  322. return popene_internal(pidptr, environ, POPEN_FLAG_NONE, NULL, NULL, "/bin/sh", spawn_argv);
  323. }
  324. int netdata_pclose(FILE *fp_child_input, FILE *fp_child_output, pid_t pid) {
  325. int ret;
  326. siginfo_t info;
  327. debug(D_EXIT, "Request to netdata_pclose() on pid %d", pid);
  328. if (fp_child_input)
  329. fclose(fp_child_input);
  330. if (fp_child_output)
  331. fclose(fp_child_output);
  332. errno = 0;
  333. ret = waitid(P_PID, (id_t) pid, &info, WEXITED);
  334. netdata_popen_tracking_del_pid(pid);
  335. if (ret != -1) {
  336. switch (info.si_code) {
  337. case CLD_EXITED:
  338. if(info.si_status)
  339. error("child pid %d exited with code %d.", info.si_pid, info.si_status);
  340. return(info.si_status);
  341. case CLD_KILLED:
  342. if(info.si_status == 15) {
  343. info("child pid %d killed by signal %d.", info.si_pid, info.si_status);
  344. return(0);
  345. }
  346. else {
  347. error("child pid %d killed by signal %d.", info.si_pid, info.si_status);
  348. return(-1);
  349. }
  350. case CLD_DUMPED:
  351. error("child pid %d core dumped by signal %d.", info.si_pid, info.si_status);
  352. return(-2);
  353. case CLD_STOPPED:
  354. error("child pid %d stopped by signal %d.", info.si_pid, info.si_status);
  355. return(0);
  356. case CLD_TRAPPED:
  357. error("child pid %d trapped by signal %d.", info.si_pid, info.si_status);
  358. return(-4);
  359. case CLD_CONTINUED:
  360. error("child pid %d continued by signal %d.", info.si_pid, info.si_status);
  361. return(0);
  362. default:
  363. error("child pid %d gave us a SIGCHLD with code %d and status %d.", info.si_pid, info.si_code, info.si_status);
  364. return(-5);
  365. }
  366. }
  367. else
  368. error("Cannot waitid() for pid %d", pid);
  369. return 0;
  370. }
  371. int netdata_spawn_waitpid(pid_t pid) {
  372. return netdata_pclose(NULL, NULL, pid);
  373. }