BProcess.c 11 KB

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