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 4001–5000 of 7,295

        int r;
 
        assert(u);
        assert(pid_set);
 
        set_clear(*pid_set); /* This updates input. */
 
        /* Exclude the main/control pids from being killed via the cgroup */
 
        PidRef *pid;
        FOREACH_ARGUMENT(pid, unit_main_pid(u), unit_control_pid(u))
                if (pidref_is_set(pid)) {
                        r = set_ensure_put(pid_set, NULL, PID_TO_PTR(pid->pid));
                        if (r < 0)
                                return r;
                }
 
        return 0;
}
 
static int kill_common_log(const PidRef *pid, int signo, void *userdata) {
        _cleanup_free_ char *comm = NULL;
        Unit *u = ASSERT_PTR(userdata);
 
        (void) pidref_get_comm(pid, &comm);
 
        log_unit_info(u, "Sending signal SIG%s to process " PID_FMT " (%s) on client request.",
                      signal_to_string(signo), pid->pid, strna(comm));
 
        return 1;
}
 
static int kill_or_sigqueue(PidRef *pidref, int signo, int code, int value) {
        assert(pidref_is_set(pidref));
        assert(SIGNAL_VALID(signo));
 
        switch (code) {
 
        case SI_USER:
                log_debug("Killing " PID_FMT " with signal SIG%s.", pidref->pid, signal_to_string(signo));
                return pidref_kill(pidref, signo);
 
        case SI_QUEUE:
                log_debug("Enqueuing value %i to " PID_FMT " on signal SIG%s.", value, pidref->pid, signal_to_string(signo));
                return pidref_sigqueue(pidref, signo, value);
 
        default:
                assert_not_reached();
        }
}
 
static int unit_kill_one(
                Unit *u,
                PidRef *pidref,
                const char *type,
                int signo,
                int code,
                int value,
                sd_bus_error *ret_error) {
 
        int r;
 
        assert(u);
        assert(type);
 
        if (!pidref_is_set(pidref))
                return 0;
 
        _cleanup_free_ char *comm = NULL;
        (void) pidref_get_comm(pidref, &comm);
 
        r = kill_or_sigqueue(pidref, signo, code, value);
        if (r == -ESRCH)
                return 0;
        if (r < 0) {
                /* Report this failure both to the logs and to the client */
                if (ret_error)
                        sd_bus_error_set_errnof(
                                        ret_error, r,
                                        "Failed to send signal SIG%s to %s process " PID_FMT " (%s): %m",
                                        signal_to_string(signo), type, pidref->pid, strna(comm));
 
                return log_unit_warning_errno(
                                u, r,
                                "Failed to send signal SIG%s to %s process " PID_FMT " (%s) on client request: %m",
                                signal_to_string(signo), type, pidref->pid, strna(comm));
        }
 
        log_unit_info(u, "Sent signal SIG%s to %s process " PID_FMT " (%s) on client request.",
                      signal_to_string(signo), type, pidref->pid, strna(comm));
        return 1; /* killed */
}
 
