• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

systemd / systemd / 17336716495

29 Aug 2025 05:46PM UTC coverage: 72.247% (+0.05%) from 72.194%
17336716495

push

github

yuwata
NEWS: add note about removal of /run/lock/ from our tmpfiles.d

302576 of 418806 relevant lines covered (72.25%)

657871.36 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

83.68
/src/basic/cgroup-util.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <linux/fs.h>
4
#include <linux/magic.h>
5
#include <signal.h>
6
#include <stdlib.h>
7
#include <sys/xattr.h>
8
#include <threads.h>
9
#include <unistd.h>
10

11
#include "alloc-util.h"
12
#include "capsule-util.h"
13
#include "cgroup-util.h"
14
#include "dirent-util.h"
15
#include "errno-util.h"
16
#include "extract-word.h"
17
#include "fd-util.h"
18
#include "fileio.h"
19
#include "format-util.h"
20
#include "fs-util.h"
21
#include "log.h"
22
#include "login-util.h"
23
#include "parse-util.h"
24
#include "path-util.h"
25
#include "pidref.h"
26
#include "process-util.h"
27
#include "set.h"
28
#include "special.h"
29
#include "stat-util.h"
30
#include "string-table.h"
31
#include "string-util.h"
32
#include "strv.h"
33
#include "unaligned.h"
34
#include "unit-name.h"
35
#include "user-util.h"
36
#include "xattr-util.h"
37

38
/* The structure to pass to name_to_handle_at() on cgroupfs2 */
39
typedef union {
40
        struct file_handle file_handle;
41
        uint8_t space[offsetof(struct file_handle, f_handle) + sizeof(uint64_t)];
42
} cg_file_handle;
43

44
#define CG_FILE_HANDLE_INIT                                     \
45
        (cg_file_handle) {                                      \
46
                .file_handle.handle_bytes = sizeof(uint64_t),   \
47
                .file_handle.handle_type = FILEID_KERNFS,       \
48
        }
49

50
/* The .f_handle field is not aligned to 64bit on some archs, hence read it via an unaligned accessor */
51
#define CG_FILE_HANDLE_CGROUPID(fh) unaligned_read_ne64(fh.file_handle.f_handle)
52

53
int cg_path_open(const char *controller, const char *path) {
828✔
54
        _cleanup_free_ char *fs = NULL;
828✔
55
        int r;
828✔
56

57
        r = cg_get_path(controller, path, /* suffix=*/ NULL, &fs);
828✔
58
        if (r < 0)
828✔
59
                return r;
60

61
        return RET_NERRNO(open(fs, O_DIRECTORY|O_CLOEXEC));
828✔
62
}
63

64
int cg_cgroupid_open(int cgroupfs_fd, uint64_t id) {
1✔
65
        _cleanup_close_ int fsfd = -EBADF;
1✔
66

67
        if (cgroupfs_fd < 0) {
1✔
68
                fsfd = open("/sys/fs/cgroup", O_CLOEXEC|O_DIRECTORY);
×
69
                if (fsfd < 0)
×
70
                        return -errno;
×
71

72
                cgroupfs_fd = fsfd;
73
        }
74

75
        cg_file_handle fh = CG_FILE_HANDLE_INIT;
1✔
76
        unaligned_write_ne64(fh.file_handle.f_handle, id);
1✔
77

78
        return RET_NERRNO(open_by_handle_at(cgroupfs_fd, &fh.file_handle, O_DIRECTORY|O_CLOEXEC));
2✔
79
}
80

81
int cg_path_from_cgroupid(int cgroupfs_fd, uint64_t id, char **ret) {
×
82
        _cleanup_close_ int cgfd = -EBADF;
×
83
        int r;
×
84

85
        cgfd = cg_cgroupid_open(cgroupfs_fd, id);
×
86
        if (cgfd < 0)
×
87
                return cgfd;
88

89
        _cleanup_free_ char *path = NULL;
×
90
        r = fd_get_path(cgfd, &path);
×
91
        if (r < 0)
×
92
                return r;
93

94
        if (!path_startswith(path, "/sys/fs/cgroup/"))
×
95
                return -EXDEV; /* recognizable error */
96

97
        if (ret)
×
98
                *ret = TAKE_PTR(path);
×
99
        return 0;
100
}
101

102
int cg_get_cgroupid_at(int dfd, const char *path, uint64_t *ret) {
4,742✔
103
        cg_file_handle fh = CG_FILE_HANDLE_INIT;
4,742✔
104
        int mnt_id;
4,742✔
105

106
        assert(dfd >= 0 || (dfd == AT_FDCWD && path_is_absolute(path)));
9,446✔
107
        assert(ret);
4,742✔
108

109
        /* This is cgroupfs so we know the size of the handle, thus no need to loop around like
110
         * name_to_handle_at_loop() does in mountpoint-util.c */
111
        if (name_to_handle_at(dfd, strempty(path), &fh.file_handle, &mnt_id, isempty(path) ? AT_EMPTY_PATH : 0) < 0) {
9,484✔
112
                assert(errno != EOVERFLOW);
×
113
                return -errno;
×
114
        }
115

116
        *ret = CG_FILE_HANDLE_CGROUPID(fh);
4,742✔
117
        return 0;
4,742✔
118
}
119

120
int cg_enumerate_processes(const char *controller, const char *path, FILE **ret) {
14,249✔
121
        _cleanup_free_ char *fs = NULL;
14,249✔
122
        FILE *f;
14,249✔
123
        int r;
14,249✔
124

125
        assert(ret);
14,249✔
126

127
        r = cg_get_path(controller, path, "cgroup.procs", &fs);
14,249✔
128
        if (r < 0)
14,249✔
129
                return r;
130

131
        f = fopen(fs, "re");
14,249✔
132
        if (!f)
14,249✔
133
                return -errno;
9,079✔
134

135
        *ret = f;
5,170✔
136
        return 0;
5,170✔
137
}
138

139
int cg_read_pid(FILE *f, pid_t *ret, CGroupFlags flags) {
9,473✔
140
        unsigned long ul;
9,473✔
141

142
        /* Note that the cgroup.procs might contain duplicates! See cgroups.txt for details. */
143

144
        assert(f);
9,473✔
145
        assert(ret);
9,473✔
146

147
        /* NB: The kernel returns ENODEV if we tried to read from cgroup.procs of a cgroup that has been
148
         * removed already. Callers should handle that! */
149

150
        for (;;) {
9,473✔
151
                errno = 0;
9,473✔
152
                if (fscanf(f, "%lu", &ul) != 1) {
9,473✔
153

154
                        if (feof(f)) {
5,385✔
155
                                *ret = 0;
5,385✔
156
                                return 0;
5,385✔
157
                        }
158

159
                        return errno_or_else(EIO);
×
160
                }
161

162
                if (ul > PID_T_MAX)
4,088✔
163
                        return -EIO;
164

165
                /* In some circumstances (e.g. WSL), cgroups might contain unmappable PIDs from other
166
                 * contexts. These show up as zeros, and depending on the caller, can either be plain
167
                 * skipped over, or returned as-is. */
168
                if (ul == 0 && !FLAGS_SET(flags, CGROUP_DONT_SKIP_UNMAPPED))
4,088✔
169
                        continue;
×
170

171
                *ret = (pid_t) ul;
4,088✔
172
                return 1;
4,088✔
173
        }
174
}
175

176
int cg_read_pidref(FILE *f, PidRef *ret, CGroupFlags flags) {
6,475✔
177
        int r;
6,475✔
178

179
        assert(f);
6,475✔
180
        assert(ret);
6,475✔
181

182
        for (;;) {
×
183
                pid_t pid;
6,475✔
184

185
                r = cg_read_pid(f, &pid, flags);
6,475✔
186
                if (r < 0)
6,475✔
187
                        return log_debug_errno(r, "Failed to read pid from cgroup item: %m");
×
188
                if (r == 0) {
6,475✔
189
                        *ret = PIDREF_NULL;
4,797✔
190
                        return 0;
4,797✔
191
                }
192

193
                if (pid == 0)
1,678✔
194
                        return -EREMOTE;
195

196
                r = pidref_set_pid(ret, pid);
1,678✔
197
                if (r >= 0)
1,678✔
198
                        return 1;
199
                if (r != -ESRCH)
×
200
                        return r;
201

202
                /* ESRCH → gone by now? just skip over it, read the next */
203
        }
204
}
205

206
bool cg_kill_supported(void) {
×
207
        static thread_local int supported = -1;
×
208

209
        if (supported >= 0)
×
210
                return supported;
×
211

212
        if (cg_all_unified() <= 0)
×
213
                return (supported = false);
×
214

215
        if (access("/sys/fs/cgroup/init.scope/cgroup.kill", F_OK) >= 0)
×
216
                return (supported = true);
×
217
        if (errno != ENOENT)
×
218
                log_debug_errno(errno, "Failed to check whether cgroup.kill is available, assuming not: %m");
×
219
        return (supported = false);
×
220
}
221

222
int cg_enumerate_subgroups(const char *controller, const char *path, DIR **ret) {
13,797✔
223
        _cleanup_free_ char *fs = NULL;
13,797✔
224
        DIR *d;
13,797✔
225
        int r;
13,797✔
226

227
        assert(ret);
13,797✔
228

229
        /* This is not recursive! */
230

231
        r = cg_get_path(controller, path, NULL, &fs);
13,797✔
232
        if (r < 0)
13,797✔
233
                return r;
234

235
        d = opendir(fs);
13,797✔
236
        if (!d)
13,797✔
237
                return -errno;
9,079✔
238

239
        *ret = d;
4,718✔
240
        return 0;
4,718✔
241
}
242

243
int cg_read_subgroup(DIR *d, char **ret) {
6,080✔
244
        assert(d);
6,080✔
245
        assert(ret);
6,080✔
246

247
        FOREACH_DIRENT_ALL(de, d, return -errno) {
227,026✔
248
                if (de->d_type != DT_DIR)
222,093✔
249
                        continue;
211,080✔
250

251
                if (dot_or_dot_dot(de->d_name))
11,013✔
252
                        continue;
9,866✔
253

254
                return strdup_to_full(ret, de->d_name);
1,147✔
255
        }
256

257
        *ret = NULL;
4,933✔
258
        return 0;
4,933✔
259
}
260

