BProcess.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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. static void call_handler (BProcess *o, int normally, uint8_t normally_exit_status)
  48. {
  49. DEBUGERROR(&o->d_err, o->handler(o->user, normally, normally_exit_status))
  50. }
  51. static BProcess * find_process (BProcessManager *o, pid_t pid)
  52. {
  53. for (LinkedList1Node *node = LinkedList1_GetFirst(&o->processes); node; node = LinkedList1Node_Next(node)) {
  54. BProcess *p = UPPER_OBJECT(node, BProcess, list_node);
  55. if (p->pid == pid) {
  56. return p;
  57. }
  58. }
  59. return NULL;
  60. }
  61. static void work_signals (BProcessManager *o)
  62. {
  63. // read exit status with waitpid()
  64. int status;
  65. pid_t pid = waitpid(-1, &status, WNOHANG);
  66. if (pid <= 0) {
  67. return;
  68. }
  69. // schedule next waitpid
  70. BPending_Set(&o->wait_job);
  71. // find process
  72. BProcess *p = find_process(o, pid);
  73. if (!p) {
  74. BLog(BLOG_DEBUG, "unknown child %p");
  75. }
  76. if (WIFEXITED(status)) {
  77. uint8_t exit_status = WEXITSTATUS(status);
  78. BLog(BLOG_INFO, "child %"PRIiMAX" exited with status %"PRIu8, (intmax_t)pid, exit_status);
  79. if (p) {
  80. call_handler(p, 1, exit_status);
  81. return;
  82. }
  83. }
  84. else if (WIFSIGNALED(status)) {
  85. int signo = WTERMSIG(status);
  86. BLog(BLOG_INFO, "child %"PRIiMAX" exited with signal %d", (intmax_t)pid, signo);
  87. if (p) {
  88. call_handler(p, 0, 0);
  89. return;
  90. }
  91. }
  92. else {
  93. BLog(BLOG_ERROR, "unknown wait status type for pid %"PRIiMAX" (%d)", (intmax_t)pid, status);
  94. }
  95. }
  96. static void wait_job_handler (BProcessManager *o)
  97. {
  98. DebugObject_Access(&o->d_obj);
  99. work_signals(o);
  100. return;
  101. }
  102. static void signal_handler (BProcessManager *o, int signo)
  103. {
  104. ASSERT(signo == SIGCHLD)
  105. DebugObject_Access(&o->d_obj);
  106. work_signals(o);
  107. return;
  108. }
  109. int BProcessManager_Init (BProcessManager *o, BReactor *reactor)
  110. {
  111. // init arguments
  112. o->reactor = reactor;
  113. // init signal handling
  114. sigset_t sset;
  115. ASSERT_FORCE(sigemptyset(&sset) == 0)
  116. ASSERT_FORCE(sigaddset(&sset, SIGCHLD) == 0)
  117. if (!BUnixSignal_Init(&o->signal, o->reactor, sset, (BUnixSignal_handler)signal_handler, o)) {
  118. BLog(BLOG_ERROR, "BUnixSignal_Init failed");
  119. goto fail0;
  120. }
  121. // init processes list
  122. LinkedList1_Init(&o->processes);
  123. // init wait job
  124. BPending_Init(&o->wait_job, BReactor_PendingGroup(o->reactor), (BPending_handler)wait_job_handler, o);
  125. DebugObject_Init(&o->d_obj);
  126. return 1;
  127. fail0:
  128. return 0;
  129. }
  130. void BProcessManager_Free (BProcessManager *o)
  131. {
  132. ASSERT(LinkedList1_IsEmpty(&o->processes))
  133. DebugObject_Free(&o->d_obj);
  134. // free wait job
  135. BPending_Free(&o->wait_job);
  136. // free signal handling
  137. BUnixSignal_Free(&o->signal, 1);
  138. }
  139. static int fds_contains (const int *fds, int fd, size_t *pos)
  140. {
  141. for (size_t i = 0; fds[i] >= 0; i++) {
  142. if (fds[i] == fd) {
  143. if (pos) {
  144. *pos = i;
  145. }
  146. return 1;
  147. }
  148. }
  149. return 0;
  150. }
  151. int BProcess_Init2 (BProcess *o, BProcessManager *m, BProcess_handler handler, void *user, const char *file, char *const argv[], struct BProcess_params params)
  152. {
  153. // init arguments
  154. o->m = m;
  155. o->handler = handler;
  156. o->user = user;
  157. // count fds
  158. size_t num_fds;
  159. for (num_fds = 0; params.fds[num_fds] >= 0; num_fds++);
  160. // block signals
  161. // needed to prevent parent's signal handlers from being called
  162. // in the child
  163. sigset_t sset_all;
  164. sigfillset(&sset_all);
  165. sigset_t sset_old;
  166. if (sigprocmask(SIG_SETMASK, &sset_all, &sset_old) < 0) {
  167. BLog(BLOG_ERROR, "sigprocmask failed");
  168. goto fail0;
  169. }
  170. // fork
  171. pid_t pid = fork();
  172. if (pid == 0) {
  173. // this is child
  174. // restore signal dispositions
  175. for (int i = 1; i < NSIG; i++) {
  176. struct sigaction sa;
  177. memset(&sa, 0, sizeof(sa));
  178. sa.sa_handler = SIG_DFL;
  179. sa.sa_flags = 0;
  180. sigaction(i, &sa, NULL);
  181. }
  182. // unblock signals
  183. sigset_t sset_none;
  184. sigemptyset(&sset_none);
  185. if (sigprocmask(SIG_SETMASK, &sset_none, NULL) < 0) {
  186. abort();
  187. }
  188. // copy fds array
  189. int *fds2 = malloc((num_fds + 1) * sizeof(fds2[0]));
  190. if (!fds2) {
  191. abort();
  192. }
  193. memcpy(fds2, params.fds, (num_fds + 1) * sizeof(fds2[0]));
  194. // find maximum file descriptors
  195. int max_fd = sysconf(_SC_OPEN_MAX);
  196. if (max_fd < 0) {
  197. abort();
  198. }
  199. // close file descriptors
  200. for (int i = 0; i < max_fd; i++) {
  201. // if it's one of the given fds, don't close it
  202. if (fds_contains(fds2, i, NULL)) {
  203. continue;
  204. }
  205. close(i);
  206. }
  207. // map fds to requested fd numbers
  208. while (*fds2 >= 0) {
  209. // resolve possible conflict
  210. size_t cpos;
  211. if (fds_contains(fds2 + 1, *params.fds_map, &cpos)) {
  212. // dup() the fd to a new number; the old one will be closed
  213. // in the following dup2()
  214. if ((fds2[1 + cpos] = dup(fds2[1 + cpos])) < 0) {
  215. abort();
  216. }
  217. }
  218. if (*fds2 != *params.fds_map) {
  219. // dup fd
  220. if (dup2(*fds2, *params.fds_map) < 0) {
  221. abort();
  222. }
  223. // close original fd
  224. close(*fds2);
  225. }
  226. fds2++;
  227. params.fds_map++;
  228. }
  229. // make sure standard streams are open
  230. open_standard_streams();
  231. // make session leader if requested
  232. if (params.do_setsid) {
  233. setsid();
  234. }
  235. // assume identity of username, if requested
  236. if (params.username) {
  237. long bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
  238. if (bufsize < 0) {
  239. bufsize = 16384;
  240. }
  241. char *buf = malloc(bufsize);
  242. if (!buf) {
  243. abort();
  244. }
  245. struct passwd pwd;
  246. struct passwd *res;
  247. getpwnam_r(params.username, &pwd, buf, bufsize, &res);
  248. if (!res) {
  249. abort();
  250. }
  251. if (initgroups(params.username, pwd.pw_gid) < 0) {
  252. abort();
  253. }
  254. if (setgid(pwd.pw_gid) < 0) {
  255. abort();
  256. }
  257. if (setuid(pwd.pw_uid) < 0) {
  258. abort();
  259. }
  260. }
  261. execv(file, argv);
  262. abort();
  263. }
  264. // restore original signal mask
  265. ASSERT_FORCE(sigprocmask(SIG_SETMASK, &sset_old, NULL) == 0)
  266. if (pid < 0) {
  267. BLog(BLOG_ERROR, "fork failed");
  268. goto fail0;
  269. }
  270. // remember pid
  271. o->pid = pid;
  272. // add to processes list
  273. LinkedList1_Append(&o->m->processes, &o->list_node);
  274. DebugObject_Init(&o->d_obj);
  275. DebugError_Init(&o->d_err, BReactor_PendingGroup(m->reactor));
  276. return 1;
  277. fail0:
  278. return 0;
  279. }
  280. 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)
  281. {
  282. struct BProcess_params params;
  283. params.username = username;
  284. params.fds = fds;
  285. params.fds_map = fds_map;
  286. params.do_setsid = 0;
  287. return BProcess_Init2(o, m, handler, user, file, argv, params);
  288. }
  289. int BProcess_Init (BProcess *o, BProcessManager *m, BProcess_handler handler, void *user, const char *file, char *const argv[], const char *username)
  290. {
  291. int fds[] = {-1};
  292. return BProcess_InitWithFds(o, m, handler, user, file, argv, username, fds, NULL);
  293. }
  294. void BProcess_Free (BProcess *o)
  295. {
  296. DebugError_Free(&o->d_err);
  297. DebugObject_Free(&o->d_obj);
  298. // remove from processes list
  299. LinkedList1_Remove(&o->m->processes, &o->list_node);
  300. }
  301. int BProcess_Terminate (BProcess *o)
  302. {
  303. DebugObject_Access(&o->d_obj);
  304. DebugError_AssertNoError(&o->d_err);
  305. ASSERT(o->pid > 0)
  306. if (kill(o->pid, SIGTERM) < 0) {
  307. BLog(BLOG_ERROR, "kill(%"PRIiMAX", SIGTERM) failed", (intmax_t)o->pid);
  308. return 0;
  309. }
  310. return 1;
  311. }
  312. int BProcess_Kill (BProcess *o)
  313. {
  314. DebugObject_Access(&o->d_obj);
  315. DebugError_AssertNoError(&o->d_err);
  316. ASSERT(o->pid > 0)
  317. if (kill(o->pid, SIGKILL) < 0) {
  318. BLog(BLOG_ERROR, "kill(%"PRIiMAX", SIGKILL) failed", (intmax_t)o->pid);
  319. return 0;
  320. }
  321. return 1;
  322. }