int unit_kill(
                Unit *u,
                KillWhom whom,
                const char *subgroup,
                int signo,
                int code,
                int value,
                sd_bus_error *ret_error) {
 
        PidRef *main_pid, *control_pid;
        bool killed = false;
        int ret = 0, r;
 
        /* This is the common implementation for explicit user-requested killing of unit processes, shared by
         * various unit types. Do not confuse with unit_kill_context(), which is what we use when we want to
         * stop a service ourselves. */
 
        assert(u);
        assert(whom >= 0);
        assert(whom < _KILL_WHOM_MAX);
        assert(SIGNAL_VALID(signo));
        assert(IN_SET(code, SI_USER, SI_QUEUE));
 
        if (subgroup) {
                if (!IN_SET(whom, KILL_CGROUP, KILL_CGROUP_FAIL))
                        return sd_bus_error_set(ret_error, SD_BUS_ERROR_NOT_SUPPORTED,
                                                "Killing by subgroup is only supported for 'cgroup' or 'cgroup-kill' modes.");
 
                if (!unit_cgroup_delegate(u))
                        return sd_bus_error_set(ret_error, SD_BUS_ERROR_NOT_SUPPORTED,
                                                "Killing by subgroup is only available for units with control group delegation enabled.");
        }
 
        main_pid = unit_main_pid(u);
        control_pid = unit_control_pid(u);
 
        if (!UNIT_HAS_CGROUP_CONTEXT(u) && !main_pid && !control_pid)
                return sd_bus_error_set(ret_error, SD_BUS_ERROR_NOT_SUPPORTED, "Unit type does not support process killing.");
 
        if (IN_SET(whom, KILL_MAIN, KILL_MAIN_FAIL)) {
                if (!main_pid)
                        return sd_bus_error_setf(ret_error, BUS_ERROR_NO_SUCH_PROCESS, "%s units have no main processes", unit_type_to_string(u->type));
                if (!pidref_is_set(main_pid))
                        return sd_bus_error_set_const(ret_error, BUS_ERROR_NO_SUCH_PROCESS, "No main process to kill");
        }
 
        if (IN_SET(whom, KILL_CONTROL, KILL_CONTROL_FAIL)) {
                if (!control_pid)
                        return sd_bus_error_setf(ret_error, BUS_ERROR_NO_SUCH_PROCESS, "%s units have no control processes", unit_type_to_string(u->type));
                if (!pidref_is_set(control_pid))
                        return sd_bus_error_set_const(ret_error, BUS_ERROR_NO_SUCH_PROCESS, "No control process to kill");
        }
 
        if (IN_SET(whom, KILL_CONTROL, KILL_CONTROL_FAIL, KILL_ALL, KILL_ALL_FAIL)) {
                r = unit_kill_one(u, control_pid, "control", signo, code, value, ret_error);
                RET_GATHER(ret, r);
                killed = killed || r > 0;
        }
 
        if (IN_SET(whom, KILL_MAIN, KILL_MAIN_FAIL, KILL_ALL, KILL_ALL_FAIL)) {
                r = unit_kill_one(u, main_pid, "main", signo, code, value, ret >= 0 ? ret_error : NULL);
                RET_GATHER(ret, r);
                killed = killed || r > 0;
        }
 
        /* Note: if we shall enqueue rather than kill we won't do this via the cgroup mechanism, since it
         * doesn't really make much sense (and given that enqueued values are a relatively expensive
         * resource, and we shouldn't allow us to be subjects for such allocation sprees) */
        if (IN_SET(whom, KILL_ALL, KILL_ALL_FAIL, KILL_CGROUP, KILL_CGROUP_FAIL) && code == SI_USER) {
                CGroupRuntime *crt = unit_get_cgroup_runtime(u);
                if (crt && crt->cgroup_path) {
                        _cleanup_set_free_ Set *pid_set = NULL;
                        _cleanup_free_ char *joined = NULL;
                        const char *p;
 
                        if (empty_or_root(subgroup))
                                p = crt->cgroup_path;
                        else {
                                joined = path_join(crt->cgroup_path, subgroup);
                                if (!joined)
                                        return -ENOMEM;
 
                                p = joined;
                        }
 
                        if (signo == SIGKILL) {
                                r = cg_kill_kernel_sigkill(p, /* ret_n_pids_killed= */ NULL);
                                if (r >= 0) {
                                        killed = true;
                                        log_unit_info(u, "Killed unit cgroup '%s' with SIGKILL on client request.", p);
                                        goto finish;
                                }
                                if (r != -EOPNOTSUPP) {
                                        if (ret >= 0)
                                                sd_bus_error_set_errnof(ret_error, r,
                                                                        "Failed to kill unit cgroup: %m");
                                        RET_GATHER(ret, log_unit_warning_errno(u, r, "Failed to kill unit cgroup '%s': %m", p));
                                        goto finish;
                                }
                                /* Fall back to manual enumeration */
                        } else if (IN_SET(whom, KILL_ALL, KILL_ALL_FAIL)) {
                                /* Exclude the main/control pids from being killed via the cgroup if not
                                 * SIGKILL */
                                r = unit_pid_set(u, &pid_set);
                                if (r < 0)
                                        return log_oom();
                        }
 
                        r = cg_kill_recursive(p, signo, /* flags= */ 0, pid_set, kill_common_log, u);
                        if (r < 0 && !IN_SET(r, -ESRCH, -ENOENT)) {
                                if (ret >= 0)
                                        sd_bus_error_set_errnof(
                                                        ret_error, r,
                                                        "Failed to send signal SIG%s to processes in unit cgroup '%s': %m",
                                                        signal_to_string(signo), p);
 
                                RET_GATHER(ret, log_unit_warning_errno(
                                                        u, r,
                                                        "Failed to send signal SIG%s to processes in unit cgroup '%s' on client request: %m",
                                                        signal_to_string(signo), p));
                        }
                        killed = killed || r > 0;
                }
        }
 
finish:
        /* If the "fail" versions of the operation are requested, then complain if the set of processes we killed is empty */
        if (ret >= 0 && !killed && IN_SET(whom, KILL_ALL_FAIL, KILL_CONTROL_FAIL, KILL_MAIN_FAIL, KILL_CGROUP_FAIL))
                return sd_bus_error_set_const(ret_error, BUS_ERROR_NO_SUCH_PROCESS, "No matching processes to kill");
 
        return ret;
}
 