261
int cg_kill(
13,750✔
262
                const char *path,
263
                int sig,
264
                CGroupFlags flags,
265
                Set *killed_pids,
266
                cg_kill_log_func_t log_kill,
267
                void *userdata) {
268

269
        _cleanup_set_free_ Set *allocated_set = NULL;
13,750✔
270
        int r, ret = 0;
13,750✔
271

272
        assert(path);
13,750✔
273
        assert(sig >= 0);
13,750✔
274

275
         /* Don't send SIGCONT twice. Also, SIGKILL always works even when process is suspended, hence
276
          * don't send SIGCONT on SIGKILL. */
277
        if (IN_SET(sig, SIGCONT, SIGKILL))
13,750✔
278
                flags &= ~CGROUP_SIGCONT;
2,018✔
279

280
        /* This goes through the tasks list and kills them all. This is repeated until no further processes
281
         * are added to the tasks list, to properly handle forking processes.
282
         *
283
         * When sending SIGKILL, prefer cg_kill_kernel_sigkill(), which is fully atomic. */
284

285
        if (!killed_pids) {
13,750✔
286
                killed_pids = allocated_set = set_new(NULL);
699✔
287
                if (!killed_pids)
699✔
288
                        return -ENOMEM;
289
        }
290

291
        bool done;
13,835✔
292
        do {
13,835✔
293
                _cleanup_fclose_ FILE *f = NULL;
9,079✔
294
                int ret_log_kill;
13,835✔
295

296
                done = true;
13,835✔
297

298
                r = cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, path, &f);
13,835✔
299
                if (r == -ENOENT)
13,835✔
300
                        break;
301
                if (r < 0)
4,756✔
302
                        return RET_GATHER(ret, log_debug_errno(r, "Failed to enumerate cgroup items: %m"));
×
303

304
                for (;;) {
6,338✔
305
                        _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
6,338✔
306

307
                        r = cg_read_pidref(f, &pidref, flags);
6,338✔
308
                        if (r == -ENODEV) {
6,338✔
309
                                /* reading from cgroup.pids will result in ENODEV if the cgroup is
310
                                 * concurrently removed. Just leave in that case, because a removed cgroup
311
                                 * contains no processes anymore. */
312
                                done = true;
313
                                break;
314
                        }
315
                        if (r < 0)
6,338✔
316
                                return RET_GATHER(ret, log_debug_errno(r, "Failed to read pidref from cgroup '%s': %m", path));
×
317
                        if (r == 0)
6,338✔
318
                                break;
319

320
                        if ((flags & CGROUP_IGNORE_SELF) && pidref_is_self(&pidref))
1,582✔
321
                                continue;
700✔
322

323
                        if (set_contains(killed_pids, PID_TO_PTR(pidref.pid)))
882✔
324
                                continue;
632✔
325

326
                        /* Ignore kernel threads to mimic the behavior of cgroup.kill. */
327
                        if (pidref_is_kernel_thread(&pidref) > 0) {
250✔
328
                                log_debug("Ignoring kernel thread with pid " PID_FMT " in cgroup '%s'", pidref.pid, path);
×
329
                                continue;
×
330
                        }
331

332
                        if (log_kill)
250✔
333
                                ret_log_kill = log_kill(&pidref, sig, userdata);
90✔
334

335
                        /* If we haven't killed this process yet, kill it */
336
                        r = pidref_kill(&pidref, sig);
250✔
337
                        if (r < 0 && r != -ESRCH)
250✔
338
                                RET_GATHER(ret, log_debug_errno(r, "Failed to kill process with pid " PID_FMT " from cgroup '%s': %m", pidref.pid, path));
×
339
                        if (r >= 0) {
250✔
340
                                if (flags & CGROUP_SIGCONT)
250✔
341
                                        (void) pidref_kill(&pidref, SIGCONT);
158✔
342

343
                                if (ret == 0) {
250✔
344
                                        if (log_kill)
154✔
345
                                                ret = ret_log_kill;
346
                                        else
347
                                                ret = 1;
64✔
348
                                }
349
                        }
350

351
                        done = false;
250✔
352

353
                        r = set_put(killed_pids, PID_TO_PTR(pidref.pid));
250✔
354
                        if (r < 0)
250✔
355
                                return RET_GATHER(ret, r);
×
356
                }
357

358
                /* To avoid racing against processes which fork quicker than we can kill them, we repeat this
359
                 * until no new pids need to be killed. */
360

361
        } while (!done);
4,756✔
362

363
        return ret;
364
}
365

366
int cg_kill_recursive(
13,049✔
367
                const char *path,
368
                int sig,
369
                CGroupFlags flags,
370
                Set *killed_pids,
371
                cg_kill_log_func_t log_kill,
372
                void *userdata) {
373

374
        _cleanup_set_free_ Set *allocated_set = NULL;
×
375
        _cleanup_closedir_ DIR *d = NULL;
13,049✔
376
        int r, ret;
13,049✔
377

378
        assert(path);
13,049✔
379
        assert(sig >= 0);
13,049✔
380

381
        if (!killed_pids) {
13,049✔
382
                killed_pids = allocated_set = set_new(NULL);
12,575✔
383
                if (!killed_pids)
12,575✔
384
                        return -ENOMEM;
385
        }
386

387
        ret = cg_kill(path, sig, flags, killed_pids, log_kill, userdata);
13,049✔
388

389
        r = cg_enumerate_subgroups(SYSTEMD_CGROUP_CONTROLLER, path, &d);
13,049✔
390
        if (r < 0) {
13,049✔
391
                if (r != -ENOENT)
9,079✔
392
                        RET_GATHER(ret, log_debug_errno(r, "Failed to enumerate cgroup '%s' subgroups: %m", path));
×
393

394
                return ret;
9,079✔
395
        }
396

397
        for (;;) {
4,182✔
398
                _cleanup_free_ char *fn = NULL, *p = NULL;
4,076✔
399

400
                r = cg_read_subgroup(d, &fn);
4,076✔
401
                if (r < 0) {
4,076✔
402
                        RET_GATHER(ret, log_debug_errno(r, "Failed to read subgroup from cgroup '%s': %m", path));
×
403
                        break;
404
                }
405
                if (r == 0)
4,076✔
406
                        break;
407

408
                p = path_join(empty_to_root(path), fn);
106✔
409
                if (!p)
106✔
410
                        return -ENOMEM;
×
411

412
                r = cg_kill_recursive(p, sig, flags, killed_pids, log_kill, userdata);
106✔
413
                if (r < 0)
106✔
414
                        log_debug_errno(r, "Failed to recursively kill processes in cgroup '%s': %m", p);
×
415
                if (r != 0 && ret >= 0)
106✔
416
                        ret = r;
15✔
417
        }
418

419
        return ret;
3,970✔
420
}
421

422
int cg_kill_kernel_sigkill(const char *path) {
×
423
        _cleanup_free_ char *killfile = NULL;
×
424
        int r;
×
425

426
        /* Kills the cgroup at `path` directly by writing to its cgroup.kill file.  This sends SIGKILL to all
427
         * processes in the cgroup and has the advantage of being completely atomic, unlike cg_kill_items(). */
428

429
        assert(path);
×
430

431
        if (!cg_kill_supported())
×
432
                return -EOPNOTSUPP;
433

434
        r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, path, "cgroup.kill", &killfile);
×
435
        if (r < 0)
×
436
                return r;
437

438
        r = write_string_file(killfile, "1", WRITE_STRING_FILE_DISABLE_BUFFER);
×
439
        if (r < 0)
×
440
                return log_debug_errno(r, "Failed to write to cgroup.kill for cgroup '%s': %m", path);
×
441

442
        return 0;
443
}
444

445
static const char *controller_to_dirname(const char *controller) {
×
446
        assert(controller);
×
447

448
        /* Converts a controller name to the directory name below /sys/fs/cgroup/ we want to mount it
449
         * to. Effectively, this just cuts off the name= prefixed used for named hierarchies, if it is
450
         * specified. */
451

452
        if (streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
×
453
                if (cg_hybrid_unified() > 0)
×
454
                        controller = SYSTEMD_CGROUP_CONTROLLER_HYBRID;
455
                else
456
                        controller = SYSTEMD_CGROUP_CONTROLLER_LEGACY;
×
457
        }
458

459
        return startswith(controller, "name=") ?: controller;
×
460
}
461

462
static int join_path_legacy(const char *controller, const char *path, const char *suffix, char **ret) {
×
463
        const char *dn;
×
464
        char *t = NULL;
×
465

466
        assert(ret);
×
467
        assert(controller);
×
468

469
        dn = controller_to_dirname(controller);
×
470

471
        if (isempty(path) && isempty(suffix))
×
472
                t = path_join("/sys/fs/cgroup", dn);
×
473
        else if (isempty(path))
×
474
                t = path_join("/sys/fs/cgroup", dn, suffix);
×
475
        else if (isempty(suffix))
×
476
                t = path_join("/sys/fs/cgroup", dn, path);
×
477
        else
478
                t = path_join("/sys/fs/cgroup", dn, path, suffix);
×
479
        if (!t)
×
480
                return -ENOMEM;
481

482
        *ret = t;
×
483
        return 0;
×
484
}
485

486
static int join_path_unified(const char *path, const char *suffix, char **ret) {
227,515✔
487
        char *t;
227,515✔
488

489
        assert(ret);
227,515✔
490

491
        if (isempty(path) && isempty(suffix))
241,404✔
492
                t = strdup("/sys/fs/cgroup");
1,412✔
493
        else if (isempty(path))
226,103✔
494
                t = path_join("/sys/fs/cgroup", suffix);
12,477✔
495
        else if (isempty(suffix))
213,626✔
496
                t = path_join("/sys/fs/cgroup", path);
84,321✔
497
        else
498
                t = path_join("/sys/fs/cgroup", path, suffix);
129,305✔
499
        if (!t)
227,515✔
500
                return -ENOMEM;
501

502
        *ret = t;
227,515✔
503
        return 0;
227,515✔
504
}
505

