HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/core/unit.c

263,853 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 1de634c975a3311494dacb28ce1bb5e67261717a

Lines 5001–6000 of 7,295

        case KILL_KILL:
                *ret_noteworthy = true;
                return c->final_kill_signal;
 
        case KILL_WATCHDOG:
                *ret_noteworthy = true;
                return c->watchdog_signal;
 
        default:
                assert_not_reached();
        }
}
 
static int unit_kill_context_one(
                Unit *u,
                const PidRef *pidref,
                const char *type,
                bool is_alien,
                int sig,
                bool send_sighup,
                cg_kill_log_func_t log_func) {
 
        int r;
 
        assert(u);
        assert(type);
 
        /* This returns > 0 if it makes sense to wait for SIGCHLD for the process, == 0 if not. */
 
        if (!pidref_is_set(pidref))
                return 0;
 
        if (log_func)
                log_func(pidref, sig, u);
 
        r = pidref_kill_and_sigcont(pidref, sig);
        if (r == -ESRCH)
                return !is_alien;
        if (r < 0) {
                _cleanup_free_ char *comm = NULL;
 
                (void) pidref_get_comm(pidref, &comm);
                return log_unit_warning_errno(u, r, "Failed to kill %s process " PID_FMT " (%s), ignoring: %m", type, pidref->pid, strna(comm));
        }
 
        if (send_sighup)
                (void) pidref_kill(pidref, SIGHUP);
 
        return !is_alien;
}
 
typedef struct PidsMaxRestore {
        const char *cgroup_path;
        uint64_t max;
        Unit *unit;
} PidsMaxRestore;
 
static void pids_max_restore(PidsMaxRestore *p) {
        int r;
 
        assert(p);
        assert(p->unit);
 
        if (!p->cgroup_path)
                return;
 
        char value[DECIMAL_STR_MAX(uint64_t) + 1] = "max";
        if (p->max != CGROUP_LIMIT_MAX)
                xsprintf(value, "%" PRIu64, p->max);
 
        r = cg_set_attribute(p->cgroup_path, "pids.max", value);
        if (r < 0)
                log_unit_warning_errno(p->unit,
                                       r,
                                       "Failed to restore pids.max to %s for control group %s, ignoring: %m",
                                       value, empty_to_root(p->cgroup_path));
 
        p->cgroup_path = NULL;
}
 
int unit_kill_context(Unit *u, KillOperation k) {
        bool wait_for_exit = false, send_sighup;
        cg_kill_log_func_t log_func = NULL;
        int sig, r;
 
        assert(u);
 
        /* Kill the processes belonging to this unit, in preparation for shutting the unit down.  Returns > 0
         * if we killed something worth waiting for, 0 otherwise. Do not confuse with unit_kill_common()
         * which is used for user-requested killing of unit processes. */
 
        KillContext *c = unit_get_kill_context(u);
        if (!c || c->kill_mode == KILL_NONE)
                return 0;
 
        bool noteworthy;
        sig = operation_to_signal(c, k, &noteworthy);
        if (noteworthy)
                log_func = log_kill;
 
        send_sighup =
                c->send_sighup &&
                IN_SET(k, KILL_TERMINATE, KILL_TERMINATE_AND_LOG) &&
                sig != SIGHUP;
 
        bool is_alien;
        PidRef *main_pid = unit_main_pid_full(u, &is_alien);
        r = unit_kill_context_one(u, main_pid, "main", is_alien, sig, send_sighup, log_func);
        wait_for_exit = wait_for_exit || r > 0;
 
        r = unit_kill_context_one(u, unit_control_pid(u), "control", /* is_alien= */ false, sig, send_sighup, log_func);
        wait_for_exit = wait_for_exit || r > 0;
 
        CGroupRuntime *crt = unit_get_cgroup_runtime(u);
        if (crt && crt->cgroup_path &&
            (c->kill_mode == KILL_CONTROL_GROUP || (c->kill_mode == KILL_MIXED && k == KILL_KILL))) {
                _cleanup_(pids_max_restore) PidsMaxRestore state = {
                        .unit = u,
                };
                _cleanup_set_free_ Set *pid_set = NULL;
 
                /* Stop more processes from being spawned when zapping the cgroup. Restore previous state
                 * before returning. */
                if (sig == SIGKILL) {
                        r = cg_get_attribute_as_uint64(crt->cgroup_path, "pids.max", &state.max);
                        if (r < 0)
                                log_unit_warning_errno(u,
                                                       r,
                                                       "Failed to read pids.max for control group %s, ignoring: %m",
                                                       empty_to_root(crt->cgroup_path));
                        else {
                                r = cg_set_attribute(crt->cgroup_path, "pids.max", "0");
                                if (r < 0)
                                        log_unit_warning_errno(u,
                                                               r,
                                                               "Failed to set pids.max to 0 for control group %s, ignoring: %m",
                                                               empty_to_root(crt->cgroup_path));
                                else
                                        state.cgroup_path = crt->cgroup_path;
                        }
                }
 
                /* Exclude the main/control pids from being killed via the cgroup */
                r = unit_pid_set(u, &pid_set);
                if (r < 0)
                        return r;
 
                r = cg_kill_recursive(
                                crt->cgroup_path,
                                sig,
                                CGROUP_SIGCONT|CGROUP_IGNORE_SELF,
                                pid_set,
                                log_func, u);
                if (r < 0) {
                        if (!IN_SET(r, -EAGAIN, -ESRCH, -ENOENT))
                                log_unit_warning_errno(u, r, "Failed to kill control group %s, ignoring: %m", empty_to_root(crt->cgroup_path));
 
                } else if (r > 0) {
 
                        wait_for_exit = true;
 
                        if (send_sighup) {
                                r = unit_pid_set(u, &pid_set);
                                if (r < 0)
                                        return r;
 
                                (void) cg_kill_recursive(
                                                crt->cgroup_path,
                                                SIGHUP,
                                                CGROUP_IGNORE_SELF,
                                                pid_set,
                                                /* log_kill= */ NULL,
                                                /* userdata= */ NULL);
                        }
                }
        }
 
        return wait_for_exit;
}
 