int unit_following_set(Unit *u, Set **s) {
        assert(u);
        assert(s);
 
        if (UNIT_VTABLE(u)->following_set)
                return UNIT_VTABLE(u)->following_set(u, s);
 
        *s = NULL;
        return 0;
}
 
UnitFileState unit_get_unit_file_state(Unit *u) {
        int r;
 
        assert(u);
 
        if (u->unit_file_state >= 0 || !u->fragment_path)
                return u->unit_file_state;
 
        /* If we know this is a transient unit no need to ask the unit file state for details. Let's bypass
         * the more expensive on-disk check. */
        if (u->transient)
                return (u->unit_file_state = UNIT_FILE_TRANSIENT);
 
        r = unit_file_get_state(
                        u->manager->runtime_scope,
                        /* root_dir= */ NULL,
                        u->id,
                        &u->unit_file_state);
        if (r < 0)
                u->unit_file_state = UNIT_FILE_BAD;
 
        return u->unit_file_state;
}
 
PresetAction unit_get_unit_file_preset(Unit *u) {
        int r;
 
        assert(u);
 
        if (u->unit_file_preset >= 0)
                return u->unit_file_preset;
 
        /* If this is a transient or perpetual unit file it doesn't make much sense to ask the preset
         * database about this, because enabling/disabling makes no sense for either. Hence don't. */
        if (!u->fragment_path || u->transient || u->perpetual)
                return (u->unit_file_preset = -ENOEXEC);
 
        _cleanup_free_ char *bn = NULL;
        r = path_extract_filename(u->fragment_path, &bn);
        if (r < 0)
                return (u->unit_file_preset = r);
        if (r == O_DIRECTORY)
                return (u->unit_file_preset = -EISDIR);
 
        return (u->unit_file_preset = unit_file_query_preset(
                                u->manager->runtime_scope,
                                /* root_dir= */ NULL,
                                bn,
                                /* cached= */ NULL));
}
 
Unit* unit_ref_set(UnitRef *ref, Unit *source, Unit *target) {
        assert(ref);
        assert(source);
        assert(target);
 
        if (ref->target)
                unit_ref_unset(ref);
 
        ref->source = source;
        ref->target = target;
        LIST_PREPEND(refs_by_target, target->refs_by_target, ref);
        return target;
}
 
void unit_ref_unset(UnitRef *ref) {
        assert(ref);
 
        if (!ref->target)
                return;
 
        /* We are about to drop a reference to the unit, make sure the garbage collection has a look at it as it might
         * be unreferenced now. */
        unit_add_to_gc_queue(ref->target);
 
        LIST_REMOVE(refs_by_target, ref->target->refs_by_target, ref);
        ref->source = ref->target = NULL;
}
 
static int user_from_unit_name(Unit *u, char **ret) {
 
        static const uint8_t hash_key[] = {
                0x58, 0x1a, 0xaf, 0xe6, 0x28, 0x58, 0x4e, 0x96,
                0xb4, 0x4e, 0xf5, 0x3b, 0x8c, 0x92, 0x07, 0xec
        };
 
        _cleanup_free_ char *n = NULL;
        int r;
 
        assert(u);
        assert(ret);
 
        r = unit_name_to_prefix(u->id, &n);
        if (r < 0)
                return r;
 
        if (valid_user_group_name(n, 0)) {
                *ret = TAKE_PTR(n);
                return 0;
        }
 
        /* If we can't use the unit name as a user name, then let's hash it and use that */
        if (asprintf(ret, "_du%016" PRIx64, siphash24(n, strlen(n), hash_key)) < 0)
                return -ENOMEM;
 
        return 0;
}
 