506
int cg_get_path(const char *controller, const char *path, const char *suffix, char **ret) {
227,761✔
507
        int r;
227,761✔
508

509
        assert(ret);
227,761✔
510

511
        if (!controller) {
227,761✔
512
                char *t;
246✔
513

514
                /* If no controller is specified, we return the path *below* the controllers, without any
515
                 * prefix. */
516

517
                if (isempty(path) && isempty(suffix))
246✔
518
                        return -EINVAL;
519

520
                if (isempty(suffix))
246✔
521
                        t = strdup(path);
×
522
                else if (isempty(path))
246✔
523
                        t = strdup(suffix);
×
524
                else
525
                        t = path_join(path, suffix);
246✔
526
                if (!t)
246✔
527
                        return -ENOMEM;
528

529
                *ret = path_simplify(t);
246✔
530
                return 0;
246✔
531
        }
532

533
        if (!cg_controller_is_valid(controller))
227,515✔
534
                return -EINVAL;
535

536
        r = cg_all_unified();
227,515✔
537
        if (r < 0)
227,515✔
538
                return r;
539
        if (r > 0)
227,515✔
540
                r = join_path_unified(path, suffix, ret);
227,515✔
541
        else
542
                r = join_path_legacy(controller, path, suffix, ret);
×
543
        if (r < 0)
227,515✔
544
                return r;
545

546
        path_simplify(*ret);
227,515✔
547
        return 0;
227,515✔
548
}
549

550
static int controller_is_v1_accessible(const char *root, const char *controller) {
×
551
        const char *cpath, *dn;
×
552

553
        assert(controller);
×
554

555
        dn = controller_to_dirname(controller);
×
556

557
        /* If root if specified, we check that:
558
         * - possible subcgroup is created at root,
559
         * - we can modify the hierarchy. */
560

561
        cpath = strjoina("/sys/fs/cgroup/", dn, root, root ? "/cgroup.procs" : NULL);
×
562
        return access_nofollow(cpath, root ? W_OK : F_OK);
×
563
}
564

565
int cg_get_path_and_check(const char *controller, const char *path, const char *suffix, char **ret) {
20,085✔
566
        int r;
20,085✔
567

568
        assert(controller);
20,085✔
569
        assert(ret);
20,085✔
570

571
        if (!cg_controller_is_valid(controller))
20,085✔
572
                return -EINVAL;
573

574
        r = cg_all_unified();
20,085✔
575
        if (r < 0)
20,085✔
576
                return r;
577
        if (r > 0) {
20,085✔
578
                /* In the unified hierarchy all controllers are considered accessible,
579
                 * except for the named hierarchies */
580
                if (startswith(controller, "name="))
20,085✔
581
                        return -EOPNOTSUPP;
582
        } else {
583
                /* Check if the specified controller is actually accessible */
584
                r = controller_is_v1_accessible(NULL, controller);
×
585
                if (r < 0)
×
586
                        return r;
587
        }
588

589
        return cg_get_path(controller, path, suffix, ret);
20,085✔
590
}
591

592
int cg_set_xattr(const char *path, const char *name, const void *value, size_t size, int flags) {
6,069✔
593
        _cleanup_free_ char *fs = NULL;
6,069✔
594
        int r;
6,069✔
595

596
        assert(path);
6,069✔
597
        assert(name);
6,069✔
598
        assert(value || size <= 0);
6,069✔
599

600
        r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, path, NULL, &fs);
6,069✔
601
        if (r < 0)
6,069✔
602
                return r;
603

604
        return RET_NERRNO(setxattr(fs, name, value, size, flags));
6,069✔
605
}
606

607
int cg_get_xattr(const char *path, const char *name, char **ret, size_t *ret_size) {
16,096✔
608
        _cleanup_free_ char *fs = NULL;
16,096✔
609
        int r;
16,096✔
610

611
        assert(path);
16,096✔
612
        assert(name);
16,096✔
613

614
        r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, path, NULL, &fs);
16,096✔
615
        if (r < 0)
16,096✔
616
                return r;
617

618
        return lgetxattr_malloc(fs, name, ret, ret_size);
16,096✔
619
}
620

621
int cg_get_xattr_bool(const char *path, const char *name) {
167✔
622
        _cleanup_free_ char *fs = NULL;
167✔
623
        int r;
167✔
624

625
        assert(path);
167✔
626
        assert(name);
167✔
627

628
        r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, path, NULL, &fs);
167✔
629
        if (r < 0)
167✔
630
                return r;
631

632
        return getxattr_at_bool(AT_FDCWD, fs, name, /* at_flags= */ 0);
167✔
633
}
634

635
int cg_remove_xattr(const char *path, const char *name) {
30,081✔
636
        _cleanup_free_ char *fs = NULL;
30,081✔
637
        int r;
30,081✔
638

639
        assert(path);
30,081✔
640
        assert(name);
30,081✔
641

642
        r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, path, NULL, &fs);
30,081✔
643
        if (r < 0)
30,081✔
644
                return r;
645

646
        return RET_NERRNO(removexattr(fs, name));
60,162✔
647
}
648

649
int cg_pid_get_path(const char *controller, pid_t pid, char **ret_path) {
41,094✔
650
        _cleanup_fclose_ FILE *f = NULL;
41,094✔
651
        const char *fs, *controller_str = NULL;  /* avoid false maybe-uninitialized warning */
41,094✔
652
        int unified, r;
41,094✔
653

654
        assert(pid >= 0);
41,094✔
655
        assert(ret_path);
41,094✔
656

657
        if (controller) {
41,094✔
658
                if (!cg_controller_is_valid(controller))
40,899✔
659
                        return -EINVAL;
660
        } else
661
                controller = SYSTEMD_CGROUP_CONTROLLER;
662

663
        unified = cg_unified_controller(controller);
41,094✔
664
        if (unified < 0)
41,094✔
665
                return unified;
666
        if (unified == 0) {
41,094✔
667
                if (streq(controller, SYSTEMD_CGROUP_CONTROLLER))
×
668
                        controller_str = SYSTEMD_CGROUP_CONTROLLER_LEGACY;
669
                else
670
                        controller_str = controller;
×
671
        }
672

673
        fs = procfs_file_alloca(pid, "cgroup");
47,302✔
674
        r = fopen_unlocked(fs, "re", &f);
41,094✔
675
        if (r == -ENOENT)
41,094✔
676
                return -ESRCH;
677
        if (r < 0)
36,799✔
678
                return r;
679

680
        for (;;) {
36,799✔
681
                _cleanup_free_ char *line = NULL;
36,799✔
682
                char *e;
36,799✔
683

684
                r = read_line(f, LONG_LINE_MAX, &line);
36,799✔
685
                if (r < 0)
36,799✔
686
                        return r;
687
                if (r == 0)
36,793✔
688
                        return -ENODATA;
689

690
                if (unified) {
36,793✔
691
                        e = startswith(line, "0:");
36,793✔
692
                        if (!e)
36,793✔
693
                                continue;
×
694

695
                        e = strchr(e, ':');
36,793✔
696
                        if (!e)
36,793✔
697
                                continue;
×
698
                } else {
699
                        char *l;
×
700

701
                        l = strchr(line, ':');
×
702
                        if (!l)
×
703
                                continue;
×
704

705
                        l++;
×
706
                        e = strchr(l, ':');
×
707
                        if (!e)
×
708
                                continue;
×
709
                        *e = 0;
×
710

711
                        assert(controller_str);
×
712
                        r = string_contains_word(l, ",", controller_str);
×
713
                        if (r < 0)
×
714
                                return r;
715
                        if (r == 0)
×
716
                                continue;
×
717
                }
718

719
                _cleanup_free_ char *path = strdup(e + 1);
36,793✔
720
                if (!path)
36,793✔
721
                        return -ENOMEM;
722

723
                /* Refuse cgroup paths from outside our cgroup namespace */
724
                if (startswith(path, "/../"))
36,793✔
725
                        return -EUNATCH;
726

727
                /* Truncate suffix indicating the process is a zombie */
728
                e = endswith(path, " (deleted)");
36,793✔
729
                if (e)
36,793✔
730
                        *e = 0;
172✔
731

732
                *ret_path = TAKE_PTR(path);
36,793✔
733
                return 0;
36,793✔
734
        }
735
}
736

737
int cg_pidref_get_path(const char *controller, const PidRef *pidref, char **ret_path) {
10,075✔
738
        _cleanup_free_ char *path = NULL;
10,075✔
739
        int r;
10,075✔
740

741
        assert(ret_path);
10,075✔
742

743
        if (!pidref_is_set(pidref))
10,075✔
744
                return -ESRCH;
745
        if (pidref_is_remote(pidref))
20,150✔
746
                return -EREMOTE;
747

748
        // XXX: Ideally we'd use pidfd_get_cgroupid() + cg_path_from_cgroupid() here, to extract this
749
        // bit of information from pidfd directly. However, the latter requires privilege and it's
750
        // not entirely clear how to handle cgroups from outer namespace.
751

752
        r = cg_pid_get_path(controller, pidref->pid, &path);
10,075✔
753
        if (r < 0)
10,075✔
754
                return r;
755

756
        /* Before we return the path, make sure the procfs entry for this pid still matches the pidref */
757
        r = pidref_verify(pidref);
10,075✔
758
        if (r < 0)
10,075✔
759
                return r;
760

761
        *ret_path = TAKE_PTR(path);
10,075✔
762
        return 0;
10,075✔
763
}
764

765
int cg_is_empty(const char *controller, const char *path) {
2,432✔
766
        _cleanup_free_ char *t = NULL;
2,432✔
767
        int r;
2,432✔
768

769
        /* Check if the cgroup hierarchy under 'path' is empty. On cgroup v2 it's exposed via the "populated"
770
         * attribute of "cgroup.events". */
771

772
        assert(path);
2,432✔
773

774
        /* The root cgroup is always populated */
775
        if (empty_or_root(path))
2,432✔
776
                return false;
777

778
        r = cg_get_keyed_attribute(controller, path, "cgroup.events", STRV_MAKE("populated"), &t);
2,432✔
779
        if (r == -ENOENT)
2,432✔
780
                return true;
781
        if (r < 0)
280✔
782
                return r;
783

784
        return streq(t, "0");
280✔
785
}
786

