HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/basic/cgroup-util.c

52,399 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: f120ac143df121a59d7f7a64724a2feb913781c8

Lines 1–1000 of 1,825

/* SPDX-License-Identifier: LGPL-2.1-or-later */
 
#include <linux/fs.h>
#include <linux/magic.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/xattr.h>
#include <threads.h>
#include <unistd.h>
 
#include "alloc-util.h"
#include "capsule-util.h"
#include "cgroup-util.h"
#include "dirent-util.h"
#include "errno-util.h"
#include "extract-word.h"
#include "fd-util.h"
#include "fileio.h"
#include "format-util.h"
#include "fs-util.h"
#include "log.h"
#include "login-util.h"
#include "parse-util.h"
#include "path-util.h"
#include "pidref.h"
#include "process-util.h"
#include "set.h"
#include "special.h"
#include "stat-util.h"
#include "string-table.h"
#include "string-util.h"
#include "strv.h"
#include "unaligned.h"
#include "unit-name.h"
#include "user-util.h"
#include "xattr-util.h"
 
int cg_is_available(void) {
        struct statfs fs;
 
        if (statfs("/sys/fs/cgroup/", &fs) < 0) {
                if (errno == ENOENT) /* sysfs not mounted? */
                        return false;
 
                return log_debug_errno(errno, "Failed to statfs /sys/fs/cgroup/: %m");
        }
 
        return is_fs_type(&fs, CGROUP2_SUPER_MAGIC);
}
 
int cg_path_open(const char *path) {
        _cleanup_free_ char *fs = NULL;
        int r;
 
        r = cg_get_path(path, /* suffix= */ NULL, &fs);
        if (r < 0)
                return r;
 
        return RET_NERRNO(open(fs, O_DIRECTORY|O_CLOEXEC));
}
 
int cg_cgroupid_open(int cgroupfs_fd, uint64_t id) {
        _cleanup_close_ int fsfd = -EBADF;
 
        if (cgroupfs_fd < 0) {
                fsfd = open("/sys/fs/cgroup", O_CLOEXEC|O_DIRECTORY);
                if (fsfd < 0)
                        return -errno;
 
                cgroupfs_fd = fsfd;
        }
 
        union {
                struct file_handle file_handle;
                uint8_t space[offsetof(struct file_handle, f_handle) + sizeof(uint64_t)];
        } fh = {
                .file_handle.handle_bytes = sizeof(uint64_t),
                .file_handle.handle_type = FILEID_KERNFS,
        };
 
        unaligned_write_ne64(fh.file_handle.f_handle, id);
 
        return RET_NERRNO(open_by_handle_at(cgroupfs_fd, &fh.file_handle, O_DIRECTORY|O_CLOEXEC));
}
 
int cg_path_from_cgroupid(int cgroupfs_fd, uint64_t id, char **ret) {
        _cleanup_close_ int cgfd = -EBADF;
        int r;
 
        cgfd = cg_cgroupid_open(cgroupfs_fd, id);
        if (cgfd < 0)
                return cgfd;
 
        _cleanup_free_ char *path = NULL;
        r = fd_get_path(cgfd, &path);
        if (r < 0)
                return r;
 
        if (!path_startswith(path, "/sys/fs/cgroup/"))
                return -EXDEV; /* recognizable error */
 
        if (ret)
                *ret = TAKE_PTR(path);
        return 0;
}
 
int cg_enumerate_processes(const char *path, FILE **ret) {
        _cleanup_free_ char *fs = NULL;
        FILE *f;
        int r;
 
        assert(ret);
 
        r = cg_get_path(path, "cgroup.procs", &fs);
        if (r < 0)
                return r;
 
        f = fopen(fs, "re");
        if (!f)
                return -errno;
 
        *ret = f;
        return 0;
}
 
