HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/core/manager.c

215,074 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: e0aa34f4c11534f81d2a7e0a2a8c2aa218451eb3

Lines 1–1000 of 5,689

/* SPDX-License-Identifier: LGPL-2.1-or-later */
 
#include <fcntl.h>
#include <linux/kd.h>
#include <sys/inotify.h>
#include <sys/ioctl.h>
#include <sys/mount.h>
#include <sys/reboot.h>
#include <sys/wait.h>
#include <unistd.h>
 
#include "sd-bus.h"
#include "sd-daemon.h"
#include "sd-messages.h"
#include "sd-netlink.h"
#include "sd-path.h"
 
#include "all-units.h"
#include "alloc-util.h"
#include "architecture.h"
#include "audit-fd.h"
#include "boot-timestamps.h"
#include "bpf-restrict-fs.h"
#include "bpf-restrict-fsaccess.h"
#include "build-path.h"
#include "bus-common-errors.h"
#include "bus-error.h"
#include "clean-ipc.h"
#include "common-signal.h"
#include "confidential-virt.h"
#include "constants.h"
#include "creds-util.h"
#include "daemon-util.h"
#include "dbus-job.h"
#include "dbus-manager.h"
#include "dbus-unit.h"
#include "dbus.h"
#include "dirent-util.h"
#include "dynamic-user.h"
#include "env-util.h"
#include "escape.h"
#include "event-util.h"
#include "exec-util.h"
#include "execute.h"
#include "exit-status.h"
#include "fd-util.h"
#include "fdset.h"
#include "format-util.h"
#include "fs-util.h"
#include "generator-setup.h"
#include "hashmap.h"
#include "initrd-util.h"
#include "inotify-util.h"
#include "install.h"
#include "io-util.h"
#include "iovec-util.h"
#include "libaudit-util.h"
#include "locale-setup.h"
#include "log.h"
#include "luo.h"
#include "manager-dump.h"
#include "manager-serialize.h"
#include "manager.h"
#include "mkdir.h"
#include "mount-util.h"
#include "notify-recv.h"
#include "parse-util.h"
#include "path-lookup.h"
#include "path-util.h"
#include "plymouth-util.h"
#include "pretty-print.h"
#include "prioq.h"
#include "process-util.h"
#include "psi-util.h"
#include "ratelimit.h"
#include "rlimit-util.h"
#include "rm-rf.h"
#include "selinux-util.h"
#include "serialize.h"
#include "service.h"
#include "set.h"
#include "signal-util.h"
#include "socket-util.h"
#include "special.h"
#include "stat-util.h"
#include "string-table.h"
#include "string-util.h"
#include "strv.h"
#include "strxcpyx.h"
#include "sysctl-util.h"
#include "syslog-util.h"
#include "taint.h"
#include "terminal-util.h"
#include "time-util.h"
#include "transaction.h"
#include "umask-util.h"
#include "unit-name.h"
#include "user-util.h"
#include "varlink-unit.h"
#include "varlink.h"
#include "virt.h"
#include "watchdog.h"
 
/* Make sure clients notifying us don't block */
#define MANAGER_SOCKET_RCVBUF_SIZE (8*U64_MB)
 
/* Initial delay and the interval for printing status messages about running jobs */
#define JOBS_IN_PROGRESS_WAIT_USEC (2*USEC_PER_SEC)
#define JOBS_IN_PROGRESS_QUIET_WAIT_USEC (25*USEC_PER_SEC)
#define JOBS_IN_PROGRESS_PERIOD_USEC (USEC_PER_SEC / 3)
#define JOBS_IN_PROGRESS_PERIOD_DIVISOR 3
 
/* If there are more than 1K bus messages queue across our API and direct buses, then let's not add more on top until
 * the queue gets more empty. */
#define MANAGER_BUS_BUSY_THRESHOLD 1024LU
 
/* How many units and jobs to process of the bus queue before returning to the event loop. */
#define MANAGER_BUS_MESSAGE_BUDGET 100U
 
#define DEFAULT_TASKS_MAX ((const CGroupTasksMax) { 15U, 100U }) /* 15% */
 
static int manager_dispatch_notify_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
static int manager_dispatch_signal_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
static int manager_dispatch_time_change_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
static int manager_dispatch_idle_pipe_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
static int manager_dispatch_user_lookup_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
static int manager_dispatch_handoff_timestamp_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
static int manager_dispatch_pidref_transport_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
static int manager_dispatch_jobs_in_progress(sd_event_source *source, usec_t usec, void *userdata);
static int manager_dispatch_run_queue(sd_event_source *source, void *userdata);
static int manager_dispatch_sigchld(sd_event_source *source, void *userdata);
static int manager_dispatch_timezone_change(sd_event_source *source, const struct inotify_event *event, void *userdata);
static int manager_run_environment_generators(Manager *m);
static int manager_run_generators(Manager *m);
static void manager_vacuum(Manager *m);
 