787
int cg_split_spec(const char *spec, char **ret_controller, char **ret_path) {
23✔
788
        _cleanup_free_ char *controller = NULL, *path = NULL;
23✔
789
        int r;
23✔
790

791
        assert(spec);
23✔
792

793
        if (*spec == '/') {
23✔
794
                if (!path_is_normalized(spec))
15✔
795
                        return -EINVAL;
796

797
                if (ret_path) {
15✔
798
                        r = path_simplify_alloc(spec, &path);
15✔
799
                        if (r < 0)
15✔
800
                                return r;
801
                }
802

803
        } else {
804
                const char *e;
8✔
805

806
                e = strchr(spec, ':');
8✔
807
                if (e) {
8✔
808
                        controller = strndup(spec, e-spec);
6✔
809
                        if (!controller)
6✔
810
                                return -ENOMEM;
811
                        if (!cg_controller_is_valid(controller))
6✔
812
                                return -EINVAL;
813

814
                        if (!isempty(e + 1)) {
3✔
815
                                path = strdup(e+1);
2✔
816
                                if (!path)
2✔
817
                                        return -ENOMEM;
818

819
                                if (!path_is_normalized(path) ||
2✔
820
                                    !path_is_absolute(path))
2✔
821
                                        return -EINVAL;
822

823
                                path_simplify(path);
1✔
824
                        }
825

826
                } else {
827
                        if (!cg_controller_is_valid(spec))
2✔
828
                                return -EINVAL;
829

830
                        if (ret_controller) {
1✔
831
                                controller = strdup(spec);
1✔
832
                                if (!controller)
1✔
833
                                        return -ENOMEM;
834
                        }
835
                }
836
        }
837

838
        if (ret_controller)
18✔
839
                *ret_controller = TAKE_PTR(controller);
18✔
840
        if (ret_path)
18✔
841
                *ret_path = TAKE_PTR(path);
18✔
842
        return 0;
843
}
844

845
int cg_mangle_path(const char *path, char **ret) {
435✔
846
        _cleanup_free_ char *c = NULL, *p = NULL;
435✔
847
        int r;
435✔
848

849
        assert(path);
435✔
850
        assert(ret);
435✔
851

852
        /* First, check if it already is a filesystem path */
853
        if (path_startswith(path, "/sys/fs/cgroup"))
435✔
854
                return path_simplify_alloc(path, ret);
431✔
855

856
        /* Otherwise, treat it as cg spec */
857
        r = cg_split_spec(path, &c, &p);
4✔
858
        if (r < 0)
4✔
859
                return r;
860

861
        return cg_get_path(c ?: SYSTEMD_CGROUP_CONTROLLER, p ?: "/", NULL, ret);
8✔
862
}
863

864
int cg_get_root_path(char **ret_path) {
13,372✔
865
        char *p, *e;
13,372✔
866
        int r;
13,372✔
867

868
        assert(ret_path);
13,372✔
869

870
        r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, &p);
13,372✔
871
        if (r < 0)
13,372✔
872
                return r;
13,372✔
873

874
        e = endswith(p, "/" SPECIAL_INIT_SCOPE);
13,372✔
875
        if (e)
13,372✔
876
                *e = 0;
13,339✔
877

878
        *ret_path = p;
13,372✔
879
        return 0;
13,372✔
880
}
881

882
int cg_shift_path(const char *cgroup, const char *root, const char **ret_shifted) {
11,976✔
883
        int r;
11,976✔
884

885
        assert(cgroup);
11,976✔
886
        assert(ret_shifted);
11,976✔
887

888
        _cleanup_free_ char *rt = NULL;
11,976✔
889
        if (!root) {
11,976✔
890
                /* If the root was specified let's use that, otherwise
891
                 * let's determine it from PID 1 */
892

893
                r = cg_get_root_path(&rt);
1,939✔
894
                if (r < 0)
1,939✔
895
                        return r;
896

897
                root = rt;
1,939✔
898
        }
899

900
        *ret_shifted = path_startswith_full(cgroup, root, PATH_STARTSWITH_RETURN_LEADING_SLASH|PATH_STARTSWITH_REFUSE_DOT_DOT) ?: cgroup;
11,976✔
901
        return 0;
11,976✔
902
}
903

904
int cg_pid_get_path_shifted(pid_t pid, const char *root, char **ret_cgroup) {
16,099✔
905
        _cleanup_free_ char *raw = NULL;
16,099✔
906
        const char *c;
16,099✔
907
        int r;
16,099✔
908

909
        assert(pid >= 0);
16,099✔
910
        assert(ret_cgroup);
16,099✔
911

912
        r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &raw);
16,099✔
913
        if (r < 0)
16,099✔
914
                return r;
915

916
        r = cg_shift_path(raw, root, &c);
11,798✔
917
        if (r < 0)
11,798✔
918
                return r;
919

920
        if (c == raw) {
11,798✔
921
                *ret_cgroup = TAKE_PTR(raw);
11,798✔
922
                return 0;
11,798✔
923
        }
924

925
        return strdup_to(ret_cgroup, c);
×
926
}
927

