HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/basic/process-util.c

80,575 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: bcee9c39d1c691fd8f4fc26f16e925d3ccd6fa54

Lines 2001–2419 of 2,419

        * right-away */
        if (priority > current)
                return r;
 
        if (getrlimit(RLIMIT_NICE, &highest) < 0)
                return -errno;
 
        limit = rlimit_to_nice(highest.rlim_cur);
 
        /* Push to the allowed limit if we're higher than that. Note that we could also be less nice than
         * limit allows us, but still higher than what's requested. In that case our current value is
         * the best choice. */
        if (current > limit)
                if (setpriority(PRIO_PROCESS, 0, limit) < 0)
                        return -errno;
 
        log_debug("Cannot set requested nice level (%i), using next best (%i).", priority, MIN(current, limit));
        return 0;
}
 
_noreturn_ void freeze(void) {
        log_close();
 
        /* Make sure nobody waits for us (i.e. on one of our sockets) anymore. Note that we use
         * close_all_fds_without_malloc() instead of plain close_all_fds() here, since we want this function
         * to be compatible with being called from signal handlers. */
        (void) close_all_fds_without_malloc(NULL, 0);
 
        /* Let's not freeze right away, but keep reaping zombies. */
        for (;;) {
                siginfo_t si = {};
 
                if (waitid(P_ALL, 0, &si, WEXITED) < 0 && errno != EINTR)
                        break;
        }
 
        /* waitid() failed with an ECHLD error (because there are no left-over child processes) or any other
         * (unexpected) error. Freeze for good now! */
        for (;;)
                pause();
}
 
int get_process_threads(pid_t pid) {
        _cleanup_free_ char *t = NULL;
        int n, r;
 
        if (pid < 0)
                return -EINVAL;
 
        r = procfs_file_get_field(pid, "status", "Threads", &t);
        if (r == -ENOENT)
                return -ESRCH;
        if (r < 0)
                return r;
 
        r = safe_atoi(t, &n);
        if (r < 0)
                return r;
        if (n < 0)
                return -EINVAL;
 
        return n;
}
 
int is_reaper_process(void) {
        int b = 0, r;
 
        /* 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;
 
        r = prctl_safe(PR_GET_CHILD_SUBREAPER, (unsigned long) &b, 0, 0, 0);
        if (r < 0)
                return r;
 
        return b != 0;
}
 
int make_reaper_process(bool b) {
        int r;
 
        if (getpid_cached() == 1) {
 
                if (!b)
                        return -EINVAL;
 
                return 0;
        }
 
        r = prctl_safe(PR_SET_CHILD_SUBREAPER, b, 0, 0, 0);
        if (r < 0)
                return r;
 
        return 0;
}
 
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(posix_spawnattr_t*, posix_spawnattr_destroy, NULL);
 
int execvpe_safe(const char *file, char * const *argv, char * const *envp) {
        _cleanup_free_ char *resolved = NULL;
        int r;
 
        assert(file);
        assert(argv);
        assert(envp);
 
        /* Like execvpe(), but doesn't fall back to running the file via /bin/sh if execve() fails with
         * ENOEXEC. Without this a truncated or otherwise broken binary would "successfully" run as an empty
         * shell script instead of failing. Returns a negative errno on failure. */
 
        r = find_executable(file, &resolved);
        if (r < 0)
                return r;
 
        execve(resolved, argv, envp);
        return -errno;
}
 
int execvp_safe(const char *file, char * const *argv) {
        return execvpe_safe(file, argv, environ);
}
 
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_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.
         * 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;
 
        static bool have_clone_into_cgroup = true; /* kernel 5.7+ */
        _cleanup_close_ int cgroup_fd = -EBADF;
 
        if (cgroup && have_clone_into_cgroup) {
                _cleanup_free_ char *resolved_cgroup = NULL;
 
                r = cg_get_path(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)
                        flags |= POSIX_SPAWN_SETCGROUP;
                else if (r != ENOSYS)
                        return -r;
                /* If libc lacks posix_spawnattr_setcgroup_np we silently skip POSIX_SPAWN_SETCGROUP — the
                 * caller will then need to attach the child to the cgroup themselves. */
        }
 
        r = posix_spawnattr_setflags(&attr, flags);
        if (r != 0)
                return -r;
        r = posix_spawnattr_setsigmask(&attr, &mask);
        if (r != 0)
                return -r;
 
        _cleanup_close_ int pidfd = -EBADF;
 
        r = pidfd_spawn(&pidfd, path, NULL, &attr, argv, envp);
        if (ERRNO_IS_NOT_SUPPORTED(r) && FLAGS_SET(flags, POSIX_SPAWN_SETCGROUP) && cg_is_threaded(cgroup) > 0)
                return -EUCLEAN; /* clone3() could also return EOPNOTSUPP if the target cgroup is in threaded mode,
                                    turn that into something recognizable */
        if ((ERRNO_IS_NOT_SUPPORTED(r) || ERRNO_IS_PRIVILEGE(r)) &&
            FLAGS_SET(flags, POSIX_SPAWN_SETCGROUP)) {
                /* Compiled on a newer host, or seccomp&friends blocking clone3()? Fallback, but
                 * need to disable POSIX_SPAWN_SETCGROUP, which is what redirects to clone3().
                 * CLONE_INTO_CGROUP definitely won't work, hence remember the fact so that we don't
                 * retry every time.
                 * Note, CLONE_INTO_CGROUP is supported since kernel v5.7, but some architectures still
                 * do not support clone3(). Hence, we need to keep the fallback logic for a while. */
                have_clone_into_cgroup = false;
 
                flags &= ~POSIX_SPAWN_SETCGROUP;
                r = posix_spawnattr_setflags(&attr, flags);
                if (r != 0)
                        return -r;
 
                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))
                return -r;
 
        /* pidfd_spawn unavailable (libc or kernel missing) — fall back to plain posix_spawn. */
 
        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;
}
 