static usec_t manager_watch_jobs_next_time(Manager *m) {
        usec_t timeout;
 
        if (MANAGER_IS_USER(m))
                /* Let the user manager without a timeout show status quickly, so the system manager can make
                 * use of it, if it wants to. */
                timeout = JOBS_IN_PROGRESS_WAIT_USEC * 2 / 3;
        else if (manager_get_show_status_on(m))
                /* When status is on, just use the usual timeout. */
                timeout = JOBS_IN_PROGRESS_WAIT_USEC;
        else
                timeout = JOBS_IN_PROGRESS_QUIET_WAIT_USEC;
 
        return usec_add(now(CLOCK_MONOTONIC), timeout);
}
 
static bool manager_is_confirm_spawn_disabled(Manager *m) {
        assert(m);
 
        if (!m->confirm_spawn)
                return true;
 
        return access("/run/systemd/confirm_spawn_disabled", F_OK) >= 0;
}
 
static void manager_watch_jobs_in_progress(Manager *m) {
        usec_t next;
        int r;
 
        assert(m);
 
        /* We do not want to show the cylon animation if the user
         * needs to confirm service executions otherwise confirmation
         * messages will be screwed by the cylon animation. */
        if (!manager_is_confirm_spawn_disabled(m))
                return;
 
        if (m->jobs_in_progress_event_source)
                return;
 
        next = manager_watch_jobs_next_time(m);
        r = sd_event_add_time(
                        m->event,
                        &m->jobs_in_progress_event_source,
                        CLOCK_MONOTONIC,
                        next, 0,
                        manager_dispatch_jobs_in_progress, m);
        if (r < 0)
                return;
 
        (void) sd_event_source_set_description(m->jobs_in_progress_event_source, "manager-jobs-in-progress");
}
 
static void manager_flip_auto_status(Manager *m, bool enable, const char *reason) {
        assert(m);
 
        if (enable) {
                if (m->show_status == SHOW_STATUS_AUTO)
                        manager_set_show_status(m, SHOW_STATUS_TEMPORARY, reason);
        } else {
                if (m->show_status == SHOW_STATUS_TEMPORARY)
                        manager_set_show_status(m, SHOW_STATUS_AUTO, reason);
        }
}
 
static void manager_print_jobs_in_progress(Manager *m) {
        Job *j;
        unsigned counter = 0, print_nr;
        char cylon[6 + CYLON_BUFFER_EXTRA + 1];
        unsigned cylon_pos;
        uint64_t timeout = 0;
 
        assert(m);
        assert(m->n_running_jobs > 0);
 
        manager_flip_auto_status(m, true, "delay");
 
        print_nr = (m->jobs_in_progress_iteration / JOBS_IN_PROGRESS_PERIOD_DIVISOR) % m->n_running_jobs;
 
        HASHMAP_FOREACH(j, m->jobs)
                if (j->state == JOB_RUNNING && counter++ == print_nr)
                        break;
 
        /* m->n_running_jobs must be consistent with the contents of m->jobs,
         * so the above loop must have succeeded in finding j. */
        assert(counter == print_nr + 1);
        assert(j);
 
        cylon_pos = m->jobs_in_progress_iteration % 14;
        if (cylon_pos >= 8)
                cylon_pos = 14 - cylon_pos;
        draw_cylon(cylon, sizeof(cylon), 6, cylon_pos);
 
        m->jobs_in_progress_iteration++;
 
        char job_of_n[STRLEN("( of ) ") + DECIMAL_STR_MAX(unsigned)*2] = "";
        if (m->n_running_jobs > 1)
                xsprintf(job_of_n, "(%u of %u) ", counter, m->n_running_jobs);
 
        (void) job_get_timeout(j, &timeout);
 
        /* We want to use enough information for the user to identify previous lines talking about the same
         * unit, but keep the message as short as possible. So if 'Starting foo.service' or 'Starting
         * foo.service - Description' were used, 'foo.service' is enough here. On the other hand, if we used
         * 'Starting Description' before, then we shall also use 'Description' here. So we pass NULL as the
         * second argument to unit_status_string(). */
        const char *ident = unit_status_string(j->unit, NULL);
 
        const char *time = FORMAT_TIMESPAN(now(CLOCK_MONOTONIC) - j->begin_usec, 1*USEC_PER_SEC);
        const char *limit = timeout > 0 ? FORMAT_TIMESPAN(timeout - j->begin_usec, 1*USEC_PER_SEC) : "no limit";
 
        if (m->status_unit_format == STATUS_UNIT_FORMAT_DESCRIPTION)
                /* When using 'Description', we effectively don't have enough space to show the nested status
                 * without ellipsization, so let's not even try. */
                manager_status_printf(m, STATUS_TYPE_EPHEMERAL, cylon,
                                      "%sA %s job is running for %s (%s / %s)",
                                      job_of_n,
                                      job_type_to_string(j->type),
                                      ident,
                                      time, limit);
        else {
                const char *status_text = unit_status_text(j->unit);
 
                manager_status_printf(m, STATUS_TYPE_EPHEMERAL, cylon,
                                      "%sJob %s/%s running (%s / %s)%s%s",
                                      job_of_n,
                                      ident,
                                      job_type_to_string(j->type),
                                      time, limit,
                                      status_text ? ": " : "",
                                      strempty(status_text));
        }
 
        (void) sd_notifyf(/* unset_environment= */ false,
                          "STATUS=%sUser job %s/%s running (%s / %s)...",
                          job_of_n,
                          ident, job_type_to_string(j->type),
                          time, limit);
        m->status_ready = false;
}
 