int unit_add_mounts_for(Unit *u, const char *path, UnitDependencyMask mask, UnitMountDependencyType type) {
        Hashmap **unit_map, **manager_map;
        int r;
 
        assert(u);
        assert(path);
        assert(type >= 0 && type < _UNIT_MOUNT_DEPENDENCY_TYPE_MAX);
 
        unit_map = &u->mounts_for[type];
        manager_map = &u->manager->units_needing_mounts_for[type];
 
        /* Registers a unit for requiring a certain path and all its prefixes. We keep a hashtable of these
         * paths in the unit (from the path to the UnitDependencyInfo structure indicating how to the
         * dependency came to be). However, we build a prefix table for all possible prefixes so that new
         * appearing mount units can easily determine which units to make themselves a dependency of. */
 
        if (!path_is_absolute(path))
                return -EINVAL;
 
        if (hashmap_contains(*unit_map, path)) /* Exit quickly if the path is already covered. */
                return 0;
 
        if (!unit_type_supported(UNIT_MOUNT)) {
                log_once(LOG_NOTICE, "Mount unit not supported, skipping *MountsFor= dependencies.");
                return 0;
        }
 
        /* Use the canonical form of the path as the stored key. We call path_is_normalized()
         * only after simplification, since path_is_normalized() rejects paths with '.'.
         * path_is_normalized() also verifies that the path fits in PATH_MAX. */
        _cleanup_free_ char *p = NULL;
        r = path_simplify_alloc(path, &p);
        if (r < 0)
                return r;
        path = p;
 
        if (!path_is_normalized(path))
                return -EPERM;
 
        UnitDependencyInfo di = {
                .origin_mask = mask
        };
 
        r = hashmap_ensure_put(unit_map, &path_hash_ops, p, di.data);
        if (r < 0)
                return r;
        assert(r > 0);
        TAKE_PTR(p); /* path remains a valid pointer to the string stored in the hashmap */
 
        char prefix[strlen(path) + 1];
        PATH_FOREACH_PREFIX_MORE(prefix, path) {
                Set *x;
 
                x = hashmap_get(*manager_map, prefix);
                if (!x) {
                        _cleanup_free_ char *q = NULL;
 
                        r = hashmap_ensure_allocated(manager_map, &path_hash_ops);
                        if (r < 0)
                                return r;
 
                        q = strdup(prefix);
                        if (!q)
                                return -ENOMEM;
 
                        x = set_new(NULL);
                        if (!x)
                                return -ENOMEM;
 
                        r = hashmap_put(*manager_map, q, x);
                        if (r < 0) {
                                set_free(x);
                                return r;
                        }
                        q = NULL;
                }
 
                r = set_put(x, u);
                if (r < 0)
                        return r;
        }
 
        return 0;
}
 