928
int cg_path_decode_unit(const char *cgroup, char **ret_unit) {
33,995✔
929
        assert(cgroup);
33,995✔
930

931
        size_t n = strcspn(cgroup, "/");
33,995✔
932
        if (n < 3)
33,995✔
933
                return -ENXIO;
934

935
        char *c = strndupa_safe(cgroup, n);
33,972✔
936
        c = cg_unescape(c);
33,972✔
937

938
        if (!unit_name_is_valid(c, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
33,972✔
939
                return -ENXIO;
940

941
        if (ret_unit)
33,963✔
942
                return strdup_to(ret_unit, c);
33,963✔
943

944
        return 0;
945
}
946

947
static bool valid_slice_name(const char *p, size_t n) {
121,619✔
948
        assert(p || n == 0);
121,619✔
949

950
        if (n < STRLEN("x.slice"))
121,619✔
951
                return false;
952

953
        char *c = strndupa_safe(p, n);
121,556✔
954
        if (!endswith(c, ".slice"))
121,556✔
955
                return false;
956

957
        return unit_name_is_valid(cg_unescape(c), UNIT_NAME_PLAIN);
61,534✔
958
}
959

960
static const char* skip_slices(const char *p) {
43,649✔
961
        assert(p);
43,649✔
962

963
        /* Skips over all slice assignments */
964

965
        for (;;) {
133,185✔
966
                size_t n;
88,417✔
967

968
                p += strspn(p, "/");
88,417✔
969

970
                n = strcspn(p, "/");
88,417✔
971
                if (!valid_slice_name(p, n))
88,417✔
972
                        return p;
43,649✔
973

974
                p += n;
44,768✔
975
        }
976
}
977

978
int cg_path_get_unit_full(const char *path, char **ret_unit, char **ret_subgroup) {
17,804✔
979
        int r;
17,804✔
980

981
        assert(path);
17,804✔
982

983
        const char *e = skip_slices(path);
17,804✔
984

985
        _cleanup_free_ char *unit = NULL;
17,804✔
986
        r = cg_path_decode_unit(e, &unit);
17,804✔
987
        if (r < 0)
17,804✔
988
                return r;
989

990
        /* We skipped over the slices, don't accept any now */
991
        if (endswith(unit, ".slice"))
17,776✔
992
                return -ENXIO;
993

994
        if (ret_subgroup) {
17,776✔
995
                _cleanup_free_ char *subgroup = NULL;
×
996
                e += strcspn(e, "/");
587✔
997
                e += strspn(e, "/");
587✔
998

999
                if (isempty(e))
587✔
1000
                        subgroup = NULL;
1001
                else {
1002
                        subgroup = strdup(e);
229✔
1003
                        if (!subgroup)
229✔
1004
                                return -ENOMEM;
×
1005
                }
1006

1007
                path_simplify(subgroup);
587✔
1008

1009
                *ret_subgroup = TAKE_PTR(subgroup);
587✔
1010
        }
1011

1012
        if (ret_unit)
17,776✔
1013
                *ret_unit = TAKE_PTR(unit);
17,776✔
1014

1015
        return 0;
1016
}
1017

1018
int cg_path_get_unit_path(const char *path, char **ret) {
9,875✔
1019
        _cleanup_free_ char *path_copy = NULL;
9,875✔
1020
        char *unit_name;
9,875✔
1021

1022
        assert(path);
9,875✔
1023
        assert(ret);
9,875✔
1024

1025
        path_copy = strdup(path);
9,875✔
1026
        if (!path_copy)
9,875✔
1027
                return -ENOMEM;
1028

1029
        unit_name = (char*) skip_slices(path_copy);
9,875✔
1030
        unit_name[strcspn(unit_name, "/")] = 0;
9,875✔
1031

1032
        if (!unit_name_is_valid(cg_unescape(unit_name), UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
9,875✔
1033
                return -ENXIO;
1034

1035
        *ret = TAKE_PTR(path_copy);
9,872✔
1036

1037
        return 0;
9,872✔
1038
}
1039

1040
int cg_pid_get_unit_full(pid_t pid, char **ret_unit, char **ret_subgroup) {
662✔
1041
        int r;
662✔
1042

1043
        _cleanup_free_ char *cgroup = NULL;
662✔
1044
        r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
662✔
1045
        if (r < 0)
662✔
1046
                return r;
1047

1048
        return cg_path_get_unit_full(cgroup, ret_unit, ret_subgroup);
662✔
1049
}
1050

1051
int cg_pidref_get_unit_full(const PidRef *pidref, char **ret_unit, char **ret_subgroup) {
573✔
1052
        int r;
573✔
1053

1054
        if (!pidref_is_set(pidref))
573✔
1055
                return -ESRCH;
573✔
1056
        if (pidref_is_remote(pidref))
1,146✔
1057
                return -EREMOTE;
1058

1059
        _cleanup_free_ char *unit = NULL, *subgroup = NULL;
573✔
1060
        r = cg_pid_get_unit_full(pidref->pid, &unit, &subgroup);
573✔
1061
        if (r < 0)
573✔
1062
                return r;
1063

1064
        r = pidref_verify(pidref);
573✔
1065
        if (r < 0)
573✔
1066
                return r;
1067

1068
        if (ret_unit)
573✔
1069
                *ret_unit = TAKE_PTR(unit);
573✔
1070
        if (ret_subgroup)
573✔
1071
                *ret_subgroup = TAKE_PTR(subgroup);
22✔
1072
        return 0;
1073
}
1074

1075
static const char* skip_session(const char *p) {
15,569✔
1076
        size_t n;
15,569✔
1077

1078
        /* Skip session-*.scope, but require it to be there. */
1079

1080
        if (isempty(p))
15,569✔
1081
                return NULL;
1082

1083
        p += strspn(p, "/");
15,565✔
1084

1085
        n = strcspn(p, "/");
15,565✔
1086
        if (n < STRLEN("session-x.scope"))
15,565✔
1087
                return NULL;
1088

1089
        const char *s = startswith(p, "session-");
15,377✔
1090
        if (!s)
15,377✔
1091
                return NULL;
1092

1093
        /* Note that session scopes never need unescaping, since they cannot conflict with the kernel's
1094
         * own names, hence we don't need to call cg_unescape() here. */
1095
        char *f = strndupa_safe(s, p + n - s),
27✔
1096
             *e = endswith(f, ".scope");
27✔
1097
        if (!e)
27✔
1098
                return NULL;
1099
        *e = '\0';
27✔
1100

1101
        if (!session_id_valid(f))
27✔
1102
                return NULL;
1103

1104
        return skip_leading_slash(p + n);
27✔
1105
}
1106

1107
static const char* skip_user_manager(const char *p) {
15,970✔
1108
        size_t n;
15,970✔
1109

1110
        /* Skip user@*.service or capsule@*.service, but require either of them to be there. */
1111

1112
        if (isempty(p))
15,970✔
1113
                return NULL;
15,970✔
1114

1115
        p += strspn(p, "/");
15,966✔
1116

1117
        n = strcspn(p, "/");
15,966✔
1118
        if (n < CONST_MIN(STRLEN("user@x.service"), STRLEN("capsule@x.service")))
15,966✔
1119
                return NULL;
1120

1121
        /* Any possible errors from functions called below are converted to NULL return, so our callers won't
1122
         * resolve user/capsule name. */
1123
        _cleanup_free_ char *unit_name = strndup(p, n);
15,780✔
1124
        if (!unit_name)
15,780✔
1125
                return NULL;
1126

1127
        _cleanup_free_ char *i = NULL;
15,780✔
1128
        UnitNameFlags type = unit_name_to_instance(unit_name, &i);
15,780✔
1129

1130
        if (type != UNIT_NAME_INSTANCE)
15,780✔
1131
                return NULL;
1132

1133
        /* Note that user manager services never need unescaping, since they cannot conflict with the
1134
         * kernel's own names, hence we don't need to call cg_unescape() here.  Prudently check validity of
1135
         * instance names, they should be always valid as we validate them upon unit start. */
1136
        if (!(startswith(unit_name, "user@") && parse_uid(i, NULL) >= 0) &&
586✔
1137
            !(startswith(unit_name, "capsule@") && capsule_name_is_valid(i) > 0))
100✔
1138
                return NULL;
90✔
1139

1140
        return skip_leading_slash(p + n);
401✔
1141
}
1142

1143
static const char* skip_user_prefix(const char *path) {
15,970✔
1144
        const char *e, *t;
15,970✔
1145

1146
        assert(path);
15,970✔
1147

1148
        /* Skip slices, if there are any */
1149
        e = skip_slices(path);
15,970✔
1150

1151
        /* Skip the user manager, if it's in the path now... */
1152
        t = skip_user_manager(e);
15,970✔
1153
        if (t)
15,970✔
1154
                return t;
1155

1156
        /* Alternatively skip the user session if it is in the path... */
1157
        return skip_session(e);
15,569✔
1158
}
1159

1160
int cg_path_get_user_unit(const char *path, char **ret) {
8,013✔
1161
        const char *t;
8,013✔
1162

1163
        assert(path);
8,013✔
1164

1165
        t = skip_user_prefix(path);
8,013✔
1166
        if (!t)
8,013✔
1167
                return -ENXIO;
1168

1169
        /* And from here on it looks pretty much the same as for a system unit, hence let's use the same
1170
         * parser. */
1171
        return cg_path_get_unit(t, ret);
222✔
1172
}
1173

1174
int cg_pid_get_user_unit(pid_t pid, char **ret_unit) {
57✔
1175
        _cleanup_free_ char *cgroup = NULL;
57✔
1176
        int r;
57✔
1177

1178
        r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
57✔
1179
        if (r < 0)
57✔
1180
                return r;
1181

1182
        return cg_path_get_user_unit(cgroup, ret_unit);
57✔
1183
}
1184

1185
int cg_path_get_machine_name(const char *path, char **ret_machine) {
40✔
1186
        _cleanup_free_ char *u = NULL;
40✔
1187
        const char *sl;
40✔
1188
        int r;
40✔
1189

1190
        r = cg_path_get_unit(path, &u);
40✔
1191
        if (r < 0)
40✔
1192
                return r;
1193

1194
        sl = strjoina("/run/systemd/machines/unit:", u);
200✔
1195
        return readlink_malloc(sl, ret_machine);
40✔
1196
}
1197

1198
int cg_pid_get_machine_name(pid_t pid, char **ret_machine) {
40✔
1199
        _cleanup_free_ char *cgroup = NULL;
40✔
1200
        int r;
40✔
1201

1202
        r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
40✔
1203
        if (r < 0)
40✔
1204
                return r;
1205

1206
        return cg_path_get_machine_name(cgroup, ret_machine);
40✔
1207
}
1208

1209
int cg_path_get_session(const char *path, char **ret_session) {
8,855✔
1210
        _cleanup_free_ char *unit = NULL;
8,855✔
1211
        char *start, *end;
8,855✔
1212
        int r;
8,855✔
1213

1214
        assert(path);
8,855✔
1215

1216
        r = cg_path_get_unit(path, &unit);
8,855✔
1217
        if (r < 0)
8,855✔
1218
                return r;
1219

1220
        start = startswith(unit, "session-");
8,854✔
1221
        if (!start)
8,854✔
1222
                return -ENXIO;
1223
        end = endswith(start, ".scope");
350✔
1224
        if (!end)
350✔
1225
                return -ENXIO;
1226

1227
        *end = 0;
350✔
1228
        if (!session_id_valid(start))
350✔
1229
                return -ENXIO;
1230

1231
        if (!ret_session)
349✔
1232
                return 0;
1233

1234
        return strdup_to(ret_session, start);
349✔
1235
}
1236

1237
int cg_pid_get_session(pid_t pid, char **ret_session) {
838✔
1238
        _cleanup_free_ char *cgroup = NULL;
838✔
1239
        int r;
838✔
1240

1241
        r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
838✔
1242
        if (r < 0)
838✔
1243
                return r;
1244

1245
        return cg_path_get_session(cgroup, ret_session);
838✔
1246
}
1247

1248
int cg_pidref_get_session(const PidRef *pidref, char **ret) {
359✔
1249
        int r;
359✔
1250

1251
        if (!pidref_is_set(pidref))
359✔
1252
                return -ESRCH;
359✔
1253
        if (pidref_is_remote(pidref))
718✔
1254
                return -EREMOTE;
1255

1256
        _cleanup_free_ char *session = NULL;
359✔
1257
        r = cg_pid_get_session(pidref->pid, &session);
359✔
1258
        if (r < 0)
359✔
1259
                return r;
1260

1261
        r = pidref_verify(pidref);
305✔
1262
        if (r < 0)
305✔
1263
                return r;
1264

1265
        if (ret)
305✔
1266
                *ret = TAKE_PTR(session);
305✔
1267
        return 0;
1268
}
1269

1270
int cg_path_get_owner_uid(const char *path, uid_t *ret_uid) {
8,219✔
1271
        _cleanup_free_ char *slice = NULL;
8,219✔
1272
        char *start, *end;
8,219✔
1273
        int r;
8,219✔
1274

1275
        assert(path);
8,219✔
1276

1277
        r = cg_path_get_slice(path, &slice);
8,219✔
1278
        if (r < 0)
8,219✔
1279
                return r;
1280

1281
        start = startswith(slice, "user-");
8,219✔
1282
        if (!start)
8,219✔
1283
                return -ENXIO;
1284

1285
        end = endswith(start, ".slice");
313✔
1286
        if (!end)
313✔
1287
                return -ENXIO;
1288

1289
        *end = 0;
313✔
1290
        if (parse_uid(start, ret_uid) < 0)
313✔
1291
                return -ENXIO;
×
1292

1293
        return 0;
1294
}
1295

1296
int cg_pid_get_owner_uid(pid_t pid, uid_t *ret_uid) {
225✔
1297
        _cleanup_free_ char *cgroup = NULL;
225✔
1298
        int r;
225✔
1299

1300
        r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
225✔
1301
        if (r < 0)
225✔
1302
                return r;
1303

1304
        return cg_path_get_owner_uid(cgroup, ret_uid);
225✔
1305
}
1306

1307
int cg_pidref_get_owner_uid(const PidRef *pidref, uid_t *ret) {
54✔
1308
        int r;
54✔
1309

1310
        if (!pidref_is_set(pidref))
54✔
1311
                return -ESRCH;
54✔
1312
        if (pidref_is_remote(pidref))
54✔
1313
                return -EREMOTE;
1314

1315
        uid_t uid;
54✔
1316
        r = cg_pid_get_owner_uid(pidref->pid, &uid);
54✔
1317
        if (r < 0)
54✔
1318
                return r;
1319

1320
        r = pidref_verify(pidref);
12✔
1321
        if (r < 0)
12✔
1322
                return r;
1323

1324
        if (ret)
12✔
1325
                *ret = uid;
12✔
1326

1327
        return 0;
1328
}
1329

1330
int cg_path_get_slice(const char *p, char **ret_slice) {
16,436✔
1331
        const char *e = NULL;
16,436✔
1332

1333
        assert(p);
16,436✔
1334

1335
        /* Finds the right-most slice unit from the beginning, but stops before we come to
1336
         * the first non-slice unit. */
1337

1338
        for (;;) {
49,968✔
1339
                const char *s;
33,202✔
1340
                int n;
33,202✔
1341

1342
                n = path_find_first_component(&p, /* accept_dot_dot = */ false, &s);
33,202✔
1343
                if (n < 0)
33,202✔
1344
                        return n;
×
1345
                if (!valid_slice_name(s, n))
33,202✔
1346
                        break;
1347

1348
                e = s;
16,766✔
1349
        }
1350

1351
        if (e)
16,436✔
1352
                return cg_path_decode_unit(e, ret_slice);
16,182✔
1353

1354
        if (ret_slice)
254✔
1355
                return strdup_to(ret_slice, SPECIAL_ROOT_SLICE);
254✔
1356

1357
        return 0;
1358
}
1359

1360
int cg_pid_get_slice(pid_t pid, char **ret_slice) {
61✔
1361
        _cleanup_free_ char *cgroup = NULL;
61✔
1362
        int r;
61✔
1363

1364
        r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
61✔
1365
        if (r < 0)
61✔
1366
                return r;
1367

1368
        return cg_path_get_slice(cgroup, ret_slice);
61✔
1369
}
1370

1371
int cg_path_get_user_slice(const char *p, char **ret_slice) {
7,957✔
1372
        const char *t;
7,957✔
1373
        assert(p);
7,957✔
1374

1375
        t = skip_user_prefix(p);
7,957✔
1376
        if (!t)
7,957✔
1377
                return -ENXIO;
1378

1379
        /* And now it looks pretty much the same as for a system slice, so let's just use the same parser
1380
         * from here on. */
1381
        return cg_path_get_slice(t, ret_slice);
206✔
1382
}
1383

1384
int cg_pid_get_user_slice(pid_t pid, char **ret_slice) {
1✔
1385
        _cleanup_free_ char *cgroup = NULL;
1✔
1386
        int r;
1✔
1387

1388
        r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1✔
1389
        if (r < 0)
1✔
1390
                return r;
1391

1392
        return cg_path_get_user_slice(cgroup, ret_slice);
1✔
1393
}
1394

1395
bool cg_needs_escape(const char *p) {
21,794✔
1396

1397
        /* Checks if the specified path is a valid cgroup name by our rules, or if it must be escaped. Note
1398
         * that we consider escaped cgroup names invalid here, as they need to be escaped a second time if
1399
         * they shall be used. Also note that various names cannot be made valid by escaping even if we
1400
         * return true here (because too long, or contain the forbidden character "/"). */
1401

1402
        if (!filename_is_valid(p))
21,794✔
1403
                return true;
1404

1405
        if (IN_SET(p[0], '_', '.'))
21,790✔
1406
                return true;
1407

1408
        if (STR_IN_SET(p, "notify_on_release", "release_agent", "tasks"))
21,784✔
1409
                return true;
2✔
1410

1411
        if (startswith(p, "cgroup."))
21,782✔
1412
                return true;
1413

1414
        for (CGroupController c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
304,920✔
1415
                const char *q;
283,140✔
1416

1417
                q = startswith(p, cgroup_controller_to_string(c));
283,140✔
1418
                if (!q)
283,140✔
1419
                        continue;
283,140✔
1420

1421
                if (q[0] == '.')
×
1422
                        return true;
1423
        }
1424

1425
        return false;
1426
}
1427

1428
int cg_escape(const char *p, char **ret) {
21,571✔
1429
        _cleanup_free_ char *n = NULL;
21,571✔
1430

1431
        /* This implements very minimal escaping for names to be used as file names in the cgroup tree: any
1432
         * name which might conflict with a kernel name or is prefixed with '_' is prefixed with a '_'. That
1433
         * way, when reading cgroup names it is sufficient to remove a single prefixing underscore if there
1434
         * is one. */
1435

1436
        /* The return value of this function (unlike cg_unescape()) needs free()! */
1437

1438
        if (cg_needs_escape(p)) {
21,571✔
1439
                n = strjoin("_", p);
7✔
1440
                if (!n)
7✔
1441
                        return -ENOMEM;
1442

1443
                if (!filename_is_valid(n)) /* became invalid due to the prefixing? Or contained things like a slash that cannot be fixed by prefixing? */
7✔
1444
                        return -EINVAL;
1445
        } else {
1446
                n = strdup(p);
21,564✔
1447
                if (!n)
21,564✔
1448
                        return -ENOMEM;
1449
        }
1450

1451
        *ret = TAKE_PTR(n);
21,571✔
1452
        return 0;
21,571✔
1453
}
1454

1455
char* cg_unescape(const char *p) {
105,589✔
1456
        assert(p);
105,589✔
1457

1458
        /* The return value of this function (unlike cg_escape())
1459
         * doesn't need free()! */
1460

1461
        if (p[0] == '_')
105,589✔
1462
                return (char*) p+1;
14✔
1463

1464
        return (char*) p;
1465
}
1466

1467
#define CONTROLLER_VALID                        \
1468
        DIGITS LETTERS                          \
1469
        "_"
1470

1471
bool cg_controller_is_valid(const char *p) {
288,517✔
1472
        const char *t, *s;
288,517✔
1473

1474
        if (!p)
288,517✔
1475
                return false;
1476

1477
        if (streq(p, SYSTEMD_CGROUP_CONTROLLER))
288,517✔
1478
                return true;
1479

1480
        s = startswith(p, "name=");
50,776✔
1481
        if (s)
50,776✔
1482
                p = s;
2✔
1483

1484
        if (IN_SET(*p, 0, '_'))
50,776✔
1485
                return false;
1486

1487
        for (t = p; *t; t++)
326,333✔
1488
                if (!strchr(CONTROLLER_VALID, *t))
275,568✔
1489
                        return false;
1490

1491
        if (t - p > NAME_MAX)
50,765✔
1492
                return false;
×
1493

1494
        return true;
1495
}
1496

1497
int cg_slice_to_path(const char *unit, char **ret) {
9,327✔
1498
        _cleanup_free_ char *p = NULL, *s = NULL, *e = NULL;
9,327✔
1499
        const char *dash;
9,327✔
1500
        int r;
9,327✔
1501

1502
        assert(unit);
9,327✔
1503
        assert(ret);
9,327✔
1504

1505
        if (streq(unit, SPECIAL_ROOT_SLICE))
9,327✔
1506
                return strdup_to(ret, "");
7✔
1507

1508
        if (!unit_name_is_valid(unit, UNIT_NAME_PLAIN))
9,320✔
1509
                return -EINVAL;
1510

1511
        if (!endswith(unit, ".slice"))
9,309✔
1512
                return -EINVAL;
1513

1514
        r = unit_name_to_prefix(unit, &p);
9,308✔
1515
        if (r < 0)
9,308✔
1516
                return r;
1517

1518
        dash = strchr(p, '-');
9,308✔
1519

1520
        /* Don't allow initial dashes */
1521
        if (dash == p)
9,308✔
1522
                return -EINVAL;
1523

1524
        while (dash) {
9,616✔
1525
                _cleanup_free_ char *escaped = NULL;
313✔
1526
                char n[dash - p + sizeof(".slice")];
313✔
1527

1528
#if HAS_FEATURE_MEMORY_SANITIZER
1529
                /* msan doesn't instrument stpncpy, so it thinks
1530
                 * n is later used uninitialized:
1531
                 * https://github.com/google/sanitizers/issues/926
1532
                 */
1533
                zero(n);
1534
#endif
1535

1536
                /* Don't allow trailing or double dashes */
1537
                if (IN_SET(dash[1], 0, '-'))
313✔
1538
                        return -EINVAL;
1539

1540
                strcpy(stpncpy(n, p, dash - p), ".slice");
311✔
1541
                if (!unit_name_is_valid(n, UNIT_NAME_PLAIN))
311✔
1542
                        return -EINVAL;
1543

1544
                r = cg_escape(n, &escaped);
311✔
1545
                if (r < 0)
311✔
1546
                        return r;
1547

1548
                if (!strextend(&s, escaped, "/"))
311✔
1549
                        return -ENOMEM;
1550

1551
                dash = strchr(dash+1, '-');
311✔
1552
        }
1553

1554
        r = cg_escape(unit, &e);
9,303✔
1555
        if (r < 0)
9,303✔
1556
                return r;
1557

1558
        if (!strextend(&s, e))
9,303✔
1559
                return -ENOMEM;
1560

1561
        *ret = TAKE_PTR(s);
9,303✔
1562
        return 0;
9,303✔
1563
}
1564

1565
int cg_is_threaded(const char *path) {
×
1566
        _cleanup_free_ char *fs = NULL, *contents = NULL;
×
1567
        _cleanup_strv_free_ char **v = NULL;
×
1568
        int r;
×
1569

1570
        r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, path, "cgroup.type", &fs);
×
1571
        if (r < 0)
×
1572
                return r;
1573

1574
        r = read_full_virtual_file(fs, &contents, NULL);
×
1575
        if (r == -ENOENT)
×
1576
                return false; /* Assume no. */
1577
        if (r < 0)
×
1578
                return r;
1579

1580
        v = strv_split(contents, NULL);
×
1581
        if (!v)
×
1582
                return -ENOMEM;
1583

1584
        /* If the cgroup is in the threaded mode, it contains "threaded".
1585
         * If one of the parents or siblings is in the threaded mode, it may contain "invalid". */
1586
        return strv_contains(v, "threaded") || strv_contains(v, "invalid");
×
1587
}
1588

1589
int cg_set_attribute(const char *controller, const char *path, const char *attribute, const char *value) {
41,019✔
1590
        _cleanup_free_ char *p = NULL;
41,019✔
1591
        int r;
41,019✔
1592

1593
        assert(attribute);
41,019✔
1594

1595
        r = cg_get_path(controller, path, attribute, &p);
41,019✔
1596
        if (r < 0)
41,019✔
1597
                return r;
1598

1599
        /* https://lore.kernel.org/all/20250419183545.1982187-1-shakeel.butt@linux.dev/ adds O_NONBLOCK
1600
         * semantics to memory.max and memory.high to skip synchronous memory reclaim when O_NONBLOCK is
1601
         * enabled. Let's always open cgroupv2 attribute files in nonblocking mode to immediately take
1602
         * advantage of this and any other asynchronous resource reclaim that's added to the cgroupv2 API in
1603
         * the future. */
1604
        return write_string_file(p, value, WRITE_STRING_FILE_DISABLE_BUFFER|WRITE_STRING_FILE_OPEN_NONBLOCKING);
41,019✔
1605
}
1606

1607
int cg_get_attribute(const char *controller, const char *path, const char *attribute, char **ret) {
27,218✔
1608
        _cleanup_free_ char *p = NULL;
27,218✔
1609
        int r;
27,218✔
1610

1611
        assert(attribute);
27,218✔
1612

1613
        r = cg_get_path(controller, path, attribute, &p);
27,218✔
1614
        if (r < 0)
27,218✔
1615
                return r;
1616

1617
        return read_one_line_file(p, ret);
27,218✔
1618
}
1619

1620
int cg_get_attribute_as_uint64(const char *controller, const char *path, const char *attribute, uint64_t *ret) {
23,013✔
1621
        _cleanup_free_ char *value = NULL;
23,013✔
1622
        uint64_t v;
23,013✔
1623
        int r;
23,013✔
1624

1625
        assert(ret);
23,013✔
1626

1627
        r = cg_get_attribute(controller, path, attribute, &value);
23,013✔
1628
        if (r == -ENOENT)
23,013✔
1629
                return -ENODATA;
1630
        if (r < 0)
21,027✔
1631
                return r;
1632

1633
        if (streq(value, "max")) {
21,027✔
1634
                *ret = CGROUP_LIMIT_MAX;
4,986✔
1635
                return 0;
4,986✔
1636
        }
1637

1638
        r = safe_atou64(value, &v);
16,041✔
1639
        if (r < 0)
16,041✔
1640
                return r;
1641

1642
        *ret = v;
16,041✔
1643
        return 0;
16,041✔
1644
}
1645

1646
int cg_get_attribute_as_bool(const char *controller, const char *path, const char *attribute) {
64✔
1647
        _cleanup_free_ char *value = NULL;
64✔
1648
        int r;
64✔
1649

1650
        r = cg_get_attribute(controller, path, attribute, &value);
64✔
1651
        if (r == -ENOENT)
64✔
1652
                return -ENODATA;
1653
        if (r < 0)
64✔
1654
                return r;
1655

1656
        return parse_boolean(value);
64✔
1657
}
1658

1659
int cg_get_owner(const char *path, uid_t *ret_uid) {
35✔
1660
        _cleanup_free_ char *f = NULL;
35✔
1661
        struct stat stats;
35✔
1662
        int r;
35✔
1663

1664
        assert(ret_uid);
35✔
1665

1666
        r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, path, NULL, &f);
35✔
1667
        if (r < 0)
35✔
1668
                return r;
1669

1670
        if (stat(f, &stats) < 0)
35✔
1671
                return -errno;
16✔
1672

1673
        r = stat_verify_directory(&stats);
19✔
1674
        if (r < 0)
19✔
1675
                return r;
1676

1677
        *ret_uid = stats.st_uid;
19✔
1678
        return 0;
19✔
1679
}
1680

1681
int cg_get_keyed_attribute(
21,378✔
1682
                const char *controller,
1683
                const char *path,
1684
                const char *attribute,
1685
                char * const *keys,
1686
                char **values) {
1687

1688
        _cleanup_free_ char *filename = NULL, *contents = NULL;
21,378✔
1689
        size_t n;
21,378✔
1690
        int r;
21,378✔
1691

1692
        assert(path);
21,378✔
1693
        assert(attribute);
21,378✔
1694

1695
        /* Reads one or more fields of a cgroup v2 keyed attribute file. The 'keys' parameter should be an strv with
1696
         * all keys to retrieve. The 'values' parameter should be passed as string size with the same number of
1697
         * entries as 'keys'. On success each entry will be set to the value of the matching key.
1698
         *
1699
         * If the attribute file doesn't exist at all returns ENOENT, if any key is not found returns ENXIO. */
1700

1701
        r = cg_get_path(controller, path, attribute, &filename);
21,378✔
1702
        if (r < 0)
21,378✔
1703
                return r;
1704

1705
        r = read_full_file(filename, &contents, /* ret_size = */ NULL);
21,378✔
1706
        if (r < 0)
21,378✔
1707
                return r;
1708

1709
        n = strv_length(keys);
19,173✔
1710
        if (n == 0) /* No keys to retrieve? That's easy, we are done then */
19,173✔
1711
                return 0;
1712
        assert(strv_is_uniq(keys));
19,173✔
1713

1714
        /* Let's build this up in a temporary array for now in order not to clobber the return parameter on failure */
1715
        char **v = newa0(char*, n);
19,173✔
1716
        size_t n_done = 0;
19,173✔
1717

1718
        for (const char *p = contents; *p;) {
64,071✔
1719
                const char *w;
1720
                size_t i;
1721

1722
                for (i = 0; i < n; i++) {
108,969✔
1723
                        w = first_word(p, keys[i]);
70,667✔
1724
                        if (w)
70,667✔
1725
                                break;
1726
                }
1727

1728
                if (w) {
64,071✔
1729
                        if (v[i]) { /* duplicate entry? */
25,769✔
1730
                                r = -EBADMSG;
×
1731
                                goto fail;
×
1732
                        }
1733

1734
                        size_t l = strcspn(w, NEWLINE);
25,769✔
1735

1736
                        v[i] = strndup(w, l);
25,769✔
1737
                        if (!v[i]) {
25,769✔
1738
                                r = -ENOMEM;
×
1739
                                goto fail;
×
1740
                        }
1741

1742
                        n_done++;
25,769✔
1743
                        if (n_done >= n)
25,769✔
1744
                                break;
1745

1746
                        p = w + l;
6,596✔
1747
                } else
1748
                        p += strcspn(p, NEWLINE);
38,302✔
1749

1750
                p += strspn(p, NEWLINE);
44,898✔
1751
        }
1752

1753
        if (n_done < n) {
19,173✔
1754
                r = -ENXIO;
×
1755
                goto fail;
×
1756
        }
1757

1758
        memcpy(values, v, sizeof(char*) * n);
19,173✔
1759
        return 0;
19,173✔
1760

1761
fail:
×
1762
        free_many_charp(v, n);
21,378✔
1763
        return r;
1764
}
1765

1766
int cg_mask_to_string(CGroupMask mask, char **ret) {
8,381✔
1767
        _cleanup_free_ char *s = NULL;
8,381✔
1768
        bool space = false;
8,381✔
1769
        CGroupController c;
8,381✔
1770
        size_t n = 0;
8,381✔
1771

1772
        assert(ret);
8,381✔
1773

1774
        if (mask == 0) {
8,381✔
1775
                *ret = NULL;
4,797✔
1776
                return 0;
4,797✔
1777
        }
1778

1779
        for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
50,176✔
1780
                const char *k;
46,592✔
1781
                size_t l;
46,592✔
1782

1783
                if (!FLAGS_SET(mask, CGROUP_CONTROLLER_TO_MASK(c)))
46,592✔
1784
                        continue;
26,235✔
1785

1786
                k = cgroup_controller_to_string(c);
20,357✔
1787
                l = strlen(k);
20,357✔
1788

1789
                if (!GREEDY_REALLOC(s, n + space + l + 1))
20,357✔
1790
                        return -ENOMEM;
1791

1792
                if (space)
20,357✔
1793
                        s[n] = ' ';
16,773✔
1794
                memcpy(s + n + space, k, l);
20,357✔
1795
                n += space + l;
20,357✔
1796

1797
                space = true;
20,357✔
1798
        }
1799

1800
        assert(s);
3,584✔
1801

1802
        s[n] = 0;
3,584✔
1803
        *ret = TAKE_PTR(s);
3,584✔
1804

1805
        return 0;
3,584✔
1806
}
1807

1808
int cg_mask_from_string(const char *value, CGroupMask *ret) {
3,653✔
1809
        CGroupMask m = 0;
3,653✔
1810

1811
        assert(ret);
3,653✔
1812
        assert(value);
3,653✔
1813

1814
        for (;;) {
24,732✔
1815
                _cleanup_free_ char *n = NULL;
21,079✔
1816
                CGroupController v;
24,732✔
1817
                int r;
24,732✔
1818

1819
                r = extract_first_word(&value, &n, NULL, 0);
24,732✔
1820
                if (r < 0)
24,732✔
1821
                        return r;
×
1822
                if (r == 0)
24,732✔
1823
                        break;
1824

1825
                v = cgroup_controller_from_string(n);
21,079✔
1826
                if (v < 0)
21,079✔
1827
                        continue;
750✔
1828

1829
                m |= CGROUP_CONTROLLER_TO_MASK(v);
20,329✔
1830
        }
1831

1832
        *ret = m;
3,653✔
1833
        return 0;
3,653✔
1834
}
1835

1836
int cg_mask_supported_subtree(const char *root, CGroupMask *ret) {
493✔
1837
        CGroupMask mask;
493✔
1838
        int r;
493✔
1839

1840
        /* Determines the mask of supported cgroup controllers. Only includes controllers we can make sense of and that
1841
         * are actually accessible. Only covers real controllers, i.e. not the CGROUP_CONTROLLER_BPF_xyz
1842
         * pseudo-controllers. */
1843

1844
        r = cg_all_unified();
493✔
1845
        if (r < 0)
493✔
1846
                return r;
493✔
1847
        if (r > 0) {
493✔
1848
                _cleanup_free_ char *controllers = NULL, *path = NULL;
493✔
1849

1850
                /* In the unified hierarchy we can read the supported and accessible controllers from
1851
                 * the top-level cgroup attribute */
1852

1853
                r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, root, "cgroup.controllers", &path);
493✔
1854
                if (r < 0)
493✔
1855
                        return r;
1856

1857
                r = read_one_line_file(path, &controllers);
493✔
1858
                if (r < 0)
493✔
1859
                        return r;
1860

1861
                r = cg_mask_from_string(controllers, &mask);
493✔
1862
                if (r < 0)
493✔
1863
                        return r;
1864

1865
                /* Mask controllers that are not supported in unified hierarchy. */
1866
                mask &= CGROUP_MASK_V2;
493✔
1867

1868
        } else {
1869
                CGroupController c;
×
1870

1871
                /* In the legacy hierarchy, we check which hierarchies are accessible. */
1872

1873
                mask = 0;
×
1874
                for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
×
1875
                        CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
×
1876
                        const char *n;
×
1877

1878
                        if (!FLAGS_SET(CGROUP_MASK_V1, bit))
×
1879
                                continue;
×
1880

1881
                        n = cgroup_controller_to_string(c);
×
1882
                        if (controller_is_v1_accessible(root, n) >= 0)
×
1883
                                mask |= bit;
×
1884
                }
1885
        }