static int have_ask_password(void) {
        _cleanup_closedir_ DIR *dir = NULL;
 
        dir = opendir("/run/systemd/ask-password");
        if (!dir) {
                if (errno == ENOENT)
                        return false;
 
                return -errno;
        }
 
        FOREACH_DIRENT_ALL(de, dir, return -errno) {
                if (!IN_SET(de->d_type, DT_REG, DT_UNKNOWN))
                        continue;
 
                if (startswith(de->d_name, "ask."))
                        return true;
        }
 
        return false;
}
 
static int manager_dispatch_ask_password_fd(sd_event_source *source,
                                            int fd, uint32_t revents, void *userdata) {
        Manager *m = ASSERT_PTR(userdata);
 
        (void) flush_fd(fd);
 
        m->have_ask_password = have_ask_password();
        if (m->have_ask_password < 0)
                /* Log error but continue. Negative have_ask_password is treated as unknown status. */
                log_warning_errno(m->have_ask_password, "Failed to list /run/systemd/ask-password/, ignoring: %m");
 
        return 0;
}
 
static void manager_close_ask_password(Manager *m) {
        assert(m);
 
        m->ask_password_event_source = sd_event_source_disable_unref(m->ask_password_event_source);
        m->have_ask_password = -EINVAL;
}
 
static int manager_check_ask_password(Manager *m) {
        int r;
 
        assert(m);
 
        /* We only care about passwords prompts when running in system mode (because that's the only time we
         * manage a console) */
        if (!MANAGER_IS_SYSTEM(m))
                return 0;
 
        if (!m->ask_password_event_source) {
                _cleanup_close_ int inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
                if (inotify_fd < 0)
                        return log_error_errno(errno, "Failed to create inotify object: %m");
 
                (void) mkdir_label("/run/systemd/ask-password", 0755);
                r = inotify_add_watch_and_warn(inotify_fd, "/run/systemd/ask-password", IN_CLOSE_WRITE|IN_DELETE|IN_MOVED_TO|IN_ONLYDIR);
                if (r < 0)
                        return r;
 
                _cleanup_(sd_event_source_disable_unrefp) sd_event_source *event_source = NULL;
                r = sd_event_add_io(
                                m->event,
                                &event_source,
                                inotify_fd,
                                EPOLLIN,
                                manager_dispatch_ask_password_fd,
                                m);
                if (r < 0)
                        return log_error_errno(r, "Failed to add event source for /run/systemd/ask-password/: %m");
 
                r = sd_event_source_set_io_fd_own(event_source, true);
                if (r < 0)
                        return log_error_errno(r, "Failed to pass ownership of /run/systemd/ask-password/ inotify fd to event source: %m");
                TAKE_FD(inotify_fd);
 
                (void) sd_event_source_set_description(event_source, "manager-ask-password");
 
                m->ask_password_event_source = TAKE_PTR(event_source);
 
                /* Queries might have been added meanwhile... */
                (void) manager_dispatch_ask_password_fd(m->ask_password_event_source, sd_event_source_get_io_fd(m->ask_password_event_source), EPOLLIN, m);
        }
 
        return m->have_ask_password;
}
 
static int manager_watch_idle_pipe(Manager *m) {
        int r;
 
        assert(m);
 
        if (m->idle_pipe_event_source)
                return 0;
 
        if (m->idle_pipe[2] < 0)
                return 0;
 
        r = sd_event_add_io(m->event, &m->idle_pipe_event_source, m->idle_pipe[2], EPOLLIN, manager_dispatch_idle_pipe_fd, m);
        if (r < 0)
                return log_error_errno(r, "Failed to watch idle pipe: %m");
 
        (void) sd_event_source_set_description(m->idle_pipe_event_source, "manager-idle-pipe");
 
        return 0;
}
 
static void manager_close_idle_pipe(Manager *m) {
        assert(m);
 
        m->idle_pipe_event_source = sd_event_source_disable_unref(m->idle_pipe_event_source);
 
        safe_close_pair(m->idle_pipe);
        safe_close_pair(m->idle_pipe + 2);
}
 
static int manager_setup_time_change(Manager *m) {
        int r;
 
        assert(m);
 
        if (MANAGER_IS_TEST_RUN(m))
                return 0;
 
        m->time_change_event_source = sd_event_source_disable_unref(m->time_change_event_source);
 
        r = event_add_time_change(m->event, &m->time_change_event_source, manager_dispatch_time_change_fd, m);
        if (r < 0)
                return log_error_errno(r, "Failed to create time change event source: %m");
 
        /* Schedule this slightly earlier than the .timer event sources */
        r = sd_event_source_set_priority(m->time_change_event_source, EVENT_PRIORITY_TIME_CHANGE);
        if (r < 0)
                return log_error_errno(r, "Failed to set priority of time change event sources: %m");
 
        log_debug("Set up TFD_TIMER_CANCEL_ON_SET timerfd.");
 
        return 0;
}
 