int unit_setup_exec_runtime(Unit *u) {
        _cleanup_(exec_shared_runtime_unrefp) ExecSharedRuntime *esr = NULL;
        _cleanup_(dynamic_creds_unrefp) DynamicCreds *dcreds = NULL;
        _cleanup_set_free_ Set *units = NULL;
        ExecRuntime **rt;
        ExecContext *ec;
        size_t offset;
        Unit *other;
        int r;
 
        offset = UNIT_VTABLE(u)->exec_runtime_offset;
        assert(offset > 0);
 
        /* Check if there already is an ExecRuntime for this unit? */
        rt = (ExecRuntime**) ((uint8_t*) u + offset);
        if (*rt)
                return 0;
 
        ec = ASSERT_PTR(unit_get_exec_context(u));
 
        r = unit_get_transitive_dependency_set(u, UNIT_ATOM_JOINS_NAMESPACE_OF, &units);
        if (r < 0)
                return r;
 
        /* Try to get it from somebody else */
        SET_FOREACH(other, units) {
                r = exec_shared_runtime_acquire(u->manager, NULL, other->id, false, &esr);
                if (r < 0)
                        return r;
                if (r > 0)
                        break;
        }
 
        if (!esr) {
                r = exec_shared_runtime_acquire(u->manager, ec, u->id, true, &esr);
                if (r < 0)
                        return r;
        }
 
        if (ec->dynamic_user) {
                r = dynamic_creds_make(u->manager, ec->user, ec->group, &dcreds);
                if (r < 0)
                        return r;
        }
 
        r = exec_runtime_make(u, ec, esr, dcreds, rt);
        if (r < 0)
                return r;
 
        TAKE_PTR(esr);
        TAKE_PTR(dcreds);
 
        return r;
}
 
CGroupRuntime* unit_setup_cgroup_runtime(Unit *u) {
        assert(u);
        assert(UNIT_HAS_CGROUP_CONTEXT(u));
 
        size_t offset = UNIT_VTABLE(u)->cgroup_runtime_offset;
        assert(offset > 0);
 
        CGroupRuntime **rt = (CGroupRuntime**) ((uint8_t*) u + offset);
        if (*rt)
                return *rt;
 
        return (*rt = cgroup_runtime_new());
}
 
bool unit_type_supported(UnitType t) {
        static int8_t cache[_UNIT_TYPE_MAX] = {}; /* -1: disabled, 1: enabled: 0: don't know */
        int r;
 
        assert(t >= 0 && t < _UNIT_TYPE_MAX);
 
        if (cache[t] == 0) {
                char *e;
 
                e = strjoina("SYSTEMD_SUPPORT_", unit_type_to_string(t));
 
                r = getenv_bool(ascii_strupper(e));
                if (r < 0 && r != -ENXIO)
                        log_debug_errno(r, "Failed to parse $%s, ignoring: %m", e);
 
                cache[t] = r == 0 ? -1 : 1;
        }
        if (cache[t] < 0)
                return false;
 
        if (!unit_vtable[t]->supported)
                return true;
 
        return unit_vtable[t]->supported();
}
 
void unit_warn_if_dir_nonempty(Unit *u, const char* where) {
        int r;
 
        assert(u);
        assert(where);
 
        if (!unit_log_level_test(u, LOG_NOTICE))
                return;
 
        r = dir_is_empty(where, /* ignore_hidden_or_backup= */ false);
        if (r > 0 || r == -ENOTDIR)
                return;
        if (r < 0) {
                log_unit_warning_errno(u, r, "Failed to check directory %s: %m", where);
                return;
        }
 
        log_unit_struct(u, LOG_NOTICE,
                        LOG_MESSAGE_ID(SD_MESSAGE_OVERMOUNTING_STR),
                        LOG_UNIT_INVOCATION_ID(u),
                        LOG_UNIT_MESSAGE(u, "Directory %s to mount over is not empty, mounting anyway.", where),
                        LOG_ITEM("WHERE=%s", where));
}
 