static int unit_verify_contexts(const Unit *u) {
        assert(u);
 
        const ExecContext *ec = unit_get_exec_context(u);
        if (!ec)
                return 0;
 
        if (MANAGER_IS_USER(u->manager) && ec->dynamic_user)
                return log_unit_error_errno(u, SYNTHETIC_ERRNO(ENOEXEC), "DynamicUser= enabled for user unit, which is not supported. Refusing.");
 
        if (ec->dynamic_user && ec->working_directory_home)
                return log_unit_error_errno(u, SYNTHETIC_ERRNO(ENOEXEC), "WorkingDirectory=~ is not allowed under DynamicUser=yes. Refusing.");
 
        if (ec->working_directory && path_below_api_vfs(ec->working_directory) &&
            exec_needs_mount_namespace(ec, /* params= */ NULL))
                return log_unit_error_errno(u, SYNTHETIC_ERRNO(ENOEXEC), "WorkingDirectory= may not be below /proc/, /sys/ or /dev/ when using mount namespacing. Refusing.");
 
        if (exec_needs_pid_namespace(ec, /* params= */ NULL) && !UNIT_VTABLE(u)->notify_pidref)
                return log_unit_error_errno(u, SYNTHETIC_ERRNO(ENOEXEC), "PrivatePIDs= setting is only supported for service units. Refusing.");
 
        if ((ec->user || ec->dynamic_user || ec->group || ec->pam_name) && ec->private_users == PRIVATE_USERS_MANAGED)
                return log_unit_error_errno(u, SYNTHETIC_ERRNO(ENOEXEC), "PrivateUsers=managed may not be used in combination with User=/DynamicUser=/Group=/PAMName=. Refusing.");
 
        if (ec->user_namespace_path && ec->private_users != PRIVATE_USERS_NO)
                return log_unit_error_errno(u, SYNTHETIC_ERRNO(ENOEXEC), "PrivateUsers= may not be used with custom UserNamespacePath=. Refusing.");
 
        if (ec->private_pids != PRIVATE_PIDS_NO && ec->pam_name)
                return log_unit_error_errno(u, SYNTHETIC_ERRNO(ENOEXEC), "PAM is not supported under PrivatePIDs=. Refusing.");
 
        const KillContext *kc = unit_get_kill_context(u);
 
        if (ec->pam_name && kc && !IN_SET(kc->kill_mode, KILL_CONTROL_GROUP, KILL_MIXED))
                return log_unit_error_errno(u, SYNTHETIC_ERRNO(ENOEXEC), "Unit has PAM enabled. Kill mode must be set to 'control-group' or 'mixed'. Refusing.");
 
        return 0;
}
 
static PrivateTmp unit_get_private_var_tmp(const Unit *u, const ExecContext *c) {
        assert(u);
        assert(c);
        assert(c->private_tmp >= 0 && c->private_tmp < _PRIVATE_TMP_MAX);
 
        /* Disable disconnected private tmpfs on /var/tmp/ when DefaultDependencies=no and
         * RootImage=/RootDirectory= are not set, as /var/ may be a separate partition.
         * See https://github.com/systemd/systemd/issues/37258. */
 
        /* PrivateTmp=yes/no also enables/disables private tmpfs on /var/tmp/. */
        if (c->private_tmp != PRIVATE_TMP_DISCONNECTED)
                return c->private_tmp;
 
        /* When DefaultDependencies=yes, disconnected tmpfs is also enabled on /var/tmp/, and an explicit
         * dependency to the mount on /var/ will be added in unit_add_exec_dependencies(). */
        if (u->default_dependencies)
                return PRIVATE_TMP_DISCONNECTED;
 
        /* When RootImage=/RootDirectory= is enabled, /var/ should be prepared by the image or directory,
         * hence we can mount a disconnected tmpfs on /var/tmp/. */
        if (exec_context_with_rootfs(c))
                return PRIVATE_TMP_DISCONNECTED;
 
        /* Even if DefaultDependencies=no, enable disconnected tmpfs when
         * RequiresMountsFor=/WantsMountsFor=/var/ is explicitly set. */
        for (UnitMountDependencyType t = 0; t < _UNIT_MOUNT_DEPENDENCY_TYPE_MAX; t++)
                if (hashmap_contains(u->mounts_for[t], "/var/"))
                        return PRIVATE_TMP_DISCONNECTED;
 
        /* Check the same but for After=. */
        Unit *m = manager_get_unit(u->manager, "var.mount");
        if (m && unit_has_dependency(u, UNIT_ATOM_AFTER, m))
                return PRIVATE_TMP_DISCONNECTED;
 
        return PRIVATE_TMP_NO;
}
 
static PrivateTmp unit_get_private_tmp(const Unit *u, const ExecContext *c) {
        assert(u);
        assert(c);
        assert(c->private_tmp >= 0 && c->private_tmp < _PRIVATE_TMP_MAX);
 
        /* Upgrade "PrivateTmp=yes" (a.k.a. 'connected') to 'disconnected' when
         * DefaultDependencies=no and RootImage=/RootDirectory= are not set, as /tmp/ may be a
         * separate partition. See https://github.com/systemd/systemd/issues/28515.
         *
         * Note that the change goes in the opposite direction than unit_get_private_var_tmp()
         * above. For /var/tmp/, we need to disable the setting, because we don't want to create
         * the /var/tmp/ directory if /var/ is a mount point. We don't have this problem with
         * /tmp/ because there is no nesting. */
 
        if (c->private_tmp != PRIVATE_TMP_CONNECTED ||
            u->default_dependencies ||
            exec_context_with_rootfs(c))
                return c->private_tmp;
 
        /* Even if DefaultDependencies=no, honour tmpfs setting when
         * RequiresMountsFor=/WantsMountsFor=/tmp/ is explicitly set. */
        for (UnitMountDependencyType t = 0; t < _UNIT_MOUNT_DEPENDENCY_TYPE_MAX; t++)
                if (hashmap_contains(u->mounts_for[t], "/tmp/"))
                        return c->private_tmp;
 
        /* Check the same but for After=. */
        Unit *m = manager_get_unit(u->manager, "tmp.mount");
        if (!m)
                return c->private_tmp;
 
        if (unit_has_dependency(u, UNIT_ATOM_AFTER, m))
                return c->private_tmp;
 
        return PRIVATE_TMP_DISCONNECTED;
}
 