static int manager_read_timezone_stat(Manager *m) {
        struct stat st;
        bool changed;
 
        assert(m);
 
        /* Read the current stat() data of /etc/localtime so that we detect changes */
        if (lstat(etc_localtime(), &st) < 0) {
                log_debug_errno(errno, "Failed to stat /etc/localtime, ignoring: %m");
                changed = m->etc_localtime_accessible;
                m->etc_localtime_accessible = false;
        } else {
                usec_t k;
 
                k = timespec_load(&st.st_mtim);
                changed = !m->etc_localtime_accessible || k != m->etc_localtime_mtime;
 
                m->etc_localtime_mtime = k;
                m->etc_localtime_accessible = true;
        }
 
        return changed;
}
 
static int manager_setup_timezone_change(Manager *m) {
        _cleanup_(sd_event_source_unrefp) sd_event_source *new_event = NULL;
        int r;
 
        assert(m);
 
        if (MANAGER_IS_TEST_RUN(m))
                return 0;
 
        /* We watch /etc/localtime for three events: change of the link count (which might mean removal from /etc even
         * though another link might be kept), renames, and file close operations after writing. Note we don't bother
         * with IN_DELETE_SELF, as that would just report when the inode is removed entirely, i.e. after the link count
         * went to zero and all fds to it are closed.
         *
         * Note that we never follow symlinks here. This is a simplification, but should cover almost all cases
         * correctly.
         *
         * Note that we create the new event source first here, before releasing the old one. This should optimize
         * behaviour as this way sd-event can reuse the old watch in case the inode didn't change. */
 
        r = sd_event_add_inotify(m->event, &new_event, etc_localtime(),
                                 IN_ATTRIB|IN_MOVE_SELF|IN_CLOSE_WRITE|IN_DONT_FOLLOW, manager_dispatch_timezone_change, m);
        if (r == -ENOENT) {
                /* If the file doesn't exist yet, subscribe to /etc instead, and wait until it is created either by
                 * O_CREATE or by rename() */
                _cleanup_free_ char *localtime_dir = NULL;
 
                int dir_r = path_extract_directory(etc_localtime(), &localtime_dir);
                if (dir_r < 0)
                        return log_error_errno(dir_r, "Failed to extract directory from path '%s': %m", etc_localtime());
 
                log_debug_errno(r, "%s doesn't exist yet, watching %s instead.", etc_localtime(), localtime_dir);
 
                r = sd_event_add_inotify(m->event, &new_event, localtime_dir,
                                         IN_CREATE|IN_MOVED_TO|IN_ONLYDIR, manager_dispatch_timezone_change, m);
        }
        if (r < 0)
                return log_error_errno(r, "Failed to create timezone change event source: %m");
 
        /* Schedule this slightly earlier than the .timer event sources */
        r = sd_event_source_set_priority(new_event, EVENT_PRIORITY_TIME_ZONE);
        if (r < 0)
                return log_error_errno(r, "Failed to set priority of timezone change event sources: %m");
 
        sd_event_source_unref(m->timezone_change_event_source);
        m->timezone_change_event_source = TAKE_PTR(new_event);
 
        return 0;
}
 
static int manager_enable_special_signals(Manager *m) {
        _cleanup_close_ int fd = -EBADF;
 
        assert(m);
 
        if (!MANAGER_IS_SYSTEM(m) || MANAGER_IS_TEST_RUN(m))
                return 0;
 
        /* Enable that we get SIGINT on control-alt-del. In containers this will fail with EPERM (older) or
         * EINVAL (newer), so ignore that. */
        if (reboot(RB_DISABLE_CAD) < 0 && !IN_SET(errno, EPERM, EINVAL))
                log_warning_errno(errno, "Failed to enable ctrl-alt-del handling, ignoring: %m");
 
        fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
        if (fd < 0)
                /* Support systems without virtual console (ENOENT) gracefully */
                log_full_errno(fd == -ENOENT ? LOG_DEBUG : LOG_WARNING, fd, "Failed to open %s, ignoring: %m", "/dev/tty0");
        else {
                /* Enable that we get SIGWINCH on kbrequest */
                if (ioctl(fd, KDSIGACCEPT, SIGWINCH) < 0)
                        log_warning_errno(errno, "Failed to enable kbrequest handling, ignoring: %m");
        }
 
        return 0;
}
 
