BProcess.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. /**
  2. * @file BProcess.c
  3. * @author Ambroz Bizjak <ambrop7@gmail.com>
  4. *
  5. * @section LICENSE
  6. *
  7. * This file is part of BadVPN.
  8. *
  9. * BadVPN is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License version 2
  11. * as published by the Free Software Foundation.
  12. *
  13. * BadVPN is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License along
  19. * with this program; if not, write to the Free Software Foundation, Inc.,
  20. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. */
  22. #include <stddef.h>
  23. #include <string.h>
  24. #include <inttypes.h>
  25. #include <stdlib.h>
  26. #include <sys/types.h>
  27. #include <sys/wait.h>
  28. #include <unistd.h>
  29. #include <signal.h>
  30. #include <grp.h>
  31. #include <pwd.h>
  32. #include <errno.h>
  33. #include <sys/stat.h>
  34. #include <fcntl.h>
  35. #include <misc/offset.h>
  36. #include <base/BLog.h>
  37. #include "BProcess.h"
  38. #include <generated/blog_channel_BProcess.h>
  39. static void call_handler (BProcess *o, int normally, uint8_t normally_exit_status)
  40. {
  41. DEBUGERROR(&o->d_err, o->handler(o->user, normally, normally_exit_status))
  42. }
  43. static BProcess * find_process (BProcessManager *o, pid_t pid)
  44. {
  45. LinkedList2Iterator it;
  46. LinkedList2Iterator_InitForward(&it, &o->processes);
  47. LinkedList2Node *node;
  48. while (node = LinkedList2Iterator_Next(&it)) {
  49. BProcess *p = UPPER_OBJECT(node, BProcess, list_node);
  50. if (p->pid == pid) {
  51. LinkedList2Iterator_Free(&it);
  52. return p;
  53. }
  54. }
  55. return NULL;
  56. }
  57. static void work_signals (BProcessManager *o)
  58. {
  59. // read exit status with waitpid()
  60. int status;
  61. pid_t pid = waitpid(-1, &status, WNOHANG);
  62. if (pid <= 0) {
  63. return;
  64. }
  65. // schedule next waitpid
  66. BPending_Set(&o->wait_job);
  67. // find process
  68. BProcess *p = find_process(o, pid);
  69. if (!p) {
  70. BLog(BLOG_DEBUG, "unknown child %p");
  71. }
  72. if (WIFEXITED(status)) {
  73. uint8_t exit_status = WEXITSTATUS(status);
  74. BLog(BLOG_INFO, "child %"PRIiMAX" exited with status %"PRIu8, (intmax_t)pid, exit_status);
  75. if (p) {
  76. call_handler(p, 1, exit_status);
  77. return;
  78. }
  79. }
  80. else if (WIFSIGNALED(status)) {
  81. int signo = WTERMSIG(status);
  82. BLog(BLOG_INFO, "child %"PRIiMAX" exited with signal %d", (intmax_t)pid, signo);
  83. if (p) {
  84. call_handler(p, 0, 0);
  85. return;
  86. }
  87. }
  88. else {
  89. BLog(BLOG_ERROR, "unknown wait status type for pid %"PRIiMAX" (%d)", (intmax_t)pid, status);
  90. }
  91. }
  92. static void wait_job_handler (BProcessManager *o)
  93. {
  94. DebugObject_Access(&o->d_obj);
  95. work_signals(o);
  96. return;
  97. }
  98. static void signal_handler (BProcessManager *o, int signo)
  99. {
  100. ASSERT(signo == SIGCHLD)
  101. DebugObject_Access(&o->d_obj);
  102. work_signals(o);
  103. return;
  104. }
  105. int BProcessManager_Init (BProcessManager *o, BReactor *reactor)
  106. {
  107. // init arguments
  108. o->reactor = reactor;
  109. // init signal handling
  110. sigset_t sset;
  111. ASSERT_FORCE(sigemptyset(&sset) == 0)
  112. ASSERT_FORCE(sigaddset(&sset, SIGCHLD) == 0)
  113. if (!BUnixSignal_Init(&o->signal, o->reactor, sset, (BUnixSignal_handler)signal_handler, o)) {
  114. BLog(BLOG_ERROR, "BUnixSignal_Init failed");
  115. goto fail0;
  116. }
  117. // init processes list
  118. LinkedList2_Init(&o->processes);
  119. // init wait job
  120. BPending_Init(&o->wait_job, BReactor_PendingGroup(o->reactor), (BPending_handler)wait_job_handler, o);
  121. DebugObject_Init(&o->d_obj);
  122. return 1;
  123. fail0:
  124. return 0;
  125. }
  126. void BProcessManager_Free (BProcessManager *o)
  127. {
  128. ASSERT(LinkedList2_IsEmpty(&o->processes))
  129. DebugObject_Free(&o->d_obj);
  130. // free wait job
  131. BPending_Free(&o->wait_job);
  132. // free signal handling
  133. BUnixSignal_Free(&o->signal, 1);
  134. }
  135. static int fds_contains (const int *fds, int fd, size_t *pos)
  136. {
  137. for (size_t i = 0; fds[i] >= 0; i++) {
  138. if (fds[i] == fd) {
  139. if (pos) {
  140. *pos = i;
  141. }
  142. return 1;
  143. }
  144. }
  145. return 0;
  146. }
  147. static int ensure_standard_stream (const int *fds_map, size_t fds_map_size, int fd)
  148. {
  149. // if some file descriptor from parent is being used for this standard stream, keep it
  150. for (size_t i = 0; i < fds_map_size; i++) {
  151. if (fds_map[i] == fd) {
  152. return 1;
  153. }
  154. }
  155. // open /dev/null
  156. int ofd = open("/dev/null", O_RDWR);
  157. if (ofd < 0) {
  158. return 0;
  159. }
  160. // map the new fd to the standard stream
  161. if (ofd != fd) {
  162. if (dup2(ofd, fd) < 0) {
  163. return 0;
  164. }
  165. close(ofd);
  166. }
  167. return 1;
  168. }
  169. 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)
  170. {
  171. // init arguments
  172. o->m = m;
  173. o->handler = handler;
  174. o->user = user;
  175. // count fds
  176. size_t num_fds;
  177. for (num_fds = 0; fds[num_fds] >= 0; num_fds++);
  178. // block signals
  179. // needed to prevent parent's signal handlers from being called
  180. // in the child
  181. sigset_t sset_all;
  182. sigfillset(&sset_all);
  183. sigset_t sset_old;
  184. if (sigprocmask(SIG_SETMASK, &sset_all, &sset_old) < 0) {
  185. BLog(BLOG_ERROR, "sigprocmask failed");
  186. goto fail0;
  187. }
  188. // fork
  189. pid_t pid = fork();
  190. if (pid == 0) {
  191. // this is child
  192. // restore signal dispositions
  193. for (int i = 1; i < NSIG; i++) {
  194. struct sigaction sa;
  195. memset(&sa, 0, sizeof(sa));
  196. sa.sa_handler = SIG_DFL;
  197. sa.sa_flags = 0;
  198. sigaction(i, &sa, NULL);
  199. }
  200. // unblock signals
  201. sigset_t sset_none;
  202. sigemptyset(&sset_none);
  203. if (sigprocmask(SIG_SETMASK, &sset_none, NULL) < 0) {
  204. abort();
  205. }
  206. // copy fds array
  207. int *fds2 = malloc((num_fds + 1) * sizeof(fds2[0]));
  208. if (!fds2) {
  209. abort();
  210. }
  211. memcpy(fds2, fds, (num_fds + 1) * sizeof(fds2[0]));
  212. // find maximum file descriptors
  213. int max_fd = sysconf(_SC_OPEN_MAX);
  214. if (max_fd < 0) {
  215. abort();
  216. }
  217. // close file descriptors
  218. for (int i = 0; i < max_fd; i++) {
  219. // if it's one of the given fds, don't close it
  220. if (fds_contains(fds2, i, NULL)) {
  221. continue;
  222. }
  223. close(i);
  224. }
  225. const int *orig_fds_map = fds_map;
  226. // map fds to requested fd numbers
  227. while (*fds2 >= 0) {
  228. // resolve possible conflict
  229. size_t cpos;
  230. if (fds_contains(fds2 + 1, *fds_map, &cpos)) {
  231. // dup() the fd to a new number; the old one will be closed
  232. // in the following dup2()
  233. if ((fds2[1 + cpos] = dup(fds2[1 + cpos])) < 0) {
  234. abort();
  235. }
  236. }
  237. if (*fds2 != *fds_map) {
  238. // dup fd
  239. if (dup2(*fds2, *fds_map) < 0) {
  240. abort();
  241. }
  242. // close original fd
  243. close(*fds2);
  244. }
  245. fds2++;
  246. fds_map++;
  247. }
  248. // make sure standard streams are open
  249. if (!ensure_standard_stream(orig_fds_map, num_fds, 0)) {
  250. abort();
  251. }
  252. if (!ensure_standard_stream(orig_fds_map, num_fds, 1)) {
  253. abort();
  254. }
  255. if (!ensure_standard_stream(orig_fds_map, num_fds, 2)) {
  256. abort();
  257. }
  258. // assume identity of username, if requested
  259. if (username) {
  260. long bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
  261. if (bufsize < 0) {
  262. bufsize = 16384;
  263. }
  264. char *buf = malloc(bufsize);
  265. if (!buf) {
  266. abort();
  267. }
  268. struct passwd pwd;
  269. struct passwd *res;
  270. getpwnam_r(username, &pwd, buf, bufsize, &res);
  271. if (!res) {
  272. abort();
  273. }
  274. if (initgroups(username, pwd.pw_gid) < 0) {
  275. abort();
  276. }
  277. if (setgid(pwd.pw_gid) < 0) {
  278. abort();
  279. }
  280. if (setuid(pwd.pw_uid) < 0) {
  281. abort();
  282. }
  283. }
  284. execv(file, argv);
  285. abort();
  286. }
  287. // restore original signal mask
  288. ASSERT_FORCE(sigprocmask(SIG_SETMASK, &sset_old, NULL) == 0)
  289. if (pid < 0) {
  290. BLog(BLOG_ERROR, "fork failed");
  291. goto fail0;
  292. }
  293. // remember pid
  294. o->pid = pid;
  295. // add to processes list
  296. LinkedList2_Append(&o->m->processes, &o->list_node);
  297. DebugObject_Init(&o->d_obj);
  298. DebugError_Init(&o->d_err, BReactor_PendingGroup(m->reactor));
  299. return 1;
  300. fail0:
  301. return 0;
  302. }
  303. int BProcess_Init (BProcess *o, BProcessManager *m, BProcess_handler handler, void *user, const char *file, char *const argv[], const char *username)
  304. {
  305. int fds[] = {-1};
  306. return BProcess_InitWithFds(o, m, handler, user, file, argv, username, fds, NULL);
  307. }
  308. void BProcess_Free (BProcess *o)
  309. {
  310. DebugError_Free(&o->d_err);
  311. DebugObject_Free(&o->d_obj);
  312. // remove from processes list
  313. LinkedList2_Remove(&o->m->processes, &o->list_node);
  314. }
  315. int BProcess_Terminate (BProcess *o)
  316. {
  317. DebugObject_Access(&o->d_obj);
  318. DebugError_AssertNoError(&o->d_err);
  319. ASSERT(o->pid > 0)
  320. if (kill(o->pid, SIGTERM) < 0) {
  321. BLog(BLOG_ERROR, "kill(%"PRIiMAX", SIGTERM) failed", (intmax_t)o->pid);
  322. return 0;
  323. }
  324. return 1;
  325. }
  326. int BProcess_Kill (BProcess *o)
  327. {
  328. DebugObject_Access(&o->d_obj);
  329. DebugError_AssertNoError(&o->d_err);
  330. ASSERT(o->pid > 0)
  331. if (kill(o->pid, SIGKILL) < 0) {
  332. BLog(BLOG_ERROR, "kill(%"PRIiMAX", SIGKILL) failed", (intmax_t)o->pid);
  333. return 0;
  334. }
  335. return 1;
  336. }