popen.c 11 KB

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