int cg_read_pid(FILE *f, pid_t *ret, CGroupFlags flags) {
        unsigned long ul;
 
        /* Note that the cgroup.procs might contain duplicates! See cgroups.txt for details. */
 
        assert(f);
        assert(ret);
 
        /* NB: The kernel returns ENODEV if we tried to read from cgroup.procs of a cgroup that has been
         * removed already. Callers should handle that! */
 
        for (;;) {
                errno = 0;
                if (fscanf(f, "%lu", &ul) != 1) {
 
                        if (feof(f)) {
                                *ret = 0;
                                return 0;
                        }
 
                        return errno_or_else(EIO);
                }
 
                if (ul > PID_T_MAX)
                        return -EIO;
 
                /* In some circumstances (e.g. WSL), cgroups might contain unmappable PIDs from other
                 * contexts. These show up as zeros, and depending on the caller, can either be plain
                 * skipped over, or returned as-is. */
                if (ul == 0 && !FLAGS_SET(flags, CGROUP_DONT_SKIP_UNMAPPED))
                        continue;
 
                *ret = (pid_t) ul;
                return 1;
        }
}
 
int cg_read_pidref(FILE *f, PidRef *ret, CGroupFlags flags) {
        int r;
 
        assert(f);
        assert(ret);
 
        for (;;) {
                pid_t pid;
 
                r = cg_read_pid(f, &pid, flags);
                if (r < 0)
                        return log_debug_errno(r, "Failed to read pid from cgroup item: %m");
                if (r == 0) {
                        *ret = PIDREF_NULL;
                        return 0;
                }
 
                if (pid == 0)
                        return -EREMOTE;
 
                r = pidref_set_pid(ret, pid);
                if (r >= 0)
                        return 1;
                if (r != -ESRCH)
                        return r;
 
                /* ESRCH → gone by now? just skip over it, read the next */
        }
}
 
bool cg_kill_supported(void) {
        static thread_local int supported = -1;
 
        if (supported >= 0)
                return supported;
 
        if (cg_is_available() <= 0)
                return (supported = false);
 
        if (access("/sys/fs/cgroup/init.scope/cgroup.kill", F_OK) >= 0)
                return (supported = true);
        if (errno != ENOENT)
                log_debug_errno(errno, "Failed to check whether cgroup.kill is available, assuming not: %m");
        return (supported = false);
}
 
int cg_enumerate_subgroups(const char *path, DIR **ret) {
        _cleanup_free_ char *fs = NULL;
        DIR *d;
        int r;
 
        assert(ret);
 
        /* This is not recursive! */
 
        r = cg_get_path(path, /* suffix= */ NULL, &fs);
        if (r < 0)
                return r;
 
        d = opendir(fs);
        if (!d)
                return -errno;
 
        *ret = d;
        return 0;
}
 
int cg_read_subgroup(DIR *d, char **ret) {
        assert(d);
        assert(ret);
 
        FOREACH_DIRENT_ALL(de, d, return -errno) {
                if (de->d_type != DT_DIR)
                        continue;
 
                if (dot_or_dot_dot(de->d_name))
                        continue;
 
                return strdup_to_full(ret, de->d_name);
        }
 
        *ret = NULL;
        return 0;
}
 
