run-child-proc.cc 14 KB

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