int unit_patch_contexts(Unit *u) {
        CGroupContext *cc;
        ExecContext *ec;
        int r;
 
        assert(u);
 
        /* Patch in the manager defaults into the exec and cgroup
         * contexts, _after_ the rest of the settings have been
         * initialized */
 
        ec = unit_get_exec_context(u);
        if (ec) {
                /* This only copies in the ones that need memory */
                for (unsigned i = 0; i < _RLIMIT_MAX; i++)
                        if (u->manager->defaults.rlimit[i] && !ec->rlimit[i]) {
                                ec->rlimit[i] = newdup(struct rlimit, u->manager->defaults.rlimit[i], 1);
                                if (!ec->rlimit[i])
                                        return -ENOMEM;
                        }
 
                if (MANAGER_IS_USER(u->manager) && !ec->working_directory) {
                        r = get_home_dir(&ec->working_directory);
                        if (r < 0)
                                return r;
 
                        if (!ec->working_directory_home)
                                /* If home directory is implied by us, allow it to be missing. */
                                ec->working_directory_missing_ok = true;
                }
 
                if (ec->private_devices)
                        ec->capability_bounding_set &= ~((UINT64_C(1) << CAP_MKNOD) | (UINT64_C(1) << CAP_SYS_RAWIO));
 
                if (ec->protect_kernel_modules)
                        ec->capability_bounding_set &= ~(UINT64_C(1) << CAP_SYS_MODULE);
 
                if (ec->protect_kernel_logs)
                        ec->capability_bounding_set &= ~(UINT64_C(1) << CAP_SYSLOG);
 
                if (ec->protect_clock)
                        ec->capability_bounding_set &= ~((UINT64_C(1) << CAP_SYS_TIME) | (UINT64_C(1) << CAP_WAKE_ALARM));
 
                if (ec->dynamic_user) {
                        if (!ec->user) {
                                r = user_from_unit_name(u, &ec->user);
                                if (r < 0)
                                        return r;
                        }
 
                        if (!ec->group) {
                                ec->group = strdup(ec->user);
                                if (!ec->group)
                                        return -ENOMEM;
                        }
 
                        /* If the dynamic user option is on, let's make sure that the unit can't leave its
                         * UID/GID around in the file system or on IPC objects. Hence enforce a strict
                         * sandbox. */
 
                        /* With DynamicUser= we want private directories, so if the user hasn't manually
                         * selected PrivateTmp=, enable it, but to a fully private (disconnected) tmpfs
                         * instance. */
                        if (ec->private_tmp == PRIVATE_TMP_NO)
                                ec->private_tmp = PRIVATE_TMP_DISCONNECTED;
                        ec->remove_ipc = true;
                        ec->protect_system = PROTECT_SYSTEM_STRICT;
                        if (ec->protect_home == PROTECT_HOME_NO)
                                ec->protect_home = PROTECT_HOME_READ_ONLY;
 
                        /* Make sure this service can neither benefit from SUID/SGID binaries nor create
                         * them. */
                        ec->no_new_privileges = true;
                        ec->restrict_suid_sgid = true;
                }
 
                /* Table of possible combinations:
                 *                           /var/tmp          /tmp
                 * PrivateTmp=no             no                no
                 * PrivateTmp=connected      connected         connected,disconnected
                 * PrivateTmp=disconnected   disconnected,no   disconnected
                 */
                ec->private_var_tmp = unit_get_private_var_tmp(u, ec);
                ec->private_tmp = unit_get_private_tmp(u, ec);
 
                FOREACH_ARRAY(d, ec->directories, _EXEC_DIRECTORY_TYPE_MAX)
                        exec_directory_sort(d);
        }
 
        cc = unit_get_cgroup_context(u);
        if (cc && ec) {
 
                if (ec->private_devices &&
                    cc->device_policy == CGROUP_DEVICE_POLICY_AUTO)
                        cc->device_policy = CGROUP_DEVICE_POLICY_CLOSED;
 
                /* Only add these if needed, as they imply that everything else is blocked. */
                if (cgroup_context_has_device_policy(cc)) {
                        if (ec->root_image || ec->mount_images || ec->root_mstack) {
 
                                /* When RootImage= or MountImages= is specified, the following devices are
                                 * touched. For RootMStack= there's the possibility the are touched. */
                                FOREACH_STRING(p, "/dev/loop-control", "/dev/mapper/control") {
                                        r = cgroup_context_add_device_allow(cc, p, CGROUP_DEVICE_READ|CGROUP_DEVICE_WRITE);
                                        if (r < 0)
                                                return r;
                                }
                                FOREACH_STRING(p, "block-loop", "block-blkext", "block-device-mapper") {
                                        r = cgroup_context_add_device_allow(cc, p, CGROUP_DEVICE_READ|CGROUP_DEVICE_WRITE|CGROUP_DEVICE_MKNOD);
                                        if (r < 0)
                                                return r;
                                }
 
                                /* Make sure "block-loop" can be resolved, i.e. make sure "loop" shows up in /proc/devices.
                                * Same for mapper and verity. */
                                FOREACH_STRING(p, "modprobe@loop.service", "modprobe@dm_mod.service", "modprobe@dm_verity.service") {
                                        r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_WANTS, p, true, UNIT_DEPENDENCY_FILE);
                                        if (r < 0)
                                                return r;
                                }
                        }
 
                        if (ec->protect_clock) {
                                r = cgroup_context_add_device_allow(cc, "char-rtc", CGROUP_DEVICE_READ);
                                if (r < 0)
                                        return r;
                        }
                }
        }
 
        return unit_verify_contexts(u);
}
 