int cg_kill(
                const char *path,
                int sig,
                CGroupFlags flags,
                Set *killed_pids,
                cg_kill_log_func_t log_kill,
                void *userdata) {
 
        _cleanup_set_free_ Set *allocated_set = NULL;
        int r, ret = 0;
 
        assert(path);
        assert(sig >= 0);
 
         /* Don't send SIGCONT twice. Also, SIGKILL always works even when process is suspended, hence
          * don't send SIGCONT on SIGKILL. */
        if (IN_SET(sig, SIGCONT, SIGKILL))
                flags &= ~CGROUP_SIGCONT;
 
        /* This goes through the tasks list and kills them all. This is repeated until no further processes
         * are added to the tasks list, to properly handle forking processes.
         *
         * When sending SIGKILL, prefer cg_kill_kernel_sigkill(), which is fully atomic. */
 
        if (!killed_pids) {
                killed_pids = allocated_set = set_new(NULL);
                if (!killed_pids)
                        return -ENOMEM;
        }
 
        bool done;
        do {
                _cleanup_fclose_ FILE *f = NULL;
                int ret_log_kill;
 
                done = true;
 
                r = cg_enumerate_processes(path, &f);
                if (r == -ENOENT)
                        break;
                if (r < 0)
                        return RET_GATHER(ret, log_debug_errno(r, "Failed to enumerate cgroup items: %m"));
 
                for (;;) {
                        _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
 
                        r = cg_read_pidref(f, &pidref, flags);
                        if (r == -ENODEV) {
                                /* reading from cgroup.pids will result in ENODEV if the cgroup is
                                 * concurrently removed. Just leave in that case, because a removed cgroup
                                 * contains no processes anymore. */
                                done = true;
                                break;
                        }
                        if (r < 0)
                                return RET_GATHER(ret, log_debug_errno(r, "Failed to read pidref from cgroup '%s': %m", path));
                        if (r == 0)
                                break;
 
                        if ((flags & CGROUP_IGNORE_SELF) && pidref_is_self(&pidref))
                                continue;
 
                        if (set_contains(killed_pids, PID_TO_PTR(pidref.pid)))
                                continue;
 
                        /* Ignore kernel threads to mimic the behavior of cgroup.kill. */
                        if (pidref_is_kernel_thread(&pidref) > 0) {
                                log_debug("Ignoring kernel thread with pid " PID_FMT " in cgroup '%s'", pidref.pid, path);
                                continue;
                        }
 
                        if (log_kill)
                                ret_log_kill = log_kill(&pidref, sig, userdata);
 
                        /* If we haven't killed this process yet, kill it */
                        r = pidref_kill(&pidref, sig);
                        if (r < 0 && r != -ESRCH)
                                RET_GATHER(ret, log_debug_errno(r, "Failed to kill process with pid " PID_FMT " from cgroup '%s': %m", pidref.pid, path));
                        if (r >= 0) {
                                if (flags & CGROUP_SIGCONT)
                                        (void) pidref_kill(&pidref, SIGCONT);
 
                                if (ret == 0) {
                                        if (log_kill)
                                                ret = ret_log_kill;
                                        else
                                                ret = 1;
                                }
                        }
 
                        done = false;
 
                        r = set_put(killed_pids, PID_TO_PTR(pidref.pid));
                        if (r < 0)
                                return RET_GATHER(ret, r);
                }
 
                /* To avoid racing against processes which fork quicker than we can kill them, we repeat this
                 * until no new pids need to be killed. */
 
        } while (!done);
 
        return ret;
}
 
int cg_kill_recursive(
                const char *path,
                int sig,
                CGroupFlags flags,
                Set *killed_pids,
                cg_kill_log_func_t log_kill,
                void *userdata) {
 
        _cleanup_set_free_ Set *allocated_set = NULL;
        _cleanup_closedir_ DIR *d = NULL;
        int r, ret;
 
        assert(path);
        assert(sig >= 0);
 
        if (!killed_pids) {
                killed_pids = allocated_set = set_new(NULL);
                if (!killed_pids)
                        return -ENOMEM;
        }
 
        ret = cg_kill(path, sig, flags, killed_pids, log_kill, userdata);
 
        r = cg_enumerate_subgroups(path, &d);
        if (r < 0) {
                if (r != -ENOENT)
                        RET_GATHER(ret, log_debug_errno(r, "Failed to enumerate cgroup '%s' subgroups: %m", path));
 
                return ret;
        }
 
        for (;;) {
                _cleanup_free_ char *fn = NULL, *p = NULL;
 
                r = cg_read_subgroup(d, &fn);
                if (r < 0) {
                        RET_GATHER(ret, log_debug_errno(r, "Failed to read subgroup from cgroup '%s': %m", path));
                        break;
                }
                if (r == 0)
                        break;
 
                p = path_join(empty_to_root(path), fn);
                if (!p)
                        return -ENOMEM;
 
                r = cg_kill_recursive(p, sig, flags, killed_pids, log_kill, userdata);
                if (r < 0)
                        log_debug_errno(r, "Failed to recursively kill processes in cgroup '%s': %m", p);
                if (r != 0 && ret >= 0)
                        ret = r;
        }
 
        return ret;
}
 
int cg_kill_kernel_sigkill(const char *path, uint64_t *ret_n_pids_killed) {
        _cleanup_free_ char *killfile = NULL;
        uint64_t n_pids = UINT64_MAX;
        int r;
 
        /* Kills the cgroup at `path` directly by writing to its cgroup.kill file.  This sends SIGKILL to all
         * processes in the cgroup and has the advantage of being completely atomic, unlike cg_kill_items(). */
 
        assert(path);
 
        if (!cg_kill_supported())
                return -EOPNOTSUPP;
 
        r = cg_get_path(path, "cgroup.kill", &killfile);
        if (r < 0)
                return r;
 
        if (ret_n_pids_killed) {
                /* This is not and cannot be atomic so there is a chance the counter might not be accurate
                 * if a process starts/stops between this read and the next write, but this is used for
                 * informational purposes so that's ok. */
                r = cg_get_attribute_as_uint64(path, "pids.current", &n_pids);
                if (r < 0)
                        log_debug_errno(r, "Failed to read pids.current from cgroup '%s', ignoring: %m", path);
        }
 
        r = write_string_file(killfile, "1", WRITE_STRING_FILE_DISABLE_BUFFER);
        if (r < 0)
                return log_debug_errno(r, "Failed to write to cgroup.kill for cgroup '%s': %m", path);
 
        if (ret_n_pids_killed)
                *ret_n_pids_killed = n_pids;
 
        return 0;
}
 
int cg_get_path(const char *path, const char *suffix, char **ret) {
        char *t;
 
        assert(ret);
 
        if (isempty(path))
                path = TAKE_PTR(suffix);
 
        t = path_join("/sys/fs/cgroup", path, suffix);
        if (!t)
                return -ENOMEM;
 
        *ret = path_simplify(t);
        return 0;
}
 
int cg_set_xattr(const char *path, const char *name, const void *value, size_t size, int flags) {
        _cleanup_free_ char *fs = NULL;
        int r;
 
        assert(path);
        assert(name);
        assert(value || size <= 0);
 
        r = cg_get_path(path, /* suffix= */ NULL, &fs);
        if (r < 0)
                return r;
 
        return RET_NERRNO(setxattr(fs, name, value, size, flags));
}
 
int cg_get_xattr(const char *path, const char *name, char **ret, size_t *ret_size) {
        _cleanup_free_ char *fs = NULL;
        int r;
 
        assert(path);
        assert(name);
 
        r = cg_get_path(path, /* suffix= */ NULL, &fs);
        if (r < 0)
                return r;
 
        return lgetxattr_malloc(fs, name, ret, ret_size);
}
 
int cg_get_xattr_bool(const char *path, const char *name) {
        _cleanup_free_ char *fs = NULL;
        int r;
 
        assert(path);
        assert(name);
 
        r = cg_get_path(path, /* suffix= */ NULL, &fs);
        if (r < 0)
                return r;
 
        return getxattr_at_bool(AT_FDCWD, fs, name, /* at_flags= */ 0);
}
 
int cg_remove_xattr(const char *path, const char *name) {
        _cleanup_free_ char *fs = NULL;
        int r;
 
        assert(path);
        assert(name);
 
        r = cg_get_path(path, /* suffix= */ NULL, &fs);
        if (r < 0)
                return r;
 
        return RET_NERRNO(removexattr(fs, name));
}
 
int cg_pid_get_path(pid_t pid, char **ret_path) {
        _cleanup_fclose_ FILE *f = NULL;
        const char *fs;
        int r;
 
        assert(pid >= 0);
        assert(ret_path);
 
        fs = procfs_file_alloca(pid, "cgroup");
        r = fopen_unlocked(fs, "re", &f);
        if (r == -ENOENT)
                return -ESRCH;
        if (r < 0)
                return r;
 
        for (;;) {
                _cleanup_free_ char *line = NULL;
                char *e;
 
                r = read_line(f, LONG_LINE_MAX, &line);
                if (r < 0)
                        return r;
                if (r == 0)
                        return -ENODATA;
 
                e = startswith(line, "0:");
                if (!e)
                        continue;
 
                e = strchr(e, ':');
                if (!e)
                        continue;
 
                _cleanup_free_ char *path = strdup(e + 1);
                if (!path)
                        return -ENOMEM;
 
                /* Refuse cgroup paths from outside our cgroup namespace */
                if (startswith(path, "/../"))
                        return -EUNATCH;
 
                /* Truncate suffix indicating the process is a zombie */
                e = endswith(path, " (deleted)");
                if (e)
                        *e = 0;
 
                *ret_path = TAKE_PTR(path);
                return 0;
        }
}
 
int cg_pidref_get_path(const PidRef *pidref, char **ret_path) {
        _cleanup_free_ char *path = NULL;
        int r;
 
        assert(ret_path);
 
        if (!pidref_is_set(pidref))
                return -ESRCH;
        if (pidref_is_remote(pidref))
                return -EREMOTE;
 
        // XXX: Ideally we'd use pidfd_get_cgroupid() + cg_path_from_cgroupid() here, to extract this
        // bit of information from pidfd directly. However, the latter requires privilege and it's
        // not entirely clear how to handle cgroups from outer namespace.
 
        r = cg_pid_get_path(pidref->pid, &path);
        if (r < 0)
                return r;
 
        /* Before we return the path, make sure the procfs entry for this pid still matches the pidref */
        r = pidref_verify(pidref);
        if (r < 0)
                return r;
 
        *ret_path = TAKE_PTR(path);
        return 0;
}
 
int cg_is_empty(const char *path) {
        _cleanup_free_ char *t = NULL;
        int r;
 
        /* Check if the cgroup hierarchy under 'path' is empty. On cgroup v2 it's exposed via the "populated"
         * attribute of "cgroup.events". */
 
        assert(path);
 
        /* The root cgroup is always populated */
        if (empty_or_root(path))
                return false;
 
        r = cg_get_keyed_attribute(path, "cgroup.events", STRV_MAKE("populated"), &t);
        if (r == -ENOENT)
                return true;
        if (r < 0)
                return r;
 
        return streq(t, "0");
}
 
int cg_split_spec(const char *spec, char **ret_controller, char **ret_path) {
        _cleanup_free_ char *controller = NULL;
        const char *path;
        int r;
 
        assert(spec);
 
        /* This extracts the path part from the deprecated controller:path spec. The path must be absolute or
         * an empty string. No validation is done for the controller part. */
 
        if (isempty(spec) || path_is_absolute(spec)) {
                /* Assume this does not contain controller. */
                path = spec;
                goto finalize;
        }
 
        const char *e = strchr(spec, ':');
        if (!e) {
                /* Controller only. */
                if (ret_controller) {
                        controller = strdup(spec);
                        if (!controller)
                                return -ENOMEM;
                }
 
                path = NULL;
        } else {
                /* Both controller and path. */
                if (ret_controller) {
                        controller = strndup(spec, e - spec);
                        if (!controller)
                                return -ENOMEM;
                }
 
                path = e + 1;
        }
 
finalize:
        path = empty_to_null(path);
 
        if (path) {
                /* Non-empty path must be absolute. */
                if (!path_is_absolute(path))
                        return -EINVAL;
 
                /* Path must not contain dot-dot. */
                if (!path_is_safe(path))
                        return -EINVAL;
        }
 
        if (ret_path) {
                r = path_simplify_alloc(path, ret_path);
                if (r < 0)
                        return r;
        }
 
        if (ret_controller)
                *ret_controller = TAKE_PTR(controller);
 
        return 0;
}
 
int cg_get_root_path(char **ret_path) {
        char *p, *e;
        int r;
 
        assert(ret_path);
 
        r = cg_pid_get_path(1, &p);
        if (r < 0)
                return r;
 
        e = endswith(p, "/" SPECIAL_INIT_SCOPE);
        if (e)
                *e = 0;
 
        *ret_path = p;
        return 0;
}
 
int cg_shift_path(const char *cgroup, const char *root, const char **ret_shifted) {
        int r;
 
        assert(cgroup);
        assert(ret_shifted);
 
        _cleanup_free_ char *rt = NULL;
        if (!root) {
                /* If the root was specified let's use that, otherwise
                 * let's determine it from PID 1 */
 
                r = cg_get_root_path(&rt);
                if (r < 0)
                        return r;
 
                root = rt;
        }
 
        *ret_shifted = path_startswith_full(cgroup, root, PATH_STARTSWITH_RETURN_LEADING_SLASH|PATH_STARTSWITH_REFUSE_DOT_DOT) ?: cgroup;
        return 0;
}
 
int cg_pid_get_path_shifted(pid_t pid, const char *root, char **ret_cgroup) {
        _cleanup_free_ char *raw = NULL;
        const char *c;
        int r;
 
        assert(pid >= 0);
        assert(ret_cgroup);
 
        r = cg_pid_get_path(pid, &raw);
        if (r < 0)
                return r;
 
        r = cg_shift_path(raw, root, &c);
        if (r < 0)
                return r;
 
        if (c == raw) {
                *ret_cgroup = TAKE_PTR(raw);
                return 0;
        }
 
        return strdup_to(ret_cgroup, c);
}
 
int cg_pidref_get_path_shifted(const PidRef *pidref, const char *root, char **ret_cgroup) {
        _cleanup_free_ char *raw = NULL;
        const char *c;
        int r;
 
        assert(ret_cgroup);
 
        r = cg_pidref_get_path(pidref, &raw);
        if (r < 0)
                return r;
 
        r = cg_shift_path(raw, root, &c);
        if (r < 0)
                return r;
 
        if (c == raw) {
                *ret_cgroup = TAKE_PTR(raw);
                return 0;
        }
 
        return strdup_to(ret_cgroup, c);
}
 
