HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/core/execute.c

114,975 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 78c34b4e092b80db503d10431609260c5b3d8f72

Lines 1–1000 of 3,235

/* SPDX-License-Identifier: LGPL-2.1-or-later */
 
#include <fcntl.h>
#include <poll.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/prctl.h> /* IWYU pragma: keep */
#include <sys/socket.h>
#include <sys/stat.h>
#include <unistd.h>
 
#include "af-list.h"
#include "alloc-util.h"
#include "async.h"
#include "bitfield.h"
#include "capability-list.h"
#include "capability-util.h"
#include "cgroup-setup.h"
#include "coredump-util.h"
#include "cpu-set-util.h"
#include "creds-util.h"
#include "dissect-image.h"
#include "dynamic-user.h"
#include "env-file.h"
#include "env-util.h"
#include "escape.h"
#include "exec-credential.h"
#include "execute.h"
#include "execute-serialize.h"
#include "fd-util.h"
#include "fdset.h"
#include "fileio.h"
#include "format-util.h"
#include "fs-util.h"
#include "glob-util.h"
#include "hexdecoct.h"
#include "image-policy.h"
#include "io-util.h"
#include "ioprio-util.h"
#include "log.h"
#include "manager.h"
#include "mkdir.h"
#include "namespace-util.h"
#include "namespace.h"
#include "nsflags.h"
#include "open-file.h"
#include "ordered-set.h"
#include "osc-context.h"
#include "parse-util.h"
#include "path-util.h"
#include "pidref.h"
#include "process-util.h"
#include "rlimit-util.h"
#include "rm-rf.h"
#include "seccomp-util.h"
#include "securebits-util.h"
#include "serialize.h"
#include "set.h"
#include "sort-util.h"
#include "specifier.h"
#include "string-table.h"
#include "string-util.h"
#include "strv.h"
#include "syslog-util.h"
#include "terminal-util.h"
#include "tmpfile-util.h"
#include "utmp-wtmp.h"
#include "vpick.h"
 
const char* exec_context_tty_path(const ExecContext *context) {
        assert(context);
 
        if (context->stdio_as_fds)
                return NULL;
 
        if (context->tty_path)
                return context->tty_path;
 
        return "/dev/console";
}
 
int exec_context_apply_tty_size(
                const ExecContext *context,
                int input_fd,
                int output_fd,
                const char *tty_path) {
 
        unsigned rows, cols;
        int r;
 
        assert(context);
        assert(input_fd >= 0);
        assert(output_fd >= 0);
 
        if (!isatty_safe(output_fd))
                return 0;
 
        if (!tty_path)
                tty_path = exec_context_tty_path(context);
 
        /* Preferably use explicitly configured data */
        rows = context->tty_rows;
        cols = context->tty_cols;
 
        /* Fill in data from kernel command line if anything is unspecified */
        if (tty_path && (rows == UINT_MAX || cols == UINT_MAX))
                (void) proc_cmdline_tty_size(
                                tty_path,
                                rows == UINT_MAX ? &rows : NULL,
                                cols == UINT_MAX ? &cols : NULL);
 
        /* If we got nothing so far and we are talking to a physical device, then let's query dimensions from
         * the ANSI terminal driver. Note that we will not bother with this in case terminal reset via ansi
         * sequences is not enabled, as the DSR logic relies on ANSI sequences after all, and if we shall not
         * use those during initialization we need to skip it. */
        if (rows == UINT_MAX && cols == UINT_MAX &&
            exec_context_shall_ansi_seq_reset(context) &&
            isatty_safe(input_fd)) {
                r = terminal_get_size(input_fd, output_fd, &rows, &cols, /* try_dsr= */ true, /* try_csi18= */ false);
                if (r < 0)
                        log_debug_errno(r, "Failed to get terminal size by DSR, ignoring: %m");
        }
 
        return terminal_set_size_fd(output_fd, tty_path, rows, cols);
}
 
