BProcess.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. /**
  2. * @file BProcess.c
  3. * @author Ambroz Bizjak <ambrop7@gmail.com>
  4. *
  5. * @section LICENSE
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions are met:
  9. * 1. Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * 2. Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. * 3. Neither the name of the author nor the
  15. * names of its contributors may be used to endorse or promote products
  16. * derived from this software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  19. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  27. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. */
  29. #include <stddef.h>
  30. #include <string.h>
  31. #include <inttypes.h>
  32. #include <stdlib.h>
  33. #include <sys/types.h>
  34. #include <sys/wait.h>
  35. #include <unistd.h>
  36. #include <signal.h>
  37. #include <grp.h>
  38. #include <pwd.h>
  39. #include <errno.h>
  40. #include <sys/stat.h>
  41. #include <fcntl.h>
  42. #include <misc/offset.h>
  43. #include <misc/open_standard_streams.h>
  44. #include <base/BLog.h>
  45. #include "BProcess.h"
  46. #include <generated/blog_channel_BProcess.h>
  47. #define INITIAL_NUM_GROUPS 24
  48. static void call_handler (BProcess *o, int normally, uint8_t normally_exit_status)
  49. {
  50. DEBUGERROR(&o->d_err, o->handler(o->user, normally, normally_exit_status))
  51. }
  52. static BProcess * find_process (BProcessManager *o, pid_t pid)
  53. {
  54. for (LinkedList1Node *node = LinkedList1_GetFirst(&o->processes); node; node = LinkedList1Node_Next(node)) {
  55. BProcess *p = UPPER_OBJECT(node, BProcess, list_node);
  56. if (p->pid == pid) {
  57. return p;
  58. }
  59. }
  60. return NULL;
  61. }
  62. static void work_signals (BProcessManager *o)
  63. {
  64. // read exit status with waitpid()
  65. int status;
  66. pid_t pid = waitpid(-1, &status, WNOHANG);
  67. if (pid <= 0) {
  68. return;
  69. }
  70. // schedule next waitpid
  71. BPending_Set(&o->wait_job);
  72. // find process
  73. BProcess *p = find_process(o, pid);
  74. if (!p) {
  75. BLog(BLOG_DEBUG, "unknown child %p");
  76. }
  77. if (WIFEXITED(status)) {
  78. uint8_t exit_status = WEXITSTATUS(status);
  79. BLog(BLOG_INFO, "child %"PRIiMAX" exited with status %"PRIu8, (intmax_t)pid, exit_status);
  80. if (p) {
  81. call_handler(p, 1, exit_status);
  82. return;
  83. }
  84. }
  85. else if (WIFSIGNALED(status)) {
  86. int signo = WTERMSIG(status);
  87. BLog(BLOG_INFO, "child %"PRIiMAX" exited with signal %d", (intmax_t)pid, signo);
  88. if (p) {
  89. call_handler(p, 0, 0);
  90. return;
  91. }
  92. }
  93. else {
  94. BLog(BLOG_ERROR, "unknown wait status type for pid %"PRIiMAX" (%d)", (intmax_t)pid, status);
  95. }
  96. }
  97. static void wait_job_handler (BProcessManager *o)
  98. {
  99. DebugObject_Access(&o->d_obj);
  100. work_signals(o);
  101. return;
  102. }
  103. static void signal_handler (BProcessManager *o, int signo)
  104. {
  105. ASSERT(signo == SIGCHLD)
  106. DebugObject_Access(&o->d_obj);
  107. work_signals(o);
  108. return;
  109. }
  110. int BProcessManager_Init (BProcessManager *o, BReactor *reactor)
  111. {
  112. // init arguments
  113. o->reactor = reactor;
  114. // init signal handling
  115. sigset_t sset;
  116. ASSERT_FORCE(sigemptyset(&sset) == 0)
  117. ASSERT_FORCE(sigaddset(&sset, SIGCHLD) == 0)
  118. if (!BUnixSignal_Init(&o->signal, o->reactor, sset, (BUnixSignal_handler)signal_handler, o)) {
  119. BLog(BLOG_ERROR, "BUnixSignal_Init failed");
  120. goto fail0;
  121. }
  122. // init processes list
  123. LinkedList1_Init(&o->processes);
  124. // init wait job
  125. BPending_Init(&o->wait_job, BReactor_PendingGroup(o->reactor), (BPending_handler)wait_job_handler, o);
  126. DebugObject_Init(&o->d_obj);
  127. return 1;
  128. fail0:
  129. return 0;
  130. }
  131. void BProcessManager_Free (BProcessManager *o)
  132. {
  133. ASSERT(LinkedList1_IsEmpty(&o->processes))
  134. DebugObject_Free(&o->d_obj);
  135. // free wait job
  136. BPending_Free(&o->wait_job);
  137. // free signal handling
  138. BUnixSignal_Free(&o->signal, 1);
  139. }
  140. static int fds_contains (const int *fds, int fd, size_t *pos)
  141. {
  142. for (size_t i = 0; fds[i] >= 0; i++) {
  143. if (fds[i] == fd) {
  144. if (pos) {
  145. *pos = i;
  146. }
  147. return 1;
  148. }
  149. }
  150. return 0;
  151. }
  152. int BProcess_Init2 (BProcess *o, BProcessManager *m, BProcess_handler handler, void *user, const char *file, char *const argv[], struct BProcess_params params)
  153. {
  154. int res = 0;
  155. // init arguments
  156. o->m = m;
  157. o->handler = handler;
  158. o->user = user;
  159. // count fds
  160. size_t num_fds;
  161. for (num_fds = 0; params.fds[num_fds] >= 0; num_fds++);
  162. // We retrieve all the needed info and allocate all needed memory
  163. // before the fork, because doing these things in the child after
  164. // the fork may be unsafe.
  165. // Get the max FD number.
  166. int max_fd = sysconf(_SC_OPEN_MAX);
  167. if (max_fd < 0) {
  168. BLog(BLOG_ERROR, "sysconf(_SC_OPEN_MAX)");
  169. goto fail0;
  170. }
  171. char *pwnam_buf = NULL;
  172. struct passwd pwd;
  173. gid_t groups_static[INITIAL_NUM_GROUPS];
  174. gid_t *groups = groups_static;
  175. int num_groups = INITIAL_NUM_GROUPS;
  176. if (params.username) {
  177. // Get the max getpwnam_r buffer size.
  178. long pwnam_bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
  179. if (pwnam_bufsize < 0) {
  180. pwnam_bufsize = 16384;
  181. }
  182. // Allocate memory for getpwnam_r.
  183. pwnam_buf = malloc(pwnam_bufsize);
  184. if (!pwnam_buf) {
  185. BLog(BLOG_ERROR, "malloc failed");
  186. goto fail0;
  187. }
  188. // Get information about the user.
  189. struct passwd *getpwnam_res;
  190. getpwnam_r(params.username, &pwd, pwnam_buf, pwnam_bufsize, &getpwnam_res);
  191. if (!getpwnam_res) {
  192. BLog(BLOG_ERROR, "getpwnam_r failed");
  193. goto fail1;
  194. }
  195. // Retrieve the group list.
  196. // Start with a small auto-allocated list and only if it turns out
  197. // to be too small resort to malloc.
  198. while (1) {
  199. int groups_ret = getgrouplist(params.username, pwd.pw_gid, groups, &num_groups);
  200. if ((groups_ret < 0) ? (num_groups <= 0) : (num_groups != groups_ret)) {
  201. BLog(BLOG_ERROR, "getgrouplist behaved inconsistently");
  202. goto fail2;
  203. }
  204. if (groups_ret >= 0) {
  205. break;
  206. }
  207. if (groups != groups_static) {
  208. free(groups);
  209. }
  210. groups = malloc(num_groups * sizeof(gid_t));
  211. if (!groups) {
  212. BLog(BLOG_ERROR, "malloc failed");
  213. goto fail2;
  214. }
  215. }
  216. }
  217. // Make a copy of the file descriptors array.
  218. int *fds2 = malloc((num_fds + 1) * sizeof(fds2[0]));
  219. if (!fds2) {
  220. BLog(BLOG_ERROR, "malloc failed");
  221. goto fail2;
  222. }
  223. memcpy(fds2, params.fds, (num_fds + 1) * sizeof(fds2[0]));
  224. // block signals
  225. // needed to prevent parent's signal handlers from being called
  226. // in the child
  227. sigset_t sset_all;
  228. sigfillset(&sset_all);
  229. sigset_t sset_old;
  230. if (pthread_sigmask(SIG_SETMASK, &sset_all, &sset_old) != 0) {
  231. BLog(BLOG_ERROR, "pthread_sigmask failed");
  232. goto fail3;
  233. }
  234. // fork
  235. pid_t pid = fork();
  236. if (pid == 0) {
  237. // this is child
  238. // restore signal dispositions
  239. for (int i = 1; i < NSIG; i++) {
  240. struct sigaction sa;
  241. memset(&sa, 0, sizeof(sa));
  242. sa.sa_handler = SIG_DFL;
  243. sa.sa_flags = 0;
  244. sigaction(i, &sa, NULL);
  245. }
  246. // unblock signals
  247. sigset_t sset_none;
  248. sigemptyset(&sset_none);
  249. if (pthread_sigmask(SIG_SETMASK, &sset_none, NULL) != 0) {
  250. abort();
  251. }
  252. // close file descriptors, except the given fds
  253. for (int i = 0; i < max_fd; i++) {
  254. if (!fds_contains(fds2, i, NULL)) {
  255. close(i);
  256. }
  257. }
  258. // map fds to requested fd numbers
  259. while (*fds2 >= 0) {
  260. // resolve possible conflict
  261. size_t cpos;
  262. if (fds_contains(fds2 + 1, *params.fds_map, &cpos)) {
  263. // dup() the fd to a new number; the old one will be closed
  264. // in the following dup2()
  265. if ((fds2[1 + cpos] = dup(fds2[1 + cpos])) < 0) {
  266. abort();
  267. }
  268. }
  269. if (*fds2 != *params.fds_map) {
  270. // dup fd
  271. if (dup2(*fds2, *params.fds_map) < 0) {
  272. abort();
  273. }
  274. // close original fd
  275. close(*fds2);
  276. }
  277. fds2++;
  278. params.fds_map++;
  279. }
  280. // make sure standard streams are open
  281. open_standard_streams();
  282. // make session leader if requested
  283. if (params.do_setsid) {
  284. setsid();
  285. }
  286. // assume identity of username, if requested
  287. if (params.username) {
  288. if (setgroups(num_groups, groups) < 0) {
  289. abort();
  290. }
  291. if (setgid(pwd.pw_gid) < 0) {
  292. abort();
  293. }
  294. if (setuid(pwd.pw_uid) < 0) {
  295. abort();
  296. }
  297. }
  298. // do the exec
  299. execv(file, argv);
  300. // if we're still here, something went wrong
  301. abort();
  302. }
  303. // restore original signal mask
  304. ASSERT_FORCE(pthread_sigmask(SIG_SETMASK, &sset_old, NULL) == 0)
  305. if (pid < 0) {
  306. BLog(BLOG_ERROR, "fork failed");
  307. goto fail3;
  308. }
  309. // remember pid
  310. o->pid = pid;
  311. // add to processes list
  312. LinkedList1_Append(&o->m->processes, &o->list_node);
  313. DebugObject_Init(&o->d_obj);
  314. DebugError_Init(&o->d_err, BReactor_PendingGroup(m->reactor));
  315. // Returning success, but cleanup first.
  316. res = 1;
  317. fail3:
  318. free(fds2);
  319. fail2:
  320. if (groups != groups_static) {
  321. free(groups);
  322. }
  323. fail1:
  324. free(pwnam_buf);
  325. fail0:
  326. return res;
  327. }
  328. int BProcess_InitWithFds (BProcess *o, BProcessManager *m, BProcess_handler handler, void *user, const char *file, char *const argv[], const char *username, const int *fds, const int *fds_map)
  329. {
  330. struct BProcess_params params;
  331. params.username = username;
  332. params.fds = fds;
  333. params.fds_map = fds_map;
  334. params.do_setsid = 0;
  335. return BProcess_Init2(o, m, handler, user, file, argv, params);
  336. }
  337. int BProcess_Init (BProcess *o, BProcessManager *m, BProcess_handler handler, void *user, const char *file, char *const argv[], const char *username)
  338. {
  339. int fds[] = {-1};
  340. return BProcess_InitWithFds(o, m, handler, user, file, argv, username, fds, NULL);
  341. }
  342. void BProcess_Free (BProcess *o)
  343. {
  344. DebugError_Free(&o->d_err);
  345. DebugObject_Free(&o->d_obj);
  346. // remove from processes list
  347. LinkedList1_Remove(&o->m->processes, &o->list_node);
  348. }
  349. int BProcess_Terminate (BProcess *o)
  350. {
  351. DebugObject_Access(&o->d_obj);
  352. DebugError_AssertNoError(&o->d_err);
  353. ASSERT(o->pid > 0)
  354. if (kill(o->pid, SIGTERM) < 0) {
  355. BLog(BLOG_ERROR, "kill(%"PRIiMAX", SIGTERM) failed", (intmax_t)o->pid);
  356. return 0;
  357. }
  358. return 1;
  359. }
  360. int BProcess_Kill (BProcess *o)
  361. {
  362. DebugObject_Access(&o->d_obj);
  363. DebugError_AssertNoError(&o->d_err);
  364. ASSERT(o->pid > 0)
  365. if (kill(o->pid, SIGKILL) < 0) {
  366. BLog(BLOG_ERROR, "kill(%"PRIiMAX", SIGKILL) failed", (intmax_t)o->pid);
  367. return 0;
  368. }
  369. return 1;
  370. }