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

systemd / systemd / 16104615022

06 Jul 2025 08:06PM UTC coverage: 72.1% (+0.04%) from 72.057%
16104615022

push

github

web-flow
Two follow-ups for recent PRs (#38062)

12 of 13 new or added lines in 2 files covered. (92.31%)

1207 existing lines in 43 files now uncovered.

300846 of 417265 relevant lines covered (72.1%)

718237.88 hits per line

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

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

3
#include <signal.h>
4
#include <stdlib.h>
5
#include <sys/xattr.h>
6
#include <threads.h>
7
#include <unistd.h>
8

9
#include "alloc-util.h"
10
#include "capsule-util.h"
11
#include "cgroup-util.h"
12
#include "dirent-util.h"
13
#include "errno-util.h"
14
#include "extract-word.h"
15
#include "fd-util.h"
16
#include "fileio.h"
17
#include "format-util.h"
18
#include "fs-util.h"
19
#include "log.h"
20
#include "login-util.h"
21
#include "missing_fs.h"
22
#include "missing_magic.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 "unit-name.h"
34
#include "user-util.h"
35
#include "xattr-util.h"
36

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

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

49
#define CG_FILE_HANDLE_CGROUPID(fh) (*CAST_ALIGN_PTR(uint64_t, (fh).file_handle.f_handle))
50

51
int cg_path_open(const char *controller, const char *path) {
822✔
52
        _cleanup_free_ char *fs = NULL;
822✔
53
        int r;
822✔
54

55
        r = cg_get_path(controller, path, /* suffix=*/ NULL, &fs);
822✔
56
        if (r < 0)
822✔
57
                return r;
58

59
        return RET_NERRNO(open(fs, O_DIRECTORY|O_CLOEXEC));
822✔
60
}
61

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

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

70
                cgroupfs_fd = fsfd;
71
        }
72

73
        cg_file_handle fh = CG_FILE_HANDLE_INIT;
1✔
74
        CG_FILE_HANDLE_CGROUPID(fh) = id;
1✔
75

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

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

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

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

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

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

100
int cg_get_cgroupid_at(int dfd, const char *path, uint64_t *ret) {
4,082✔
101
        cg_file_handle fh = CG_FILE_HANDLE_INIT;
4,082✔
102
        int mnt_id;
4,082✔
103

104
        assert(dfd >= 0 || (dfd == AT_FDCWD && path_is_absolute(path)));
8,155✔
105
        assert(ret);
4,082✔
106

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

114
        *ret = CG_FILE_HANDLE_CGROUPID(fh);
4,082✔
115
        return 0;
4,082✔
116
}
117

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

123
        assert(ret);
14,167✔
124

125
        r = cg_get_path(controller, path, "cgroup.procs", &fs);
14,167✔
126
        if (r < 0)
14,167✔
127
                return r;
128

129
        f = fopen(fs, "re");
14,167✔
130
        if (!f)
14,167✔
131
                return -errno;
8,512✔
132

133
        *ret = f;
5,655✔
134
        return 0;
5,655✔
135
}
136

137
int cg_read_pid(FILE *f, pid_t *ret, CGroupFlags flags) {
9,523✔
138
        unsigned long ul;
9,523✔
139

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

142
        assert(f);
9,523✔
143
        assert(ret);
9,523✔
144

145
        for (;;) {
9,523✔
146
                errno = 0;
9,523✔
147
                if (fscanf(f, "%lu", &ul) != 1) {
9,523✔
148

149
                        if (feof(f)) {
5,713✔
150
                                *ret = 0;
5,713✔
151
                                return 0;
5,713✔
152
                        }
153

154
                        return errno_or_else(EIO);
×
155
                }
156

157
                if (ul > PID_T_MAX)
3,810✔
158
                        return -EIO;
159

160
                /* In some circumstances (e.g. WSL), cgroups might contain unmappable PIDs from other
161
                 * contexts. These show up as zeros, and depending on the caller, can either be plain
162
                 * skipped over, or returned as-is. */
163
                if (ul == 0 && !FLAGS_SET(flags, CGROUP_DONT_SKIP_UNMAPPED))
3,810✔
164
                        continue;
×
165

166
                *ret = (pid_t) ul;
3,810✔
167
                return 1;
3,810✔
168
        }
169
}
170

171
int cg_read_pidref(FILE *f, PidRef *ret, CGroupFlags flags) {
7,064✔
172
        int r;
7,064✔
173

174
        assert(f);
7,064✔
175
        assert(ret);
7,064✔
176

177
        for (;;) {
×
178
                pid_t pid;
7,064✔
179

180
                r = cg_read_pid(f, &pid, flags);
7,064✔
181
                if (r < 0)
7,064✔
182
                        return log_debug_errno(r, "Failed to read pid from cgroup item: %m");
×
183
                if (r == 0) {
7,064✔
184
                        *ret = PIDREF_NULL;
5,281✔
185
                        return 0;
5,281✔
186
                }
187

188
                if (pid == 0)
1,783✔
189
                        return -EREMOTE;
190

191
                r = pidref_set_pid(ret, pid);
1,783✔
192
                if (r >= 0)
1,783✔
193
                        return 1;
194
                if (r != -ESRCH)
×
195
                        return r;
196

197
                /* ESRCH → gone by now? just skip over it, read the next */
198
        }
199
}
200

201
bool cg_kill_supported(void) {
×
202
        static thread_local int supported = -1;
×
203

204
        if (supported >= 0)
×
205
                return supported;
×
206

207
        if (cg_all_unified() <= 0)
×
208
                return (supported = false);
×
209

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

217
int cg_enumerate_subgroups(const char *controller, const char *path, DIR **ret) {
13,753✔
218
        _cleanup_free_ char *fs = NULL;
13,753✔
219
        DIR *d;
13,753✔
220
        int r;
13,753✔
221

222
        assert(ret);
13,753✔
223

224
        /* This is not recursive! */
225

226
        r = cg_get_path(controller, path, NULL, &fs);
13,753✔
227
        if (r < 0)
13,753✔
228
                return r;
229

230
        d = opendir(fs);
13,753✔
231
        if (!d)
13,753✔
232
                return -errno;
8,512✔
233

234
        *ret = d;
5,241✔
235
        return 0;
5,241✔
236
}
237

238
int cg_read_subgroup(DIR *d, char **ret) {
6,205✔
239
        assert(d);
6,205✔
240
        assert(ret);
6,205✔
241

242
        FOREACH_DIRENT_ALL(de, d, return -errno) {
242,592✔
243
                if (de->d_type != DT_DIR)
237,293✔
244
                        continue;
225,789✔
245

246
                if (dot_or_dot_dot(de->d_name))
11,504✔
247
                        continue;
10,598✔
248

249
                return strdup_to_full(ret, de->d_name);
906✔
250
        }
251

252
        *ret = NULL;
5,299✔
253
        return 0;
5,299✔
254
}
255

256
int cg_kill(
13,679✔
257
                const char *path,
258
                int sig,
259
                CGroupFlags flags,
260
                Set *killed_pids,
261
                cg_kill_log_func_t log_kill,
262
                void *userdata) {
263

264
        _cleanup_set_free_ Set *allocated_set = NULL;
13,679✔
265
        int r, ret = 0;
13,679✔
266

267
        assert(path);
13,679✔
268
        assert(sig >= 0);
13,679✔
269

270
         /* Don't send SIGCONT twice. Also, SIGKILL always works even when process is suspended, hence
271
          * don't send SIGCONT on SIGKILL. */
272
        if (IN_SET(sig, SIGCONT, SIGKILL))
13,679✔
273
                flags &= ~CGROUP_SIGCONT;
2,106✔
274

275
        /* This goes through the tasks list and kills them all. This is repeated until no further processes
276
         * are added to the tasks list, to properly handle forking processes.
277
         *
278
         * When sending SIGKILL, prefer cg_kill_kernel_sigkill(), which is fully atomic. */
279

280
        if (!killed_pids) {
13,679✔
281
                killed_pids = allocated_set = set_new(NULL);
683✔
282
                if (!killed_pids)
683✔
283
                        return -ENOMEM;
284
        }
285

286
        bool done;
13,751✔
287
        do {
13,751✔
288
                _cleanup_fclose_ FILE *f = NULL;
8,512✔
289
                int ret_log_kill;
13,751✔
290

291
                done = true;
13,751✔
292

293
                r = cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, path, &f);
13,751✔
294
                if (r == -ENOENT)
13,751✔
295
                        break;
296
                if (r < 0)
5,239✔
297
                        return RET_GATHER(ret, log_debug_errno(r, "Failed to enumerate cgroup items: %m"));
×
298

299
                for (;;) {
6,920✔
300
                        _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
6,920✔
301

302
                        r = cg_read_pidref(f, &pidref, flags);
6,920✔
303
                        if (r < 0)
6,920✔
304
                                return RET_GATHER(ret, log_debug_errno(r, "Failed to read pidref from cgroup '%s': %m", path));
×
305
                        if (r == 0)
6,920✔
306
                                break;
307

308
                        if ((flags & CGROUP_IGNORE_SELF) && pidref_is_self(&pidref))
1,681✔
309
                                continue;
684✔
310

311
                        if (set_contains(killed_pids, PID_TO_PTR(pidref.pid)))
997✔
312
                                continue;
753✔
313

314
                        /* Ignore kernel threads to mimic the behavior of cgroup.kill. */
315
                        if (pidref_is_kernel_thread(&pidref) > 0) {
244✔
316
                                log_debug("Ignoring kernel thread with pid " PID_FMT " in cgroup '%s'", pidref.pid, path);
×
317
                                continue;
×
318
                        }
319

320
                        if (log_kill)
244✔
321
                                ret_log_kill = log_kill(&pidref, sig, userdata);
92✔
322

323
                        /* If we haven't killed this process yet, kill it */
324
                        r = pidref_kill(&pidref, sig);
244✔
325
                        if (r < 0 && r != -ESRCH)
244✔
326
                                RET_GATHER(ret, log_debug_errno(r, "Failed to kill process with pid " PID_FMT " from cgroup '%s': %m", pidref.pid, path));
×
327
                        if (r >= 0) {
244✔
328
                                if (flags & CGROUP_SIGCONT)
244✔
329
                                        (void) pidref_kill(&pidref, SIGCONT);
150✔
330

331
                                if (ret == 0) {
244✔
332
                                        if (log_kill)
143✔
333
                                                ret = ret_log_kill;
334
                                        else
335
                                                ret = 1;
51✔
336
                                }
337
                        }
338

339
                        done = false;
244✔
340

341
                        r = set_put(killed_pids, PID_TO_PTR(pidref.pid));
244✔
342
                        if (r < 0)
244✔
343
                                return RET_GATHER(ret, r);
×
344
                }
345

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

349
        } while (!done);
5,239✔
350

351
        return ret;
352
}
353