int unit_log_noncanonical_mount_path(Unit *u, const char *where) {
        assert(u);
        assert(where);
 
        /* No need to mention "." or "..", they would already have been rejected by unit_name_from_path() */
        log_unit_struct(u, LOG_ERR,
                        LOG_MESSAGE_ID(SD_MESSAGE_NON_CANONICAL_MOUNT_STR),
                        LOG_UNIT_INVOCATION_ID(u),
                        LOG_UNIT_MESSAGE(u, "Mount path %s is not canonical (contains a symlink).", where),
                        LOG_ITEM("WHERE=%s", where));
 
        return -ELOOP;
}
 
int unit_fail_if_noncanonical_mount_path(Unit *u, const char* where) {
        int r;
 
        assert(u);
        assert(where);
 
        _cleanup_free_ char *canonical_where = NULL;
        r = chase(where, /* root= */ NULL, CHASE_NONEXISTENT, &canonical_where, /* ret_fd= */ NULL);
        if (r < 0) {
                log_unit_debug_errno(u, r, "Failed to check %s for symlinks, ignoring: %m", where);
                return 0;
        }
 
        /* We will happily ignore a trailing slash (or any redundant slashes) */
        if (path_equal(where, canonical_where))
                return 0;
 
        return unit_log_noncanonical_mount_path(u, where);
}
 
bool unit_is_pristine(Unit *u) {
        assert(u);
 
        /* Check if the unit already exists or is already around, in a number of different ways. Note that to
         * cater for unit types such as slice, we are generally fine with units that are marked UNIT_LOADED
         * even though nothing was actually loaded, as those unit types don't require a file on disk.
         *
         * Note that we don't check for drop-ins here, because we allow drop-ins for transient units
         * identically to non-transient units, both unit-specific and hierarchical. E.g. for a-b-c.service:
         * service.d/….conf, a-.service.d/….conf, a-b-.service.d/….conf, a-b-c.service.d/….conf.
         */
 
        return IN_SET(u->load_state, UNIT_NOT_FOUND, UNIT_LOADED) &&
               !u->fragment_path &&
               !u->source_path &&
               !u->job &&
               !u->merged_into;
}
 
PidRef* unit_control_pid(Unit *u) {
        assert(u);
 
        if (UNIT_VTABLE(u)->control_pid)
                return UNIT_VTABLE(u)->control_pid(u);
 
        return NULL;
}
 
PidRef* unit_main_pid_full(Unit *u, bool *ret_is_alien) {
        assert(u);
 
        if (UNIT_VTABLE(u)->main_pid)
                return UNIT_VTABLE(u)->main_pid(u, ret_is_alien);
 
        if (ret_is_alien)
                *ret_is_alien = false;
        return NULL;
}
 
static void unit_modify_user_nft_set(Unit *u, bool add, NFTSetSource source, uint32_t element) {
        int r;
 
        assert(u);
 
        if (!MANAGER_IS_SYSTEM(u->manager))
                return;
 
        CGroupContext *c;
        c = unit_get_cgroup_context(u);
        if (!c)
                return;
 
        FOREACH_ARRAY(nft_set, c->nft_set_context.sets, c->nft_set_context.n_sets) {
                if (nft_set->source != source)
                        continue;
 
                if (!u->manager->nfnl) {
                        r = sd_nfnl_socket_open(&u->manager->nfnl);
                        if (r < 0)
                                return (void) log_once_errno(LOG_WARNING, r, "Failed to open NETLINK_NETFILTER socket, ignoring: %m");
                }
 
                r = nft_set_element_modify_any(u->manager->nfnl, add, nft_set->nfproto, nft_set->table, nft_set->set, &element, sizeof(element));
                if (r < 0)
                        log_warning_errno(r, "Failed to %s NFT set entry: family %s, table %s, set %s, ID %u, ignoring: %m",
                                          add? "add" : "delete", nfproto_to_string(nft_set->nfproto), nft_set->table, nft_set->set, element);
                else
                        log_debug("%s NFT set entry: family %s, table %s, set %s, ID %u",
                                  add? "Added" : "Deleted", nfproto_to_string(nft_set->nfproto), nft_set->table, nft_set->set, element);
        }
}
 
