run-child-proc.cc 13 KB

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