354
int cg_kill_recursive(
12,994✔
355
                const char *path,
356
                int sig,
357
                CGroupFlags flags,
358
                Set *killed_pids,
359
                cg_kill_log_func_t log_kill,
360
                void *userdata) {
361

362
        _cleanup_set_free_ Set *allocated_set = NULL;
×
363
        _cleanup_closedir_ DIR *d = NULL;
12,994✔
364
        int r, ret;
12,994✔
365

366
        assert(path);
12,994✔
367
        assert(sig >= 0);
12,994✔
368

369
        if (!killed_pids) {
12,994✔
370
                killed_pids = allocated_set = set_new(NULL);
12,393✔
371
                if (!killed_pids)
12,393✔
372
                        return -ENOMEM;
373
        }
374

375
        ret = cg_kill(path, sig, flags, killed_pids, log_kill, userdata);
12,994✔
376

377
        r = cg_enumerate_subgroups(SYSTEMD_CGROUP_CONTROLLER, path, &d);
12,994✔
378
        if (r < 0) {
12,994✔
379
                if (r != -ENOENT)
8,512✔
380
                        RET_GATHER(ret, log_debug_errno(r, "Failed to enumerate cgroup '%s' subgroups: %m", path));
×
381

382
                return ret;
8,512✔
383
        }
384

385
        for (;;) {
4,614✔
386
                _cleanup_free_ char *fn = NULL, *p = NULL;
4,548✔
387

388
                r = cg_read_subgroup(d, &fn);
4,548✔
389
                if (r < 0) {
4,548✔
390
                        RET_GATHER(ret, log_debug_errno(r, "Failed to read subgroup from cgroup '%s': %m", path));
×
391
                        break;
392
                }
393
                if (r == 0)
4,548✔
394
                        break;
395

396
                p = path_join(empty_to_root(path), fn);
66✔
397
                if (!p)
66✔
398
                        return -ENOMEM;
×
399

400
                r = cg_kill_recursive(p, sig, flags, killed_pids, log_kill, userdata);
66✔
401
                if (r < 0)
66✔
402
                        log_debug_errno(r, "Failed to recursively kill processes in cgroup '%s': %m", p);
×
403
                if (r != 0 && ret >= 0)
66✔
404
                        ret = r;
15✔
405
        }
406

407
        return ret;
4,482✔
408
}
409

410
int cg_kill_kernel_sigkill(const char *path) {
×
411
        _cleanup_free_ char *killfile = NULL;
×
412
        int r;
×
413

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

417
        assert(path);
×
418

419
        if (!cg_kill_supported())
×
420
                return -EOPNOTSUPP;
421

422
        r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, path, "cgroup.kill", &killfile);
×
423
        if (r < 0)
×
424
                return r;
425

426
        r = write_string_file(killfile, "1", WRITE_STRING_FILE_DISABLE_BUFFER);
×
427
        if (r < 0)
×
428
                return log_debug_errno(r, "Failed to write to cgroup.kill for cgroup '%s': %m", path);
×
429

430
        return 0;
431
}
432

433
static const char *controller_to_dirname(const char *controller) {
×
434
        assert(controller);
×
435

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

440
        if (streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
×
441
                if (cg_hybrid_unified() > 0)
×
442
                        controller = SYSTEMD_CGROUP_CONTROLLER_HYBRID;
443
                else
444
                        controller = SYSTEMD_CGROUP_CONTROLLER_LEGACY;
×
445
        }
446

447
        return startswith(controller, "name=") ?: controller;
×
448
}
449

450
static int join_path_legacy(const char *controller, const char *path, const char *suffix, char **ret) {
×
451
        const char *dn;
×
452
        char *t = NULL;
×
453

454
        assert(ret);
×
455
        assert(controller);
×
456

457
        dn = controller_to_dirname(controller);
×
458

459
        if (isempty(path) && isempty(suffix))
×
460
                t = path_join("/sys/fs/cgroup", dn);
×
461
        else if (isempty(path))
×
462
                t = path_join("/sys/fs/cgroup", dn, suffix);
×
463
        else if (isempty(suffix))
×
464
                t = path_join("/sys/fs/cgroup", dn, path);
×
465
        else
466
                t = path_join("/sys/fs/cgroup", dn, path, suffix);
×
467
        if (!t)
×
468
                return -ENOMEM;
469

470
        *ret = t;
×
471
        return 0;
×
472
}
473

474
static int join_path_unified(const char *path, const char *suffix, char **ret) {
215,032✔
475
        char *t;
215,032✔
476

477
        assert(ret);
215,032✔
478

479
        if (isempty(path) && isempty(suffix))
230,414✔
480
                t = strdup("/sys/fs/cgroup");
1,130✔
481
        else if (isempty(path))
213,902✔
482
                t = path_join("/sys/fs/cgroup", suffix);
14,252✔
483
        else if (isempty(suffix))
199,650✔
484
                t = path_join("/sys/fs/cgroup", path);
74,614✔
485
        else
486
                t = path_join("/sys/fs/cgroup", path, suffix);
125,036✔
487
        if (!t)
215,032✔
488
                return -ENOMEM;
489

490
        *ret = t;
215,032✔
491
        return 0;
215,032✔
492
}
493

494
int cg_get_path(const char *controller, const char *path, const char *suffix, char **ret) {
215,032✔
495
        int r;
215,032✔
496

497
        assert(ret);
215,032✔
498

499
        if (!controller) {
215,032✔
500
                char *t;
×
501

502
                /* If no controller is specified, we return the path *below* the controllers, without any
503
                 * prefix. */
504

505
                if (isempty(path) && isempty(suffix))
×
506
                        return -EINVAL;
507

508
                if (isempty(suffix))
×
509
                        t = strdup(path);
×
510
                else if (isempty(path))
×
511
                        t = strdup(suffix);
×
512
                else
513
                        t = path_join(path, suffix);
×
514
                if (!t)
×
515
                        return -ENOMEM;
516

517
                *ret = path_simplify(t);
×
518
                return 0;
×
519
        }
520

521
        if (!cg_controller_is_valid(controller))
215,032✔
522
                return -EINVAL;
523

524
        r = cg_all_unified();
215,032✔
525
        if (r < 0)
215,032✔
526
                return r;
527
        if (r > 0)
215,032✔
528
                r = join_path_unified(path, suffix, ret);
215,032✔
529
        else
530
                r = join_path_legacy(controller, path, suffix, ret);
×
531
        if (r < 0)
215,032✔
532
                return r;
533

534
        path_simplify(*ret);
215,032✔
535
        return 0;
215,032✔
536
}
537

538
static int controller_is_v1_accessible(const char *root, const char *controller) {
×
539
        const char *cpath, *dn;
×
540

541
        assert(controller);
×
542

543
        dn = controller_to_dirname(controller);
×
544

545
        /* If root if specified, we check that:
546
         * - possible subcgroup is created at root,
547
         * - we can modify the hierarchy. */
548

549
        cpath = strjoina("/sys/fs/cgroup/", dn, root, root ? "/cgroup.procs" : NULL);
×
550
        return access_nofollow(cpath, root ? W_OK : F_OK);
×
551
}
552

553
int cg_get_path_and_check(const char *controller, const char *path, const char *suffix, char **ret) {
19,398✔
554
        int r;
19,398✔
555

556
        assert(controller);
19,398✔
557
        assert(ret);
19,398✔
558

559
        if (!cg_controller_is_valid(controller))
19,398✔
560
                return -EINVAL;
561

562
        r = cg_all_unified();
19,398✔
563
        if (r < 0)
19,398✔
564
                return r;
565
        if (r > 0) {
19,398✔
566
                /* In the unified hierarchy all controllers are considered accessible,
567
                 * except for the named hierarchies */
568
                if (startswith(controller, "name="))
19,398✔
569
                        return -EOPNOTSUPP;
570
        } else {
571
                /* Check if the specified controller is actually accessible */
572
                r = controller_is_v1_accessible(NULL, controller);
×
573
                if (r < 0)
×
574
                        return r;
575
        }
576

577
        return cg_get_path(controller, path, suffix, ret);
19,398✔
578
}
579

580
int cg_set_xattr(const char *path, const char *name, const void *value, size_t size, int flags) {
4,520✔
581
        _cleanup_free_ char *fs = NULL;
4,520✔
582
        int r;
4,520✔
583

584
        assert(path);
4,520✔
585
        assert(name);
4,520✔
586
        assert(value || size <= 0);
4,520✔
587

588
        r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, path, NULL, &fs);
4,520✔
589
        if (r < 0)
4,520✔
590
                return r;
591

592
        return RET_NERRNO(setxattr(fs, name, value, size, flags));
4,520✔
593
}
594