static int manager_setup_signals(Manager *m) {
        static const struct sigaction sa = {
                .sa_handler = SIG_DFL,
                .sa_flags = SA_NOCLDSTOP|SA_RESTART,
        };
        sigset_t mask;
        int r;
 
        assert(m);
 
        assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
 
        /* We make liberal use of realtime signals here. On Linux we have 29 of them, between
         * SIGRTMIN+0 ... SIGRTMIN+29. The glibc has one more (SIGRTMAX is SIGRTMIN+30),
         * but musl does not (SIGRTMAX is SIGRTMIN+29). */
 
        assert_se(sigemptyset(&mask) == 0);
        sigset_add_many(&mask,
                        SIGCHLD,     /* Child died */
                        SIGTERM,     /* Reexecute daemon */
                        SIGHUP,      /* Reload configuration */
                        SIGUSR1,     /* systemd: reconnect to D-Bus */
                        SIGUSR2,     /* systemd: dump status */
                        SIGINT,      /* Kernel sends us this on control-alt-del */
                        SIGWINCH,    /* Kernel sends us this on kbrequest (alt-arrowup) */
                        SIGPWR,      /* Some kernel drivers and upsd send us this on power failure */
 
                        SIGRTMIN+0,  /* systemd: start default.target */
                        SIGRTMIN+1,  /* systemd: isolate rescue.target */
                        SIGRTMIN+2,  /* systemd: isolate emergency.target */
                        SIGRTMIN+3,  /* systemd: start halt.target */
                        SIGRTMIN+4,  /* systemd: start poweroff.target */
                        SIGRTMIN+5,  /* systemd: start reboot.target */
                        SIGRTMIN+6,  /* systemd: start kexec.target */
                        SIGRTMIN+7,  /* systemd: start soft-reboot.target */
 
                        /* ... space for more special targets ... */
 
                        SIGRTMIN+13, /* systemd: Immediate halt */
                        SIGRTMIN+14, /* systemd: Immediate poweroff */
                        SIGRTMIN+15, /* systemd: Immediate reboot */
                        SIGRTMIN+16, /* systemd: Immediate kexec */
                        SIGRTMIN+17, /* systemd: Immediate soft-reboot */
                        SIGRTMIN+18, /* systemd: control command */
 
                        /* ... space ... */
 
                        SIGRTMIN+20, /* systemd: enable status messages */
                        SIGRTMIN+21, /* systemd: disable status messages */
                        SIGRTMIN+22, /* systemd: set log level to LOG_DEBUG */
                        SIGRTMIN+23, /* systemd: set log level to LOG_INFO */
                        SIGRTMIN+24, /* systemd: Immediate exit (--user only) */
                        SIGRTMIN+25, /* systemd: reexecute manager */
 
                        SIGRTMIN+26, /* systemd: set log target to journal-or-kmsg */
                        SIGRTMIN+27, /* systemd: set log target to console */
                        SIGRTMIN+28, /* systemd: set log target to kmsg */
                        SIGRTMIN+29, /* systemd: set log target to syslog-or-kmsg (obsolete) */
 
                        /* ... one free signal here SIGRTMIN+30 (glibc only) ... */
                        -1);
        assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
 
        m->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
        if (m->signal_fd < 0)
                return -errno;
 
        r = sd_event_add_io(m->event, &m->signal_event_source, m->signal_fd, EPOLLIN, manager_dispatch_signal_fd, m);
        if (r < 0)
                return r;
 
        (void) sd_event_source_set_description(m->signal_event_source, "manager-signal");
 
        /* Process signals a bit earlier than the rest of things, but later than notify_fd processing, so that the
         * notify processing can still figure out to which process/service a message belongs, before we reap the
         * process. Also, process this before handling cgroup notifications, so that we always collect child exit
         * status information before detecting that there's no process in a cgroup. */
        r = sd_event_source_set_priority(m->signal_event_source, EVENT_PRIORITY_SIGNALS);
        if (r < 0)
                return r;
 
        /* Report to supervisor that we now process the above signals. We report this as level "2", to
         * indicate that we support more than sysvinit's signals (of course, sysvinit never sent this
         * message, but conceptually it makes sense to consider level "1" to be equivalent to sysvinit's
         * signal handling). Also, by setting this to "2" people looking for this hopefully won't
         * misunderstand this as a boolean concept. Signal level 2 shall refer to the signals PID 1
         * understands at the time of release of systemd v256, i.e. including basic SIGRTMIN+18 handling for
         * memory pressure and stuff. When more signals are hooked up (or more SIGRTMIN+18 multiplex
         * operations added, this level should be increased). */
        (void) sd_notify(/* unset_environment= */ false,
                         "X_SYSTEMD_SIGNALS_LEVEL=2");
 
        return manager_enable_special_signals(m);
}
 
