run-child-proc.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. #include <cstdlib>
  2. #include <cstring>
  3. #include <cstdio>
  4. #include <sys/types.h>
  5. #include <sys/stat.h>
  6. #include <sys/ioctl.h>
  7. #include <sys/un.h>
  8. #include <sys/socket.h>
  9. #include <fcntl.h>
  10. #include <unistd.h>
  11. #include <termios.h>
  12. #include "service.h"
  13. #include "proc-service.h"
  14. #include "mconfig.h"
  15. #ifdef SUPPORT_CGROUPS
  16. extern std::string cgroups_path;
  17. extern bool have_cgroups_path;
  18. #endif
  19. #if USE_INITGROUPS
  20. #include <grp.h>
  21. #endif
  22. extern sigset_t orig_signal_mask;
  23. // Move an fd, if necessary, to another fd. The original destination fd will be closed.
  24. // if fd is specified as -1, returns -1 immediately. Returns 0 on success.
  25. static int move_fd(int fd, int dest)
  26. {
  27. if (fd == -1) return -1;
  28. if (fd == dest) return 0;
  29. if (dup2(fd, dest) == -1) {
  30. return -1;
  31. }
  32. close(fd);
  33. return 0;
  34. }
  35. // Move a file descriptor to another, freeing up the original descriptor so that it can be used
  36. // for some reserved purpose.
  37. static int move_reserved_fd(int *fd, int min_fd)
  38. {
  39. int new_fd = fcntl(*fd, F_DUPFD_CLOEXEC, min_fd);
  40. if (new_fd != -1) {
  41. close(*fd);
  42. *fd = new_fd;
  43. }
  44. return new_fd;
  45. }
  46. void base_process_service::run_child_proc(run_proc_params params) noexcept
  47. {
  48. // Child process. Must not risk throwing any uncaught exception from here until exit().
  49. const char * const *args = params.args;
  50. const char *working_dir = params.working_dir;
  51. const char *logfile = params.logfile;
  52. bool on_console = params.on_console;
  53. int wpipefd = params.wpipefd;
  54. int csfd = params.csfd;
  55. int notify_fd = params.notify_fd;
  56. int force_notify_fd = params.force_notify_fd;
  57. const char *notify_var = params.notify_var;
  58. uid_t uid = params.uid;
  59. gid_t gid = params.gid;
  60. const std::vector<service_rlimits> &rlimits = params.rlimits;
  61. int output_fd = params.output_fd;
  62. // If the console already has a session leader, presumably it is us. On the other hand
  63. // if it has no session leader, and we don't create one, then control inputs such as
  64. // ^C will have no effect. (We check here, before we potentially re-assign STDIN).
  65. bool do_set_ctty = on_console && (tcgetsid(0) == -1);
  66. // For the moment, we'll block all signals, since apparently even dup() can be interrupted
  67. // (thanks, POSIX...).
  68. sigset_t sigall_set;
  69. sigfillset(&sigall_set);
  70. sigprocmask(SIG_SETMASK, &sigall_set, nullptr);
  71. constexpr int bufsz = 11 + ((CHAR_BIT * sizeof(pid_t) + 2) / 3) + 1;
  72. // "LISTEN_PID=" - 11 characters; the expression above gives a conservative estimate
  73. // on the maxiumum number of bytes required for LISTEN=nnn, including nul terminator,
  74. // where nnn is a pid_t in decimal (i.e. one decimal digit is worth just over 3 bits).
  75. char nbuf[bufsz];
  76. // "DINIT_CS_FD=" - 12 bytes. (we -1 from sizeof(int) in account of sign bit).
  77. constexpr int csenvbufsz = 12 + ((CHAR_BIT * sizeof(int) - 1 + 2) / 3) + 1;
  78. char csenvbuf[csenvbufsz];
  79. environment::env_map proc_env_map;
  80. run_proc_err err;
  81. err.stage = exec_stage::ARRANGE_FDS;
  82. // We need to shuffle various file descriptors around to get them in the right places.
  83. int minfd = (socket_fd == -1) ? 3 : 4;
  84. // If input_fd is set, deal with it now (move it to STDIN) so we can throw away that file descriptor
  85. if (params.input_fd != -1) {
  86. if (move_fd(params.input_fd, STDIN_FILENO) != 0) goto failure_out;
  87. }
  88. if (force_notify_fd != -1) {
  89. // Move wpipefd/csfd/socket_fd to another fd if necessary:
  90. if (wpipefd == force_notify_fd) {
  91. if (move_reserved_fd(&wpipefd, minfd) == -1) {
  92. goto failure_out;
  93. }
  94. }
  95. if (csfd == force_notify_fd) {
  96. if (move_reserved_fd(&csfd, minfd) == -1) {
  97. goto failure_out;
  98. }
  99. }
  100. if (socket_fd == force_notify_fd) {
  101. // Note that we might move this again later
  102. if (move_reserved_fd(&socket_fd, 0) == -1) {
  103. goto failure_out;
  104. }
  105. }
  106. // allocate the forced notification fd:
  107. if (notify_fd != force_notify_fd) {
  108. if (dup2(notify_fd, force_notify_fd) == -1) {
  109. goto failure_out;
  110. }
  111. close(notify_fd);
  112. notify_fd = force_notify_fd;
  113. }
  114. }
  115. // Make sure we have the fds for stdin/out/err (and pre-opened socket) available:
  116. if (wpipefd < minfd) {
  117. wpipefd = fcntl(wpipefd, F_DUPFD_CLOEXEC, minfd);
  118. if (wpipefd == -1) goto failure_out;
  119. }
  120. if (csfd != -1 && csfd < minfd) {
  121. csfd = fcntl(csfd, F_DUPFD, minfd);
  122. if (csfd == -1) goto failure_out;
  123. }
  124. if (notify_fd < minfd && notify_fd != force_notify_fd) {
  125. notify_fd = fcntl(notify_fd, F_DUPFD, minfd);
  126. if (notify_fd == -1) goto failure_out;
  127. }
  128. try {
  129. // Set up notify-fd variable:
  130. if (notify_var != nullptr && *notify_var != 0) {
  131. err.stage = exec_stage::SET_NOTIFYFD_VAR;
  132. // We need to do an allocation: the variable name length, '=', and space for the value,
  133. // and nul terminator:
  134. int notify_var_len = strlen(notify_var);
  135. int req_sz = notify_var_len + ((CHAR_BIT * sizeof(int) - 1 + 2) / 3) + 1;
  136. char * var_str = (char *) malloc(req_sz);
  137. if (var_str == nullptr) goto failure_out;
  138. snprintf(var_str, req_sz, "%s=%d", notify_var, notify_fd);
  139. service_env.set_var(var_str);
  140. }
  141. // Set up Systemd-style socket activation:
  142. if (socket_fd != -1) {
  143. err.stage = exec_stage::SETUP_ACTIVATION_SOCKET;
  144. // If we passing a pre-opened socket, it has to be fd number 3. (Thanks, Systemd).
  145. if (dup2(socket_fd, 3) == -1) goto failure_out;
  146. if (socket_fd != 3) close(socket_fd);
  147. service_env.set_var("LISTEN_FDS=1");
  148. snprintf(nbuf, bufsz, "LISTEN_PID=%jd", static_cast<intmax_t>(getpid()));
  149. service_env.set_var(nbuf);
  150. }
  151. if (csfd != -1) {
  152. err.stage = exec_stage::SETUP_CONTROL_SOCKET;
  153. snprintf(csenvbuf, csenvbufsz, "DINIT_CS_FD=%d", csfd);
  154. service_env.set_var(csenvbuf);
  155. }
  156. // We'll re-use READ_ENV_FILE stage here; it's accurate enough.
  157. err.stage = exec_stage::READ_ENV_FILE;
  158. proc_env_map = service_env.build(main_env);
  159. }
  160. catch (std::system_error &sys_err) {
  161. errno = sys_err.code().value();
  162. goto failure_out;
  163. }
  164. catch (std::bad_alloc &) {
  165. errno = ENOMEM;
  166. goto failure_out;
  167. }
  168. if (working_dir != nullptr && *working_dir != 0) {
  169. err.stage = exec_stage::CHDIR;
  170. if (chdir(working_dir) == -1) {
  171. goto failure_out;
  172. }
  173. }
  174. if (!on_console) {
  175. // Re-set stdin (possibly), stdout, stderr
  176. int begin = (params.input_fd == -1) ? 0 : 1;
  177. for (int i = begin; i < 3; i++) {
  178. if (i != force_notify_fd) close(i);
  179. }
  180. err.stage = exec_stage::SETUP_STDINOUTERR;
  181. // Either: notify_fd == 0, i.e. the notification fd is STDIN (bad form, but we'll allow it)
  182. // and in that case it's already open
  183. // or: params.input_fd != 1, i.e. our STDIN is already open
  184. // or: we most open STDIN ourself (from /dev/null)
  185. if (notify_fd != 0 && params.input_fd == -1 && move_fd(open("/dev/null", O_RDONLY), 0) != 0) {
  186. goto failure_out;
  187. }
  188. // stdin = 0. That's what we should have; proceed with opening stdout and stderr. We have to
  189. // take care not to clobber the notify_fd.
  190. if (output_fd == -1) {
  191. output_fd = open(logfile, O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR);
  192. if (output_fd == -1) {
  193. // On failure to open a log file, change the error stage to give more precise
  194. // information:
  195. if (this->log_type == log_type_id::LOGFILE) err.stage = exec_stage::OPEN_LOGFILE;
  196. goto failure_out;
  197. }
  198. // Set permission of logfile if present
  199. // if log type is NONE, we don't want to change ownership/permissions of /dev/null!
  200. if (this->log_type == log_type_id::LOGFILE) {
  201. if (fchown(output_fd, logfile_uid, logfile_gid) == -1) goto failure_out;
  202. if (fchmod(output_fd, logfile_perms) == -1) goto failure_out;
  203. }
  204. }
  205. if (notify_fd != 1) {
  206. if (move_fd(output_fd, 1) != 0) {
  207. goto failure_out;
  208. }
  209. if (notify_fd != 2 && dup2(1, 2) != 2) {
  210. goto failure_out;
  211. }
  212. }
  213. else if (move_fd(output_fd, 2) != 0) {
  214. goto failure_out;
  215. }
  216. // We have the option of creating a session and process group, or just a new process
  217. // group. If we just create a new process group, the child process cannot make itself
  218. // a session leader if it wants to do that (eg getty/login will generally want this).
  219. // If we do neither, and we are running with a controlling terminal, a ^C or similar
  220. // will also affect the child process (which probably isn't so bad, though since we
  221. // will handle the shutdown ourselves it's not necessary). Creating a new session
  222. // (and a new process group as part of that) seems like a safe bet, and has the
  223. // advantage of letting us signal the process as part of a process group.
  224. setsid();
  225. }
  226. else {
  227. // "run on console" - run as a foreground job on the terminal/console device
  228. // if do_set_ctty is false, we are the session leader; we are probably running
  229. // as a user process. Don't create a new session leader in that case, and run
  230. // as part of the parent session. Otherwise, the new session cannot claim the
  231. // terminal as a controlling terminal (it is already claimed), meaning that it
  232. // will not see control signals from ^C etc.
  233. if (do_set_ctty) {
  234. // Become session leader
  235. setsid();
  236. ioctl(0, TIOCSCTTY, 0);
  237. }
  238. setpgid(0,0);
  239. if (params.in_foreground) {
  240. tcsetpgrp(0, getpgrp());
  241. }
  242. }
  243. // Resource limits
  244. err.stage = exec_stage::SET_RLIMITS;
  245. for (auto &limit : rlimits) {
  246. rlimit setlimits;
  247. if (!limit.hard_set || !limit.soft_set) {
  248. // if either hard or soft limit is not set, use current:
  249. if (getrlimit(limit.resource_id, &setlimits) != 0) goto failure_out;
  250. }
  251. if (limit.hard_set) setlimits.rlim_max = limit.limits.rlim_max;
  252. if (limit.soft_set) setlimits.rlim_cur = limit.limits.rlim_cur;
  253. if (setrlimit(limit.resource_id, &setlimits) != 0) goto failure_out;
  254. }
  255. #if SUPPORT_CGROUPS
  256. if (params.run_in_cgroup != nullptr && *params.run_in_cgroup != 0) {
  257. err.stage = exec_stage::ENTER_CGROUP;
  258. int sys_fs_cgroup_fd = open("/sys/fs/cgroup", O_RDONLY | O_DIRECTORY | O_PATH);
  259. if (sys_fs_cgroup_fd == -1) goto failure_out;
  260. const char *run_cgroup_path = params.run_in_cgroup;
  261. if (run_cgroup_path[0] != '/') {
  262. // A relative cgroup path must be resolved against our own path (cgroups_path)
  263. if (!have_cgroups_path) {
  264. errno = ENOENT;
  265. goto failure_out;
  266. }
  267. if (!cgroups_path.empty()) {
  268. int cgrp_root_path = openat(sys_fs_cgroup_fd, cgroups_path.c_str(), O_RDONLY | O_DIRECTORY | O_PATH);
  269. if (cgrp_root_path == -1) goto failure_out;
  270. close(sys_fs_cgroup_fd);
  271. sys_fs_cgroup_fd = cgrp_root_path;
  272. }
  273. }
  274. else {
  275. ++run_cgroup_path; // skip leading slash
  276. }
  277. int cgroup_dir_fd = openat(sys_fs_cgroup_fd, run_cgroup_path, O_RDONLY | O_DIRECTORY | O_PATH);
  278. if (cgroup_dir_fd == -1) goto failure_out;
  279. close(sys_fs_cgroup_fd);
  280. int cgroup_procs_fd = openat(cgroup_dir_fd, "cgroup.procs", O_WRONLY);
  281. if (cgroup_procs_fd == -1) goto failure_out;
  282. close(cgroup_dir_fd);
  283. // We need to write our own pid into the cgroup.procs file
  284. char pidbuf[std::numeric_limits<pid_t>::digits10 + 3];
  285. // +1 for most significant digit, +1 for '\n', +1 for nul terminator
  286. int num_chars;
  287. if (sizeof(pid_t) <= sizeof(unsigned)) {
  288. num_chars = sprintf(pidbuf, "%u\n", (unsigned)getpid());
  289. }
  290. else if (sizeof(pid_t) <= sizeof(unsigned long)) {
  291. num_chars = sprintf(pidbuf, "%lu\n", (unsigned long)getpid());
  292. }
  293. else {
  294. static_assert(sizeof(pid_t) <= sizeof(unsigned long long), "pid_t is too big");
  295. num_chars = sprintf(pidbuf, "%llu\n", (unsigned long long)getpid());
  296. }
  297. if (write(cgroup_procs_fd, pidbuf, num_chars) == -1) goto failure_out;
  298. close(cgroup_procs_fd);
  299. }
  300. #endif
  301. if (uid != uid_t(-1)) {
  302. err.stage = exec_stage::SET_UIDGID;
  303. // We must set group first (i.e. before we drop privileges)
  304. #if USE_INITGROUPS
  305. // Initialize supplementary groups unless disabled; non-POSIX API
  306. if (gid != gid_t(-1)) {
  307. // Specific group; use that, with no supplementary groups.
  308. // Note: for compatibility with FreeBSD, clear the groups list first before setting the
  309. // effective gid, because on FreeBSD setgroups also sets the effective gid.
  310. if (setgroups(0, nullptr)) goto failure_out;
  311. if (setregid(gid, gid) != 0) goto failure_out;
  312. }
  313. else {
  314. // No specific group; use groups associated with user.
  315. errno = 0;
  316. auto *pw = getpwuid(uid);
  317. if (pw) {
  318. if (setregid(pw->pw_gid, pw->pw_gid) != 0) goto failure_out;
  319. if (initgroups(pw->pw_name, pw->pw_gid) != 0) goto failure_out;
  320. }
  321. else {
  322. // null result with no errno indicates missing passwd entry; use ENOENT for want of a more
  323. // specific error code.
  324. if (errno == 0) errno = ENOENT;
  325. goto failure_out;
  326. }
  327. }
  328. #else
  329. // No support for supplementary groups; just set the specified group.
  330. if (gid != gid_t(-1)) {
  331. if (setregid(gid, gid) != 0) goto failure_out;
  332. }
  333. #endif
  334. if (setreuid(uid, uid) != 0) goto failure_out;
  335. }
  336. // Restore signal mask. If running on the console, we'll keep various control signals that can
  337. // be invoked from the terminal masked, with the exception of SIGHUP and possibly SIGINT.
  338. {
  339. sigset_t sigwait_set = orig_signal_mask;
  340. sigdelset(&sigwait_set, SIGCHLD);
  341. sigdelset(&sigwait_set, SIGTERM);
  342. if (on_console && params.in_foreground) {
  343. if (params.unmask_sigint) {
  344. sigdelset(&sigwait_set, SIGINT);
  345. }
  346. else {
  347. sigaddset(&sigwait_set, SIGINT);
  348. }
  349. sigaddset(&sigwait_set, SIGQUIT);
  350. sigaddset(&sigwait_set, SIGTSTP);
  351. sigaddset(&sigwait_set, SIGTTIN);
  352. sigaddset(&sigwait_set, SIGTTOU);
  353. }
  354. sigprocmask(SIG_SETMASK, &sigwait_set, nullptr);
  355. }
  356. err.stage = exec_stage::DO_EXEC;
  357. // (on linux we could use execvpe, but it's not POSIX and not in eg FreeBSD).
  358. bp_sys::environ = const_cast<char **>(proc_env_map.env_list.data());
  359. execvp(args[0], const_cast<char **>(args));
  360. // If we got here, the exec failed:
  361. failure_out:
  362. err.st_errno = errno;
  363. write(wpipefd, &err, sizeof(err));
  364. _exit(0);
  365. }