595
int cg_get_xattr(const char *path, const char *name, char **ret, size_t *ret_size) {
16,092✔
596
        _cleanup_free_ char *fs = NULL;
16,092✔
597
        int r;
16,092✔
598

599
        assert(path);
16,092✔
600
        assert(name);
16,092✔
601

602
        r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, path, NULL, &fs);
16,092✔
603
        if (r < 0)
16,092✔
604
                return r;
605

606
        return lgetxattr_malloc(fs, name, ret, ret_size);
16,092✔
607
}
608

609
int cg_get_xattr_bool(const char *path, const char *name) {
147✔
610
        _cleanup_free_ char *fs = NULL;
147✔
611
        int r;
147✔
612

613
        assert(path);
147✔
614
        assert(name);
147✔
615

616
        r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, path, NULL, &fs);
147✔
617
        if (r < 0)
147✔
618
                return r;
619

620
        return getxattr_at_bool(AT_FDCWD, fs, name, /* at_flags= */ 0);
147✔
621
}
622

623
int cg_remove_xattr(const char *path, const char *name) {
25,128✔
624
        _cleanup_free_ char *fs = NULL;
25,128✔
625
        int r;
25,128✔
626

627
        assert(path);
25,128✔
628
        assert(name);
25,128✔
629

630
        r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, path, NULL, &fs);
25,128✔
631
        if (r < 0)
25,128✔
632
                return r;
633

634
        return RET_NERRNO(removexattr(fs, name));
50,256✔
635
}
636

637
int cg_pid_get_path(const char *controller, pid_t pid, char **ret_path) {
42,380✔
638
        _cleanup_fclose_ FILE *f = NULL;
42,380✔
639
        const char *fs, *controller_str = NULL;  /* avoid false maybe-uninitialized warning */
42,380✔
640
        int unified, r;
42,380✔
641

642
        assert(pid >= 0);
42,380✔
643
        assert(ret_path);
42,380✔
644

645
        if (controller) {
42,380✔
646
                if (!cg_controller_is_valid(controller))
42,197✔
647
                        return -EINVAL;
648
        } else
649
                controller = SYSTEMD_CGROUP_CONTROLLER;
650

651
        unified = cg_unified_controller(controller);
42,380✔
652
        if (unified < 0)
42,380✔
653
                return unified;
654
        if (unified == 0) {
42,380✔
655
                if (streq(controller, SYSTEMD_CGROUP_CONTROLLER))
×
656
                        controller_str = SYSTEMD_CGROUP_CONTROLLER_LEGACY;
657
                else
658
                        controller_str = controller;
×
659
        }
660

661
        fs = procfs_file_alloca(pid, "cgroup");
48,708✔
662
        r = fopen_unlocked(fs, "re", &f);
42,380✔
663
        if (r == -ENOENT)
42,380✔
664
                return -ESRCH;
665
        if (r < 0)
38,080✔
666
                return r;
667

668
        for (;;) {
38,079✔
669
                _cleanup_free_ char *line = NULL;
38,079✔
670
                char *e;
38,079✔
671

672
                r = read_line(f, LONG_LINE_MAX, &line);
38,079✔
673
                if (r < 0)
38,079✔
674
                        return r;
675
                if (r == 0)
38,069✔
676
                        return -ENODATA;
677

678
                if (unified) {
38,069✔
679
                        e = startswith(line, "0:");
38,069✔
680
                        if (!e)
38,069✔
681
                                continue;
×
682

683
                        e = strchr(e, ':');
38,069✔
684
                        if (!e)
38,069✔
685
                                continue;
×
686
                } else {
687
                        char *l;
×
688

689
                        l = strchr(line, ':');
×
690
                        if (!l)
×
691
                                continue;
×
692

693
                        l++;
×
694
                        e = strchr(l, ':');
×
695
                        if (!e)
×
696
                                continue;
×
697
                        *e = 0;
×
698

699
                        assert(controller_str);
×
700
                        r = string_contains_word(l, ",", controller_str);
×
701
                        if (r < 0)
×
702
                                return r;
703
                        if (r == 0)
×
704
                                continue;
×
705
                }
706

707
                _cleanup_free_ char *path = strdup(e + 1);
38,069✔
708
                if (!path)
38,069✔
709
                        return -ENOMEM;
710

711
                /* Refuse cgroup paths from outside our cgroup namespace */
712
                if (startswith(path, "/../"))
38,069✔
713
                        return -EUNATCH;
714

715
                /* Truncate suffix indicating the process is a zombie */
716
                e = endswith(path, " (deleted)");
38,069✔
717
                if (e)
38,069✔
718
                        *e = 0;
149✔
719

720
                *ret_path = TAKE_PTR(path);
38,069✔
721
                return 0;
38,069✔
722
        }
723
}
724

725
int cg_pidref_get_path(const char *controller, const PidRef *pidref, char **ret_path) {
10,565✔
726
        _cleanup_free_ char *path = NULL;
10,565✔
727
        int r;
10,565✔
728

729
        assert(ret_path);
10,565✔
730

731
        if (!pidref_is_set(pidref))
10,565✔
732
                return -ESRCH;
733
        if (pidref_is_remote(pidref))
21,130✔
734
                return -EREMOTE;
735

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

740
        r = cg_pid_get_path(controller, pidref->pid, &path);
10,565✔
741
        if (r < 0)
10,565✔
742
                return r;
743

744
        /* Before we return the path, make sure the procfs entry for this pid still matches the pidref */
745
        r = pidref_verify(pidref);
10,563✔
746
        if (r < 0)
10,563✔
747
                return r;
748

749
        *ret_path = TAKE_PTR(path);
10,563✔
750
        return 0;
10,563✔
751
}
752

753
int cg_is_empty(const char *controller, const char *path) {
2,289✔
754
        _cleanup_free_ char *t = NULL;
2,289✔
755
        int r;
2,289✔
756

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

760
        assert(path);
2,289✔
761

762
        /* The root cgroup is always populated */
763
        if (empty_or_root(path))
2,289✔
764
                return false;
765

766
        r = cg_get_keyed_attribute(SYSTEMD_CGROUP_CONTROLLER, path, "cgroup.events", STRV_MAKE("populated"), &t);
2,289✔
767
        if (r == -ENOENT)
2,289✔
768
                return true;
769
        if (r < 0)
4✔
770
                return r;
771

772
        return streq(t, "0");
4✔
773
}
774

775
int cg_split_spec(const char *spec, char **ret_controller, char **ret_path) {
23✔
776
        _cleanup_free_ char *controller = NULL, *path = NULL;
23✔
777
        int r;
23✔
778

779
        assert(spec);
23✔
780

781
        if (*spec == '/') {
23✔
782
                if (!path_is_normalized(spec))
15✔
783
                        return -EINVAL;
784

785
                if (ret_path) {
15✔
786
                        r = path_simplify_alloc(spec, &path);
15✔
787
                        if (r < 0)
15✔
788
                                return r;
789
                }
790

791
        } else {
792
                const char *e;
8✔
793

794
                e = strchr(spec, ':');
8✔
795
                if (e) {
8✔
796
                        controller = strndup(spec, e-spec);
6✔
797
                        if (!controller)
6✔
798
                                return -ENOMEM;
799
                        if (!cg_controller_is_valid(controller))
6✔
800
                                return -EINVAL;
801

802
                        if (!isempty(e + 1)) {
3✔
803
                                path = strdup(e+1);
2✔
804
                                if (!path)
2✔
805
                                        return -ENOMEM;
806

807
                                if (!path_is_normalized(path) ||
2✔
808
                                    !path_is_absolute(path))
2✔
809
                                        return -EINVAL;
810

811
                                path_simplify(path);
1✔
812
                        }
813

814
                } else {
815
                        if (!cg_controller_is_valid(spec))
2✔
816
                                return -EINVAL;
817

818
                        if (ret_controller) {
1✔
819
                                controller = strdup(spec);
1✔
820
                                if (!controller)
1✔
821
                                        return -ENOMEM;
822
                        }
823
                }
824
        }
825

826
        if (ret_controller)
18✔
827
                *ret_controller = TAKE_PTR(controller);
18✔
828
        if (ret_path)
18✔
829
                *ret_path = TAKE_PTR(path);
18✔
830
        return 0;
831
}
832

833
int cg_mangle_path(const char *path, char **ret) {
121✔
834
        _cleanup_free_ char *c = NULL, *p = NULL;
121✔
835
        int r;
121✔
836

837
        assert(path);
121✔
838
        assert(ret);
121✔
839

840
        /* First, check if it already is a filesystem path */
841
        if (path_startswith(path, "/sys/fs/cgroup"))
121✔
842
                return path_simplify_alloc(path, ret);
117✔
843

844
        /* Otherwise, treat it as cg spec */
845
        r = cg_split_spec(path, &c, &p);
4✔
846
        if (r < 0)
4✔
847
                return r;
848

849
        return cg_get_path(c ?: SYSTEMD_CGROUP_CONTROLLER, p ?: "/", NULL, ret);
8✔
850
}
851

852
int cg_get_root_path(char **ret_path) {
14,690✔
853
        char *p, *e;
14,690✔
854
        int r;
14,690✔
855

856
        assert(ret_path);
14,690✔
857

858
        r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, &p);
14,690✔
859
        if (r < 0)
14,690✔
860
                return r;
14,690✔
861

862
        e = endswith(p, "/" SPECIAL_INIT_SCOPE);
14,690✔
863
        if (e)
14,690✔
864
                *e = 0;
14,659✔
865

866
        *ret_path = p;
14,690✔
867
        return 0;
14,690✔
868
}
869