static char** sanitize_environment(char **l) {
 
        /* Let's remove some environment variables that we need ourselves to communicate with our clients */
        strv_env_unset_many(
                        l,
                        "CACHE_DIRECTORY",
                        "CONFIGURATION_DIRECTORY",
                        "CPU_PRESSURE_WATCH",
                        "CPU_PRESSURE_WRITE",
                        "CREDENTIALS_DIRECTORY",
                        "EXIT_CODE",
                        "EXIT_STATUS",
                        "IO_PRESSURE_WATCH",
                        "IO_PRESSURE_WRITE",
                        "INVOCATION_ID",
                        "JOURNAL_STREAM",
                        "LISTEN_FDNAMES",
                        "LISTEN_FDS",
                        "LISTEN_PID",
                        "LISTEN_PIDFDID",
                        "LOGS_DIRECTORY",
                        "LOG_NAMESPACE",
                        "MAINPID",
                        "MANAGERPID",
                        "MEMORY_PRESSURE_WATCH",
                        "MEMORY_PRESSURE_WRITE",
                        "MONITOR_EXIT_CODE",
                        "MONITOR_EXIT_STATUS",
                        "MONITOR_INVOCATION_ID",
                        "MONITOR_SERVICE_RESULT",
                        "MONITOR_UNIT",
                        "NOTIFY_SOCKET",
                        "PIDFILE",
                        "REMOTE_ADDR",
                        "REMOTE_PORT",
                        "RUNTIME_DIRECTORY",
                        "SERVICE_RESULT",
                        "STATE_DIRECTORY",
                        "SYSTEMD_EXEC_PID",
                        "TRIGGER_PATH",
                        "TRIGGER_TIMER_MONOTONIC_USEC",
                        "TRIGGER_TIMER_REALTIME_USEC",
                        "TRIGGER_UNIT",
                        "WATCHDOG_PID",
                        "WATCHDOG_USEC");
 
        /* Let's order the environment alphabetically, just to make it pretty */
        return strv_sort(l);
}
 
int manager_default_environment(Manager *m) {
        assert(m);
 
        m->transient_environment = strv_free(m->transient_environment);
 
        if (MANAGER_IS_SYSTEM(m)) {
                /* The system manager always starts with a clean environment for its children. It does not
                 * import the kernel's or the parents' exported variables.
                 *
                 * The initial passed environment is untouched to keep /proc/self/environ valid; it is used
                 * for tagging the init process inside containers. */
                char *path = strjoin("PATH=", default_PATH());
                if (!path)
                        return log_oom();
 
                if (strv_consume(&m->transient_environment, path) < 0)
                        return log_oom();
 
                /* Import locale variables LC_*= from configuration */
                (void) locale_setup(&m->transient_environment);
        } else {
                /* The user manager passes its own environment along to its children, except for $PATH and
                 * session envs. */
 
                m->transient_environment = strv_copy(environ);
                if (!m->transient_environment)
                        return log_oom();
 
                char *path = strjoin("PATH=", default_user_PATH());
                if (!path)
                        return log_oom();
 
                if (strv_env_replace_consume(&m->transient_environment, path) < 0)
                        return log_oom();
 
                /* Envvars set for our 'manager' class session are private and should not be propagated
                 * to children. Also it's likely that the graphical session will set these on their own. */
                strv_env_unset_many(m->transient_environment,
                                    "XDG_SESSION_ID",
                                    "XDG_SESSION_CLASS",
                                    "XDG_SESSION_TYPE",
                                    "XDG_SESSION_DESKTOP",
                                    "XDG_SESSION_EXTRA_DEVICE_ACCESS",
                                    "XDG_SEAT",
                                    "XDG_VTNR");
        }
 
        sanitize_environment(m->transient_environment);
        return 0;
}
 
static int manager_setup_prefix(Manager *m) {
        struct table_entry {
                uint64_t type;
                const char *suffix;
        };
 
        static const struct table_entry paths_system[_EXEC_DIRECTORY_TYPE_MAX] = {
                [EXEC_DIRECTORY_RUNTIME]       = { SD_PATH_SYSTEM_RUNTIME,       NULL },
                [EXEC_DIRECTORY_STATE]         = { SD_PATH_SYSTEM_STATE_PRIVATE, NULL },
                [EXEC_DIRECTORY_CACHE]         = { SD_PATH_SYSTEM_STATE_CACHE,   NULL },
                [EXEC_DIRECTORY_LOGS]          = { SD_PATH_SYSTEM_STATE_LOGS,    NULL },
                [EXEC_DIRECTORY_CONFIGURATION] = { SD_PATH_SYSTEM_CONFIGURATION, NULL },
        };
 
        static const struct table_entry paths_user[_EXEC_DIRECTORY_TYPE_MAX] = {
                [EXEC_DIRECTORY_RUNTIME]       = { SD_PATH_USER_RUNTIME,       NULL  },
                [EXEC_DIRECTORY_STATE]         = { SD_PATH_USER_STATE_PRIVATE, NULL  },
                [EXEC_DIRECTORY_CACHE]         = { SD_PATH_USER_STATE_CACHE,   NULL  },
                [EXEC_DIRECTORY_LOGS]          = { SD_PATH_USER_STATE_PRIVATE, "log" },
                [EXEC_DIRECTORY_CONFIGURATION] = { SD_PATH_USER_CONFIGURATION, NULL  },
        };
 
        assert(m);
 
        const struct table_entry *p = MANAGER_IS_SYSTEM(m) ? paths_system : paths_user;
        int r;
 
        for (ExecDirectoryType i = 0; i < _EXEC_DIRECTORY_TYPE_MAX; i++) {
                r = sd_path_lookup(p[i].type, p[i].suffix, &m->prefix[i]);
                if (r < 0)
                        return log_warning_errno(r, "Failed to lookup %s path: %m",
                                                 exec_directory_type_to_string(i));
        }
 
        return 0;
}
 
