diff options
Diffstat (limited to 'src/libnm-systemd-shared/src/basic/process-util.c')
-rw-r--r-- | src/libnm-systemd-shared/src/basic/process-util.c | 674 |
1 files changed, 628 insertions, 46 deletions
diff --git a/src/libnm-systemd-shared/src/basic/process-util.c b/src/libnm-systemd-shared/src/basic/process-util.c index 8601e0da54..0f1894b3af 100644 --- a/src/libnm-systemd-shared/src/basic/process-util.c +++ b/src/libnm-systemd-shared/src/basic/process-util.c @@ -7,6 +7,7 @@ #include <limits.h> #include <linux/oom.h> #include <pthread.h> +#include <spawn.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> @@ -26,6 +27,7 @@ #include "alloc-util.h" #include "architecture.h" #include "argv-util.h" +#include "dirent-util.h" #include "env-file.h" #include "env-util.h" #include "errno-util.h" @@ -97,7 +99,7 @@ static int get_process_state(pid_t pid) { return (unsigned char) state; } -int get_process_comm(pid_t pid, char **ret) { +int pid_get_comm(pid_t pid, char **ret) { _cleanup_free_ char *escaped = NULL, *comm = NULL; int r; @@ -135,15 +137,35 @@ int get_process_comm(pid_t pid, char **ret) { return 0; } -static int get_process_cmdline_nulstr( +int pidref_get_comm(const PidRef *pid, char **ret) { + _cleanup_free_ char *comm = NULL; + int r; + + if (!pidref_is_set(pid)) + return -ESRCH; + + r = pid_get_comm(pid->pid, &comm); + if (r < 0) + return r; + + r = pidref_verify(pid); + if (r < 0) + return r; + + if (ret) + *ret = TAKE_PTR(comm); + return 0; +} + +static int pid_get_cmdline_nulstr( pid_t pid, size_t max_size, ProcessCmdlineFlags flags, char **ret, size_t *ret_size) { + _cleanup_free_ char *t = NULL; const char *p; - char *t; size_t k; int r; @@ -167,18 +189,17 @@ static int get_process_cmdline_nulstr( return r; if (k == 0) { - t = mfree(t); - if (!(flags & PROCESS_CMDLINE_COMM_FALLBACK)) return -ENOENT; /* Kernel threads have no argv[] */ _cleanup_free_ char *comm = NULL; - r = get_process_comm(pid, &comm); + r = pid_get_comm(pid, &comm); if (r < 0) return r; + free(t); t = strjoin("[", comm, "]"); if (!t) return -ENOMEM; @@ -189,12 +210,15 @@ static int get_process_cmdline_nulstr( t[max_size] = '\0'; } - *ret = t; - *ret_size = k; + if (ret) + *ret = TAKE_PTR(t); + if (ret_size) + *ret_size = k; + return r; } -int get_process_cmdline(pid_t pid, size_t max_columns, ProcessCmdlineFlags flags, char **ret) { +int pid_get_cmdline(pid_t pid, size_t max_columns, ProcessCmdlineFlags flags, char **ret) { _cleanup_free_ char *t = NULL; size_t k; char *ans; @@ -202,7 +226,7 @@ int get_process_cmdline(pid_t pid, size_t max_columns, ProcessCmdlineFlags flags assert(pid >= 0); assert(ret); - /* Retrieve and format a commandline. See above for discussion of retrieval options. + /* Retrieve and format a command line. See above for discussion of retrieval options. * * There are two main formatting modes: * @@ -216,7 +240,7 @@ int get_process_cmdline(pid_t pid, size_t max_columns, ProcessCmdlineFlags flags * Returns -ESRCH if the process doesn't exist, and -ENOENT if the process has no command line (and * PROCESS_CMDLINE_COMM_FALLBACK is not specified). Returns 0 and sets *line otherwise. */ - int full = get_process_cmdline_nulstr(pid, max_columns, flags, &t, &k); + int full = pid_get_cmdline_nulstr(pid, max_columns, flags, &t, &k); if (full < 0) return full; @@ -259,7 +283,27 @@ int get_process_cmdline(pid_t pid, size_t max_columns, ProcessCmdlineFlags flags return 0; } -int get_process_cmdline_strv(pid_t pid, ProcessCmdlineFlags flags, char ***ret) { +int pidref_get_cmdline(const PidRef *pid, size_t max_columns, ProcessCmdlineFlags flags, char **ret) { + _cleanup_free_ char *s = NULL; + int r; + + if (!pidref_is_set(pid)) + return -ESRCH; + + r = pid_get_cmdline(pid->pid, max_columns, flags, &s); + if (r < 0) + return r; + + r = pidref_verify(pid); + if (r < 0) + return r; + + if (ret) + *ret = TAKE_PTR(s); + return 0; +} + +int pid_get_cmdline_strv(pid_t pid, ProcessCmdlineFlags flags, char ***ret) { _cleanup_free_ char *t = NULL; char **args; size_t k; @@ -269,7 +313,7 @@ int get_process_cmdline_strv(pid_t pid, ProcessCmdlineFlags flags, char ***ret) assert((flags & ~PROCESS_CMDLINE_COMM_FALLBACK) == 0); assert(ret); - r = get_process_cmdline_nulstr(pid, SIZE_MAX, flags, &t, &k); + r = pid_get_cmdline_nulstr(pid, SIZE_MAX, flags, &t, &k); if (r < 0) return r; @@ -281,6 +325,27 @@ int get_process_cmdline_strv(pid_t pid, ProcessCmdlineFlags flags, char ***ret) return 0; } +int pidref_get_cmdline_strv(const PidRef *pid, ProcessCmdlineFlags flags, char ***ret) { + _cleanup_strv_free_ char **args = NULL; + int r; + + if (!pidref_is_set(pid)) + return -ESRCH; + + r = pid_get_cmdline_strv(pid->pid, flags, &args); + if (r < 0) + return r; + + r = pidref_verify(pid); + if (r < 0) + return r; + + if (ret) + *ret = TAKE_PTR(args); + + return 0; +} + int container_get_leader(const char *machine, pid_t *pid) { _cleanup_free_ char *s = NULL, *class = NULL; const char *p; @@ -322,7 +387,34 @@ int container_get_leader(const char *machine, pid_t *pid) { return 0; } -int is_kernel_thread(pid_t pid) { +int namespace_get_leader(pid_t pid, NamespaceType type, pid_t *ret) { + int r; + + assert(ret); + + for (;;) { + pid_t ppid; + + r = get_process_ppid(pid, &ppid); + if (r < 0) + return r; + + r = in_same_namespace(pid, ppid, type); + if (r < 0) + return r; + if (r == 0) { + /* If the parent and the child are not in the same + * namespace, then the child is the leader we are + * looking for. */ + *ret = pid; + return 0; + } + + pid = ppid; + } +} + +int pid_is_kernel_thread(pid_t pid) { _cleanup_free_ char *line = NULL; unsigned long long flags; size_t l, i; @@ -380,6 +472,23 @@ int is_kernel_thread(pid_t pid) { return !!(flags & PF_KTHREAD); } +int pidref_is_kernel_thread(const PidRef *pid) { + int result, r; + + if (!pidref_is_set(pid)) + return -ESRCH; + + result = pid_is_kernel_thread(pid->pid); + if (result < 0) + return result; + + r = pidref_verify(pid); /* Verify that the PID wasn't reused since */ + if (r < 0) + return r; + + return result; +} + int get_process_capeff(pid_t pid, char **ret) { const char *p; int r; @@ -449,16 +558,14 @@ static int get_process_id(pid_t pid, const char *field, uid_t *ret) { _cleanup_free_ char *line = NULL; char *l; - r = read_line(f, LONG_LINE_MAX, &line); + r = read_stripped_line(f, LONG_LINE_MAX, &line); if (r < 0) return r; if (r == 0) break; - l = strstrip(line); - - if (startswith(l, field)) { - l += strlen(field); + l = startswith(line, field); + if (l) { l += strspn(l, WHITESPACE); l[strcspn(l, WHITESPACE)] = 0; @@ -470,7 +577,8 @@ static int get_process_id(pid_t pid, const char *field, uid_t *ret) { return -EIO; } -int get_process_uid(pid_t pid, uid_t *ret) { +int pid_get_uid(pid_t pid, uid_t *ret) { + assert(ret); if (pid == 0 || pid == getpid_cached()) { *ret = getuid(); @@ -480,6 +588,26 @@ int get_process_uid(pid_t pid, uid_t *ret) { return get_process_id(pid, "Uid:", ret); } +int pidref_get_uid(const PidRef *pid, uid_t *ret) { + uid_t uid; + int r; + + if (!pidref_is_set(pid)) + return -ESRCH; + + r = pid_get_uid(pid->pid, &uid); + if (r < 0) + return r; + + r = pidref_verify(pid); + if (r < 0) + return r; + + if (ret) + *ret = uid; + return 0; +} + int get_process_gid(pid_t pid, gid_t *ret) { if (pid == 0 || pid == getpid_cached()) { @@ -606,6 +734,82 @@ int get_process_ppid(pid_t pid, pid_t *ret) { return 0; } +int pid_get_start_time(pid_t pid, uint64_t *ret) { + _cleanup_free_ char *line = NULL; + const char *p; + int r; + + assert(pid >= 0); + + p = procfs_file_alloca(pid, "stat"); + r = read_one_line_file(p, &line); + if (r == -ENOENT) + return -ESRCH; + if (r < 0) + return r; + + /* Let's skip the pid and comm fields. The latter is enclosed in () but does not escape any () in its + * value, so let's skip over it manually */ + + p = strrchr(line, ')'); + if (!p) + return -EIO; + + p++; + + unsigned long llu; + + if (sscanf(p, " " + "%*c " /* state */ + "%*u " /* ppid */ + "%*u " /* pgrp */ + "%*u " /* session */ + "%*u " /* tty_nr */ + "%*u " /* tpgid */ + "%*u " /* flags */ + "%*u " /* minflt */ + "%*u " /* cminflt */ + "%*u " /* majflt */ + "%*u " /* cmajflt */ + "%*u " /* utime */ + "%*u " /* stime */ + "%*u " /* cutime */ + "%*u " /* cstime */ + "%*i " /* priority */ + "%*i " /* nice */ + "%*u " /* num_threads */ + "%*u " /* itrealvalue */ + "%lu ", /* starttime */ + &llu) != 1) + return -EIO; + + if (ret) + *ret = llu; + + return 0; +} + +int pidref_get_start_time(const PidRef *pid, uint64_t *ret) { + uint64_t t; + int r; + + if (!pidref_is_set(pid)) + return -ESRCH; + + r = pid_get_start_time(pid->pid, ret ? &t : NULL); + if (r < 0) + return r; + + r = pidref_verify(pid); + if (r < 0) + return r; + + if (ret) + *ret = t; + + return 0; +} + int get_process_umask(pid_t pid, mode_t *ret) { _cleanup_free_ char *m = NULL; const char *p; @@ -670,7 +874,7 @@ int wait_for_terminate_and_check(const char *name, pid_t pid, WaitFlags flags) { assert(pid > 1); if (!name) { - r = get_process_comm(pid, &buffer); + r = pid_get_comm(pid, &buffer); if (r < 0) log_debug_errno(r, "Failed to acquire process name of " PID_FMT ", ignoring: %m", pid); else @@ -824,7 +1028,7 @@ int getenv_for_pid(pid_t pid, const char *field, char **ret) { _cleanup_fclose_ FILE *f = NULL; char *value = NULL; const char *path; - size_t l, sum = 0; + size_t sum = 0; int r; assert(pid >= 0); @@ -859,9 +1063,9 @@ int getenv_for_pid(pid_t pid, const char *field, char **ret) { if (r < 0) return r; - l = strlen(field); for (;;) { _cleanup_free_ char *line = NULL; + const char *match; if (sum > ENVIRONMENT_BLOCK_MAX) /* Give up searching eventually */ return -ENOBUFS; @@ -874,8 +1078,9 @@ int getenv_for_pid(pid_t pid, const char *field, char **ret) { sum += r; - if (strneq(line, field, l) && line[l] == '=') { - value = strdup(line + l + 1); + match = startswith(line, field); + if (match && *match == '=') { + value = strdup(match + 1); if (!value) return -ENOMEM; @@ -892,6 +1097,9 @@ int pid_is_my_child(pid_t pid) { pid_t ppid; int r; + if (pid < 0) + return -ESRCH; + if (pid <= 1) return false; @@ -902,11 +1110,28 @@ int pid_is_my_child(pid_t pid) { return ppid == getpid_cached(); } -bool pid_is_unwaited(pid_t pid) { +int pidref_is_my_child(const PidRef *pid) { + int r, result; + + if (!pidref_is_set(pid)) + return -ESRCH; + + result = pid_is_my_child(pid->pid); + if (result < 0) + return result; + + r = pidref_verify(pid); + if (r < 0) + return r; + + return result; +} + +int pid_is_unwaited(pid_t pid) { /* Checks whether a PID is still valid at all, including a zombie */ if (pid < 0) - return false; + return -ESRCH; if (pid <= 1) /* If we or PID 1 would be dead and have been waited for, this code would not be running */ return true; @@ -920,13 +1145,31 @@ bool pid_is_unwaited(pid_t pid) { return errno != ESRCH; } -bool pid_is_alive(pid_t pid) { +int pidref_is_unwaited(const PidRef *pid) { + int r; + + if (!pidref_is_set(pid)) + return -ESRCH; + + if (pid->pid == 1 || pidref_is_self(pid)) + return true; + + r = pidref_kill(pid, 0); + if (r == -ESRCH) + return false; + if (r < 0) + return r; + + return true; +} + +int pid_is_alive(pid_t pid) { int r; /* Checks whether a PID is still valid and not a zombie */ if (pid < 0) - return false; + return -ESRCH; if (pid <= 1) /* If we or PID 1 would be a zombie, this code would not be running */ return true; @@ -935,10 +1178,33 @@ bool pid_is_alive(pid_t pid) { return true; r = get_process_state(pid); - if (IN_SET(r, -ESRCH, 'Z')) + if (r == -ESRCH) return false; + if (r < 0) + return r; - return true; + return r != 'Z'; +} + +int pidref_is_alive(const PidRef *pidref) { + int r, result; + + if (!pidref_is_set(pidref)) + return -ESRCH; + + result = pid_is_alive(pidref->pid); + if (result < 0) { + assert(result != -ESRCH); + return result; + } + + r = pidref_verify(pidref); + if (r == -ESRCH) + return false; + if (r < 0) + return r; + + return result; } int pid_from_same_root_fs(pid_t pid) { @@ -1057,7 +1323,10 @@ void valgrind_summary_hack(void) { pid_t pid; pid = raw_clone(SIGCHLD); if (pid < 0) - log_emergency_errno(errno, "Failed to fork off valgrind helper: %m"); + log_struct_errno( + LOG_EMERG, errno, + "MESSAGE_ID=" SD_MESSAGE_VALGRIND_HELPER_FORK_STR, + LOG_MESSAGE( "Failed to fork off valgrind helper: %m")); else if (pid == 0) exit(EXIT_SUCCESS); else { @@ -1104,7 +1373,7 @@ pid_t getpid_cached(void) { * https://sourceware.org/git/gitweb.cgi?p=glibc.git;h=c579f48edba88380635ab98cb612030e3ed8691e */ - __atomic_compare_exchange_n( + (void) __atomic_compare_exchange_n( &cached_pid, ¤t_value, CACHED_PID_BUSY, @@ -1159,6 +1428,51 @@ static void restore_sigsetp(sigset_t **ssp) { (void) sigprocmask(SIG_SETMASK, *ssp, NULL); } +pid_t clone_with_nested_stack(int (*fn)(void *), int flags, void *userdata) { + size_t ps; + pid_t pid; + void *mystack; + + /* A wrapper around glibc's clone() call that automatically sets up a "nested" stack. Only supports + * invocations without CLONE_VM, so that we can continue to use the parent's stack mapping. + * + * Note: glibc's clone() wrapper does not synchronize malloc() locks. This means that if the parent + * is threaded these locks will be in an undefined state in the child, and hence memory allocations + * are likely going to run into deadlocks. Hence: if you use this function make sure your parent is + * strictly single-threaded or your child never calls malloc(). */ + + assert((flags & (CLONE_VM|CLONE_PARENT_SETTID|CLONE_CHILD_SETTID| + CLONE_CHILD_CLEARTID|CLONE_SETTLS)) == 0); + + /* We allocate some space on the stack to use as the stack for the child (hence "nested"). Note that + * the net effect is that the child will have the start of its stack inside the stack of the parent, + * but since they are a CoW copy of each other that's fine. We allocate one page-aligned page. But + * since we don't want to deal with differences between systems where the stack grows backwards or + * forwards we'll allocate one more and place the stack address in the middle. Except that we also + * want it page aligned, hence we'll allocate one page more. Makes 3. */ + + ps = page_size(); + mystack = alloca(ps*3); + mystack = (uint8_t*) mystack + ps; /* move pointer one page ahead since stacks usually grow backwards */ + mystack = (void*) ALIGN_TO((uintptr_t) mystack, ps); /* align to page size (moving things further ahead) */ + +#if HAVE_CLONE + pid = clone(fn, mystack, flags, userdata); +#else + pid = __clone2(fn, mystack, ps, flags, userdata); +#endif + if (pid < 0) + return -errno; + + return pid; +} + +static int fork_flags_to_signal(ForkFlags flags) { + return (flags & FORK_DEATHSIG_SIGTERM) ? SIGTERM : + (flags & FORK_DEATHSIG_SIGINT) ? SIGINT : + SIGKILL; +} + int safe_fork_full( const char *name, const int stdio_fds[3], @@ -1170,9 +1484,12 @@ int safe_fork_full( pid_t original_pid, pid; sigset_t saved_ss, ss; _unused_ _cleanup_(restore_sigsetp) sigset_t *saved_ssp = NULL; - bool block_signals = false, block_all = false; + bool block_signals = false, block_all = false, intermediary = false; int prio, r; + assert(!FLAGS_SET(flags, FORK_DETACH) || !ret_pid); + assert(!FLAGS_SET(flags, FORK_DETACH|FORK_WAIT)); + /* A wrapper around fork(), that does a couple of important initializations in addition to mere forking. Always * returns the child's PID in *ret_pid. Returns == 0 in the child, and > 0 in the parent. */ @@ -1185,9 +1502,10 @@ int safe_fork_full( fflush(stderr); /* This one shouldn't be necessary, stderr should be unbuffered anyway, but let's better be safe than sorry */ } - if (flags & (FORK_RESET_SIGNALS|FORK_DEATHSIG)) { - /* We temporarily block all signals, so that the new child has them blocked initially. This way, we can - * be sure that SIGTERMs are not lost we might send to the child. */ + if (flags & (FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGTERM|FORK_DEATHSIG_SIGINT)) { + /* We temporarily block all signals, so that the new child has them blocked initially. This + * way, we can be sure that SIGTERMs are not lost we might send to the child. (Note that for + * FORK_DEATHSIG_SIGKILL we don't bother, since it cannot be blocked anyway.) */ assert_se(sigfillset(&ss) >= 0); block_signals = block_all = true; @@ -1206,17 +1524,47 @@ int safe_fork_full( saved_ssp = &saved_ss; } - if ((flags & (FORK_NEW_MOUNTNS|FORK_NEW_USERNS)) != 0) + if (FLAGS_SET(flags, FORK_DETACH)) { + assert(!FLAGS_SET(flags, FORK_WAIT)); + assert(!ret_pid); + + /* Fork off intermediary child if needed */ + + r = is_reaper_process(); + if (r < 0) + return log_full_errno(prio, r, "Failed to determine if we are a reaper process: %m"); + + if (!r) { + /* Not a reaper process, hence do a double fork() so we are reparented to one */ + + pid = fork(); + if (pid < 0) + return log_full_errno(prio, errno, "Failed to fork off '%s': %m", strna(name)); + if (pid > 0) { + log_debug("Successfully forked off intermediary '%s' as PID " PID_FMT ".", strna(name), pid); + return 1; /* return in the parent */ + } + + intermediary = true; + } + } + + if ((flags & (FORK_NEW_MOUNTNS|FORK_NEW_USERNS|FORK_NEW_NETNS)) != 0) pid = raw_clone(SIGCHLD| (FLAGS_SET(flags, FORK_NEW_MOUNTNS) ? CLONE_NEWNS : 0) | - (FLAGS_SET(flags, FORK_NEW_USERNS) ? CLONE_NEWUSER : 0)); + (FLAGS_SET(flags, FORK_NEW_USERNS) ? CLONE_NEWUSER : 0) | + (FLAGS_SET(flags, FORK_NEW_NETNS) ? CLONE_NEWNET : 0)); else pid = fork(); if (pid < 0) return log_full_errno(prio, errno, "Failed to fork off '%s': %m", strna(name)); if (pid > 0) { - /* We are in the parent process */ + /* If we are in the intermediary process, exit now */ + if (intermediary) + _exit(EXIT_SUCCESS); + + /* We are in the parent process */ log_debug("Successfully forked off '%s' as PID " PID_FMT ".", strna(name), pid); if (flags & FORK_WAIT) { @@ -1259,8 +1607,8 @@ int safe_fork_full( r, "Failed to rename process, ignoring: %m"); } - if (flags & (FORK_DEATHSIG|FORK_DEATHSIG_SIGINT)) - if (prctl(PR_SET_PDEATHSIG, (flags & FORK_DEATHSIG_SIGINT) ? SIGINT : SIGTERM) < 0) { + if (flags & (FORK_DEATHSIG_SIGTERM|FORK_DEATHSIG_SIGINT|FORK_DEATHSIG_SIGKILL)) + if (prctl(PR_SET_PDEATHSIG, fork_flags_to_signal(flags)) < 0) { log_full_errno(prio, errno, "Failed to set death signal: %m"); _exit(EXIT_FAILURE); } @@ -1285,7 +1633,7 @@ int safe_fork_full( } } - if (flags & FORK_DEATHSIG) { + if (flags & (FORK_DEATHSIG_SIGTERM|FORK_DEATHSIG_SIGKILL|FORK_DEATHSIG_SIGINT)) { pid_t ppid; /* Let's see if the parent PID is still the one we started from? If not, then the parent * already died by the time we set PR_SET_PDEATHSIG, hence let's emulate the effect */ @@ -1294,8 +1642,9 @@ int safe_fork_full( if (ppid == 0) /* Parent is in a different PID namespace. */; else if (ppid != original_pid) { - log_debug("Parent died early, raising SIGTERM."); - (void) raise(SIGTERM); + int sig = fork_flags_to_signal(flags); + log_debug("Parent died early, raising %s.", signal_to_string(sig)); + (void) raise(sig); _exit(EXIT_FAILURE); } } @@ -1328,6 +1677,9 @@ int safe_fork_full( log_full_errno(prio, r, "Failed to rearrange stdio fds: %m"); _exit(EXIT_FAILURE); } + + /* Turn off O_NONBLOCK on the fdio fds, in case it was left on */ + stdio_disable_nonblock(); } else { r = make_null_stdio(); if (r < 0) { @@ -1389,6 +1741,30 @@ int safe_fork_full( return 0; } +int pidref_safe_fork_full( + const char *name, + const int stdio_fds[3], + const int except_fds[], + size_t n_except_fds, + ForkFlags flags, + PidRef *ret_pid) { + + pid_t pid; + int r, q; + + assert(!FLAGS_SET(flags, FORK_WAIT)); + + r = safe_fork_full(name, stdio_fds, except_fds, n_except_fds, flags, &pid); + if (r < 0) + return r; + + q = pidref_set_pid(ret_pid, pid); + if (q < 0) /* Let's not fail for this, no matter what, the process exists after all, and that's key */ + *ret_pid = PIDREF_MAKE_FROM_PID(pid); + + return r; +} + int namespace_fork( const char *outer_name, const char *inner_name, @@ -1411,7 +1787,7 @@ int namespace_fork( r = safe_fork_full(outer_name, NULL, except_fds, n_except_fds, - (flags|FORK_DEATHSIG) & ~(FORK_REOPEN_LOG|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE), ret_pid); + (flags|FORK_DEATHSIG_SIGINT|FORK_DEATHSIG_SIGTERM|FORK_DEATHSIG_SIGKILL) & ~(FORK_REOPEN_LOG|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE), ret_pid); if (r < 0) return r; if (r == 0) { @@ -1633,6 +2009,212 @@ int get_process_threads(pid_t pid) { return n; } +int is_reaper_process(void) { + int b = 0; + + /* Checks if we are running in a reaper process, i.e. if we are expected to deal with processes + * reparented to us. This simply checks if we are PID 1 or if PR_SET_CHILD_SUBREAPER was called. */ + + if (getpid_cached() == 1) + return true; + + if (prctl(PR_GET_CHILD_SUBREAPER, (unsigned long) &b, 0UL, 0UL, 0UL) < 0) + return -errno; + + return b != 0; +} + +int make_reaper_process(bool b) { + + if (getpid_cached() == 1) { + + if (!b) + return -EINVAL; + + return 0; + } + + /* Some prctl()s insist that all 5 arguments are specified, others do not. Let's always specify all, + * to avoid any ambiguities */ + if (prctl(PR_SET_CHILD_SUBREAPER, (unsigned long) b, 0UL, 0UL, 0UL) < 0) + return -errno; + + return 0; +} + +DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(posix_spawnattr_t*, posix_spawnattr_destroy, NULL); + +int posix_spawn_wrapper( + const char *path, + char * const *argv, + char * const *envp, + const char *cgroup, + PidRef *ret_pidref) { + + short flags = POSIX_SPAWN_SETSIGMASK|POSIX_SPAWN_SETSIGDEF; + posix_spawnattr_t attr; + sigset_t mask; + int r; + + /* Forks and invokes 'path' with 'argv' and 'envp' using CLONE_VM and CLONE_VFORK, which means the + * caller will be blocked until the child either exits or exec's. The memory of the child will be + * fully shared with the memory of the parent, so that there are no copy-on-write or memory.max + * issues. + * + * Also, move the newly-created process into 'cgroup' through POSIX_SPAWN_SETCGROUP (clone3()) + * if available. Note that CLONE_INTO_CGROUP is only supported on cgroup v2. + * returns 1: We're already in the right cgroup + * 0: 'cgroup' not specified or POSIX_SPAWN_SETCGROUP is not supported. The caller + * needs to call 'cg_attach' on their own */ + + assert(path); + assert(argv); + assert(ret_pidref); + + assert_se(sigfillset(&mask) >= 0); + + r = posix_spawnattr_init(&attr); + if (r != 0) + return -r; /* These functions return a positive errno on failure */ + + /* Initialization needs to succeed before we can set up a destructor. */ + _unused_ _cleanup_(posix_spawnattr_destroyp) posix_spawnattr_t *attr_destructor = &attr; + +#if HAVE_PIDFD_SPAWN + _cleanup_close_ int cgroup_fd = -EBADF; + + if (cgroup) { + _cleanup_free_ char *resolved_cgroup = NULL; + + r = cg_get_path_and_check( + SYSTEMD_CGROUP_CONTROLLER, + cgroup, + /* suffix= */ NULL, + &resolved_cgroup); + if (r < 0) + return r; + + cgroup_fd = open(resolved_cgroup, O_PATH|O_DIRECTORY|O_CLOEXEC); + if (cgroup_fd < 0) + return -errno; + + r = posix_spawnattr_setcgroup_np(&attr, cgroup_fd); + if (r != 0) + return -r; + + flags |= POSIX_SPAWN_SETCGROUP; + } +#endif + + r = posix_spawnattr_setflags(&attr, flags); + if (r != 0) + return -r; + r = posix_spawnattr_setsigmask(&attr, &mask); + if (r != 0) + return -r; + +#if HAVE_PIDFD_SPAWN + _cleanup_close_ int pidfd = -EBADF; + + r = pidfd_spawn(&pidfd, path, NULL, &attr, argv, envp); + if (r == 0) { + r = pidref_set_pidfd_consume(ret_pidref, TAKE_FD(pidfd)); + if (r < 0) + return r; + + return FLAGS_SET(flags, POSIX_SPAWN_SETCGROUP); + } + if (!(ERRNO_IS_NOT_SUPPORTED(r) || ERRNO_IS_PRIVILEGE(r))) + return -r; + + /* Compiled on a newer host, or seccomp&friends blocking clone3()? Fallback, but need to change the + * flags to remove the cgroup one, which is what redirects to clone3() */ + flags &= ~POSIX_SPAWN_SETCGROUP; + r = posix_spawnattr_setflags(&attr, flags); + if (r != 0) + return -r; +#endif + + pid_t pid; + r = posix_spawn(&pid, path, NULL, &attr, argv, envp); + if (r != 0) + return -r; + + r = pidref_set_pid(ret_pidref, pid); + if (r < 0) + return r; + + return 0; /* We did not use CLONE_INTO_CGROUP so return 0, the caller will have to move the child */ +} + +int proc_dir_open(DIR **ret) { + DIR *d; + + assert(ret); + + d = opendir("/proc"); + if (!d) + return -errno; + + *ret = d; + return 0; +} + +int proc_dir_read(DIR *d, pid_t *ret) { + assert(d); + + for (;;) { + struct dirent *de; + + errno = 0; + de = readdir_no_dot(d); + if (!de) { + if (errno != 0) + return -errno; + + break; + } + + if (!IN_SET(de->d_type, DT_DIR, DT_UNKNOWN)) + continue; + + if (parse_pid(de->d_name, ret) >= 0) + return 1; + } + + if (ret) + *ret = 0; + return 0; +} + +int proc_dir_read_pidref(DIR *d, PidRef *ret) { + int r; + + assert(d); + + for (;;) { + pid_t pid; + + r = proc_dir_read(d, &pid); + if (r < 0) + return r; + if (r == 0) + break; + + r = pidref_set_pid(ret, pid); + if (r == -ESRCH) /* gone by now? skip it */ + continue; + if (r < 0) + return r; + + return 1; + } + + if (ret) + *ret = PIDREF_NULL; + return 0; +} + static const char *const sigchld_code_table[] = { [CLD_EXITED] = "exited", [CLD_KILLED] = "killed", |