1886

1887
        *ret = mask;
493✔
1888
        return 0;
493✔
1889
}
1890

1891
int cg_mask_supported(CGroupMask *ret) {
244✔
1892
        _cleanup_free_ char *root = NULL;
244✔
1893
        int r;
244✔
1894

1895
        r = cg_get_root_path(&root);
244✔
1896
        if (r < 0)
244✔
1897
                return r;
1898

1899
        return cg_mask_supported_subtree(root, ret);
244✔
1900
}
1901

1902
/* The hybrid mode was initially implemented in v232 and simply mounted cgroup2 on
1903
 * /sys/fs/cgroup/systemd. This unfortunately broke other tools (such as docker) which expected the v1
1904
 * "name=systemd" hierarchy on /sys/fs/cgroup/systemd. From v233 and on, the hybrid mode mounts v2 on
1905
 * /sys/fs/cgroup/unified and maintains "name=systemd" hierarchy on /sys/fs/cgroup/systemd for compatibility
1906
 * with other tools.
1907
 *
1908
 * To keep live upgrade working, we detect and support v232 layout. When v232 layout is detected, to keep
1909
 * cgroup v2 process management but disable the compat dual layout, we return true on
1910
 * cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER) and false on cg_hybrid_unified().
1911
 */
1912
static thread_local bool unified_systemd_v232;
1913