ExecContext *unit_get_exec_context(const Unit *u) {
        size_t offset;
        assert(u);
 
        if (u->type < 0)
                return NULL;
 
        offset = UNIT_VTABLE(u)->exec_context_offset;
        if (offset <= 0)
                return NULL;
 
        return (ExecContext*) ((uint8_t*) u + offset);
}
 
KillContext *unit_get_kill_context(const Unit *u) {
        size_t offset;
        assert(u);
 
        if (u->type < 0)
                return NULL;
 
        offset = UNIT_VTABLE(u)->kill_context_offset;
        if (offset <= 0)
                return NULL;
 
        return (KillContext*) ((uint8_t*) u + offset);
}
 
CGroupContext *unit_get_cgroup_context(const Unit *u) {
        size_t offset;
 
        if (u->type < 0)
                return NULL;
 
        offset = UNIT_VTABLE(u)->cgroup_context_offset;
        if (offset <= 0)
                return NULL;
 
        return (CGroupContext*) ((uint8_t*) u + offset);
}
 
ExecRuntime *unit_get_exec_runtime(const Unit *u) {
        size_t offset;
 
        if (u->type < 0)
                return NULL;
 
        offset = UNIT_VTABLE(u)->exec_runtime_offset;
        if (offset <= 0)
                return NULL;
 
        return *(ExecRuntime**) ((uint8_t*) u + offset);
}
 
CGroupRuntime *unit_get_cgroup_runtime(const Unit *u) {
        size_t offset;
 
        if (u->type < 0)
                return NULL;
 
        offset = UNIT_VTABLE(u)->cgroup_runtime_offset;
        if (offset <= 0)
                return NULL;
 
        return *(CGroupRuntime**) ((uint8_t*) u + offset);
}
 
static const char* unit_drop_in_dir(Unit *u, UnitWriteFlags flags) {
        assert(u);
 
        if (UNIT_WRITE_FLAGS_NOOP(flags))
                return NULL;
 
        if (u->transient) /* Redirect drop-ins for transient units always into the transient directory. */
                return u->manager->lookup_paths.transient;
 
        if (flags & UNIT_PERSISTENT)
                return u->manager->lookup_paths.persistent_control;
 
        if (flags & UNIT_RUNTIME)
                return u->manager->lookup_paths.runtime_control;
 
        return NULL;
}
 
const char* unit_escape_setting(const char *s, UnitWriteFlags flags, char **buf) {
        assert(s);
        assert(popcount(flags & (UNIT_ESCAPE_EXEC_SYNTAX_ENV | UNIT_ESCAPE_EXEC_SYNTAX | UNIT_ESCAPE_C)) <= 1);
        assert(buf);
 
        _cleanup_free_ char *t = NULL;
 
        /* Returns a string with any escaping done. If no escaping was necessary, *buf is set to NULL, and
         * the input pointer is returned as-is. If an allocation was needed, the return buffer pointer is
         * written to *buf. This means the return value always contains a properly escaped version, but *buf
         * only contains a pointer if an allocation was made. Callers can use this to optimize memory
         * allocations. */
 
        if (flags & UNIT_ESCAPE_SPECIFIERS) {
                t = specifier_escape(s);
                if (!t)
                        return NULL;
 
                s = t;
        }
 
        /* We either do C-escaping or shell-escaping, to additionally escape characters that we parse for
         * ExecStart= and friends, i.e. '$' and quotes. */
 
        if (flags & (UNIT_ESCAPE_EXEC_SYNTAX_ENV | UNIT_ESCAPE_EXEC_SYNTAX)) {
                char *t2;
 
                if (flags & UNIT_ESCAPE_EXEC_SYNTAX_ENV) {
                        t2 = strreplace(s, "$", "$$");
                        if (!t2)
                                return NULL;
                        free_and_replace(t, t2);
                }
 
                t2 = shell_escape(t ?: s, "\"");
                if (!t2)
                        return NULL;
                free_and_replace(t, t2);
 
                s = t;
 
        } else if (flags & UNIT_ESCAPE_C) {
                char *t2;
 
                t2 = cescape(s);
                if (!t2)
                        return NULL;
                free_and_replace(t, t2);
 
                s = t;
        }
 
        *buf = TAKE_PTR(t);
        return s;
}
 
char* unit_concat_strv(char **l, UnitWriteFlags flags) {
        _cleanup_free_ char *result = NULL;
        size_t n = 0;
 
        /* Takes a list of strings, escapes them, and concatenates them. This may be used to format command
         * lines in a way suitable for ExecStart= stanzas. */
 
        STRV_FOREACH(i, l) {
                _cleanup_free_ char *buf = NULL;
                const char *p;
                size_t a;
                char *q;
 
                p = unit_escape_setting(*i, flags, &buf);
                if (!p)
                        return NULL;
 
                a = (n > 0) + 1 + strlen(p) + 1; /* separating space + " + entry + " */
                if (!GREEDY_REALLOC(result, n + a + 1))
                        return NULL;
 
                q = result + n;
                if (n > 0)
                        *(q++) = ' ';
 
                *(q++) = '"';
                q = stpcpy(q, p);
                *(q++) = '"';
 
                n += a;
        }
 
        if (!GREEDY_REALLOC(result, n + 1))
                return NULL;
 
        result[n] = 0;
 
        return TAKE_PTR(result);
}
 
int unit_write_setting(Unit *u, UnitWriteFlags flags, const char *name, const char *data) {
        _cleanup_free_ char *p = NULL, *q = NULL, *escaped = NULL;
        const char *dir, *wrapped;
        int r;
 
        assert(u);
        assert(name);
        assert(data);
 
        if (UNIT_WRITE_FLAGS_NOOP(flags))
                return 0;
 
        data = unit_escape_setting(data, flags, &escaped);
        if (!data)
                return -ENOMEM;
 
        /* Prefix the section header. If we are writing this out as transient file, then let's suppress this if the
         * previous section header is the same */
 
        if (flags & UNIT_PRIVATE) {
                if (!UNIT_VTABLE(u)->private_section)
                        return -EINVAL;
 
                if (!u->transient_file || u->last_section_private < 0)
                        data = strjoina("[", UNIT_VTABLE(u)->private_section, "]\n", data);
                else if (u->last_section_private == 0)
                        data = strjoina("\n[", UNIT_VTABLE(u)->private_section, "]\n", data);
        } else {
                if (!u->transient_file || u->last_section_private < 0)
                        data = strjoina("[Unit]\n", data);
                else if (u->last_section_private > 0)
                        data = strjoina("\n[Unit]\n", data);
        }
 
        if (u->transient_file) {
                /* When this is a transient unit file in creation, then let's not create a new drop-in,
                 * but instead write to the transient unit file. */
                fputs_with_newline(u->transient_file, data);
 
                /* Remember which section we wrote this entry to */
                u->last_section_private = !!(flags & UNIT_PRIVATE);
                return 0;
        }
 
        dir = unit_drop_in_dir(u, flags);
        if (!dir)
                return -EINVAL;
 
        wrapped = strjoina("# This is a drop-in unit file extension, created via \"systemctl set-property\"\n"
                           "# or an equivalent operation. Do not edit.\n",
                           data,
                           "\n");
 
        r = drop_in_file(dir, u->id, 50, name, &p, &q);
        if (r < 0)
                return r;
 
        (void) mkdir_p_label(p, 0755);
 
        /* Make sure the drop-in dir is registered in our path cache. This way we don't need to stupidly
         * recreate the cache after every drop-in we write. */
        if (u->manager->unit_path_cache) {
                r = set_put_strdup_full(&u->manager->unit_path_cache, &path_hash_ops_free, p);
                if (r < 0)
                        return r;
        }
 
        r = write_string_file(q, wrapped, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC|WRITE_STRING_FILE_LABEL);
        if (r < 0)
                return r;
 
        _cleanup_strv_free_ char **dropins = NULL;
        r = unit_find_dropin_paths(u, /* use_unit_path_cache= */ true, &dropins);
        if (r < 0)
                return r;
        strv_free_and_replace(u->dropin_paths, dropins);
 
        u->dropin_mtime = now(CLOCK_REALTIME);
 
        return 0;
}
 
int unit_write_settingf(Unit *u, UnitWriteFlags flags, const char *name, const char *format, ...) {
        _cleanup_free_ char *p = NULL;
        va_list ap;
        int r;
 
        assert(u);
        assert(name);
        assert(format);
 
        if (UNIT_WRITE_FLAGS_NOOP(flags))
                return 0;
 
        va_start(ap, format);
        r = vasprintf(&p, format, ap);
        va_end(ap);
 
        if (r < 0)
                return -ENOMEM;
 
        return unit_write_setting(u, flags, name, p);
}
 
int unit_make_transient(Unit *u) {
        _cleanup_free_ char *path = NULL;
        FILE *f;
 
        assert(u);
 
        if (!UNIT_VTABLE(u)->can_transient)
                return -EOPNOTSUPP;
 
        (void) mkdir_p_label(u->manager->lookup_paths.transient, 0755);
 
        path = path_join(u->manager->lookup_paths.transient, u->id);
        if (!path)
                return -ENOMEM;
 
        /* Let's open the file we'll write the transient settings into. This file is kept open as long as we are
         * creating the transient, and is closed in unit_load(), as soon as we start loading the file. */
 
        WITH_UMASK(0022) {
                f = fopen(path, "we");
                if (!f)
                        return -errno;
        }
 
        safe_fclose(u->transient_file);
        u->transient_file = f;
 
        free_and_replace(u->fragment_path, path);
 
        u->source_path = mfree(u->source_path);
        u->dropin_paths = strv_free(u->dropin_paths);
        u->fragment_mtime = u->source_mtime = u->dropin_mtime = 0;
 
        u->load_state = UNIT_STUB;
        u->load_error = 0;
        u->transient = true;
 
        unit_add_to_dbus_queue(u);
        unit_add_to_gc_queue(u);
 
        fputs("# This is a transient unit file, created programmatically via the systemd API. Do not edit.\n",
              u->transient_file);
 
        return 0;
}
 
int manager_setup_transient_unit(Manager *m, const char *name, Unit **ret, sd_bus_error *reterr_error) {
        Unit *u;
        int r;
 
        assert(m);
        assert(name);
        assert(ret);
 
        UnitType t = unit_name_to_type(name);
        if (t < 0)
                return sd_bus_error_setf(reterr_error, SD_BUS_ERROR_INVALID_ARGS,
                                         "Invalid unit name or type: %s", name);
 
        if (!unit_vtable[t]->can_transient)
                return sd_bus_error_setf(reterr_error, SD_BUS_ERROR_INVALID_ARGS,
                                         "Unit type %s does not support transient units.",
                                         unit_type_to_string(t));
 
        r = manager_load_unit(m, name, /* path= */ NULL, reterr_error, &u);
        if (r < 0)
                return r;
 
        if (!unit_is_pristine(u))
                return sd_bus_error_setf(reterr_error, BUS_ERROR_UNIT_EXISTS,
                                         "Unit %s was already loaded or has a fragment file.", name);
 
        /* OK, the unit failed to load and is unreferenced, now let's
         * fill in the transient data instead */
        r = unit_make_transient(u);
        if (r < 0)
                return r;
 
        *ret = u;
        return 0;
}
 
static bool ignore_leftover_process(const char *comm) {
        return comm && comm[0] == '('; /* Most likely our own helper process (PAM?), ignore */
}
 
static int log_kill(const PidRef *pid, int sig, void *userdata) {
        const Unit *u = ASSERT_PTR(userdata);
        _cleanup_free_ char *comm = NULL;
 
        assert(pidref_is_set(pid));
 
        (void) pidref_get_comm(pid, &comm);
 
        if (ignore_leftover_process(comm))
                /* Although we didn't log anything, as this callback is used in unit_kill_context we must return 1
                 * here to let the manager know that a process was killed. */
                return 1;
 
        log_unit_notice(u,
                        "Killing process " PID_FMT " (%s) with signal SIG%s.",
                        pid->pid,
                        strna(comm),
                        signal_to_string(sig));
 
        return 1;
}
 
static int operation_to_signal(
                const KillContext *c,
                KillOperation k,
                bool *ret_noteworthy) {
 
        assert(c);
        assert(ret_noteworthy);
 
        switch (k) {
 
        case KILL_TERMINATE:
        case KILL_TERMINATE_AND_LOG:
                *ret_noteworthy = k == KILL_TERMINATE_AND_LOG;
                return c->kill_signal;
 
        case KILL_RESTART:
                *ret_noteworthy = false;
                return restart_kill_signal(c);