int safe_mlockall(int flags) {
        int r;
 
        /* When dealing with sensitive data, let's lock ourselves into memory. We do this only when
         * privileged however, as otherwise the amount of lockable memory that RLIMIT_MEMLOCK grants us is
         * frequently too low to make this work. The resource limit has no effect on CAP_IPC_LOCK processes,
         * hence that's the capability we check for. */
        r = have_effective_cap(CAP_IPC_LOCK);
        if (r < 0)
                return log_debug_errno(r, "Failed to determine if we have CAP_IPC_LOCK: %m");
        if (r == 0)
                return log_debug_errno(SYNTHETIC_ERRNO(EPERM), "Lacking CAP_IPC_LOCK, skipping mlockall().");
 
        if (mlockall(flags) < 0)
                return log_debug_errno(errno, "Failed to call mlockall(): %m");
 
        log_debug("Successfully called mlockall().");
        return 0;
}
 
static const char *const sigchld_code_table[] = {
        [CLD_EXITED] = "exited",
        [CLD_KILLED] = "killed",
        [CLD_DUMPED] = "dumped",
        [CLD_TRAPPED] = "trapped",
        [CLD_STOPPED] = "stopped",
        [CLD_CONTINUED] = "continued",
};
 
DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
 
static const char* const sched_policy_table[] = {
        [SCHED_OTHER] = "other",
        [SCHED_BATCH] = "batch",
        [SCHED_IDLE]  = "idle",
        [SCHED_FIFO]  = "fifo",
        [SCHED_EXT]   = "ext",
        [SCHED_RR]    = "rr",
};
 
DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
 
_noreturn_ void report_errno_and_exit(int errno_fd, int error) {
        int r;
 
        if (error >= 0)
                _exit(EXIT_SUCCESS);
 
        assert(errno_fd >= 0);
 
        r = loop_write(errno_fd, &error, sizeof(error));
        if (r < 0)
                log_debug_errno(r, "Failed to write errno to errno_fd=%d: %m", errno_fd);
 
        _exit(EXIT_FAILURE);
}
 
int read_errno(int errno_fd) {
        int r;
 
        assert(errno_fd >= 0);
 
        /* The issue here is that it's impossible to distinguish between an error code returned by child and
         * IO error arose when reading it. So, the function logs errors and return EIO for the later case. */
 
        ssize_t n = loop_read(errno_fd, &r, sizeof(r), /* do_poll= */ false);
        if (n < 0) {
                log_debug_errno(n, "Failed to read errno: %m");
                return -EIO;
        }
        if (n == 0) /* the process exited without reporting an error, assuming success */
                return 0;
        if (n != sizeof(r))
                return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Received unexpected amount of bytes (%zi) while reading errno.", n);
 
        if (r == 0)
                return 0;
        if (r < 0) /* child process reported an error, return it */
                return log_debug_errno(r, "Child process failed with errno: %m");
 
        return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Received positive errno from child, refusing: %d", r);
}
 
int prctl_safe(int op, unsigned long arg2, unsigned long arg3, unsigned long arg4, unsigned long arg5) {
 
        /* prctl(2) is a bit messy: it's a variadic function, defined with "unsigned long" arguments. This
         * means that unless people explicitly cast it's quite likely they end up passing a shorter type even
         * though unsigned long is required. And most of the time it might even kind of work, but not
         * always. Moreover, some calls insist on all unused arguments being zeroed out, others don't
         * care. Let's define this wrapper to enforce the right types, and that all arguments are always
         * passed, to avoid this confusion. */
 
        return RET_NERRNO(prctl(op, arg2, arg3, arg4, arg5));
}
 
int proc_set_comm(const char *comm) {
        return prctl_safe(PR_SET_NAME, (unsigned long) comm, 0, 0, 0);
}
 
int proc_set_nnp(void) {
        return prctl_safe(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
}
 
nsec_t proc_get_timerslack(void) {
        int r;
 
        r = prctl_safe(PR_GET_TIMERSLACK, 0, 0, 0, 0);
        if (r < 0)
                return NSEC_INFINITY;
 
        return r;
}