870
int cg_shift_path(const char *cgroup, const char *root, const char **ret_shifted) {
11,456✔
871
        int r;
11,456✔
872

873
        assert(cgroup);
11,456✔
874
        assert(ret_shifted);
11,456✔
875

876
        _cleanup_free_ char *rt = NULL;
11,456✔
877
        if (!root) {
11,456✔
878
                /* If the root was specified let's use that, otherwise
879
                 * let's determine it from PID 1 */
880

881
                r = cg_get_root_path(&rt);
1,826✔
882
                if (r < 0)
1,826✔
883
                        return r;
884

885
                root = rt;
1,826✔
886
        }
887

888
        *ret_shifted = path_startswith_full(cgroup, root, PATH_STARTSWITH_RETURN_LEADING_SLASH|PATH_STARTSWITH_REFUSE_DOT_DOT) ?: cgroup;
11,456✔
889
        return 0;
11,456✔
890
}
891

892
int cg_pid_get_path_shifted(pid_t pid, const char *root, char **ret_cgroup) {
15,589✔
893
        _cleanup_free_ char *raw = NULL;
15,589✔
894
        const char *c;
15,589✔
895
        int r;
15,589✔
896

897
        assert(pid >= 0);
15,589✔
898
        assert(ret_cgroup);
15,589✔
899

900
        r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &raw);
15,589✔
901
        if (r < 0)
15,589✔
902
                return r;
903

904
        r = cg_shift_path(raw, root, &c);
11,280✔
905
        if (r < 0)
11,280✔
906
                return r;
907

908
        if (c == raw) {
11,280✔
909
                *ret_cgroup = TAKE_PTR(raw);
11,280✔
910
                return 0;
11,280✔
911
        }
912

913
        return strdup_to(ret_cgroup, c);
×
914
}
915