int cg_path_decode_unit(const char *cgroup, char **ret_unit) {
        assert(cgroup);
 
        size_t n = strcspn(cgroup, "/");
        if (n < 3)
                return -ENXIO;
 
        char *c = strndupa_safe(cgroup, n);
        c = cg_unescape(c);
 
        if (!unit_name_is_valid(c, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
                return -ENXIO;
 
        if (ret_unit)
                return strdup_to(ret_unit, c);
 
        return 0;
}
 
static bool valid_slice_name(const char *p, size_t n) {
        assert(p || n == 0);
 
        if (n < STRLEN("x.slice"))
                return false;
 
        char *c = strndupa_safe(p, n);
        if (!endswith(c, ".slice"))
                return false;
 
        return unit_name_is_valid(cg_unescape(c), UNIT_NAME_PLAIN);
}
 
static const char* skip_slices(const char *p) {
        assert(p);
 
        /* Skips over all slice assignments */
 
        for (;;) {
                size_t n;
 
                p += strspn(p, "/");
 
                n = strcspn(p, "/");
                if (!valid_slice_name(p, n))
                        return p;
 
                p += n;
        }
}
 
int cg_path_get_unit_full(const char *path, char **ret_unit, char **ret_subgroup) {
        int r;
 
        assert(path);
 
        const char *e = skip_slices(path);
 
        _cleanup_free_ char *unit = NULL;
        r = cg_path_decode_unit(e, &unit);
        if (r < 0)
                return r;
 
        /* We skipped over the slices, don't accept any now */
        if (endswith(unit, ".slice"))
                return -ENXIO;
 
        if (ret_subgroup) {
                _cleanup_free_ char *subgroup = NULL;
                e += strcspn(e, "/");
                e += strspn(e, "/");
 
                if (isempty(e))
                        subgroup = NULL;
                else {
                        subgroup = strdup(e);
                        if (!subgroup)
                                return -ENOMEM;
                }
 
                path_simplify(subgroup);
 
                *ret_subgroup = TAKE_PTR(subgroup);
        }
 
        if (ret_unit)
                *ret_unit = TAKE_PTR(unit);
 
        return 0;
}
 
int cg_path_get_unit_path(const char *path, char **ret) {
        _cleanup_free_ char *path_copy = NULL;
        char *unit_name;
 
        assert(path);
        assert(ret);
 
        path_copy = strdup(path);
        if (!path_copy)
                return -ENOMEM;
 
        unit_name = (char*) skip_slices(path_copy);
        unit_name[strcspn(unit_name, "/")] = 0;
 
        if (!unit_name_is_valid(cg_unescape(unit_name), UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
                return -ENXIO;
 
        *ret = TAKE_PTR(path_copy);
 
        return 0;
}
 
int cg_pid_get_unit_full(pid_t pid, char **ret_unit, char **ret_subgroup) {
        int r;
 
        _cleanup_free_ char *cgroup = NULL;
        r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
        if (r < 0)
                return r;
 
        return cg_path_get_unit_full(cgroup, ret_unit, ret_subgroup);
}
 
int cg_pidref_get_unit_full(const PidRef *pidref, char **ret_unit, char **ret_subgroup) {
        int r;
 
        if (!pidref_is_set(pidref))
                return -ESRCH;
        if (pidref_is_remote(pidref))
                return -EREMOTE;
 
        _cleanup_free_ char *unit = NULL, *subgroup = NULL;
        r = cg_pid_get_unit_full(pidref->pid, &unit, &subgroup);
        if (r < 0)
                return r;
 
        r = pidref_verify(pidref);
        if (r < 0)
                return r;
 
        if (ret_unit)
                *ret_unit = TAKE_PTR(unit);
        if (ret_subgroup)
                *ret_subgroup = TAKE_PTR(subgroup);
        return 0;
}
 
static const char* skip_session(const char *p) {
        size_t n;
 
        /* Skip session-*.scope, but require it to be there. */
 
        if (isempty(p))
                return NULL;
 
        p += strspn(p, "/");
 
        n = strcspn(p, "/");
        if (n < STRLEN("session-x.scope"))
                return NULL;
 
        const char *s = startswith(p, "session-");
        if (!s)
                return NULL;
 
        /* Note that session scopes never need unescaping, since they cannot conflict with the kernel's
         * own names, hence we don't need to call cg_unescape() here. */
        char *f = strndupa_safe(s, p + n - s),
             *e = endswith(f, ".scope");
        if (!e)
                return NULL;
        *e = '\0';
 
        if (!session_id_valid(f))
                return NULL;
 
        return skip_leading_slash(p + n);
}
 
static const char* skip_user_manager(const char *p) {
        size_t n;
 
        /* Skip user@*.service or capsule@*.service, but require either of them to be there. */
 
        if (isempty(p))
                return NULL;
 
        p += strspn(p, "/");
 
        n = strcspn(p, "/");
        if (n < CONST_MIN(STRLEN("user@x.service"), STRLEN("capsule@x.service")))
                return NULL;
 
        /* Any possible errors from functions called below are converted to NULL return, so our callers won't
         * resolve user/capsule name. */
        _cleanup_free_ char *unit_name = strndup(p, n);
        if (!unit_name)
                return NULL;
 
        _cleanup_free_ char *i = NULL;
        UnitNameFlags type = unit_name_to_instance(unit_name, &i);
 
        if (type != UNIT_NAME_INSTANCE)
                return NULL;
 
        /* Note that user manager services never need unescaping, since they cannot conflict with the
         * kernel's own names, hence we don't need to call cg_unescape() here.  Prudently check validity of
         * instance names, they should be always valid as we validate them upon unit start. */
        if (!(startswith(unit_name, "user@") && parse_uid(i, NULL) >= 0) &&
            !(startswith(unit_name, "capsule@") && capsule_name_is_valid(i) > 0))
                return NULL;
 
        return skip_leading_slash(p + n);
}
 
static const char* skip_user_prefix(const char *path) {
        const char *e, *t;
 
        assert(path);
 
        /* Skip slices, if there are any */
        e = skip_slices(path);
 
        /* Skip the user manager, if it's in the path now... */
        t = skip_user_manager(e);
        if (t)
                return t;
 
        /* Alternatively skip the user session if it is in the path... */
        return skip_session(e);
}
 
int cg_path_get_user_unit_full(const char *path, char **ret_unit, char **ret_subgroup) {