run-child-proc.cc 12 KB

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