static void manager_free_unit_name_maps(Manager *m) {
        m->unit_id_map = hashmap_free(m->unit_id_map);
        m->unit_name_map = hashmap_free(m->unit_name_map);
        m->unit_path_cache = set_free(m->unit_path_cache);
        m->unit_cache_timestamp_hash = 0;
}
 
static int manager_setup_run_queue(Manager *m) {
        int r;
 
        assert(m);
        assert(!m->run_queue_event_source);
 
        r = sd_event_add_defer(m->event, &m->run_queue_event_source, manager_dispatch_run_queue, m);
        if (r < 0)
                return r;
 
        r = sd_event_source_set_priority(m->run_queue_event_source, EVENT_PRIORITY_RUN_QUEUE);
        if (r < 0)
                return r;
 
        r = sd_event_source_set_enabled(m->run_queue_event_source, SD_EVENT_OFF);
        if (r < 0)
                return r;
 
        (void) sd_event_source_set_description(m->run_queue_event_source, "manager-run-queue");
 
        return 0;
}
 
static int manager_setup_sigchld_event_source(Manager *m) {
        int r;
 
        assert(m);
        assert(!m->sigchld_event_source);
 
        r = sd_event_add_defer(m->event, &m->sigchld_event_source, manager_dispatch_sigchld, m);
        if (r < 0)
                return r;
 
        r = sd_event_source_set_priority(m->sigchld_event_source, EVENT_PRIORITY_SIGCHLD);
        if (r < 0)
                return r;
 
        r = sd_event_source_set_enabled(m->sigchld_event_source, SD_EVENT_OFF);
        if (r < 0)
                return r;
 
        (void) sd_event_source_set_description(m->sigchld_event_source, "manager-sigchld");
 
        return 0;
}
 
typedef int (*pressure_add_t)(sd_event *, sd_event_source **, sd_event_handler_t, void *);
typedef int (*pressure_set_period_t)(sd_event_source *, usec_t, usec_t);
 
static const struct {
        pressure_add_t add;
        pressure_set_period_t set_period;
} pressure_dispatch_table[_PRESSURE_RESOURCE_MAX] = {
        [PRESSURE_MEMORY] = { sd_event_add_memory_pressure, sd_event_source_set_memory_pressure_period },
        [PRESSURE_CPU]    = { sd_event_add_cpu_pressure,    sd_event_source_set_cpu_pressure_period    },
        [PRESSURE_IO]     = { sd_event_add_io_pressure,     sd_event_source_set_io_pressure_period     },
};
 
int manager_setup_pressure_event_source(Manager *m, PressureResource t) {
        int r;
 
        assert(m);
        assert(t >= 0 && t < _PRESSURE_RESOURCE_MAX);
 
        m->pressure_event_source[t] = sd_event_source_disable_unref(m->pressure_event_source[t]);
 
        r = pressure_dispatch_table[t].add(m->event, &m->pressure_event_source[t], NULL, NULL);
        if (r < 0)
                log_full_errno(ERRNO_IS_NOT_SUPPORTED(r) || ERRNO_IS_PRIVILEGE(r) || (r == -EHOSTDOWN) ? LOG_DEBUG : LOG_NOTICE, r,
                               "Failed to establish %s pressure event source, ignoring: %m", pressure_resource_to_string(t));
        else if (m->defaults.pressure[t].threshold_usec != USEC_INFINITY) {
 
                r = pressure_dispatch_table[t].set_period(
                                m->pressure_event_source[t],
                                m->defaults.pressure[t].threshold_usec,
                                PRESSURE_DEFAULT_WINDOW_USEC);
                if (r < 0)
                        log_warning_errno(r, "Failed to adjust %s pressure threshold, ignoring: %m", pressure_resource_to_string(t));
        }
 
        return 0;
}
 
static int manager_find_credentials_dirs(Manager *m) {
        const char *e;
        int r;
 
        assert(m);
 
        r = get_credentials_dir(&e);
        if (r < 0) {
                if (r != -ENXIO)
                        log_debug_errno(r, "Failed to determine credentials directory, ignoring: %m");
        } else {
                m->received_credentials_directory = strdup(e);
                if (!m->received_credentials_directory)
                        return -ENOMEM;
        }
 
        r = get_encrypted_credentials_dir(&e);
        if (r < 0) {
                if (r != -ENXIO)
                        log_debug_errno(r, "Failed to determine encrypted credentials directory, ignoring: %m");
        } else {
                m->received_encrypted_credentials_directory = strdup(e);
                if (!m->received_encrypted_credentials_directory)
                        return -ENOMEM;
        }
 
        return 0;
}
 
void manager_set_switching_root(Manager *m, bool switching_root) {
        assert(m);
 
        m->switching_root = MANAGER_IS_SYSTEM(m) && switching_root;
}
 
double manager_get_progress(Manager *m) {
        assert(m);
 
        if (MANAGER_IS_FINISHED(m) || m->n_installed_jobs == 0)
                return 1.0;
 
        return 1.0 - ((double) hashmap_size(m->jobs) / (double) m->n_installed_jobs);
}
 
static int compare_job_priority(const void *a, const void *b) {
        const Job *x = a, *y = b;
 
        return unit_compare_priority(x->unit, y->unit);
}
 
usec_t manager_default_timeout(RuntimeScope scope) {
        return scope == RUNTIME_SCOPE_SYSTEM ? DEFAULT_TIMEOUT_USEC : DEFAULT_USER_TIMEOUT_USEC;
}
 
static int pin_executor_binary(int *ret_fd) {
        _cleanup_free_ char *path = NULL;
 
        assert(ret_fd);
 
#if SYSTEMD_MULTICALL_BINARY
        int r;
 
        r = open_and_check_executable("/proc/self/exe", /* root= */ NULL, &path, ret_fd);
        if (r < 0)
                return log_debug_errno(r, "Failed to pin executor binary %s: %m", "/proc/self/exe");
#else
        int fd;
 
        fd = pin_callout_binary(SYSTEMD_EXECUTOR_BINARY_PATH, &path);
        if (fd < 0)
                return log_debug_errno(fd, "Failed to pin executor binary %s: %m", SYSTEMD_EXECUTOR_BINARY_PATH);
        *ret_fd = fd;
#endif
 
        log_debug("Using systemd-executor binary %s.", path);
        return 0;
}
 
int manager_new(RuntimeScope runtime_scope, ManagerTestRunFlags test_run_flags, Manager **ret) {
        _cleanup_(manager_freep) Manager *m = NULL;
        int r;
 
        assert(IN_SET(runtime_scope, RUNTIME_SCOPE_SYSTEM, RUNTIME_SCOPE_USER));
        assert(ret);
 
        m = new(Manager, 1);
        if (!m)
                return -ENOMEM;
 
        *m = (Manager) {
                .runtime_scope = runtime_scope,
                .objective = _MANAGER_OBJECTIVE_INVALID,
                .previous_objective = _MANAGER_OBJECTIVE_INVALID,
 
                .status_unit_format = STATUS_UNIT_FORMAT_DEFAULT,
 
                .original_log_level = -1,
                .original_log_target = _LOG_TARGET_INVALID,
 
                .watchdog_overridden[WATCHDOG_RUNTIME] = USEC_INFINITY,
                .watchdog_overridden[WATCHDOG_REBOOT] = USEC_INFINITY,
                .watchdog_overridden[WATCHDOG_KEXEC] = USEC_INFINITY,
                .watchdog_overridden[WATCHDOG_PRETIMEOUT] = USEC_INFINITY,
 
                .show_status_overridden = _SHOW_STATUS_INVALID,
 
                .notify_fd = -EBADF,
                .signal_fd = -EBADF,
                .user_lookup_fds = EBADF_PAIR,
                .handoff_timestamp_fds = EBADF_PAIR,
                .pidref_transport_fds = EBADF_PAIR,
                .private_listen_fd = -EBADF,
                .dev_autofs_fd = -EBADF,
                .cgroup_inotify_fd = -EBADF,
                .pin_cgroupfs_fd = -EBADF,
                .idle_pipe = { -EBADF, -EBADF, -EBADF, -EBADF},
 
                 /* start as id #1, so that we can leave #0 around as "null-like" value */
                .current_job_id = 1,
 
                .have_ask_password = -EINVAL, /* we don't know */
                .first_boot = -1,
                .test_run_flags = test_run_flags,
 
                .dump_ratelimit = (const RateLimit) { .interval = 10 * USEC_PER_MINUTE, .burst = 10 },
 
                .executor_fd = -EBADF,
 
                .restrict_fsaccess_bss_map_fd = -EBADF,
        };
 
        FOREACH_ELEMENT(fd, m->restrict_fsaccess_link_fds)
                *fd = -EBADF;
 
        unit_defaults_init(&m->defaults, runtime_scope);
 
#if ENABLE_EFI
        if (MANAGER_IS_SYSTEM(m) && detect_container() <= 0)
                boot_timestamps(m->timestamps + MANAGER_TIMESTAMP_USERSPACE,
                                m->timestamps + MANAGER_TIMESTAMP_FIRMWARE,
                                m->timestamps + MANAGER_TIMESTAMP_LOADER);
#endif
 
        /* Reboot immediately if the user hits C-A-D more often than 7x per 2s */
        m->ctrl_alt_del_ratelimit = (const RateLimit) { .interval = 2 * USEC_PER_SEC, .burst = 7 };
 
        r = manager_default_environment(m);
        if (r < 0)
                return r;
 
        r = hashmap_ensure_allocated(&m->units, &string_hash_ops);
        if (r < 0)
                return r;
 
        r = hashmap_ensure_allocated(&m->cgroup_unit, &path_hash_ops);
        if (r < 0)
                return r;