1914
int cg_unified_cached(bool flush) {
293,990✔
1915
        static thread_local CGroupUnified unified_cache = CGROUP_UNIFIED_UNKNOWN;
293,990✔
1916

1917
        struct statfs fs;
293,990✔
1918

1919
        /* Checks if we support the unified hierarchy. Returns an
1920
         * error when the cgroup hierarchies aren't mounted yet or we
1921
         * have any other trouble determining if the unified hierarchy
1922
         * is supported. */
1923

1924
        if (flush)
293,990✔
1925
                unified_cache = CGROUP_UNIFIED_UNKNOWN;
4✔
1926
        else if (unified_cache >= CGROUP_UNIFIED_NONE)
293,986✔
1927
                return unified_cache;
293,990✔
1928

1929
        if (statfs("/sys/fs/cgroup/", &fs) < 0)
13,169✔
1930
                return log_debug_errno(errno, "statfs(\"/sys/fs/cgroup/\") failed: %m");
×
1931

1932
        if (F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC)) {
13,169✔
1933
                log_debug("Found cgroup2 on /sys/fs/cgroup/, full unified hierarchy");
13,169✔
1934
                unified_cache = CGROUP_UNIFIED_ALL;
13,169✔
1935
        } else if (F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC)) {
×
1936
                if (statfs("/sys/fs/cgroup/unified/", &fs) == 0 &&
×
1937
                    F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC)) {
×
1938
                        log_debug("Found cgroup2 on /sys/fs/cgroup/unified, unified hierarchy for systemd controller");
×
1939
                        unified_cache = CGROUP_UNIFIED_SYSTEMD;
×
1940
                        unified_systemd_v232 = false;
×
1941
                } else {
1942
                        if (statfs("/sys/fs/cgroup/systemd/", &fs) < 0) {
×
1943
                                if (errno == ENOENT) {
×
1944
                                        /* Some other software may have set up /sys/fs/cgroup in a configuration we do not recognize. */
1945
                                        log_debug_errno(errno, "Unsupported cgroupsv1 setup detected: name=systemd hierarchy not found.");
×
1946
                                        return -ENOMEDIUM;
×
1947
                                }
1948
                                return log_debug_errno(errno, "statfs(\"/sys/fs/cgroup/systemd\" failed: %m");
×
1949
                        }
1950

1951
                        if (F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC)) {
×
1952
                                log_debug("Found cgroup2 on /sys/fs/cgroup/systemd, unified hierarchy for systemd controller (v232 variant)");
×
1953
                                unified_cache = CGROUP_UNIFIED_SYSTEMD;
×
1954
                                unified_systemd_v232 = true;
×
1955
                        } else if (F_TYPE_EQUAL(fs.f_type, CGROUP_SUPER_MAGIC)) {
×
1956
                                log_debug("Found cgroup on /sys/fs/cgroup/systemd, legacy hierarchy");
×
1957
                                unified_cache = CGROUP_UNIFIED_NONE;
×
1958
                        } else {
1959
                                log_debug("Unexpected filesystem type %llx mounted on /sys/fs/cgroup/systemd, assuming legacy hierarchy",
×
1960
                                          (unsigned long long) fs.f_type);
1961
                                unified_cache = CGROUP_UNIFIED_NONE;
×
1962
                        }