static void unit_unref_uid_internal(
                Unit *u,
                uid_t *ref_uid,
                bool destroy_now,
                void (*_manager_unref_uid)(Manager *m, uid_t uid, bool destroy_now)) {
 
        assert(u);
        assert(ref_uid);
        assert(_manager_unref_uid);
 
        /* Generic implementation of both unit_unref_uid() and unit_unref_gid(), under the assumption that uid_t and
         * gid_t are actually the same time, with the same validity rules.
         *
         * Drops a reference to UID/GID from a unit. */
 
        assert_cc(sizeof(uid_t) == sizeof(gid_t));
        assert_cc(UID_INVALID == (uid_t) GID_INVALID);
 
        if (!uid_is_valid(*ref_uid))
                return;
 
        _manager_unref_uid(u->manager, *ref_uid, destroy_now);
        *ref_uid = UID_INVALID;
}
 
static void unit_unref_uid(Unit *u, bool destroy_now) {
        assert(u);
 
        unit_modify_user_nft_set(u, /* add= */ false, NFT_SET_SOURCE_USER, u->ref_uid);
 
        unit_unref_uid_internal(u, &u->ref_uid, destroy_now, manager_unref_uid);
}
 
static void unit_unref_gid(Unit *u, bool destroy_now) {
        assert(u);
 
        unit_modify_user_nft_set(u, /* add= */ false, NFT_SET_SOURCE_GROUP, u->ref_gid);
 
        unit_unref_uid_internal(u, (uid_t*) &u->ref_gid, destroy_now, manager_unref_gid);
}
 
void unit_unref_uid_gid(Unit *u, bool destroy_now) {
        assert(u);
 
        unit_unref_uid(u, destroy_now);
        unit_unref_gid(u, destroy_now);
}
 
static int unit_ref_uid_internal(
                Unit *u,
                uid_t *ref_uid,
                uid_t uid,
                bool clean_ipc,
                int (*_manager_ref_uid)(Manager *m, uid_t uid, bool clean_ipc)) {
 
        int r;
 
        assert(u);
        assert(ref_uid);
        assert(uid_is_valid(uid));
        assert(_manager_ref_uid);
 
        /* Generic implementation of both unit_ref_uid() and unit_ref_guid(), under the assumption that uid_t and gid_t
         * are actually the same type, and have the same validity rules.
         *
         * Adds a reference on a specific UID/GID to this unit. Each unit referencing the same UID/GID maintains a
         * reference so that we can destroy the UID/GID's IPC resources as soon as this is requested and the counter
         * drops to zero. */
 
        assert_cc(sizeof(uid_t) == sizeof(gid_t));
        assert_cc(UID_INVALID == (uid_t) GID_INVALID);
 
        if (*ref_uid == uid)
                return 0;
 
        if (uid_is_valid(*ref_uid)) /* Already set? */
                return -EBUSY;
 
        r = _manager_ref_uid(u->manager, uid, clean_ipc);
        if (r < 0)
                return r;
 
        *ref_uid = uid;
        return 1;
}
 
static int unit_ref_uid(Unit *u, uid_t uid, bool clean_ipc) {
        return unit_ref_uid_internal(u, &u->ref_uid, uid, clean_ipc, manager_ref_uid);
}
 
static int unit_ref_gid(Unit *u, gid_t gid, bool clean_ipc) {
        return unit_ref_uid_internal(u, (uid_t*) &u->ref_gid, (uid_t) gid, clean_ipc, manager_ref_gid);
}
 
static int unit_ref_uid_gid_internal(Unit *u, uid_t uid, gid_t gid, bool clean_ipc) {
        int r = 0, q = 0;
 
        assert(u);
 
        /* Reference both a UID and a GID in one go. Either references both, or neither. */
 
        if (uid_is_valid(uid)) {
                r = unit_ref_uid(u, uid, clean_ipc);
                if (r < 0)
                        return r;
        }
 
        if (gid_is_valid(gid)) {
                q = unit_ref_gid(u, gid, clean_ipc);
                if (q < 0) {
                        if (r > 0)
                                unit_unref_uid(u, false);
 
                        return q;
                }
        }
 
        return r > 0 || q > 0;
}
 
int unit_ref_uid_gid(Unit *u, uid_t uid, gid_t gid) {
        ExecContext *c;
        int r;
 
        assert(u);
 
        c = unit_get_exec_context(u);
 
        r = unit_ref_uid_gid_internal(u, uid, gid, c ? c->remove_ipc : false);
        if (r < 0)
                return log_unit_warning_errno(u, r, "Couldn't add UID/GID reference to unit, proceeding without: %m");
 
        unit_modify_user_nft_set(u, /* add= */ true, NFT_SET_SOURCE_USER, uid);
        unit_modify_user_nft_set(u, /* add= */ true, NFT_SET_SOURCE_GROUP, gid);
 
        return r;
}
 
void unit_notify_user_lookup(Unit *u, uid_t uid, gid_t gid) {
        int r;
 
        assert(u);
 
        /* This is invoked whenever one of the forked off processes let's us know the UID/GID its user name/group names
         * resolved to. We keep track of which UID/GID is currently assigned in order to be able to destroy its IPC
         * objects when no service references the UID/GID anymore. */
 
        r = unit_ref_uid_gid(u, uid, gid);
        if (r > 0)
                unit_add_to_dbus_queue(u);
}
 
int unit_acquire_invocation_id(Unit *u) {
        sd_id128_t id;
        int r;
 
        assert(u);
 
        r = sd_id128_randomize(&id);
        if (r < 0)
                return log_unit_error_errno(u, r, "Failed to generate invocation ID for unit: %m");
 
        r = unit_set_invocation_id(u, id);
        if (r < 0)
                return log_unit_error_errno(u, r, "Failed to set invocation ID for unit: %m");
 
        unit_add_to_dbus_queue(u);
        return 0;
}
 
int unit_set_exec_params(Unit *u, ExecParameters *p) {
        int r;
 
        assert(u);
        assert(p);
 
        /* Copy parameters from manager */
        r = manager_get_effective_environment(u->manager, &p->environment);
        if (r < 0)
                return r;
 
        p->runtime_scope = u->manager->runtime_scope;
 
        r = strdup_to(&p->confirm_spawn, manager_get_confirm_spawn(u->manager));
        if (r < 0)
                return r;
 
        p->prefix = u->manager->prefix;
        SET_FLAG(p->flags, EXEC_PASS_LOG_UNIT|EXEC_CHOWN_DIRECTORIES, MANAGER_IS_SYSTEM(u->manager));
 
        /* Copy parameters from unit */
        CGroupRuntime *crt = unit_get_cgroup_runtime(u);
        p->cgroup_path = crt ? crt->cgroup_path : NULL;
        SET_FLAG(p->flags, EXEC_CGROUP_DELEGATE, unit_cgroup_delegate(u));
 
        p->received_credentials_directory = u->manager->received_credentials_directory;
        p->received_encrypted_credentials_directory = u->manager->received_encrypted_credentials_directory;
 
        p->shall_confirm_spawn = u->manager->confirm_spawn;
 
        p->fallback_smack_process_label = u->manager->defaults.smack_process_label;
 
        if (u->manager->restrict_fs && p->bpf_restrict_fs_map_fd < 0) {
                int fd = bpf_restrict_fs_map_fd(u);
                if (fd < 0)
                        return fd;
 
                p->bpf_restrict_fs_map_fd = fd;
        }
 
        p->user_lookup_fd = u->manager->user_lookup_fds[1];
        p->handoff_timestamp_fd = u->manager->handoff_timestamp_fds[1];
        if (UNIT_VTABLE(u)->notify_pidref)
                p->pidref_transport_fd = u->manager->pidref_transport_fds[1];
 
        p->cgroup_id = crt ? crt->cgroup_id : 0;
        p->invocation_id = u->invocation_id;
        sd_id128_to_string(p->invocation_id, p->invocation_id_string);
        p->unit_id = strdup(u->id);
        if (!p->unit_id)
                return -ENOMEM;
 
        p->debug_invocation = u->debug_invocation;
 
        return 0;
}
 
int unit_fork_helper_process_full(Unit *u, const char *name, bool into_cgroup, ForkFlags flags, PidRef *ret) {
        CGroupRuntime *crt = NULL;
        int r;
 
        assert(u);
        assert((flags & (FORK_RESET_SIGNALS|FORK_DETACH|FORK_WAIT)) == 0); /* these don't really make sense for manager */
        assert(ret);
 
        /* Forks off a helper process and makes sure it is a member of the unit's cgroup, if configured to
         * do so. Returns == 0 in the child, and > 0 in the parent. The pidref parameter is always filled in
         * with the child's PID reference. */
 
        if (into_cgroup) {
                r = unit_realize_cgroup(u);
                if (r < 0)
                        return r;
 
                crt = unit_get_cgroup_runtime(u);
        }
 
        _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
        r = pidref_safe_fork(name, FORK_REOPEN_LOG|FORK_DEATHSIG_SIGTERM|flags, &pidref);
        if (r < 0)
                return r;
        if (r > 0) {
                *ret = TAKE_PIDREF(pidref);
                return r;
        }
 
        /* Child */
 
        (void) default_signals(SIGNALS_CRASH_HANDLER, SIGNALS_IGNORE);
        (void) ignore_signals(SIGPIPE);
 
        if (crt && crt->cgroup_path) {
                r = cg_attach(crt->cgroup_path, 0);
                if (r < 0) {
                        log_unit_error_errno(u, r, "Failed to join unit cgroup %s: %m", empty_to_root(crt->cgroup_path));
                        _exit(EXIT_CGROUP);
                }
        }
 
        *ret = TAKE_PIDREF(pidref);
        return 0;
}
 
int unit_fork_helper_process(Unit *u, const char *name, bool into_cgroup, PidRef *ret) {
        return unit_fork_helper_process_full(u, name, into_cgroup, /* flags= */ 0, ret);
}
 
int unit_fork_and_watch_rm_rf(Unit *u, char **paths, PidRef *ret_pid) {
        _cleanup_(pidref_done) PidRef pid = PIDREF_NULL;
        int r;
 
        assert(u);
        assert(ret_pid);
 
        r = unit_fork_helper_process(u, "(sd-rmrf)", /* into_cgroup= */ true, &pid);
        if (r < 0)
                return r;
        if (r == 0) {
                int ret = EXIT_SUCCESS;
 
                STRV_FOREACH(i, paths) {
                        r = rm_rf(*i, REMOVE_ROOT|REMOVE_PHYSICAL|REMOVE_MISSING_OK);
                        if (r < 0) {
                                log_error_errno(r, "Failed to remove '%s': %m", *i);
                                ret = EXIT_FAILURE;
                        }
                }
 
                _exit(ret);
        }
 
        r = unit_watch_pidref(u, &pid, /* exclusive= */ true);
        if (r < 0)
                return r;
 
        *ret_pid = TAKE_PIDREF(pid);
        return 0;
}
 
static void unit_update_dependency_mask(Hashmap *deps, Unit *other, UnitDependencyInfo di) {
        assert(deps);
        assert(other);
 
        if (di.origin_mask == 0 && di.destination_mask == 0)
                /* No bit set anymore, let's drop the whole entry */
                assert_se(hashmap_remove(deps, other));
        else
                /* Mask was reduced, let's update the entry */
                assert_se(hashmap_update(deps, other, di.data) == 0);
}
 
void unit_remove_dependencies(Unit *u, UnitDependencyMask mask) {
        Hashmap *deps;
        assert(u);
 
        /* Removes all dependencies u has on other units marked for ownership by 'mask'. */
 
        if (mask == 0)
                return;
 
        HASHMAP_FOREACH(deps, u->dependencies) {
                bool done;
 
                do {
                        UnitDependencyInfo di;
                        Unit *other;
 
                        done = true;
 
                        HASHMAP_FOREACH_KEY(di.data, other, deps) {
                                Hashmap *other_deps;
 
                                if (FLAGS_SET(~mask, di.origin_mask))
                                        continue;
 
                                di.origin_mask &= ~mask;
                                unit_update_dependency_mask(deps, other, di);
 
                                /* We updated the dependency from our unit to the other unit now. But most
                                 * dependencies imply a reverse dependency. Hence, let's delete that one
                                 * too. For that we go through all dependency types on the other unit and
                                 * delete all those which point to us and have the right mask set. */
 
                                HASHMAP_FOREACH(other_deps, other->dependencies) {
                                        UnitDependencyInfo dj;
 
                                        dj.data = hashmap_get(other_deps, u);
                                        if (FLAGS_SET(~mask, dj.destination_mask))
                                                continue;
 
                                        dj.destination_mask &= ~mask;
                                        unit_update_dependency_mask(other_deps, u, dj);
                                }
 
                                unit_add_to_gc_queue(other);
 
                                /* The unit 'other' may not be wanted by the unit 'u'. */
                                unit_submit_to_stop_when_unneeded_queue(other);
 
                                u->dependency_generation++;
                                other->dependency_generation++;
 
                                done = false;
                                break;
                        }
 
                } while (!done);
        }
}
 
static int unit_get_invocation_path(Unit *u, char **ret) {
        char *p;
        int r;
 
        assert(u);
        assert(ret);
 
        if (MANAGER_IS_SYSTEM(u->manager))
                p = strjoin("/run/systemd/units/invocation:", u->id);
        else {
                _cleanup_free_ char *user_path = NULL;
 
                r = xdg_user_runtime_dir("/systemd/units/invocation:", &user_path);
                if (r < 0)
                        return r;
 
                p = strjoin(user_path, u->id);
        }
        if (!p)
                return -ENOMEM;
 
        *ret = p;
        return 0;
}
 
static int unit_export_invocation_id(Unit *u) {
        _cleanup_free_ char *p = NULL;
        int r;
 
        assert(u);
 
        if (u->exported_invocation_id)
                return 0;
 
        if (sd_id128_is_null(u->invocation_id))
                return 0;
 
        r = unit_get_invocation_path(u, &p);
        if (r < 0)
                return log_unit_debug_errno(u, r, "Failed to get invocation path: %m");
 
        r = symlinkat_atomic_full(u->invocation_id_string, AT_FDCWD, p, SYMLINK_LABEL);
        if (r < 0)
                return log_unit_debug_errno(u, r, "Failed to create invocation ID symlink %s: %m", p);
 
        u->exported_invocation_id = true;
        return 0;
}
 
static int unit_export_log_level_max(Unit *u, int log_level_max, bool overwrite) {
        const char *p;
        char buf[2];
        int r;
 
        assert(u);
 
        /* When the debug_invocation logic runs, overwrite will be true as we always want to switch the max
         * log level that the journal applies, and we want to always restore the previous level once done */
 
        if (!overwrite && u->exported_log_level_max)
                return 0;
 
        if (log_level_max < 0)
                return 0;
 
        assert(log_level_max <= 7);
 
        buf[0] = '0' + log_level_max;
        buf[1] = 0;
 
        p = strjoina("/run/systemd/units/log-level-max:", u->id);
        r = symlink_atomic(buf, p);
        if (r < 0)
                return log_unit_debug_errno(u, r, "Failed to create maximum log level symlink %s: %m", p);
 
        u->exported_log_level_max = true;
        return 0;
}
 
static int unit_export_log_extra_fields(Unit *u, const ExecContext *c) {
        int r;
 
        if (u->exported_log_extra_fields)
                return 0;
 
        if (c->n_log_extra_fields <= 0)
                return 0;
 
        assert(c->n_log_extra_fields <= LOG_EXTRA_FIELDS_MAX);
 
        le64_t *sizes = newa(le64_t, c->n_log_extra_fields);
        struct iovec *iovec = newa(struct iovec, c->n_log_extra_fields * 2);
 
        for (size_t i = 0; i < c->n_log_extra_fields; i++) {
                sizes[i] = htole64(c->log_extra_fields[i].iov_len);
 
                iovec[i*2] = IOVEC_MAKE(sizes + i, sizeof(le64_t));
                iovec[i*2+1] = c->log_extra_fields[i];
        }
 
        const char *p = strjoina("/run/systemd/units/log-extra-fields:", u->id);
        char *pattern = strjoina(p, ".XXXXXX");
 
        _cleanup_close_ int fd = mkostemp_safe(pattern);
        if (fd < 0)
                return log_unit_debug_errno(u, fd, "Failed to create extra fields file %s: %m", p);
 
        if (writev(fd, iovec, c->n_log_extra_fields * 2) < 0) {
                r = log_unit_debug_errno(u, errno, "Failed to write extra fields: %m");
                goto fail;
        }
 
        (void) fchmod(fd, 0644);
 
        if (rename(pattern, p) < 0) {
                r = log_unit_debug_errno(u, errno, "Failed to rename extra fields file: %m");
                goto fail;
        }
 
        u->exported_log_extra_fields = true;
        return 0;
 
fail:
        (void) unlink(pattern);
        return r;
}
 
static int unit_export_log_ratelimit_interval(Unit *u, const ExecContext *c) {
        int r;