916
int cg_path_decode_unit(const char *cgroup, char **ret_unit) {
33,599✔
917
        assert(cgroup);
33,599✔
918

919
        size_t n = strcspn(cgroup, "/");
33,599✔
920
        if (n < 3)
33,599✔
921
                return -ENXIO;
922

923
        char *c = strndupa_safe(cgroup, n);
33,577✔
924
        c = cg_unescape(c);
33,577✔
925

926
        if (!unit_name_is_valid(c, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
33,577✔
927
                return -ENXIO;
928

929
        if (ret_unit)
33,569✔
930
                return strdup_to(ret_unit, c);
33,569✔
931

932
        return 0;
933
}
934

935
static bool valid_slice_name(const char *p, size_t n) {
119,888✔
936
        assert(p || n == 0);
119,888✔
937

938
        if (n < STRLEN("x.slice"))
119,888✔
939
                return false;
940

941
        char *c = strndupa_safe(p, n);
119,825✔
942
        if (!endswith(c, ".slice"))
119,825✔
943
                return false;
944

945
        return unit_name_is_valid(cg_unescape(c), UNIT_NAME_PLAIN);
60,783✔
946
}
947

948
static const char* skip_slices(const char *p) {
42,800✔
949
        assert(p);
42,800✔
950

951
        /* Skips over all slice assignments */
952

953
        for (;;) {
131,010✔
954
                size_t n;
86,905✔
955

956
                p += strspn(p, "/");
86,905✔
957

958
                n = strcspn(p, "/");
86,905✔
959
                if (!valid_slice_name(p, n))
86,905✔
960
                        return p;
42,800✔
961

962
                p += n;
44,105✔
963
        }
964
}
965

966
int cg_path_get_unit(const char *path, char **ret) {
17,530✔
967
        _cleanup_free_ char *unit = NULL;
17,530✔
968
        const char *e;
17,530✔
969
        int r;
17,530✔
970

971
        assert(path);
17,530✔
972

973
        e = skip_slices(path);
17,530✔
974

975
        r = cg_path_decode_unit(e, &unit);
17,530✔
976
        if (r < 0)
17,530✔
977
                return r;
978

979
        /* We skipped over the slices, don't accept any now */
980
        if (endswith(unit, ".slice"))
17,504✔
981
                return -ENXIO;
982

983
        if (ret)
17,504✔
984
                *ret = TAKE_PTR(unit);
17,504✔
985
        return 0;
986
}
987

988
int cg_path_get_unit_path(const char *path, char **ret) {
9,470✔
989
        _cleanup_free_ char *path_copy = NULL;
9,470✔
990
        char *unit_name;
9,470✔
991

992
        assert(path);
9,470✔
993
        assert(ret);
9,470✔
994

995
        path_copy = strdup(path);
9,470✔
996
        if (!path_copy)
9,470✔
997
                return -ENOMEM;
998

999
        unit_name = (char*) skip_slices(path_copy);
9,470✔
1000
        unit_name[strcspn(unit_name, "/")] = 0;
9,470✔
1001

1002
        if (!unit_name_is_valid(cg_unescape(unit_name), UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
9,470✔
1003
                return -ENXIO;
1004

1005
        *ret = TAKE_PTR(path_copy);
9,467✔
1006

1007
        return 0;
9,467✔
1008
}
1009

1010
int cg_pid_get_unit(pid_t pid, char **ret_unit) {
623✔
1011
        _cleanup_free_ char *cgroup = NULL;
623✔
1012
        int r;
623✔
1013

1014
        assert(ret_unit);
623✔
1015

1016
        r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
623✔
1017
        if (r < 0)
623✔
1018
                return r;
1019

1020
        return cg_path_get_unit(cgroup, ret_unit);
623✔
1021
}
1022

1023
int cg_pidref_get_unit(const PidRef *pidref, char **ret) {
542✔
1024
        _cleanup_free_ char *unit = NULL;
542✔
1025
        int r;
542✔
1026

1027
        assert(ret);
542✔
1028

1029
        if (!pidref_is_set(pidref))
542✔
1030
                return -ESRCH;
1031
        if (pidref_is_remote(pidref))
1,084✔
1032
                return -EREMOTE;
1033

1034
        r = cg_pid_get_unit(pidref->pid, &unit);
542✔
1035
        if (r < 0)
542✔
1036
                return r;
1037

1038
        r = pidref_verify(pidref);
542✔
1039
        if (r < 0)
542✔
1040
                return r;
1041

1042
        *ret = TAKE_PTR(unit);
542✔
1043
        return 0;
542✔
1044
}
1045

1046
static const char* skip_session(const char *p) {
15,349✔
1047
        size_t n;
15,349✔
1048

1049
        /* Skip session-*.scope, but require it to be there. */
1050

1051
        if (isempty(p))
15,349✔
1052
                return NULL;
1053

1054
        p += strspn(p, "/");
15,345✔
1055

1056
        n = strcspn(p, "/");
15,345✔
1057
        if (n < STRLEN("session-x.scope"))
15,345✔
1058
                return NULL;
1059

1060
        const char *s = startswith(p, "session-");
15,173✔
1061
        if (!s)
15,173✔
1062
                return NULL;
1063

1064
        /* Note that session scopes never need unescaping, since they cannot conflict with the kernel's
1065
         * own names, hence we don't need to call cg_unescape() here. */
1066
        char *f = strndupa_safe(s, p + n - s),
25✔
1067
             *e = endswith(f, ".scope");
25✔
1068
        if (!e)
25✔
1069
                return NULL;
1070
        *e = '\0';
25✔
1071

1072
        if (!session_id_valid(f))
25✔
1073
                return NULL;
1074

1075
        return skip_leading_slash(p + n);
25✔
1076
}
1077

1078
static const char* skip_user_manager(const char *p) {
15,800✔
1079
        size_t n;
15,800✔
1080

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

1083
        if (isempty(p))
15,800✔
1084
                return NULL;
15,800✔
1085

1086
        p += strspn(p, "/");
15,796✔
1087

1088
        n = strcspn(p, "/");
15,796✔
1089
        if (n < CONST_MIN(STRLEN("user@x.service"), STRLEN("capsule@x.service")))
15,796✔
1090
                return NULL;
1091

1092
        /* Any possible errors from functions called below are converted to NULL return, so our callers won't
1093
         * resolve user/capsule name. */
1094
        _cleanup_free_ char *unit_name = strndup(p, n);
15,626✔
1095
        if (!unit_name)
15,626✔
1096
                return NULL;
1097

1098
        _cleanup_free_ char *i = NULL;
15,626✔
1099
        UnitNameFlags type = unit_name_to_instance(unit_name, &i);
15,626✔
1100

1101
        if (type != UNIT_NAME_INSTANCE)
15,626✔
1102
                return NULL;
1103

1104
        /* Note that user manager services never need unescaping, since they cannot conflict with the
1105
         * kernel's own names, hence we don't need to call cg_unescape() here.  Prudently check validity of
1106
         * instance names, they should be always valid as we validate them upon unit start. */
1107
        if (!(startswith(unit_name, "user@") && parse_uid(i, NULL) >= 0) &&
668✔
1108
            !(startswith(unit_name, "capsule@") && capsule_name_is_valid(i) > 0))
116✔
1109
                return NULL;
106✔
1110

1111
        return skip_leading_slash(p + n);
451✔
1112
}
1113

1114
static const char* skip_user_prefix(const char *path) {
15,800✔
1115
        const char *e, *t;
15,800✔
1116

1117
        assert(path);
15,800✔
1118

1119
        /* Skip slices, if there are any */
1120
        e = skip_slices(path);
15,800✔
1121

1122
        /* Skip the user manager, if it's in the path now... */
1123
        t = skip_user_manager(e);
15,800✔
1124
        if (t)
15,800✔
1125
                return t;
1126

1127
        /* Alternatively skip the user session if it is in the path... */
1128
        return skip_session(e);
15,349✔
1129
}
1130

1131
int cg_path_get_user_unit(const char *path, char **ret) {
7,926✔
1132
        const char *t;
7,926✔
1133

1134
        assert(path);
7,926✔
1135

1136
        t = skip_user_prefix(path);
7,926✔
1137
        if (!t)
7,926✔
1138
                return -ENXIO;
1139

1140
        /* And from here on it looks pretty much the same as for a system unit, hence let's use the same
1141
         * parser. */
1142
        return cg_path_get_unit(t, ret);
244✔
1143
}
1144

1145
int cg_pid_get_user_unit(pid_t pid, char **ret_unit) {
53✔
1146
        _cleanup_free_ char *cgroup = NULL;
53✔
1147
        int r;
53✔
1148

1149
        r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
53✔
1150
        if (r < 0)
53✔
1151
                return r;
1152

1153
        return cg_path_get_user_unit(cgroup, ret_unit);
53✔
1154
}
1155

1156
int cg_path_get_machine_name(const char *path, char **ret_machine) {
36✔
1157
        _cleanup_free_ char *u = NULL;
36✔
1158
        const char *sl;
36✔
1159
        int r;
36✔
1160

1161
        r = cg_path_get_unit(path, &u);
36✔
1162
        if (r < 0)
36✔
1163
                return r;
1164

1165
        sl = strjoina("/run/systemd/machines/unit:", u);
180✔
1166
        return readlink_malloc(sl, ret_machine);
36✔
1167
}
1168

1169
int cg_pid_get_machine_name(pid_t pid, char **ret_machine) {
36✔
1170
        _cleanup_free_ char *cgroup = NULL;
36✔
1171
        int r;
36✔
1172

1173
        r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
36✔
1174
        if (r < 0)
36✔
1175
                return r;
1176

1177
        return cg_path_get_machine_name(cgroup, ret_machine);
36✔
1178
}
1179

1180
int cg_path_get_session(const char *path, char **ret_session) {
8,702✔
1181
        _cleanup_free_ char *unit = NULL;
8,702✔
1182
        char *start, *end;
8,702✔
1183
        int r;
8,702✔
1184

1185
        assert(path);
8,702✔
1186

1187
        r = cg_path_get_unit(path, &unit);
8,702✔
1188
        if (r < 0)
8,702✔
1189
                return r;
1190

1191
        start = startswith(unit, "session-");
8,701✔
1192
        if (!start)
8,701✔
1193
                return -ENXIO;
1194
        end = endswith(start, ".scope");
331✔
1195
        if (!end)
331✔
1196
                return -ENXIO;
1197

1198
        *end = 0;
331✔
1199
        if (!session_id_valid(start))
331✔
1200
                return -ENXIO;
1201

1202
        if (!ret_session)
330✔
1203
                return 0;
1204

1205
        return strdup_to(ret_session, start);
330✔
1206
}
1207

1208
int cg_pid_get_session(pid_t pid, char **ret_session) {
769✔
1209
        _cleanup_free_ char *cgroup = NULL;
769✔
1210
        int r;
769✔
1211

1212
        r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
769✔
1213
        if (r < 0)
769✔
1214
                return r;
1215

1216
        return cg_path_get_session(cgroup, ret_session);
769✔
1217
}
1218

1219
int cg_pidref_get_session(const PidRef *pidref, char **ret) {
338✔
1220
        int r;
338✔
1221

1222
        if (!pidref_is_set(pidref))
338✔
1223
                return -ESRCH;
338✔
1224
        if (pidref_is_remote(pidref))
676✔
1225
                return -EREMOTE;
1226

1227
        _cleanup_free_ char *session = NULL;
338✔
1228
        r = cg_pid_get_session(pidref->pid, &session);
338✔
1229
        if (r < 0)
338✔
1230
                return r;
1231

1232
        r = pidref_verify(pidref);
286✔
1233
        if (r < 0)
286✔
1234
                return r;
1235

1236
        if (ret)
286✔
1237
                *ret = TAKE_PTR(session);
286✔
1238
        return 0;
1239
}
1240

1241
int cg_path_get_owner_uid(const char *path, uid_t *ret_uid) {
8,149✔
1242
        _cleanup_free_ char *slice = NULL;
8,149✔
1243
        char *start, *end;
8,149✔
1244
        int r;
8,149✔
1245

1246
        assert(path);
8,149✔
1247

1248
        r = cg_path_get_slice(path, &slice);
8,149✔
1249
        if (r < 0)
8,149✔
1250
                return r;
1251

1252
        start = startswith(slice, "user-");
8,149✔
1253
        if (!start)
8,149✔
1254
                return -ENXIO;
1255

1256
        end = endswith(start, ".slice");
311✔
1257
        if (!end)
311✔
1258
                return -ENXIO;
1259

1260
        *end = 0;
311✔
1261
        if (parse_uid(start, ret_uid) < 0)
311✔
UNCOV
1262
                return -ENXIO;
×
1263

1264
        return 0;
1265
}
1266

1267
int cg_pid_get_owner_uid(pid_t pid, uid_t *ret_uid) {
236✔
1268
        _cleanup_free_ char *cgroup = NULL;
236✔
1269
        int r;
236✔
1270

1271
        r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
236✔
1272
        if (r < 0)
236✔
1273
                return r;
1274

1275
        return cg_path_get_owner_uid(cgroup, ret_uid);
236✔
1276
}
1277

1278
int cg_pidref_get_owner_uid(const PidRef *pidref, uid_t *ret) {
50✔
1279
        int r;
50✔
1280

1281
        if (!pidref_is_set(pidref))
50✔
1282
                return -ESRCH;
50✔
1283
        if (pidref_is_remote(pidref))
50✔
1284
                return -EREMOTE;
1285

1286
        uid_t uid;
50✔
1287
        r = cg_pid_get_owner_uid(pidref->pid, &uid);
50✔
1288
        if (r < 0)
50✔
1289
                return r;
1290

1291
        r = pidref_verify(pidref);
8✔
1292
        if (r < 0)
8✔
1293
                return r;
1294

1295
        if (ret)
8✔
1296
                *ret = uid;
8✔
1297

1298
        return 0;
1299
}
1300

1301
int cg_path_get_slice(const char *p, char **ret_slice) {
16,305✔
1302
        const char *e = NULL;
16,305✔
1303

1304
        assert(p);
16,305✔
1305

1306
        /* Finds the right-most slice unit from the beginning, but stops before we come to
1307
         * the first non-slice unit. */
1308

1309
        for (;;) {
49,661✔
1310
                const char *s;
32,983✔
1311
                int n;
32,983✔
1312

1313
                n = path_find_first_component(&p, /* accept_dot_dot = */ false, &s);
32,983✔
1314
                if (n < 0)
32,983✔
UNCOV
1315
                        return n;
×
1316
                if (!valid_slice_name(s, n))
32,983✔
1317
                        break;
1318

1319
                e = s;
16,678✔
1320
        }
1321

1322
        if (e)
16,305✔
1323
                return cg_path_decode_unit(e, ret_slice);
16,060✔
1324

1325
        if (ret_slice)
245✔
1326
                return strdup_to(ret_slice, SPECIAL_ROOT_SLICE);
245✔
1327

1328
        return 0;
1329
}
1330

1331
int cg_pid_get_slice(pid_t pid, char **ret_slice) {
57✔
1332
        _cleanup_free_ char *cgroup = NULL;
57✔
1333
        int r;
57✔
1334

1335
        r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
57✔
1336
        if (r < 0)
57✔
1337
                return r;
1338

1339
        return cg_path_get_slice(cgroup, ret_slice);
57✔
1340
}
1341

1342
int cg_path_get_user_slice(const char *p, char **ret_slice) {
7,874✔
1343
        const char *t;
7,874✔
1344
        assert(p);
7,874✔
1345

1346
        t = skip_user_prefix(p);
7,874✔
1347
        if (!t)
7,874✔
1348
                return -ENXIO;
1349

1350
        /* And now it looks pretty much the same as for a system slice, so let's just use the same parser
1351
         * from here on. */
1352
        return cg_path_get_slice(t, ret_slice);
232✔
1353
}
1354

1355
int cg_pid_get_user_slice(pid_t pid, char **ret_slice) {
1✔
1356
        _cleanup_free_ char *cgroup = NULL;
1✔
1357
        int r;
1✔
1358

1359
        r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1✔
1360
        if (r < 0)
1✔
1361
                return r;
1362

1363
        return cg_path_get_user_slice(cgroup, ret_slice);
1✔
1364
}
1365

1366
bool cg_needs_escape(const char *p) {
20,926✔
1367

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

1373
        if (!filename_is_valid(p))
20,926✔
1374
                return true;
1375

1376
        if (IN_SET(p[0], '_', '.'))
20,922✔
1377
                return true;
1378

1379
        if (STR_IN_SET(p, "notify_on_release", "release_agent", "tasks"))
20,916✔
1380
                return true;
2✔
1381

1382
        if (startswith(p, "cgroup."))
20,914✔
1383
                return true;
1384

1385
        for (CGroupController c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
292,768✔
1386
                const char *q;
271,856✔
1387

1388
                q = startswith(p, cgroup_controller_to_string(c));
271,856✔
1389
                if (!q)
271,856✔
1390
                        continue;
271,856✔
1391

UNCOV
1392
                if (q[0] == '.')
×
1393
                        return true;
1394
        }
1395

1396
        return false;
1397
}
1398

1399
int cg_escape(const char *p, char **ret) {
20,672✔
1400
        _cleanup_free_ char *n = NULL;
20,672✔
1401

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

1407
        /* The return value of this function (unlike cg_unescape()) needs free()! */
1408

1409
        if (cg_needs_escape(p)) {
20,672✔
1410
                n = strjoin("_", p);
7✔
1411
                if (!n)
7✔
1412
                        return -ENOMEM;
1413

1414
                if (!filename_is_valid(n)) /* became invalid due to the prefixing? Or contained things like a slash that cannot be fixed by prefixing? */
7✔
1415
                        return -EINVAL;
1416
        } else {
1417
                n = strdup(p);
20,665✔
1418
                if (!n)
20,665✔
1419
                        return -ENOMEM;
1420
        }
1421

1422
        *ret = TAKE_PTR(n);
20,672✔
1423
        return 0;
20,672✔
1424
}
1425

1426
char* cg_unescape(const char *p) {
103,881✔
1427
        assert(p);
103,881✔
1428

1429
        /* The return value of this function (unlike cg_escape())
1430
         * doesn't need free()! */
1431

1432
        if (p[0] == '_')
103,881✔
1433
                return (char*) p+1;
14✔
1434

1435
        return (char*) p;
1436
}
1437

1438
#define CONTROLLER_VALID                        \
1439
        DIGITS LETTERS                          \
1440
        "_"
1441

1442
bool cg_controller_is_valid(const char *p) {
276,645✔
1443
        const char *t, *s;
276,645✔
1444

1445
        if (!p)
276,645✔
1446
                return false;
1447

1448
        if (streq(p, SYSTEMD_CGROUP_CONTROLLER))
276,645✔
1449
                return true;
1450

1451
        s = startswith(p, "name=");
89,279✔
1452
        if (s)
89,279✔
1453
                p = s;
2✔
1454

1455
        if (IN_SET(*p, 0, '_'))
89,279✔
1456
                return false;
1457

1458
        for (t = p; *t; t++)
582,359✔
1459
                if (!strchr(CONTROLLER_VALID, *t))
493,091✔
1460
                        return false;
1461

1462
        if (t - p > NAME_MAX)
89,268✔
UNCOV
1463
                return false;
×
1464

1465
        return true;
1466
}
1467

1468
int cg_slice_to_path(const char *unit, char **ret) {
8,934✔
1469
        _cleanup_free_ char *p = NULL, *s = NULL, *e = NULL;
8,934✔
1470
        const char *dash;
8,934✔
1471
        int r;
8,934✔
1472

1473
        assert(unit);
8,934✔
1474
        assert(ret);
8,934✔
1475

1476
        if (streq(unit, SPECIAL_ROOT_SLICE))
8,934✔
1477
                return strdup_to(ret, "");
7✔
1478

1479
        if (!unit_name_is_valid(unit, UNIT_NAME_PLAIN))
8,927✔
1480
                return -EINVAL;
1481

1482
        if (!endswith(unit, ".slice"))
8,916✔
1483
                return -EINVAL;
1484

1485
        r = unit_name_to_prefix(unit, &p);
8,915✔
1486
        if (r < 0)
8,915✔
1487
                return r;
1488

1489
        dash = strchr(p, '-');
8,915✔
1490

1491
        /* Don't allow initial dashes */
1492
        if (dash == p)
8,915✔
1493
                return -EINVAL;
1494

1495
        while (dash) {
9,216✔
1496
                _cleanup_free_ char *escaped = NULL;
306✔
1497
                char n[dash - p + sizeof(".slice")];
306✔
1498

1499
#if HAS_FEATURE_MEMORY_SANITIZER
1500
                /* msan doesn't instrument stpncpy, so it thinks
1501
                 * n is later used uninitialized:
1502
                 * https://github.com/google/sanitizers/issues/926
1503
                 */
1504
                zero(n);
1505
#endif
1506

1507
                /* Don't allow trailing or double dashes */
1508
                if (IN_SET(dash[1], 0, '-'))
306✔
1509
                        return -EINVAL;
1510

1511
                strcpy(stpncpy(n, p, dash - p), ".slice");
304✔
1512
                if (!unit_name_is_valid(n, UNIT_NAME_PLAIN))
304✔
1513
                        return -EINVAL;
1514

1515
                r = cg_escape(n, &escaped);
304✔
1516
                if (r < 0)
304✔
1517
                        return r;
1518

1519
                if (!strextend(&s, escaped, "/"))
304✔
1520
                        return -ENOMEM;
1521

1522
                dash = strchr(dash+1, '-');
304✔
1523
        }
1524

1525
        r = cg_escape(unit, &e);
8,910✔
1526
        if (r < 0)
8,910✔
1527
                return r;
1528

1529
        if (!strextend(&s, e))
8,910✔
1530
                return -ENOMEM;
1531

1532
        *ret = TAKE_PTR(s);
8,910✔
1533
        return 0;
8,910✔
1534
}
1535

UNCOV
1536
int cg_is_threaded(const char *path) {
×
UNCOV
1537
        _cleanup_free_ char *fs = NULL, *contents = NULL;
×
UNCOV
1538
        _cleanup_strv_free_ char **v = NULL;
×
UNCOV
1539
        int r;
×
1540

UNCOV
1541
        r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, path, "cgroup.type", &fs);
×
UNCOV
1542
        if (r < 0)
×
1543
                return r;
1544

UNCOV
1545
        r = read_full_virtual_file(fs, &contents, NULL);
×
UNCOV
1546
        if (r == -ENOENT)
×
1547
                return false; /* Assume no. */
UNCOV
1548
        if (r < 0)
×
1549
                return r;
1550

UNCOV
1551
        v = strv_split(contents, NULL);
×
UNCOV
1552
        if (!v)
×
1553
                return -ENOMEM;
1554

1555
        /* If the cgroup is in the threaded mode, it contains "threaded".
1556
         * If one of the parents or siblings is in the threaded mode, it may contain "invalid". */
UNCOV
1557
        return strv_contains(v, "threaded") || strv_contains(v, "invalid");
×
1558
}
1559

1560
int cg_set_attribute(const char *controller, const char *path, const char *attribute, const char *value) {
34,866✔
1561
        _cleanup_free_ char *p = NULL;
34,866✔
1562
        int r;
34,866✔
1563

1564
        assert(attribute);
34,866✔
1565

1566
        r = cg_get_path(controller, path, attribute, &p);
34,866✔
1567
        if (r < 0)
34,866✔
1568
                return r;
1569

1570
        /* https://lore.kernel.org/all/20250419183545.1982187-1-shakeel.butt@linux.dev/ adds O_NONBLOCK
1571
         * semantics to memory.max and memory.high to skip synchronous memory reclaim when O_NONBLOCK is
1572
         * enabled. Let's always open cgroupv2 attribute files in nonblocking mode to immediately take
1573
         * advantage of this and any other asynchronous resource reclaim that's added to the cgroupv2 API in
1574
         * the future. */
1575
        return write_string_file(p, value, WRITE_STRING_FILE_DISABLE_BUFFER|WRITE_STRING_FILE_OPEN_NONBLOCKING);
34,866✔
1576
}
1577

1578
int cg_get_attribute(const char *controller, const char *path, const char *attribute, char **ret) {
31,166✔
1579
        _cleanup_free_ char *p = NULL;
31,166✔
1580
        int r;
31,166✔
1581

1582
        assert(attribute);
31,166✔
1583

1584
        r = cg_get_path(controller, path, attribute, &p);
31,166✔
1585
        if (r < 0)
31,166✔
1586
                return r;
1587

1588
        return read_one_line_file(p, ret);
31,166✔
1589
}
1590

1591
int cg_get_attribute_as_uint64(const char *controller, const char *path, const char *attribute, uint64_t *ret) {
26,097✔
1592
        _cleanup_free_ char *value = NULL;
26,097✔
1593
        uint64_t v;
26,097✔
1594
        int r;
26,097✔
1595

1596
        assert(ret);
26,097✔
1597

1598
        r = cg_get_attribute(controller, path, attribute, &value);
26,097✔
1599
        if (r == -ENOENT)
26,097✔
1600
                return -ENODATA;
1601
        if (r < 0)
24,380✔
1602
                return r;
1603

1604
        if (streq(value, "max")) {
24,380✔
1605
                *ret = CGROUP_LIMIT_MAX;
5,842✔
1606
                return 0;
5,842✔
1607
        }
1608

1609
        r = safe_atou64(value, &v);
18,538✔
1610
        if (r < 0)
18,538✔
1611
                return r;
1612

1613
        *ret = v;
18,538✔
1614
        return 0;
18,538✔
1615
}
1616

1617
int cg_get_attribute_as_bool(const char *controller, const char *path, const char *attribute) {
68✔
1618
        _cleanup_free_ char *value = NULL;
68✔
1619
        int r;
68✔
1620

1621
        r = cg_get_attribute(controller, path, attribute, &value);
68✔
1622
        if (r == -ENOENT)
68✔
1623
                return -ENODATA;
1624
        if (r < 0)
68✔
1625
                return r;
1626

1627
        return parse_boolean(value);
68✔
1628
}
1629

1630
int cg_get_owner(const char *path, uid_t *ret_uid) {
35✔
1631
        _cleanup_free_ char *f = NULL;
35✔
1632
        struct stat stats;
35✔
1633
        int r;
35✔
1634

1635
        assert(ret_uid);
35✔
1636

1637
        r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, path, NULL, &f);
35✔
1638
        if (r < 0)
35✔
1639
                return r;
1640

1641
        if (stat(f, &stats) < 0)
35✔
1642
                return -errno;
16✔
1643

1644
        r = stat_verify_directory(&stats);
19✔
1645
        if (r < 0)
19✔
1646
                return r;
1647

1648
        *ret_uid = stats.st_uid;
19✔
1649
        return 0;
19✔
1650
}
1651

1652
int cg_get_keyed_attribute(
22,577✔
1653
                const char *controller,
1654
                const char *path,
1655
                const char *attribute,
1656
                char * const *keys,
1657
                char **values) {
1658

1659
        _cleanup_free_ char *filename = NULL, *contents = NULL;
22,577✔
1660
        size_t n;
22,577✔
1661
        int r;
22,577✔
1662

1663
        assert(path);
22,577✔
1664
        assert(attribute);
22,577✔
1665

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

1672
        r = cg_get_path(controller, path, attribute, &filename);
22,577✔
1673
        if (r < 0)
22,577✔
1674
                return r;
1675

1676
        r = read_full_file(filename, &contents, /* ret_size = */ NULL);
22,577✔
1677
        if (r < 0)
22,577✔
1678
                return r;
1679

1680
        n = strv_length(keys);
20,237✔
1681
        if (n == 0) /* No keys to retrieve? That's easy, we are done then */
20,237✔
1682
                return 0;
1683
        assert(strv_is_uniq(keys));
20,237✔
1684

1685
        /* Let's build this up in a temporary array for now in order not to clobber the return parameter on failure */
1686
        char **v = newa0(char*, n);
20,237✔
1687
        size_t n_done = 0;
20,237✔
1688

1689
        for (const char *p = contents; *p;) {
68,365✔
1690
                const char *w;
1691
                size_t i;
1692

1693
                for (i = 0; i < n; i++) {
116,493✔
1694
                        w = first_word(p, keys[i]);
75,425✔
1695
                        if (w)
75,425✔
1696
                                break;
1697
                }
1698

1699
                if (w) {
68,365✔
1700
                        if (v[i]) { /* duplicate entry? */
27,297✔
UNCOV
1701
                                r = -EBADMSG;
×
UNCOV
1702
                                goto fail;
×
1703
                        }
1704

1705
                        size_t l = strcspn(w, NEWLINE);
27,297✔
1706

1707
                        v[i] = strndup(w, l);
27,297✔
1708
                        if (!v[i]) {
27,297✔
UNCOV
1709
                                r = -ENOMEM;
×
UNCOV
1710
                                goto fail;
×
1711
                        }
1712

1713
                        n_done++;
27,297✔
1714
                        if (n_done >= n)
27,297✔
1715
                                break;
1716

1717
                        p = w + l;
7,060✔
1718
                } else
1719
                        p += strcspn(p, NEWLINE);
41,068✔
1720

1721
                p += strspn(p, NEWLINE);
48,128✔
1722
        }
1723

1724
        if (n_done < n) {
20,237✔
UNCOV
1725
                r = -ENXIO;
×
UNCOV
1726
                goto fail;
×
1727
        }
1728

1729
        memcpy(values, v, sizeof(char*) * n);
20,237✔
1730
        return 0;
20,237✔
1731

UNCOV
1732
fail:
×
1733
        free_many_charp(v, n);
22,577✔
1734
        return r;
1735
}
1736

1737
int cg_mask_to_string(CGroupMask mask, char **ret) {
10,257✔
1738
        _cleanup_free_ char *s = NULL;
10,257✔
1739
        bool space = false;
10,257✔
1740
        CGroupController c;
10,257✔
1741
        size_t n = 0;
10,257✔
1742

1743
        assert(ret);
10,257✔
1744

1745
        if (mask == 0) {
10,257✔
1746
                *ret = NULL;
4,987✔
1747
                return 0;
4,987✔
1748
        }
1749

1750
        for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
73,780✔
1751
                const char *k;
68,510✔
1752
                size_t l;
68,510✔
1753

1754
                if (!FLAGS_SET(mask, CGROUP_CONTROLLER_TO_MASK(c)))
68,510✔
1755
                        continue;
32,792✔
1756

1757
                k = cgroup_controller_to_string(c);
35,718✔
1758
                l = strlen(k);
35,718✔
1759

1760
                if (!GREEDY_REALLOC(s, n + space + l + 1))
35,718✔
1761
                        return -ENOMEM;
1762

1763
                if (space)
35,718✔
1764
                        s[n] = ' ';
30,448✔
1765
                memcpy(s + n + space, k, l);
35,718✔
1766
                n += space + l;
35,718✔
1767

1768
                space = true;
35,718✔
1769
        }
1770

1771
        assert(s);
5,270✔
1772

1773
        s[n] = 0;
5,270✔
1774
        *ret = TAKE_PTR(s);
5,270✔
1775

1776
        return 0;
5,270✔
1777
}
1778

1779
int cg_mask_from_string(const char *value, CGroupMask *ret) {
5,152✔
1780
        CGroupMask m = 0;
5,152✔
1781

1782
        assert(ret);
5,152✔
1783
        assert(value);
5,152✔
1784

1785
        for (;;) {
39,440✔
1786
                _cleanup_free_ char *n = NULL;
34,288✔
1787
                CGroupController v;
39,440✔
1788
                int r;
39,440✔
1789

1790
                r = extract_first_word(&value, &n, NULL, 0);
39,440✔
1791
                if (r < 0)
39,440✔
UNCOV
1792
                        return r;
×
1793
                if (r == 0)
39,440✔
1794
                        break;
1795

1796
                v = cgroup_controller_from_string(n);
34,288✔
1797
                if (v < 0)
34,288✔
1798
                        continue;
706✔
1799

1800
                m |= CGROUP_CONTROLLER_TO_MASK(v);
33,582✔
1801
        }
1802

1803
        *ret = m;
5,152✔
1804
        return 0;
5,152✔
1805
}
1806

1807
int cg_mask_supported_subtree(const char *root, CGroupMask *ret) {
483✔
1808
        CGroupMask mask;
483✔
1809
        int r;
483✔
1810

1811
        /* Determines the mask of supported cgroup controllers. Only includes controllers we can make sense of and that
1812
         * are actually accessible. Only covers real controllers, i.e. not the CGROUP_CONTROLLER_BPF_xyz
1813
         * pseudo-controllers. */
1814

1815
        r = cg_all_unified();
483✔
1816
        if (r < 0)
483✔
1817
                return r;
483✔
1818
        if (r > 0) {
483✔
1819
                _cleanup_free_ char *controllers = NULL, *path = NULL;
483✔
1820

1821
                /* In the unified hierarchy we can read the supported and accessible controllers from
1822
                 * the top-level cgroup attribute */
1823

1824
                r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, root, "cgroup.controllers", &path);
483✔
1825
                if (r < 0)
483✔
1826
                        return r;
1827

1828
                r = read_one_line_file(path, &controllers);
483✔
1829
                if (r < 0)
483✔
1830
                        return r;
1831

1832
                r = cg_mask_from_string(controllers, &mask);
483✔
1833
                if (r < 0)
483✔
1834
                        return r;
1835

1836
                /* Mask controllers that are not supported in unified hierarchy. */
1837
                mask &= CGROUP_MASK_V2;
483✔
1838

1839
        } else {
UNCOV
1840
                CGroupController c;
×
1841

1842
                /* In the legacy hierarchy, we check which hierarchies are accessible. */
1843

UNCOV
1844
                mask = 0;
×
UNCOV
1845
                for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
×
UNCOV
1846
                        CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
×
UNCOV
1847
                        const char *n;
×
1848

UNCOV
1849
                        if (!FLAGS_SET(CGROUP_MASK_V1, bit))
×
UNCOV
1850
                                continue;
×
1851

UNCOV
1852
                        n = cgroup_controller_to_string(c);
×
UNCOV
1853
                        if (controller_is_v1_accessible(root, n) >= 0)
×
UNCOV
1854
                                mask |= bit;
×
1855
                }
1856
        }
1857

1858
        *ret = mask;
483✔
1859
        return 0;
483✔
1860
}
1861

1862
int cg_mask_supported(CGroupMask *ret) {
233✔
1863
        _cleanup_free_ char *root = NULL;
233✔
1864
        int r;
233✔
1865

1866
        r = cg_get_root_path(&root);
233✔
1867
        if (r < 0)
233✔
1868
                return r;
1869

1870
        return cg_mask_supported_subtree(root, ret);
233✔
1871
}
1872

1873
/* The hybrid mode was initially implemented in v232 and simply mounted cgroup2 on
1874
 * /sys/fs/cgroup/systemd. This unfortunately broke other tools (such as docker) which expected the v1
1875
 * "name=systemd" hierarchy on /sys/fs/cgroup/systemd. From v233 and on, the hybrid mode mounts v2 on
1876
 * /sys/fs/cgroup/unified and maintains "name=systemd" hierarchy on /sys/fs/cgroup/systemd for compatibility
1877
 * with other tools.
1878
 *
1879
 * To keep live upgrade working, we detect and support v232 layout. When v232 layout is detected, to keep
1880
 * cgroup v2 process management but disable the compat dual layout, we return true on
1881
 * cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER) and false on cg_hybrid_unified().
1882
 */
1883
static thread_local bool unified_systemd_v232;
1884

1885
int cg_unified_cached(bool flush) {
282,954✔
1886
        static thread_local CGroupUnified unified_cache = CGROUP_UNIFIED_UNKNOWN;
282,954✔
1887

1888
        struct statfs fs;
282,954✔
1889

1890
        /* Checks if we support the unified hierarchy. Returns an
1891
         * error when the cgroup hierarchies aren't mounted yet or we
1892
         * have any other trouble determining if the unified hierarchy
1893
         * is supported. */
1894

1895
        if (flush)
282,954✔
1896
                unified_cache = CGROUP_UNIFIED_UNKNOWN;
4✔
1897
        else if (unified_cache >= CGROUP_UNIFIED_NONE)
282,950✔
1898
                return unified_cache;
282,954✔
1899

1900
        if (statfs("/sys/fs/cgroup/", &fs) < 0)
13,091✔
UNCOV
1901
                return log_debug_errno(errno, "statfs(\"/sys/fs/cgroup/\") failed: %m");
×
1902

1903
        if (F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC)) {
13,091✔
1904
                log_debug("Found cgroup2 on /sys/fs/cgroup/, full unified hierarchy");
13,091✔
1905
                unified_cache = CGROUP_UNIFIED_ALL;
13,091✔
UNCOV
1906
        } else if (F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC)) {
×
UNCOV
1907
                if (statfs("/sys/fs/cgroup/unified/", &fs) == 0 &&
×
UNCOV
1908
                    F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC)) {
×
UNCOV
1909
                        log_debug("Found cgroup2 on /sys/fs/cgroup/unified, unified hierarchy for systemd controller");
×
UNCOV
1910
                        unified_cache = CGROUP_UNIFIED_SYSTEMD;
×
UNCOV
1911
                        unified_systemd_v232 = false;
×
1912
                } else {
UNCOV
1913
                        if (statfs("/sys/fs/cgroup/systemd/", &fs) < 0) {
×
UNCOV
1914
                                if (errno == ENOENT) {
×
1915
                                        /* Some other software may have set up /sys/fs/cgroup in a configuration we do not recognize. */
UNCOV
1916
                                        log_debug_errno(errno, "Unsupported cgroupsv1 setup detected: name=systemd hierarchy not found.");
×
UNCOV
1917
                                        return -ENOMEDIUM;
×
1918
                                }
UNCOV
1919
                                return log_debug_errno(errno, "statfs(\"/sys/fs/cgroup/systemd\" failed: %m");
×
1920
                        }
1921

UNCOV
1922
                        if (F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC)) {
×
UNCOV
1923
                                log_debug("Found cgroup2 on /sys/fs/cgroup/systemd, unified hierarchy for systemd controller (v232 variant)");
×
UNCOV
1924
                                unified_cache = CGROUP_UNIFIED_SYSTEMD;
×
UNCOV
1925
                                unified_systemd_v232 = true;
×
UNCOV
1926
                        } else if (F_TYPE_EQUAL(fs.f_type, CGROUP_SUPER_MAGIC)) {
×
UNCOV
1927
                                log_debug("Found cgroup on /sys/fs/cgroup/systemd, legacy hierarchy");
×
1928
                                unified_cache = CGROUP_UNIFIED_NONE;
×
1929
                        } else {
UNCOV
1930
                                log_debug("Unexpected filesystem type %llx mounted on /sys/fs/cgroup/systemd, assuming legacy hierarchy",
×
1931
                                          (unsigned long long) fs.f_type);
UNCOV
1932
                                unified_cache = CGROUP_UNIFIED_NONE;
×
1933
                        }
1934
                }
1935
        } else if (F_TYPE_EQUAL(fs.f_type, SYSFS_MAGIC)) {
×
1936
                return log_debug_errno(SYNTHETIC_ERRNO(ENOMEDIUM),
×
1937
                                       "No filesystem is currently mounted on /sys/fs/cgroup.");
1938
        } else
UNCOV
1939
                return log_debug_errno(SYNTHETIC_ERRNO(ENOMEDIUM),
×
1940
                                       "Unknown filesystem type %llx mounted on /sys/fs/cgroup.",
1941
                                       (unsigned long long)fs.f_type);
1942

1943
        return unified_cache;
13,091✔
1944
}
1945

1946
int cg_unified_controller(const char *controller) {
42,381✔
1947
        int r;
42,381✔
1948

1949
        r = cg_unified_cached(false);
42,381✔
1950
        if (r < 0)
42,381✔
1951
                return r;
1952

1953
        if (r == CGROUP_UNIFIED_NONE)
42,381✔
1954
                return false;
1955

1956
        if (r >= CGROUP_UNIFIED_ALL)
42,381✔
1957
                return true;
1958

1959
        return streq_ptr(controller, SYSTEMD_CGROUP_CONTROLLER);
×
1960
}
1961

1962
int cg_all_unified(void) {
240,567✔
1963
        int r;
240,567✔
1964

1965
        r = cg_unified_cached(false);
240,567✔
1966
        if (r < 0)
240,567✔
1967
                return r;
1968

1969
        return r >= CGROUP_UNIFIED_ALL;
240,567✔
1970
}
1971

1972
int cg_hybrid_unified(void) {
1✔
1973
        int r;
1✔
1974

1975
        r = cg_unified_cached(false);
1✔
1976
        if (r < 0)
1✔
1977
                return r;
1978

1979
        return r == CGROUP_UNIFIED_SYSTEMD && !unified_systemd_v232;
1✔
1980
}
1981

1982
int cg_is_delegated(const char *path) {
19✔
1983
        int r;
19✔
1984

1985
        assert(path);
19✔
1986

1987
        r = cg_get_xattr_bool(path, "trusted.delegate");
19✔
1988
        if (!ERRNO_IS_NEG_XATTR_ABSENT(r))
19✔
1989
                return r;
1990

1991
        /* If the trusted xattr isn't set (preferred), then check the untrusted one. Under the assumption
1992
         * that whoever is trusted enough to own the cgroup, is also trusted enough to decide if it is
1993
         * delegated or not this should be safe. */
1994
        r = cg_get_xattr_bool(path, "user.delegate");
6✔
1995
        return ERRNO_IS_NEG_XATTR_ABSENT(r) ? false : r;
6✔
1996
}
1997

1998
int cg_is_delegated_fd(int fd) {
42✔
1999
        int r;
42✔
2000

2001
        assert(fd >= 0);
42✔
2002

2003
        r = getxattr_at_bool(fd, /* path= */ NULL, "trusted.delegate", /* at_flags= */ 0);
42✔
2004
        if (!ERRNO_IS_NEG_XATTR_ABSENT(r))
42✔
2005
                return r;
2006

2007
        r = getxattr_at_bool(fd, /* path= */ NULL, "user.delegate", /* at_flags= */ 0);
40✔
2008
        return ERRNO_IS_NEG_XATTR_ABSENT(r) ? false : r;
40✔
2009
}
2010

2011
int cg_has_coredump_receive(const char *path) {
2✔
2012
        int r;
2✔
2013

2014
        assert(path);
2✔
2015

2016
        r = cg_get_xattr_bool(path, "user.coredump_receive");
2✔
2017
        if (ERRNO_IS_NEG_XATTR_ABSENT(r))
2✔
UNCOV
2018
                return false;
×
2019

2020
        return r;
2021
}
2022

2023
const uint64_t cgroup_io_limit_defaults[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2024
        [CGROUP_IO_RBPS_MAX]  = CGROUP_LIMIT_MAX,
2025
        [CGROUP_IO_WBPS_MAX]  = CGROUP_LIMIT_MAX,
2026
        [CGROUP_IO_RIOPS_MAX] = CGROUP_LIMIT_MAX,
2027
        [CGROUP_IO_WIOPS_MAX] = CGROUP_LIMIT_MAX,
2028
};
2029

2030
static const char* const cgroup_io_limit_type_table[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2031
        [CGROUP_IO_RBPS_MAX]  = "IOReadBandwidthMax",
2032
        [CGROUP_IO_WBPS_MAX]  = "IOWriteBandwidthMax",
2033
        [CGROUP_IO_RIOPS_MAX] = "IOReadIOPSMax",
2034
        [CGROUP_IO_WIOPS_MAX] = "IOWriteIOPSMax",
2035
};
2036

2037
DEFINE_STRING_TABLE_LOOKUP(cgroup_io_limit_type, CGroupIOLimitType);
5,547✔
2038

2039
void cgroup_io_limits_list(void) {
15✔
2040
        DUMP_STRING_TABLE(cgroup_io_limit_type, CGroupIOLimitType, _CGROUP_IO_LIMIT_TYPE_MAX);
75✔
2041
}
15✔
2042

2043
static const char *const cgroup_controller_table[_CGROUP_CONTROLLER_MAX] = {
2044
        [CGROUP_CONTROLLER_CPU]                             = "cpu",
2045
        [CGROUP_CONTROLLER_CPUACCT]                         = "cpuacct",
2046
        [CGROUP_CONTROLLER_CPUSET]                          = "cpuset",
2047
        [CGROUP_CONTROLLER_IO]                              = "io",
2048
        [CGROUP_CONTROLLER_BLKIO]                           = "blkio",
2049
        [CGROUP_CONTROLLER_MEMORY]                          = "memory",
2050
        [CGROUP_CONTROLLER_DEVICES]                         = "devices",
2051
        [CGROUP_CONTROLLER_PIDS]                            = "pids",
2052
        [CGROUP_CONTROLLER_BPF_FIREWALL]                    = "bpf-firewall",
2053
        [CGROUP_CONTROLLER_BPF_DEVICES]                     = "bpf-devices",
2054
        [CGROUP_CONTROLLER_BPF_FOREIGN]                     = "bpf-foreign",
2055
        [CGROUP_CONTROLLER_BPF_SOCKET_BIND]                 = "bpf-socket-bind",
2056
        [CGROUP_CONTROLLER_BPF_RESTRICT_NETWORK_INTERFACES] = "bpf-restrict-network-interfaces",
2057
};
2058

2059
DEFINE_STRING_TABLE_LOOKUP(cgroup_controller, CGroupController);
363,504✔
2060

2061
static const char* const managed_oom_mode_table[_MANAGED_OOM_MODE_MAX] = {
2062
        [MANAGED_OOM_AUTO] = "auto",
2063
        [MANAGED_OOM_KILL] = "kill",
2064
};
2065

2066
DEFINE_STRING_TABLE_LOOKUP(managed_oom_mode, ManagedOOMMode);
32,411✔
2067

2068
static const char* const managed_oom_preference_table[_MANAGED_OOM_PREFERENCE_MAX] = {
2069
        [MANAGED_OOM_PREFERENCE_NONE] = "none",
2070
        [MANAGED_OOM_PREFERENCE_AVOID] = "avoid",
2071
        [MANAGED_OOM_PREFERENCE_OMIT] = "omit",
2072
};
2073

2074
DEFINE_STRING_TABLE_LOOKUP(managed_oom_preference, ManagedOOMPreference);
15,933✔
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