void exec_context_tty_reset(const ExecContext *context, const ExecParameters *parameters, sd_id128_t invocation_id) {
        _cleanup_close_ int _fd = -EBADF, lock_fd = -EBADF;
        int fd, r;
 
        assert(context);
 
        /* Note that this is potentially a "destructive" reset of a TTY device. It's about getting rid of the
         * remains of previous uses of the TTY. It's *not* about getting things set up for coming uses. We'll
         * potentially invalidate the TTY here through hangups or VT disallocations, and hence do not keep a
         * continuous fd open. */
 
        const char *path = exec_context_tty_path(context);
 
        if (parameters && parameters->stdout_fd >= 0 && isatty_safe(parameters->stdout_fd))
                fd = parameters->stdout_fd;
        else if (path && exec_context_has_tty(context)) {
                fd = _fd = open_terminal(path, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
                if (fd < 0)
                        return (void) log_debug_errno(fd, "Failed to open terminal '%s', ignoring: %m", path);
        } else
                return;   /* nothing to do */
 
        /* Take a synchronization lock for the duration of the setup that we do here.
         * systemd-vconsole-setup.service also takes the lock to avoid being interrupted. We open a new fd
         * that will be closed automatically, and operate on it for convenience. */
        lock_fd = lock_dev_console();
        if (ERRNO_IS_NEG_PRIVILEGE(lock_fd))
                log_debug_errno(lock_fd, "No privileges to lock /dev/console, proceeding without lock: %m");
        else if (ERRNO_IS_NEG_DEVICE_ABSENT(lock_fd))
                log_debug_errno(lock_fd, "Device /dev/console does not exist, proceeding without lock: %m");
        else if (lock_fd < 0)
                log_warning_errno(lock_fd, "Failed to lock /dev/console, proceeding without lock: %m");
 
        if (context->tty_reset)
                (void) terminal_reset_defensive(
                                fd,
                                TERMINAL_RESET_SWITCH_TO_TEXT |
                                (exec_context_shall_ansi_seq_reset(context) ? TERMINAL_RESET_FORCE_ANSI_SEQ : TERMINAL_RESET_AVOID_ANSI_SEQ));
 
        r = exec_context_apply_tty_size(context, fd, fd, path);
        if (r < 0)
                log_debug_errno(r, "Failed to configure TTY dimensions, ignoring: %m");
 
        if (!sd_id128_is_null(invocation_id) && exec_context_shall_ansi_seq_reset(context)) {
                sd_id128_t context_id;
 
                r = osc_context_id_from_invocation_id(invocation_id, &context_id);
                if (r < 0)
                        log_debug_errno(r, "Failed to derive context ID from invocation ID, ignoring: %m");
                else {
                        _cleanup_free_ char *seq = NULL;
 
                        r = osc_context_close(context_id, &seq);
                        if (r < 0)
                                log_debug_errno(r, "Failed to acquire OSC close sequence, ignoring: %m");
                        else
                                (void) loop_write(fd, seq, SIZE_MAX);
                }
        }
 
        if (context->tty_vhangup)
                (void) terminal_vhangup_fd(fd);
 
        /* We don't need the fd anymore now, and it potentially points to a hungup TTY anyway, let's close it
         * hence. */
        _fd = safe_close(_fd);
 
        if (context->tty_vt_disallocate && path)
                (void) vt_disallocate(path);
}
 
bool exec_needs_network_namespace(const ExecContext *context) {
        assert(context);
 
        return context->private_network || context->network_namespace_path;
}
 
static bool exec_needs_ephemeral(const ExecContext *context) {
        return (context->root_image || context->root_directory) && context->root_ephemeral;
}
 
bool exec_needs_ipc_namespace(const ExecContext *context) {
        assert(context);
 
        return context->private_ipc || context->ipc_namespace_path;
}
 
static bool needs_cgroup_namespace(ProtectControlGroups i) {
        return IN_SET(i, PROTECT_CONTROL_GROUPS_PRIVATE, PROTECT_CONTROL_GROUPS_STRICT);
}
 
ProtectControlGroups exec_get_protect_control_groups(const ExecContext *context) {
        assert(context);
 
        /* If cgroup namespace is configured via ProtectControlGroups=private or strict but we can't actually
         * use cgroup namespace, we ignore the setting and do not unshare the namespace.
         * ProtectControlGroups=private and strict get downgraded to no and yes respectively. This ensures
         * that strict always gets a read-only mount of /sys/fs/cgroup/. */
        if (needs_cgroup_namespace(context->protect_control_groups) && !namespace_type_supported(NAMESPACE_CGROUP)) {
                if (context->protect_control_groups == PROTECT_CONTROL_GROUPS_PRIVATE)
                        return PROTECT_CONTROL_GROUPS_NO;
                if (context->protect_control_groups == PROTECT_CONTROL_GROUPS_STRICT)
                        return PROTECT_CONTROL_GROUPS_YES;
        }
        return context->protect_control_groups;
}
 
bool exec_needs_cgroup_namespace(const ExecContext *context) {
        assert(context);
 
        return needs_cgroup_namespace(exec_get_protect_control_groups(context));
}
 
bool exec_needs_cgroup_mount(const ExecContext *context) {
        assert(context);
 
        return exec_get_protect_control_groups(context) != PROTECT_CONTROL_GROUPS_NO;
}
 
bool exec_is_cgroup_mount_read_only(const ExecContext *context) {
        assert(context);
 
        return IN_SET(exec_get_protect_control_groups(context), PROTECT_CONTROL_GROUPS_YES, PROTECT_CONTROL_GROUPS_STRICT);
}
 
bool exec_needs_pid_namespace(const ExecContext *context, const ExecParameters *params) {
        assert(context);
 
        /* PID namespaces don't really make sense for control processes so let's not use them for those. */
        if (params && FLAGS_SET(params->flags, EXEC_IS_CONTROL))
                return false;
 
        return context->private_pids != PRIVATE_PIDS_NO && namespace_type_supported(NAMESPACE_PID);
}
 
bool exec_needs_mount_namespace(const ExecContext *context, const ExecParameters *params) {
        assert(context);
 
        if (context->root_image ||
            context->root_mstack)
                return true;
 
        if (context->root_directory_as_fd)
                return true;
 
        if (!strv_isempty(context->read_write_paths) ||
            !strv_isempty(context->read_only_paths) ||
            !strv_isempty(context->inaccessible_paths) ||
            !strv_isempty(context->exec_paths) ||
            !strv_isempty(context->no_exec_paths))
                return true;
 
        if (context->n_bind_mounts > 0)
                return true;
 
        if (context->n_temporary_filesystems > 0)
                return true;
 
        if (context->n_mount_images > 0)
                return true;
 
        if (context->n_extension_images > 0)
                return true;
 
        if (!strv_isempty(context->extension_directories))
                return true;
 
        if (!IN_SET(context->mount_propagation_flag, 0, MS_SHARED))
                return true;
 
        if (context->private_devices ||
            context->private_tmp != PRIVATE_TMP_NO || /* no need to check for private_var_tmp here, private_tmp is never demoted to "no" */
            context->private_mounts > 0 ||
            (context->private_mounts < 0 && exec_needs_network_namespace(context)) ||
            context->protect_system != PROTECT_SYSTEM_NO ||
            context->protect_home != PROTECT_HOME_NO ||
            context->protect_kernel_tunables ||
            context->protect_kernel_modules ||
            context->protect_kernel_logs ||
            exec_needs_cgroup_mount(context) ||
            context->protect_proc != PROTECT_PROC_DEFAULT ||
            context->proc_subset != PROC_SUBSET_ALL ||
            context->private_bpf != PRIVATE_BPF_NO ||
            exec_needs_ipc_namespace(context) ||
            exec_needs_pid_namespace(context, params))
                return true;
 
        if (context->root_directory) {
                if (exec_context_get_effective_mount_apivfs(context))
                        return true;
 
                for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
                        if (params && !params->prefix[t])
                                continue;
 
                        if (context->directories[t].n_items > 0)
                                return true;
                }
        }
 
        if (context->dynamic_user &&
            (context->directories[EXEC_DIRECTORY_STATE].n_items > 0 ||
             context->directories[EXEC_DIRECTORY_CACHE].n_items > 0 ||
             context->directories[EXEC_DIRECTORY_LOGS].n_items > 0))
                return true;
 
        if (exec_context_get_effective_bind_log_sockets(context))
                return true;
 
        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++)
                FOREACH_ARRAY(i, context->directories[t].items, context->directories[t].n_items)
                        if (FLAGS_SET(i->flags, EXEC_DIRECTORY_READ_ONLY))
                                return true;
 
        return false;
}
 
const char* exec_get_private_notify_socket_path(const ExecContext *context, const ExecParameters *params, bool needs_sandboxing) {
        assert(context);
        assert(params);
 
        if (!params->notify_socket)
                return NULL;
 
        if (!needs_sandboxing)
                return NULL;
 
        if (!exec_context_with_rootfs(context))
                return NULL;
 
        if (!exec_context_get_effective_mount_apivfs(context))
                return NULL;
 
        if (!FLAGS_SET(params->flags, EXEC_APPLY_CHROOT))
                return NULL;
 
        return "/run/host/notify";
}
 
int exec_log_level_max_with_exec_params(const ExecContext *context, const ExecParameters *params) {
        assert(params);
 
        if (params->debug_invocation)
                return LOG_DEBUG;
 
        return exec_log_level_max(context);
}
 
int exec_log_level_max(const ExecContext *context) {
        assert(context);
        return context->log_level_max < 0 ? log_get_max_level() : context->log_level_max;
}
 
bool exec_directory_is_private(const ExecContext *context, ExecDirectoryType type) {
        assert(context);
 
        if (!context->dynamic_user)
                return false;
 
        if (!EXEC_DIRECTORY_TYPE_SHALL_CHOWN(type))
                return false;
 
        if (type == EXEC_DIRECTORY_RUNTIME && context->runtime_directory_preserve_mode == EXEC_PRESERVE_NO)
                return false;
 
        return true;
}
 
int exec_params_needs_control_subcgroup(const ExecParameters *params) {
        /* Keep this in sync with exec_params_get_cgroup_path(). */
        return FLAGS_SET(params->flags, EXEC_CGROUP_DELEGATE|EXEC_CONTROL_CGROUP|EXEC_IS_CONTROL);
}
 
int exec_params_get_cgroup_path(
                const ExecParameters *params,
                const CGroupContext *c,
                const char *prefix,
                char **ret) {
 
        const char *subgroup = NULL;
        char *p;
 
        assert(params);
        assert(c);
        assert(ret);
 
        /* If we are called for a unit where cgroup delegation is on, and the payload created its own populated
         * subcgroup (which we expect it to do, after all it asked for delegation), then we cannot place the control
         * processes started after the main unit's process in the unit's main cgroup because it is now an inner one,
         * and inner cgroups may not contain processes. Hence, if delegation is on, and this is a control process,
         * let's use ".control" as subcgroup instead. Note that we do so only for ExecStartPost=, ExecReload=,
         * ExecStop=, ExecStopPost=, i.e. for the commands where the main process is already forked. For ExecStartPre=
         * this is not necessary, the cgroup is still empty. We distinguish these cases with the EXEC_CONTROL_CGROUP
         * flag, which is only passed for the former statements, not for the latter. */
 
        /* Keep this in sync with exec_params_needs_control_subcgroup(). */
        if (FLAGS_SET(params->flags, EXEC_CGROUP_DELEGATE) && (FLAGS_SET(params->flags, EXEC_CONTROL_CGROUP) || c->delegate_subgroup)) {
                if (FLAGS_SET(params->flags, EXEC_IS_CONTROL))
                        subgroup = ".control";
                else
                        subgroup = c->delegate_subgroup;
        }
 
        if (subgroup)
                p = path_join(prefix, subgroup);
        else
                p = strdup(strempty(prefix));
        if (!p)
                return -ENOMEM;
 
        *ret = p;
        return !!subgroup;
}
 
bool exec_context_get_cpu_affinity_from_numa(const ExecContext *c) {
        assert(c);
 
        return c->cpu_affinity_from_numa;
}
 
static void log_command_line(Unit *unit, const char *msg, const char *executable, char **argv) {
        assert(unit);
        assert(msg);
        assert(executable);
 
        if (!DEBUG_LOGGING)
                return;
 
        _cleanup_free_ char *cmdline = quote_command_line(argv, SHELL_ESCAPE_EMPTY);
 
        log_unit_struct(unit, LOG_DEBUG,
                        LOG_ITEM("EXECUTABLE=%s", executable),
                        LOG_UNIT_MESSAGE(unit, "%s: %s", msg, strnull(cmdline)),
                        LOG_UNIT_INVOCATION_ID(unit));
}
 
static int exec_context_load_environment(const Unit *unit, const ExecContext *c, char ***ret);
 
int exec_spawn(
                Unit *unit,
                ExecCommand *command,
                const ExecContext *context,
                ExecParameters *params,
                ExecRuntime *runtime,
                const CGroupContext *cgroup_context,
                PidRef *ret) {
 
        _cleanup_free_ char *subcgroup_path = NULL, *max_log_levels = NULL;
        _cleanup_fdset_free_ FDSet *fdset = NULL;
        _cleanup_fclose_ FILE *f = NULL;
        int r;
 
        assert(unit);
        assert(unit->manager);
        assert(unit->manager->executor_fd >= 0);
        assert(command);
        assert(context);
        assert(params);
        assert(params->fds || (params->n_socket_fds + params->n_stashed_fds == 0 && !params->fd_names));
        assert(params->n_stashed_fds == 0 || FLAGS_SET(params->flags, EXEC_PASS_FDS));
        assert(!params->files_env); /* We fill this field, ensure it comes NULL-initialized to us */
        assert(ret);
 
        LOG_CONTEXT_PUSH_UNIT(unit);
 
        r = exec_context_load_environment(unit, context, &params->files_env);
        if (r < 0)
                return log_unit_error_errno(unit, r, "Failed to load environment files: %m");
 
        /* We won't know the real executable path until we create the mount namespace in the child, but we
           want to log from the parent, so we use the possibly inaccurate path here. */
        log_command_line(unit, "About to execute", command->path, command->argv);
 
        /* We cannot spawn the main service process into the subcgroup as it might need to unshare the cgroup
         * namespace first if one is configured to make sure the root of the cgroup namespace is the service
         * cgroup and not the subcgroup. However, when running control commands on a live service, the
         * commands have to be spawned inside a subcgroup, otherwise we violate the no inner processes rule
         * of cgroupv2 as the main service process might already have enabled controllers by writing to
         * cgroup.subtree_control. */
 
        const char *cgtarget;
        if (exec_params_needs_control_subcgroup(params)) {
                r = exec_params_get_cgroup_path(params, cgroup_context, params->cgroup_path, &subcgroup_path);
                if (r < 0)
                        return log_unit_error_errno(unit, r, "Failed to acquire subcgroup path: %m");
                if (r > 0) {
                        /* If there's a subcgroup, then let's create it here now (the main cgroup was already
                         * realized by the unit logic) */
 
                        r = cg_create(subcgroup_path);
                        if (r < 0)
                                return log_unit_error_errno(unit, r, "Failed to create subcgroup '%s': %m", subcgroup_path);
                }
 
                cgtarget = subcgroup_path;
        } else
                cgtarget = params->cgroup_path;
 
        /* In order to avoid copy-on-write traps and OOM-kills when pid1's memory.current is above the
         * child's memory.max, serialize all the state needed to start the unit, and pass it to the
         * systemd-executor binary. clone() with CLONE_VM + CLONE_VFORK will pause the parent until the exec
         * and ensure all memory is shared. The child immediately execs the new binary so the delay should
         * be minimal. If glibc 2.39 is available pidfd_spawn() is used in order to get a race-free pid fd
         * and to clone directly into the target cgroup (if we booted with cgroupv2). */
 
        r = open_serialization_file("sd-executor-state", &f);
        if (r < 0)
                return log_unit_error_errno(unit, r, "Failed to open serialization stream: %m");
 
        fdset = fdset_new();
        if (!fdset)
                return log_oom();
 
        r = exec_serialize_invocation(f, fdset, context, command, params, runtime, cgroup_context);
        if (r < 0)
                return log_unit_error_errno(unit, r, "Failed to serialize parameters: %m");
 
        r = finish_serialization_file(f);
        if (r < 0)
                return log_unit_error_errno(unit, r, "Failed to finish serialization stream: %m");
 
        r = fd_cloexec(fileno(f), false);
        if (r < 0)
                return log_unit_error_errno(unit, r, "Failed to set O_CLOEXEC on serialization fd: %m");
 
        r = fdset_cloexec(fdset, false);
        if (r < 0)
                return log_unit_error_errno(unit, r, "Failed to set O_CLOEXEC on serialized fds: %m");
 
        /* If LogLevelMax= is specified, then let's use the specified log level at the beginning of the
         * executor process. To achieve that the specified log level is passed as an argument, rather than
         * the one for the manager process. */
        r = log_max_levels_to_string(context->log_level_max >= 0 ? context->log_level_max : log_get_max_level(), &max_log_levels);
        if (r < 0)
                return log_unit_error_errno(unit, r, "Failed to convert max log levels to string: %m");
 
        char serialization_fd_number[DECIMAL_STR_MAX(int)];
        xsprintf(serialization_fd_number, "%i", fileno(f));
 
        _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
        dual_timestamp start_timestamp;
 
        /* Restore the original ambient capability set the manager was started with to pass it to
         * sd-executor. */
        r = capability_ambient_set_apply(unit->manager->saved_ambient_set, /* also_inherit= */ false);
        if (r < 0)
                return log_unit_error_errno(unit, r, "Failed to apply the starting ambient set: %m");
 
        /* Record the start timestamp before we fork so that it is guaranteed to be earlier than the
         * handoff timestamp. */
        dual_timestamp_now(&start_timestamp);
 
        /* The executor binary is pinned, to avoid compatibility problems during upgrades. */
        r = posix_spawn_wrapper(
                        FORMAT_PROC_FD_PATH(unit->manager->executor_fd),
                        STRV_MAKE("systemd-executor",
                                  "--deserialize", serialization_fd_number,
                                  "--log-level", max_log_levels,
                                  "--log-target", log_target_to_string(manager_get_executor_log_target(unit->manager))),
                        environ,
                        cgtarget,
                        &pidref);
 
        /* Drop the ambient set again, so no processes other than sd-executore spawned from the manager inherit it. */
        (void) capability_ambient_set_apply(0, /* also_inherit= */ false);
 
        if (r == -EUCLEAN && cgtarget)
                return log_unit_error_errno(unit, r,
                                            "Failed to spawn process into cgroup '%s', because the cgroup "
                                            "or one of its parents or siblings is in the threaded mode.",
                                            cgtarget);
        if (r < 0)
                return log_unit_error_errno(unit, r, "Failed to spawn executor: %m");
        /* We add the new process to the cgroup both in the child (so that we can be sure that no user code is ever
         * executed outside of the cgroup) and in the parent (so that we can be sure that when we kill the cgroup the
         * process will be killed too). */
        if (r == 0 && cgtarget)
                (void) cg_attach(cgtarget, pidref.pid);
        /* r > 0: Already in the right cgroup thanks to CLONE_INTO_CGROUP */
 
        log_unit_debug(unit, "Forked %s as " PID_FMT " (%s CLONE_INTO_CGROUP)",
                       command->path, pidref.pid, r > 0 ? "via" : "without");
 
        exec_status_start(&command->exec_status, pidref.pid, &start_timestamp);
 
        *ret = TAKE_PIDREF(pidref);
        return 0;
}
 
void exec_context_init(ExecContext *c) {
        assert(c);
 
        /* When initializing a bool member to 'true', make sure to serialize in execute-serialize.c using
         * serialize_bool() instead of serialize_bool_elide(). */
 
        *c = (ExecContext) {
                .umask = 0022,
                .ioprio = IOPRIO_DEFAULT_CLASS_AND_PRIO,
                .cpu_sched_policy = SCHED_OTHER,
                .syslog_priority = LOG_DAEMON|LOG_INFO,
                .syslog_level_prefix = true,
                .ignore_sigpipe = true,
                .timer_slack_nsec = NSEC_INFINITY,
                .personality = PERSONALITY_INVALID,
                .timeout_clean_usec = USEC_INFINITY,
                .capability_bounding_set = CAP_MASK_ALL,
                .restrict_namespaces = NAMESPACE_FLAGS_INITIAL,
                .delegate_namespaces = NAMESPACE_FLAGS_INITIAL,
                .log_level_max = -1,
#if HAVE_SECCOMP
                .syscall_errno = SECCOMP_ERROR_NUMBER_KILL,
#endif
                .tty_rows = UINT_MAX,
                .tty_cols = UINT_MAX,
                .private_mounts = -1,
                .mount_apivfs = -1,
                .bind_log_sockets = -1,
                .memory_ksm = -1,
                .private_var_tmp = _PRIVATE_TMP_INVALID,
                .set_login_environment = -1,
        };
 
        FOREACH_ARRAY(d, c->directories, _EXEC_DIRECTORY_TYPE_MAX)
                d->mode = 0755;
 
        numa_policy_reset(&c->numa_policy);
 
        assert_cc(NAMESPACE_FLAGS_INITIAL != NAMESPACE_FLAGS_ALL);
}
 
void exec_context_done(ExecContext *c) {
        assert(c);
 
        c->environment = strv_free(c->environment);
        c->environment_files = strv_free(c->environment_files);
        c->pass_environment = strv_free(c->pass_environment);
        c->unset_environment = strv_free(c->unset_environment);
 
        rlimit_free_all(c->rlimit);
 
        for (size_t l = 0; l < 3; l++) {
                c->stdio_fdname[l] = mfree(c->stdio_fdname[l]);
                c->stdio_file[l] = mfree(c->stdio_file[l]);
        }
 
        c->working_directory = mfree(c->working_directory);
        c->root_directory = mfree(c->root_directory);
        c->root_image = mfree(c->root_image);
        c->root_image_options = mount_options_free_all(c->root_image_options);
        iovec_done(&c->root_hash);
        c->root_hash_path = mfree(c->root_hash_path);
        iovec_done(&c->root_hash_sig);
        c->root_hash_sig_path = mfree(c->root_hash_sig_path);
        c->root_verity = mfree(c->root_verity);
        c->root_mstack = mfree(c->root_mstack);
        c->tty_path = mfree(c->tty_path);
        c->syslog_identifier = mfree(c->syslog_identifier);
        c->user = mfree(c->user);
        c->group = mfree(c->group);
 
        c->supplementary_groups = strv_free(c->supplementary_groups);
 
        c->pam_name = mfree(c->pam_name);
 
        c->read_only_paths = strv_free(c->read_only_paths);
        c->read_write_paths = strv_free(c->read_write_paths);
        c->inaccessible_paths = strv_free(c->inaccessible_paths);
        c->exec_paths = strv_free(c->exec_paths);
        c->no_exec_paths = strv_free(c->no_exec_paths);
        c->exec_search_path = strv_free(c->exec_search_path);
 
        bind_mount_free_many(c->bind_mounts, c->n_bind_mounts);
        c->bind_mounts = NULL;
        c->n_bind_mounts = 0;
        mount_image_free_array(c->mount_images, c->n_mount_images);
        c->mount_images = NULL;
        c->n_mount_images = 0;
        mount_image_free_array(c->extension_images, c->n_extension_images);
        c->extension_images = NULL;
        c->n_extension_images = 0;
        c->extension_directories = strv_free(c->extension_directories);
        temporary_filesystem_free_many(c->temporary_filesystems, c->n_temporary_filesystems);
        c->temporary_filesystems = NULL;
        c->n_temporary_filesystems = 0;
 
        cpu_set_done(&c->cpu_set);
        numa_policy_reset(&c->numa_policy);
 
        c->utmp_id = mfree(c->utmp_id);
        c->selinux_context = mfree(c->selinux_context);
        c->apparmor_profile = mfree(c->apparmor_profile);
        c->smack_process_label = mfree(c->smack_process_label);
 
        c->restrict_filesystems = set_free(c->restrict_filesystems);
 
        c->syscall_filter = hashmap_free(c->syscall_filter);
        c->syscall_archs = set_free(c->syscall_archs);
        c->syscall_log = hashmap_free(c->syscall_log);
        c->address_families = set_free(c->address_families);
 
        FOREACH_ARRAY(d, c->directories, _EXEC_DIRECTORY_TYPE_MAX)
                exec_directory_done(d);
 
        c->log_level_max = -1;
 
        exec_context_free_log_extra_fields(c);
        c->log_filter_allowed_patterns = set_free(c->log_filter_allowed_patterns);
        c->log_filter_denied_patterns = set_free(c->log_filter_denied_patterns);
 
        c->log_ratelimit = (RateLimit) {};
 
        c->stdin_data = mfree(c->stdin_data);
        c->stdin_data_size = 0;
 
        c->user_namespace_path = mfree(c->user_namespace_path);
        c->network_namespace_path = mfree(c->network_namespace_path);
        c->ipc_namespace_path = mfree(c->ipc_namespace_path);
 
        c->log_namespace = mfree(c->log_namespace);
 
        c->load_credentials = hashmap_free(c->load_credentials);
        c->set_credentials = hashmap_free(c->set_credentials);
        c->import_credentials = ordered_set_free(c->import_credentials);
 
        c->root_image_policy = image_policy_free(c->root_image_policy);
        c->mount_image_policy = image_policy_free(c->mount_image_policy);
        c->extension_image_policy = image_policy_free(c->extension_image_policy);
 
        c->private_hostname = mfree(c->private_hostname);
}
 
int exec_context_apply_environment(
                Unit *u,
                ExecContext *c,
                char **env,
                UnitWriteFlags flags) {
 
        assert(u);
        assert(c);
 
        if (strv_length(env) > ENVIRONMENT_ASSIGNMENTS_MAX)
                return -E2BIG;
        if (!strv_env_is_valid(env))
                return -EINVAL;
 
        if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
                if (strv_isempty(env)) {
                        c->environment = strv_free(c->environment);
                        unit_write_setting(u, flags, "Environment", "Environment=");
                } else {
                        _cleanup_free_ char *joined = unit_concat_strv(env, UNIT_ESCAPE_SPECIFIERS|UNIT_ESCAPE_C);
                        if (!joined)
                                return -ENOMEM;
 
                        char **e = strv_env_merge(c->environment, env);
                        if (!e)
                                return -ENOMEM;
 
                        strv_free_and_replace(c->environment, e);
                        unit_write_settingf(u, flags, "Environment", "Environment=%s", joined);
                }
        }
 
        return 0;
}
 
int exec_context_apply_set_credential(
                Unit *u,
                ExecContext *c,
                const char *id,
                const void *data,
                size_t size,
                bool encrypted,
                UnitWriteFlags flags,
                const char **reterr_message) {
 
        int r;
 
        assert(u);
        assert(c);
        assert(id);
        assert(data || size == 0);
 
        if (!credential_name_valid(id)) {
                if (reterr_message)
                        *reterr_message = "Credential ID is invalid";
                return -EINVAL;
        }
 
        if (UNIT_WRITE_FLAGS_NOOP(flags))
                return 0;
 
        _cleanup_free_ void *copy = memdup(data, size);
        if (!copy)
                return -ENOMEM;
 
        _cleanup_free_ char *escaped_id = specifier_escape(id);
        if (!escaped_id)
                return -ENOMEM;
 
        _cleanup_free_ char *escaped_value = cescape_length(data, size);
        if (!escaped_value)
                return -ENOMEM;
 
        r = exec_context_put_set_credential(c, id, TAKE_PTR(copy), size, encrypted);
        if (r < 0)
                return r;
 
        const char *name = encrypted ? "SetCredentialEncrypted" : "SetCredential";
        unit_write_settingf(u, flags, name, "%s=%s:%s", name, escaped_id, escaped_value);
        return 0;
}
 
int exec_context_destroy_runtime_directory(const ExecContext *c, const char *runtime_prefix) {
        assert(c);
 
        if (!runtime_prefix)
                return 0;
 
        FOREACH_ARRAY(i, c->directories[EXEC_DIRECTORY_RUNTIME].items, c->directories[EXEC_DIRECTORY_RUNTIME].n_items) {
                _cleanup_free_ char *p = NULL;
 
                if (exec_directory_is_private(c, EXEC_DIRECTORY_RUNTIME))
                        p = path_join(runtime_prefix, "private", i->path);
                else
                        p = path_join(runtime_prefix, i->path);
                if (!p)
                        return -ENOMEM;
 
                /* We execute this synchronously, since we need to be sure this is gone when we start the
                 * service next. */
                (void) rm_rf(p, REMOVE_ROOT);
 
                STRV_FOREACH(symlink, i->symlinks) {
                        _cleanup_free_ char *symlink_abs = NULL;
 
                        if (exec_directory_is_private(c, EXEC_DIRECTORY_RUNTIME))
                                symlink_abs = path_join(runtime_prefix, "private", *symlink);
                        else
                                symlink_abs = path_join(runtime_prefix, *symlink);
                        if (!symlink_abs)
                                return -ENOMEM;
 
                        (void) unlink(symlink_abs);
                }
        }
 
        return 0;
}
 
int exec_context_destroy_mount_ns_dir(Unit *u) {
        _cleanup_free_ char *p = NULL;
 
        if (!u || !MANAGER_IS_SYSTEM(u->manager))
                return 0;
 
        p = path_join("/run/systemd/propagate/", u->id);
        if (!p)
                return -ENOMEM;
 
        /* This is only filled transiently (see mount_in_namespace()), should be empty or even non-existent. */
        if (rmdir(p) < 0 && errno != ENOENT)
                log_unit_debug_errno(u, errno, "Unable to remove propagation dir '%s', ignoring: %m", p);
 
        return 0;
}
 
void exec_command_done(ExecCommand *c) {
        assert(c);
 
        c->path = mfree(c->path);
        c->argv = strv_free(c->argv);
}
 
void exec_command_done_array(ExecCommand *c, size_t n) {
        FOREACH_ARRAY(i, c, n)
                exec_command_done(i);
}
 
ExecCommand* exec_command_free(ExecCommand *c) {
        if (!c)
                return NULL;
 
        exec_command_done(c);
        return mfree(c);
}
 
ExecCommand* exec_command_free_list(ExecCommand *c) {
        ExecCommand *i;
 
        while ((i = LIST_POP(command, c)))
                exec_command_free(i);
 
        return NULL;
}
 
void exec_command_free_array(ExecCommand **c, size_t n) {
        FOREACH_ARRAY(i, c, n)
                *i = exec_command_free_list(*i);
}
 
void exec_command_reset_status_array(ExecCommand *c, size_t n) {
        FOREACH_ARRAY(i, c, n)
                exec_status_reset(&i->exec_status);
}
 
void exec_command_reset_status_list_array(ExecCommand **c, size_t n) {
        FOREACH_ARRAY(i, c, n)
                LIST_FOREACH(command, z, *i)
                        exec_status_reset(&z->exec_status);
}
 
typedef struct InvalidEnvInfo {
        const Unit *unit;
        const char *path;
} InvalidEnvInfo;
 
static void invalid_env(const char *p, void *userdata) {
        InvalidEnvInfo *info = userdata;
 
        log_unit_error(info->unit, "Ignoring invalid environment assignment '%s': %s", p, info->path);
}
 
const char* exec_context_fdname(const ExecContext *c, int fd_index) {
        assert(c);
 
        switch (fd_index) {
 
        case STDIN_FILENO:
                if (c->std_input != EXEC_INPUT_NAMED_FD)
                        return NULL;
 
                return c->stdio_fdname[STDIN_FILENO] ?: "stdin";
 
        case STDOUT_FILENO:
                if (c->std_output != EXEC_OUTPUT_NAMED_FD)
                        return NULL;
 
                return c->stdio_fdname[STDOUT_FILENO] ?: "stdout";
 
        case STDERR_FILENO:
                if (c->std_error != EXEC_OUTPUT_NAMED_FD)
                        return NULL;
 
                return c->stdio_fdname[STDERR_FILENO] ?: "stderr";
 
        default:
                return NULL;
        }
}
 
static int exec_context_load_environment(const Unit *unit, const ExecContext *c, char ***ret) {
        _cleanup_strv_free_ char **v = NULL;
        int r;
 
        assert(c);
        assert(ret);
 
        STRV_FOREACH(i, c->environment_files) {
                _cleanup_strv_free_ char **paths = NULL;
                bool ignore = false;
                char *fn = *i;
 
                if (fn[0] == '-') {
                        ignore = true;
                        fn++;
                }
 
                if (!path_is_absolute(fn)) {
                        if (ignore)
                                continue;
                        return -EINVAL;
                }