1963
                }
1964
        } else if (F_TYPE_EQUAL(fs.f_type, SYSFS_MAGIC)) {
×
1965
                return log_debug_errno(SYNTHETIC_ERRNO(ENOMEDIUM),
×
1966
                                       "No filesystem is currently mounted on /sys/fs/cgroup.");
1967
        } else
1968
                return log_debug_errno(SYNTHETIC_ERRNO(ENOMEDIUM),
×
1969
                                       "Unknown filesystem type %llx mounted on /sys/fs/cgroup.",
1970
                                       (unsigned long long)fs.f_type);
1971

1972
        return unified_cache;
13,169✔
1973
}
1974

1975
int cg_unified_controller(const char *controller) {
41,095✔
1976
        int r;
41,095✔
1977

1978
        r = cg_unified_cached(false);
41,095✔
1979
        if (r < 0)
41,095✔
1980
                return r;
1981

1982
        if (r == CGROUP_UNIFIED_NONE)
41,095✔
1983
                return false;
1984

1985
        if (r >= CGROUP_UNIFIED_ALL)
41,095✔
1986
                return true;
1987

1988
        return streq_ptr(controller, SYSTEMD_CGROUP_CONTROLLER);
×
1989
}
1990

1991
int cg_all_unified(void) {
252,889✔
1992
        int r;
252,889✔
1993

1994
        r = cg_unified_cached(false);
252,889✔
1995
        if (r < 0)
252,889✔
1996
                return r;
1997

1998
        return r >= CGROUP_UNIFIED_ALL;
252,889✔
1999
}
2000

2001
int cg_hybrid_unified(void) {
1✔
2002
        int r;
1✔
2003

2004
        r = cg_unified_cached(false);
1✔
2005
        if (r < 0)
1✔
2006
                return r;
2007

2008
        return r == CGROUP_UNIFIED_SYSTEMD && !unified_systemd_v232;
1✔
2009
}
2010

2011
int cg_is_delegated(const char *path) {
19✔
2012
        int r;
19✔
2013

2014
        assert(path);
19✔
2015

2016
        r = cg_get_xattr_bool(path, "trusted.delegate");
19✔
2017
        if (!ERRNO_IS_NEG_XATTR_ABSENT(r))
19✔
2018
                return r;
2019

2020
        /* If the trusted xattr isn't set (preferred), then check the untrusted one. Under the assumption
2021
         * that whoever is trusted enough to own the cgroup, is also trusted enough to decide if it is
2022
         * delegated or not this should be safe. */
2023
        r = cg_get_xattr_bool(path, "user.delegate");
6✔
2024
        return ERRNO_IS_NEG_XATTR_ABSENT(r) ? false : r;
6✔
2025
}
2026

2027
int cg_is_delegated_fd(int fd) {
199✔
2028
        int r;
199✔
2029

2030
        assert(fd >= 0);
199✔
2031

2032
        r = getxattr_at_bool(fd, /* path= */ NULL, "trusted.delegate", /* at_flags= */ 0);
199✔
2033
        if (!ERRNO_IS_NEG_XATTR_ABSENT(r))
199✔
2034
                return r;
2035

2036
        r = getxattr_at_bool(fd, /* path= */ NULL, "user.delegate", /* at_flags= */ 0);
185✔
2037
        return ERRNO_IS_NEG_XATTR_ABSENT(r) ? false : r;
185✔
2038
}
2039

2040
int cg_has_coredump_receive(const char *path) {
2✔
2041
        int r;
2✔
2042

2043
        assert(path);
2✔
2044

2045
        r = cg_get_xattr_bool(path, "user.coredump_receive");
2✔
2046
        if (ERRNO_IS_NEG_XATTR_ABSENT(r))
2✔
2047
                return false;
×
2048

2049
        return r;
2050
}
2051

2052
const uint64_t cgroup_io_limit_defaults[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2053
        [CGROUP_IO_RBPS_MAX]  = CGROUP_LIMIT_MAX,
2054
        [CGROUP_IO_WBPS_MAX]  = CGROUP_LIMIT_MAX,
2055
        [CGROUP_IO_RIOPS_MAX] = CGROUP_LIMIT_MAX,
2056
        [CGROUP_IO_WIOPS_MAX] = CGROUP_LIMIT_MAX,
2057
};
2058

2059
static const char* const cgroup_io_limit_type_table[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2060
        [CGROUP_IO_RBPS_MAX]  = "IOReadBandwidthMax",
2061
        [CGROUP_IO_WBPS_MAX]  = "IOWriteBandwidthMax",
2062
        [CGROUP_IO_RIOPS_MAX] = "IOReadIOPSMax",
2063
        [CGROUP_IO_WIOPS_MAX] = "IOWriteIOPSMax",
2064
};
2065

2066
DEFINE_STRING_TABLE_LOOKUP(cgroup_io_limit_type, CGroupIOLimitType);
6,355✔
2067

2068
void cgroup_io_limits_list(void) {
20✔
2069
        DUMP_STRING_TABLE(cgroup_io_limit_type, CGroupIOLimitType, _CGROUP_IO_LIMIT_TYPE_MAX);
100✔
2070
}
20✔
2071

2072
static const char *const cgroup_controller_table[_CGROUP_CONTROLLER_MAX] = {
2073
        [CGROUP_CONTROLLER_CPU]                             = "cpu",
2074
        [CGROUP_CONTROLLER_CPUACCT]                         = "cpuacct",
2075
        [CGROUP_CONTROLLER_CPUSET]                          = "cpuset",
2076
        [CGROUP_CONTROLLER_IO]                              = "io",
2077
        [CGROUP_CONTROLLER_BLKIO]                           = "blkio",
2078
        [CGROUP_CONTROLLER_MEMORY]                          = "memory",
2079
        [CGROUP_CONTROLLER_DEVICES]                         = "devices",
2080
        [CGROUP_CONTROLLER_PIDS]                            = "pids",
2081
        [CGROUP_CONTROLLER_BPF_FIREWALL]                    = "bpf-firewall",
2082
        [CGROUP_CONTROLLER_BPF_DEVICES]                     = "bpf-devices",
2083
        [CGROUP_CONTROLLER_BPF_FOREIGN]                     = "bpf-foreign",
2084
        [CGROUP_CONTROLLER_BPF_SOCKET_BIND]                 = "bpf-socket-bind",
2085
        [CGROUP_CONTROLLER_BPF_RESTRICT_NETWORK_INTERFACES] = "bpf-restrict-network-interfaces",
2086
};
2087

2088
DEFINE_STRING_TABLE_LOOKUP(cgroup_controller, CGroupController);
349,282✔
2089

2090
static const char* const managed_oom_mode_table[_MANAGED_OOM_MODE_MAX] = {
2091
        [MANAGED_OOM_AUTO] = "auto",
2092
        [MANAGED_OOM_KILL] = "kill",
2093
};
2094

2095
DEFINE_STRING_TABLE_LOOKUP(managed_oom_mode, ManagedOOMMode);
31,773✔
2096

2097
static const char* const managed_oom_preference_table[_MANAGED_OOM_PREFERENCE_MAX] = {
2098
        [MANAGED_OOM_PREFERENCE_NONE] = "none",
2099
        [MANAGED_OOM_PREFERENCE_AVOID] = "avoid",
2100
        [MANAGED_OOM_PREFERENCE_OMIT] = "omit",
2101
};
2102

2103
DEFINE_STRING_TABLE_LOOKUP(managed_oom_preference, ManagedOOMPreference);
15,636✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc