chiark / gitweb /
1e9ec33a97204a140a67687e257013733386b6f5
[elogind.git] / src / basic / cgroup-util.c
1 /***
2   This file is part of systemd.
3
4   Copyright 2010 Lennart Poettering
5
6   systemd is free software; you can redistribute it and/or modify it
7   under the terms of the GNU Lesser General Public License as published by
8   the Free Software Foundation; either version 2.1 of the License, or
9   (at your option) any later version.
10
11   systemd is distributed in the hope that it will be useful, but
12   WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14   Lesser General Public License for more details.
15
16   You should have received a copy of the GNU Lesser General Public License
17   along with systemd; If not, see <http://www.gnu.org/licenses/>.
18 ***/
19
20 #include <dirent.h>
21 #include <errno.h>
22 #include <ftw.h>
23 //#include <limits.h>
24 #include <signal.h>
25 //#include <stddef.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <sys/stat.h>
29 //#include <sys/statfs.h>
30 #include <sys/types.h>
31 #include <unistd.h>
32
33 #include "alloc-util.h"
34 #include "cgroup-util.h"
35 //#include "def.h"
36 #include "dirent-util.h"
37 #include "extract-word.h"
38 #include "fd-util.h"
39 #include "fileio.h"
40 #include "formats-util.h"
41 #include "fs-util.h"
42 //#include "log.h"
43 #include "login-util.h"
44 #include "macro.h"
45 //#include "missing.h"
46 #include "mkdir.h"
47 #include "parse-util.h"
48 #include "path-util.h"
49 #include "proc-cmdline.h"
50 #include "process-util.h"
51 #include "set.h"
52 //#include "special.h"
53 #include "stat-util.h"
54 #include "stdio-util.h"
55 #include "string-table.h"
56 #include "string-util.h"
57 #include "unit-name.h"
58 #include "user-util.h"
59
60 int cg_enumerate_processes(const char *controller, const char *path, FILE **_f) {
61         _cleanup_free_ char *fs = NULL;
62         FILE *f;
63         int r;
64
65         assert(_f);
66
67         r = cg_get_path(controller, path, "cgroup.procs", &fs);
68         if (r < 0)
69                 return r;
70
71         f = fopen(fs, "re");
72         if (!f)
73                 return -errno;
74
75         *_f = f;
76         return 0;
77 }
78
79 int cg_read_pid(FILE *f, pid_t *_pid) {
80         unsigned long ul;
81
82         /* Note that the cgroup.procs might contain duplicates! See
83          * cgroups.txt for details. */
84
85         assert(f);
86         assert(_pid);
87
88         errno = 0;
89         if (fscanf(f, "%lu", &ul) != 1) {
90
91                 if (feof(f))
92                         return 0;
93
94                 return errno > 0 ? -errno : -EIO;
95         }
96
97         if (ul <= 0)
98                 return -EIO;
99
100         *_pid = (pid_t) ul;
101         return 1;
102 }
103
104 int cg_read_event(const char *controller, const char *path, const char *event,
105                   char **val)
106 {
107         _cleanup_free_ char *events = NULL, *content = NULL;
108         char *p, *line;
109         int r;
110
111         r = cg_get_path(controller, path, "cgroup.events", &events);
112         if (r < 0)
113                 return r;
114
115         r = read_full_file(events, &content, NULL);
116         if (r < 0)
117                 return r;
118
119         p = content;
120         while ((line = strsep(&p, "\n"))) {
121                 char *key;
122
123                 key = strsep(&line, " ");
124                 if (!key || !line)
125                         return -EINVAL;
126
127                 if (strcmp(key, event))
128                         continue;
129
130                 *val = strdup(line);
131                 return 0;
132         }
133
134         return -ENOENT;
135 }
136
137 int cg_enumerate_subgroups(const char *controller, const char *path, DIR **_d) {
138         _cleanup_free_ char *fs = NULL;
139         int r;
140         DIR *d;
141
142         assert(_d);
143
144         /* This is not recursive! */
145
146         r = cg_get_path(controller, path, NULL, &fs);
147         if (r < 0)
148                 return r;
149
150         d = opendir(fs);
151         if (!d)
152                 return -errno;
153
154         *_d = d;
155         return 0;
156 }
157
158 int cg_read_subgroup(DIR *d, char **fn) {
159         struct dirent *de;
160
161         assert(d);
162         assert(fn);
163
164         FOREACH_DIRENT_ALL(de, d, return -errno) {
165                 char *b;
166
167                 if (de->d_type != DT_DIR)
168                         continue;
169
170                 if (streq(de->d_name, ".") ||
171                     streq(de->d_name, ".."))
172                         continue;
173
174                 b = strdup(de->d_name);
175                 if (!b)
176                         return -ENOMEM;
177
178                 *fn = b;
179                 return 1;
180         }
181
182         return 0;
183 }
184
185 int cg_rmdir(const char *controller, const char *path) {
186         _cleanup_free_ char *p = NULL;
187         int r;
188
189         r = cg_get_path(controller, path, NULL, &p);
190         if (r < 0)
191                 return r;
192
193         r = rmdir(p);
194         if (r < 0 && errno != ENOENT)
195                 return -errno;
196
197         return 0;
198 }
199
200 int cg_kill(
201                 const char *controller,
202                 const char *path,
203                 int sig,
204                 CGroupFlags flags,
205                 Set *s,
206                 cg_kill_log_func_t log_kill,
207                 void *userdata) {
208
209         _cleanup_set_free_ Set *allocated_set = NULL;
210         bool done = false;
211         int r, ret = 0;
212         pid_t my_pid;
213
214         assert(sig >= 0);
215
216         /* This goes through the tasks list and kills them all. This
217          * is repeated until no further processes are added to the
218          * tasks list, to properly handle forking processes */
219
220         if (!s) {
221                 s = allocated_set = set_new(NULL);
222                 if (!s)
223                         return -ENOMEM;
224         }
225
226         my_pid = getpid();
227
228         do {
229                 _cleanup_fclose_ FILE *f = NULL;
230                 pid_t pid = 0;
231                 done = true;
232
233                 r = cg_enumerate_processes(controller, path, &f);
234                 if (r < 0) {
235                         if (ret >= 0 && r != -ENOENT)
236                                 return r;
237
238                         return ret;
239                 }
240
241                 while ((r = cg_read_pid(f, &pid)) > 0) {
242
243                         if ((flags & CGROUP_IGNORE_SELF) && pid == my_pid)
244                                 continue;
245
246                         if (set_get(s, PID_TO_PTR(pid)) == PID_TO_PTR(pid))
247                                 continue;
248
249                         if (log_kill)
250                                 log_kill(pid, sig, userdata);
251
252                         /* If we haven't killed this process yet, kill
253                          * it */
254                         if (kill(pid, sig) < 0) {
255                                 if (ret >= 0 && errno != ESRCH)
256                                         ret = -errno;
257                         } else {
258                                 if (flags & CGROUP_SIGCONT)
259                                         (void) kill(pid, SIGCONT);
260
261                                 if (ret == 0)
262                                         ret = 1;
263                         }
264
265                         done = false;
266
267                         r = set_put(s, PID_TO_PTR(pid));
268                         if (r < 0) {
269                                 if (ret >= 0)
270                                         return r;
271
272                                 return ret;
273                         }
274                 }
275
276                 if (r < 0) {
277                         if (ret >= 0)
278                                 return r;
279
280                         return ret;
281                 }
282
283                 /* To avoid racing against processes which fork
284                  * quicker than we can kill them we repeat this until
285                  * no new pids need to be killed. */
286
287         } while (!done);
288
289         return ret;
290 }
291
292 int cg_kill_recursive(
293                 const char *controller,
294                 const char *path,
295                 int sig,
296                 CGroupFlags flags,
297                 Set *s,
298                 cg_kill_log_func_t log_kill,
299                 void *userdata) {
300
301         _cleanup_set_free_ Set *allocated_set = NULL;
302         _cleanup_closedir_ DIR *d = NULL;
303         int r, ret;
304         char *fn;
305
306         assert(path);
307         assert(sig >= 0);
308
309         if (!s) {
310                 s = allocated_set = set_new(NULL);
311                 if (!s)
312                         return -ENOMEM;
313         }
314
315         ret = cg_kill(controller, path, sig, flags, s, log_kill, userdata);
316
317         r = cg_enumerate_subgroups(controller, path, &d);
318         if (r < 0) {
319                 if (ret >= 0 && r != -ENOENT)
320                         return r;
321
322                 return ret;
323         }
324
325         while ((r = cg_read_subgroup(d, &fn)) > 0) {
326                 _cleanup_free_ char *p = NULL;
327
328                 p = strjoin(path, "/", fn, NULL);
329                 free(fn);
330                 if (!p)
331                         return -ENOMEM;
332
333                 r = cg_kill_recursive(controller, p, sig, flags, s, log_kill, userdata);
334                 if (r != 0 && ret >= 0)
335                         ret = r;
336         }
337         if (ret >= 0 && r < 0)
338                 ret = r;
339
340         if (flags & CGROUP_REMOVE) {
341                 r = cg_rmdir(controller, path);
342                 if (r < 0 && ret >= 0 && r != -ENOENT && r != -EBUSY)
343                         return r;
344         }
345
346         return ret;
347 }
348
349 int cg_migrate(
350                 const char *cfrom,
351                 const char *pfrom,
352                 const char *cto,
353                 const char *pto,
354                 CGroupFlags flags) {
355
356         bool done = false;
357         _cleanup_set_free_ Set *s = NULL;
358         int r, ret = 0;
359         pid_t my_pid;
360
361         assert(cfrom);
362         assert(pfrom);
363         assert(cto);
364         assert(pto);
365
366         s = set_new(NULL);
367         if (!s)
368                 return -ENOMEM;
369
370         my_pid = getpid();
371
372         log_debug_elogind("Migrating \"%s\"/\"%s\" to \"%s\"/\"%s\" (%s)",
373                           cfrom, pfrom, cto, pto,
374                           ignore_self ? "ignoring self" : "watching self");
375         do {
376                 _cleanup_fclose_ FILE *f = NULL;
377                 pid_t pid = 0;
378                 done = true;
379
380                 r = cg_enumerate_processes(cfrom, pfrom, &f);
381                 if (r < 0) {
382                         if (ret >= 0 && r != -ENOENT)
383                                 return r;
384
385                         return ret;
386                 }
387
388                 while ((r = cg_read_pid(f, &pid)) > 0) {
389
390                         /* This might do weird stuff if we aren't a
391                          * single-threaded program. However, we
392                          * luckily know we are not */
393                         if ((flags & CGROUP_IGNORE_SELF) && pid == my_pid)
394                                 continue;
395
396                         if (set_get(s, PID_TO_PTR(pid)) == PID_TO_PTR(pid))
397                                 continue;
398
399                         /* Ignore kernel threads. Since they can only
400                          * exist in the root cgroup, we only check for
401                          * them there. */
402                         if (cfrom &&
403                             (isempty(pfrom) || path_equal(pfrom, "/")) &&
404                             is_kernel_thread(pid) > 0)
405                                 continue;
406
407                         r = cg_attach(cto, pto, pid);
408                         if (r < 0) {
409                                 if (ret >= 0 && r != -ESRCH)
410                                         ret = r;
411                         } else if (ret == 0)
412                                 ret = 1;
413
414                         done = false;
415
416                         r = set_put(s, PID_TO_PTR(pid));
417                         if (r < 0) {
418                                 if (ret >= 0)
419                                         return r;
420
421                                 return ret;
422                         }
423                 }
424
425                 if (r < 0) {
426                         if (ret >= 0)
427                                 return r;
428
429                         return ret;
430                 }
431         } while (!done);
432
433         return ret;
434 }
435
436 int cg_migrate_recursive(
437                 const char *cfrom,
438                 const char *pfrom,
439                 const char *cto,
440                 const char *pto,
441                 CGroupFlags flags) {
442
443         _cleanup_closedir_ DIR *d = NULL;
444         int r, ret = 0;
445         char *fn;
446
447         assert(cfrom);
448         assert(pfrom);
449         assert(cto);
450         assert(pto);
451
452         ret = cg_migrate(cfrom, pfrom, cto, pto, flags);
453
454         r = cg_enumerate_subgroups(cfrom, pfrom, &d);
455         if (r < 0) {
456                 if (ret >= 0 && r != -ENOENT)
457                         return r;
458
459                 return ret;
460         }
461
462         while ((r = cg_read_subgroup(d, &fn)) > 0) {
463                 _cleanup_free_ char *p = NULL;
464
465                 p = strjoin(pfrom, "/", fn, NULL);
466                 free(fn);
467                 if (!p)
468                         return -ENOMEM;
469
470                 r = cg_migrate_recursive(cfrom, p, cto, pto, flags);
471                 if (r != 0 && ret >= 0)
472                         ret = r;
473         }
474
475         if (r < 0 && ret >= 0)
476                 ret = r;
477
478         if (flags & CGROUP_REMOVE) {
479                 r = cg_rmdir(cfrom, pfrom);
480                 if (r < 0 && ret >= 0 && r != -ENOENT && r != -EBUSY)
481                         return r;
482         }
483
484         return ret;
485 }
486
487 int cg_migrate_recursive_fallback(
488                 const char *cfrom,
489                 const char *pfrom,
490                 const char *cto,
491                 const char *pto,
492                 CGroupFlags flags) {
493
494         int r;
495
496         assert(cfrom);
497         assert(pfrom);
498         assert(cto);
499         assert(pto);
500
501         r = cg_migrate_recursive(cfrom, pfrom, cto, pto, flags);
502         if (r < 0) {
503                 char prefix[strlen(pto) + 1];
504
505                 /* This didn't work? Then let's try all prefixes of the destination */
506
507                 PATH_FOREACH_PREFIX(prefix, pto) {
508                         int q;
509
510                         q = cg_migrate_recursive(cfrom, pfrom, cto, prefix, flags);
511                         if (q >= 0)
512                                 return q;
513                 }
514         }
515
516         return r;
517 }
518
519 static const char *controller_to_dirname(const char *controller) {
520         const char *e;
521
522         assert(controller);
523
524         /* Converts a controller name to the directory name below
525          * /sys/fs/cgroup/ we want to mount it to. Effectively, this
526          * just cuts off the name= prefixed used for named
527          * hierarchies, if it is specified. */
528
529         e = startswith(controller, "name=");
530         if (e)
531                 return e;
532
533         return controller;
534 }
535
536 static int join_path_legacy(const char *controller, const char *path, const char *suffix, char **fs) {
537         const char *dn;
538         char *t = NULL;
539
540         assert(fs);
541         assert(controller);
542
543         dn = controller_to_dirname(controller);
544
545         if (isempty(path) && isempty(suffix))
546                 t = strappend("/sys/fs/cgroup/", dn);
547         else if (isempty(path))
548                 t = strjoin("/sys/fs/cgroup/", dn, "/", suffix, NULL);
549         else if (isempty(suffix))
550                 t = strjoin("/sys/fs/cgroup/", dn, "/", path, NULL);
551         else
552                 t = strjoin("/sys/fs/cgroup/", dn, "/", path, "/", suffix, NULL);
553         if (!t)
554                 return -ENOMEM;
555
556         *fs = t;
557         return 0;
558 }
559
560 static int join_path_unified(const char *path, const char *suffix, char **fs) {
561         char *t;
562
563         assert(fs);
564
565         if (isempty(path) && isempty(suffix))
566                 t = strdup("/sys/fs/cgroup");
567         else if (isempty(path))
568                 t = strappend("/sys/fs/cgroup/", suffix);
569         else if (isempty(suffix))
570                 t = strappend("/sys/fs/cgroup/", path);
571         else
572                 t = strjoin("/sys/fs/cgroup/", path, "/", suffix, NULL);
573         if (!t)
574                 return -ENOMEM;
575
576         *fs = t;
577         return 0;
578 }
579
580 int cg_get_path(const char *controller, const char *path, const char *suffix, char **fs) {
581         int unified, r;
582
583         assert(fs);
584
585         if (!controller) {
586                 char *t;
587
588                 /* If no controller is specified, we return the path
589                  * *below* the controllers, without any prefix. */
590
591                 if (!path && !suffix)
592                         return -EINVAL;
593
594                 if (!suffix)
595                         t = strdup(path);
596                 else if (!path)
597                         t = strdup(suffix);
598                 else
599                         t = strjoin(path, "/", suffix, NULL);
600                 if (!t)
601                         return -ENOMEM;
602
603                 *fs = path_kill_slashes(t);
604                 return 0;
605         }
606
607         if (!cg_controller_is_valid(controller))
608                 return -EINVAL;
609
610         unified = cg_unified();
611         if (unified < 0)
612                 return unified;
613
614         if (unified > 0)
615                 r = join_path_unified(path, suffix, fs);
616         else
617                 r = join_path_legacy(controller, path, suffix, fs);
618         if (r < 0)
619                 return r;
620
621         path_kill_slashes(*fs);
622         return 0;
623 }
624
625 static int controller_is_accessible(const char *controller) {
626         int unified;
627
628         assert(controller);
629
630         /* Checks whether a specific controller is accessible,
631          * i.e. its hierarchy mounted. In the unified hierarchy all
632          * controllers are considered accessible, except for the named
633          * hierarchies */
634
635         if (!cg_controller_is_valid(controller))
636                 return -EINVAL;
637
638         unified = cg_unified();
639         if (unified < 0)
640                 return unified;
641         if (unified > 0) {
642                 /* We don't support named hierarchies if we are using
643                  * the unified hierarchy. */
644
645                 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER))
646                         return 0;
647
648                 if (startswith(controller, "name="))
649                         return -EOPNOTSUPP;
650
651         } else {
652                 const char *cc, *dn;
653
654                 dn = controller_to_dirname(controller);
655                 cc = strjoina("/sys/fs/cgroup/", dn);
656
657                 if (laccess(cc, F_OK) < 0)
658                         return -errno;
659         }
660
661         return 0;
662 }
663
664 int cg_get_path_and_check(const char *controller, const char *path, const char *suffix, char **fs) {
665         int r;
666
667         assert(controller);
668         assert(fs);
669
670         /* Check if the specified controller is actually accessible */
671         r = controller_is_accessible(controller);
672         if (r < 0)
673                 return r;
674
675         return cg_get_path(controller, path, suffix, fs);
676 }
677
678 static int trim_cb(const char *path, const struct stat *sb, int typeflag, struct FTW *ftwbuf) {
679         assert(path);
680         assert(sb);
681         assert(ftwbuf);
682
683         if (typeflag != FTW_DP)
684                 return 0;
685
686         if (ftwbuf->level < 1)
687                 return 0;
688
689         (void) rmdir(path);
690         return 0;
691 }
692
693 int cg_trim(const char *controller, const char *path, bool delete_root) {
694         _cleanup_free_ char *fs = NULL;
695         int r = 0;
696
697         assert(path);
698
699         r = cg_get_path(controller, path, NULL, &fs);
700         if (r < 0)
701                 return r;
702
703         errno = 0;
704         if (nftw(fs, trim_cb, 64, FTW_DEPTH|FTW_MOUNT|FTW_PHYS) != 0) {
705                 if (errno == ENOENT)
706                         r = 0;
707                 else if (errno > 0)
708                         r = -errno;
709                 else
710                         r = -EIO;
711         }
712
713         if (delete_root) {
714                 if (rmdir(fs) < 0 && errno != ENOENT)
715                         return -errno;
716         }
717
718         return r;
719 }
720
721 int cg_create(const char *controller, const char *path) {
722         _cleanup_free_ char *fs = NULL;
723         int r;
724
725         r = cg_get_path_and_check(controller, path, NULL, &fs);
726         if (r < 0)
727                 return r;
728
729         r = mkdir_parents(fs, 0755);
730         if (r < 0)
731                 return r;
732
733         if (mkdir(fs, 0755) < 0) {
734
735                 if (errno == EEXIST)
736                         return 0;
737
738                 return -errno;
739         }
740
741         return 1;
742 }
743
744 int cg_create_and_attach(const char *controller, const char *path, pid_t pid) {
745         int r, q;
746
747         assert(pid >= 0);
748
749         r = cg_create(controller, path);
750         if (r < 0)
751                 return r;
752
753         q = cg_attach(controller, path, pid);
754         if (q < 0)
755                 return q;
756
757         /* This does not remove the cgroup on failure */
758         return r;
759 }
760
761 int cg_attach(const char *controller, const char *path, pid_t pid) {
762         _cleanup_free_ char *fs = NULL;
763         char c[DECIMAL_STR_MAX(pid_t) + 2];
764         int r;
765
766         assert(path);
767         assert(pid >= 0);
768
769         r = cg_get_path_and_check(controller, path, "cgroup.procs", &fs);
770         if (r < 0)
771                 return r;
772
773         if (pid == 0)
774                 pid = getpid();
775
776         xsprintf(c, PID_FMT "\n", pid);
777
778         return write_string_file(fs, c, 0);
779 }
780
781 int cg_attach_fallback(const char *controller, const char *path, pid_t pid) {
782         int r;
783
784         assert(controller);
785         assert(path);
786         assert(pid >= 0);
787
788         r = cg_attach(controller, path, pid);
789         if (r < 0) {
790                 char prefix[strlen(path) + 1];
791
792                 /* This didn't work? Then let's try all prefixes of
793                  * the destination */
794
795                 PATH_FOREACH_PREFIX(prefix, path) {
796                         int q;
797
798                         q = cg_attach(controller, prefix, pid);
799                         if (q >= 0)
800                                 return q;
801                 }
802         }
803
804         return r;
805 }
806
807 #if 0 /// UNNEEDED by elogind
808 int cg_set_group_access(
809                 const char *controller,
810                 const char *path,
811                 mode_t mode,
812                 uid_t uid,
813                 gid_t gid) {
814
815         _cleanup_free_ char *fs = NULL;
816         int r;
817
818         if (mode == MODE_INVALID && uid == UID_INVALID && gid == GID_INVALID)
819                 return 0;
820
821         if (mode != MODE_INVALID)
822                 mode &= 0777;
823
824         r = cg_get_path(controller, path, NULL, &fs);
825         if (r < 0)
826                 return r;
827
828         return chmod_and_chown(fs, mode, uid, gid);
829 }
830
831 int cg_set_task_access(
832                 const char *controller,
833                 const char *path,
834                 mode_t mode,
835                 uid_t uid,
836                 gid_t gid) {
837
838         _cleanup_free_ char *fs = NULL, *procs = NULL;
839         int r, unified;
840
841         assert(path);
842
843         if (mode == MODE_INVALID && uid == UID_INVALID && gid == GID_INVALID)
844                 return 0;
845
846         if (mode != MODE_INVALID)
847                 mode &= 0666;
848
849         r = cg_get_path(controller, path, "cgroup.procs", &fs);
850         if (r < 0)
851                 return r;
852
853         r = chmod_and_chown(fs, mode, uid, gid);
854         if (r < 0)
855                 return r;
856
857         unified = cg_unified();
858         if (unified < 0)
859                 return unified;
860         if (unified)
861                 return 0;
862
863         /* Compatibility, Always keep values for "tasks" in sync with
864          * "cgroup.procs" */
865         if (cg_get_path(controller, path, "tasks", &procs) >= 0)
866                 (void) chmod_and_chown(procs, mode, uid, gid);
867
868         return 0;
869 }
870 #endif // 0
871
872 int cg_pid_get_path(const char *controller, pid_t pid, char **path) {
873         _cleanup_fclose_ FILE *f = NULL;
874         char line[LINE_MAX];
875         const char *fs;
876         size_t cs = 0;
877         int unified;
878
879         assert(path);
880         assert(pid >= 0);
881
882         unified = cg_unified();
883         if (unified < 0)
884                 return unified;
885         if (unified == 0) {
886                 if (controller) {
887                         if (!cg_controller_is_valid(controller))
888                                 return -EINVAL;
889                 } else
890                         controller = SYSTEMD_CGROUP_CONTROLLER;
891
892                 cs = strlen(controller);
893         }
894
895         fs = procfs_file_alloca(pid, "cgroup");
896         log_debug_elogind("Searching for PID %u in \"%s\" (controller \"%s\")",
897                           pid, fs, controller);
898         f = fopen(fs, "re");
899         if (!f)
900                 return errno == ENOENT ? -ESRCH : -errno;
901
902         FOREACH_LINE(line, f, return -errno) {
903                 char *e, *p;
904
905                 truncate_nl(line);
906
907                 if (unified) {
908                         e = startswith(line, "0:");
909                         if (!e)
910                                 continue;
911
912                         e = strchr(e, ':');
913                         if (!e)
914                                 continue;
915                 } else {
916                         char *l;
917                         size_t k;
918                         const char *word, *state;
919                         bool found = false;
920
921                         l = strchr(line, ':');
922                         if (!l)
923                                 continue;
924
925                         l++;
926                         e = strchr(l, ':');
927                         if (!e)
928                                 continue;
929
930                         *e = 0;
931                         FOREACH_WORD_SEPARATOR(word, k, l, ",", state) {
932                                 if (k == cs && memcmp(word, controller, cs) == 0) {
933                                         found = true;
934                                         break;
935                                 }
936                         }
937
938                         if (!found)
939                                 continue;
940                 }
941
942                 log_debug_elogind("Found %s:%s", line, e+1);
943                 p = strdup(e + 1);
944                 if (!p)
945                         return -ENOMEM;
946
947                 *path = p;
948                 return 0;
949         }
950
951         return -ENODATA;
952 }
953
954 int cg_install_release_agent(const char *controller, const char *agent) {
955         _cleanup_free_ char *fs = NULL, *contents = NULL;
956         const char *sc;
957         int r, unified;
958
959         assert(agent);
960
961         unified = cg_unified();
962         if (unified < 0)
963                 return unified;
964         if (unified) /* doesn't apply to unified hierarchy */
965                 return -EOPNOTSUPP;
966
967         r = cg_get_path(controller, NULL, "release_agent", &fs);
968         if (r < 0)
969                 return r;
970
971         r = read_one_line_file(fs, &contents);
972         if (r < 0)
973                 return r;
974
975         sc = strstrip(contents);
976         if (isempty(sc)) {
977                 r = write_string_file(fs, agent, 0);
978                 if (r < 0)
979                         return r;
980         } else if (!path_equal(sc, agent))
981                 return -EEXIST;
982
983         fs = mfree(fs);
984         r = cg_get_path(controller, NULL, "notify_on_release", &fs);
985         if (r < 0)
986                 return r;
987
988         contents = mfree(contents);
989         r = read_one_line_file(fs, &contents);
990         if (r < 0)
991                 return r;
992
993         sc = strstrip(contents);
994         if (streq(sc, "0")) {
995                 r = write_string_file(fs, "1", 0);
996                 if (r < 0)
997                         return r;
998
999                 return 1;
1000         }
1001
1002         if (!streq(sc, "1"))
1003                 return -EIO;
1004
1005         return 0;
1006 }
1007
1008 int cg_uninstall_release_agent(const char *controller) {
1009         _cleanup_free_ char *fs = NULL;
1010         int r, unified;
1011
1012         unified = cg_unified();
1013         if (unified < 0)
1014                 return unified;
1015         if (unified) /* Doesn't apply to unified hierarchy */
1016                 return -EOPNOTSUPP;
1017
1018         r = cg_get_path(controller, NULL, "notify_on_release", &fs);
1019         if (r < 0)
1020                 return r;
1021
1022         r = write_string_file(fs, "0", 0);
1023         if (r < 0)
1024                 return r;
1025
1026         fs = mfree(fs);
1027
1028         r = cg_get_path(controller, NULL, "release_agent", &fs);
1029         if (r < 0)
1030                 return r;
1031
1032         r = write_string_file(fs, "", 0);
1033         if (r < 0)
1034                 return r;
1035
1036         return 0;
1037 }
1038
1039 int cg_is_empty(const char *controller, const char *path) {
1040         _cleanup_fclose_ FILE *f = NULL;
1041         pid_t pid;
1042         int r;
1043
1044         assert(path);
1045
1046         r = cg_enumerate_processes(controller, path, &f);
1047         if (r == -ENOENT)
1048                 return 1;
1049         if (r < 0)
1050                 return r;
1051
1052         r = cg_read_pid(f, &pid);
1053         if (r < 0)
1054                 return r;
1055
1056         return r == 0;
1057 }
1058
1059 int cg_is_empty_recursive(const char *controller, const char *path) {
1060         int unified, r;
1061
1062         assert(path);
1063
1064         /* The root cgroup is always populated */
1065         if (controller && (isempty(path) || path_equal(path, "/")))
1066                 return false;
1067
1068         unified = cg_unified();
1069         if (unified < 0)
1070                 return unified;
1071
1072         if (unified > 0) {
1073                 _cleanup_free_ char *t = NULL;
1074
1075                 /* On the unified hierarchy we can check empty state
1076                  * via the "populated" attribute of "cgroup.events". */
1077
1078                 r = cg_read_event(controller, path, "populated", &t);
1079                 if (r < 0)
1080                         return r;
1081
1082                 return streq(t, "0");
1083         } else {
1084                 _cleanup_closedir_ DIR *d = NULL;
1085                 char *fn;
1086
1087                 r = cg_is_empty(controller, path);
1088                 if (r <= 0)
1089                         return r;
1090
1091                 r = cg_enumerate_subgroups(controller, path, &d);
1092                 if (r == -ENOENT)
1093                         return 1;
1094                 if (r < 0)
1095                         return r;
1096
1097                 while ((r = cg_read_subgroup(d, &fn)) > 0) {
1098                         _cleanup_free_ char *p = NULL;
1099
1100                         p = strjoin(path, "/", fn, NULL);
1101                         free(fn);
1102                         if (!p)
1103                                 return -ENOMEM;
1104
1105                         r = cg_is_empty_recursive(controller, p);
1106                         if (r <= 0)
1107                                 return r;
1108                 }
1109                 if (r < 0)
1110                         return r;
1111
1112                 return true;
1113         }
1114 }
1115
1116 int cg_split_spec(const char *spec, char **controller, char **path) {
1117         char *t = NULL, *u = NULL;
1118         const char *e;
1119
1120         assert(spec);
1121
1122         if (*spec == '/') {
1123                 if (!path_is_safe(spec))
1124                         return -EINVAL;
1125
1126                 if (path) {
1127                         t = strdup(spec);
1128                         if (!t)
1129                                 return -ENOMEM;
1130
1131                         *path = path_kill_slashes(t);
1132                 }
1133
1134                 if (controller)
1135                         *controller = NULL;
1136
1137                 return 0;
1138         }
1139
1140         e = strchr(spec, ':');
1141         if (!e) {
1142                 if (!cg_controller_is_valid(spec))
1143                         return -EINVAL;
1144
1145                 if (controller) {
1146                         t = strdup(spec);
1147                         if (!t)
1148                                 return -ENOMEM;
1149
1150                         *controller = t;
1151                 }
1152
1153                 if (path)
1154                         *path = NULL;
1155
1156                 return 0;
1157         }
1158
1159         t = strndup(spec, e-spec);
1160         if (!t)
1161                 return -ENOMEM;
1162         if (!cg_controller_is_valid(t)) {
1163                 free(t);
1164                 return -EINVAL;
1165         }
1166
1167         if (isempty(e+1))
1168                 u = NULL;
1169         else {
1170                 u = strdup(e+1);
1171                 if (!u) {
1172                         free(t);
1173                         return -ENOMEM;
1174                 }
1175
1176                 if (!path_is_safe(u) ||
1177                     !path_is_absolute(u)) {
1178                         free(t);
1179                         free(u);
1180                         return -EINVAL;
1181                 }
1182
1183                 path_kill_slashes(u);
1184         }
1185
1186         if (controller)
1187                 *controller = t;
1188         else
1189                 free(t);
1190
1191         if (path)
1192                 *path = u;
1193         else
1194                 free(u);
1195
1196         return 0;
1197 }
1198
1199 int cg_mangle_path(const char *path, char **result) {
1200         _cleanup_free_ char *c = NULL, *p = NULL;
1201         char *t;
1202         int r;
1203
1204         assert(path);
1205         assert(result);
1206
1207         /* First, check if it already is a filesystem path */
1208         if (path_startswith(path, "/sys/fs/cgroup")) {
1209
1210                 t = strdup(path);
1211                 if (!t)
1212                         return -ENOMEM;
1213
1214                 *result = path_kill_slashes(t);
1215                 return 0;
1216         }
1217
1218         /* Otherwise, treat it as cg spec */
1219         r = cg_split_spec(path, &c, &p);
1220         if (r < 0)
1221                 return r;
1222
1223         return cg_get_path(c ?: SYSTEMD_CGROUP_CONTROLLER, p ?: "/", NULL, result);
1224 }
1225
1226 int cg_get_root_path(char **path) {
1227 #if 0 /// elogind does not support systemd scopes and slices
1228         char *p, *e;
1229         int r;
1230
1231         assert(path);
1232
1233         r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, &p);
1234         if (r < 0)
1235                 return r;
1236
1237         e = endswith(p, "/" SPECIAL_INIT_SCOPE);
1238         if (!e)
1239                 e = endswith(p, "/" SPECIAL_SYSTEM_SLICE); /* legacy */
1240         if (!e)
1241                 e = endswith(p, "/system"); /* even more legacy */
1242         if (e)
1243                 *e = 0;
1244
1245         *path = p;
1246         return 0;
1247 #else
1248         assert(path);
1249         return cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, path);
1250 #endif // 0
1251 }
1252
1253 int cg_shift_path(const char *cgroup, const char *root, const char **shifted) {
1254         _cleanup_free_ char *rt = NULL;
1255         char *p;
1256         int r;
1257
1258         assert(cgroup);
1259         assert(shifted);
1260
1261         if (!root) {
1262                 /* If the root was specified let's use that, otherwise
1263                  * let's determine it from PID 1 */
1264
1265                 r = cg_get_root_path(&rt);
1266                 if (r < 0)
1267                         return r;
1268
1269                 root = rt;
1270                 log_debug_elogind("Determined root path: \"%s\"", root);
1271         }
1272
1273         p = path_startswith(cgroup, root);
1274         if (p && p[0] && (p > cgroup))
1275                 *shifted = p - 1;
1276         else
1277                 *shifted = cgroup;
1278
1279         return 0;
1280 }
1281
1282 int cg_pid_get_path_shifted(pid_t pid, const char *root, char **cgroup) {
1283         _cleanup_free_ char *raw = NULL;
1284         const char *c;
1285         int r;
1286
1287         assert(pid >= 0);
1288         assert(cgroup);
1289
1290         r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &raw);
1291         if (r < 0)
1292                 return r;
1293
1294         log_debug_elogind("Shifting path: \"%s\" (PID %u, root: \"%s\")",
1295                           raw, pid, root ? root : "NULL");
1296         r = cg_shift_path(raw, root, &c);
1297         if (r < 0)
1298                 return r;
1299
1300         if (c == raw) {
1301                 *cgroup = raw;
1302                 raw = NULL;
1303         } else {
1304                 char *n;
1305
1306                 n = strdup(c);
1307                 if (!n)
1308                         return -ENOMEM;
1309
1310                 *cgroup = n;
1311         }
1312         log_debug_elogind("Resulting cgroup:\"%s\"", *cgroup);
1313
1314         return 0;
1315 }
1316
1317 #if 0 /// UNNEEDED by elogind
1318 int cg_path_decode_unit(const char *cgroup, char **unit) {
1319         char *c, *s;
1320         size_t n;
1321
1322         assert(cgroup);
1323         assert(unit);
1324
1325         n = strcspn(cgroup, "/");
1326         if (n < 3)
1327                 return -ENXIO;
1328
1329         c = strndupa(cgroup, n);
1330         c = cg_unescape(c);
1331
1332         if (!unit_name_is_valid(c, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
1333                 return -ENXIO;
1334
1335         s = strdup(c);
1336         if (!s)
1337                 return -ENOMEM;
1338
1339         *unit = s;
1340         return 0;
1341 }
1342
1343 static bool valid_slice_name(const char *p, size_t n) {
1344
1345         if (!p)
1346                 return false;
1347
1348         if (n < strlen("x.slice"))
1349                 return false;
1350
1351         if (memcmp(p + n - 6, ".slice", 6) == 0) {
1352                 char buf[n+1], *c;
1353
1354                 memcpy(buf, p, n);
1355                 buf[n] = 0;
1356
1357                 c = cg_unescape(buf);
1358
1359                 return unit_name_is_valid(c, UNIT_NAME_PLAIN);
1360         }
1361
1362         return false;
1363 }
1364
1365 static const char *skip_slices(const char *p) {
1366         assert(p);
1367
1368         /* Skips over all slice assignments */
1369
1370         for (;;) {
1371                 size_t n;
1372
1373                 p += strspn(p, "/");
1374
1375                 n = strcspn(p, "/");
1376                 if (!valid_slice_name(p, n))
1377                         return p;
1378
1379                 p += n;
1380         }
1381 }
1382
1383 int cg_path_get_unit(const char *path, char **ret) {
1384         const char *e;
1385         char *unit;
1386         int r;
1387
1388         assert(path);
1389         assert(ret);
1390
1391         e = skip_slices(path);
1392
1393         r = cg_path_decode_unit(e, &unit);
1394         if (r < 0)
1395                 return r;
1396
1397         /* We skipped over the slices, don't accept any now */
1398         if (endswith(unit, ".slice")) {
1399                 free(unit);
1400                 return -ENXIO;
1401         }
1402
1403         *ret = unit;
1404         return 0;
1405 }
1406
1407 int cg_pid_get_unit(pid_t pid, char **unit) {
1408         _cleanup_free_ char *cgroup = NULL;
1409         int r;
1410
1411         assert(unit);
1412
1413         r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1414         if (r < 0)
1415                 return r;
1416
1417         return cg_path_get_unit(cgroup, unit);
1418 }
1419
1420 /**
1421  * Skip session-*.scope, but require it to be there.
1422  */
1423 static const char *skip_session(const char *p) {
1424         size_t n;
1425
1426         if (isempty(p))
1427                 return NULL;
1428
1429         p += strspn(p, "/");
1430
1431         n = strcspn(p, "/");
1432         if (n < strlen("session-x.scope"))
1433                 return NULL;
1434
1435         if (memcmp(p, "session-", 8) == 0 && memcmp(p + n - 6, ".scope", 6) == 0) {
1436                 char buf[n - 8 - 6 + 1];
1437
1438                 memcpy(buf, p + 8, n - 8 - 6);
1439                 buf[n - 8 - 6] = 0;
1440
1441                 /* Note that session scopes never need unescaping,
1442                  * since they cannot conflict with the kernel's own
1443                  * names, hence we don't need to call cg_unescape()
1444                  * here. */
1445
1446                 if (!session_id_valid(buf))
1447                         return false;
1448
1449                 p += n;
1450                 p += strspn(p, "/");
1451                 return p;
1452         }
1453
1454         return NULL;
1455 }
1456
1457 /**
1458  * Skip user@*.service, but require it to be there.
1459  */
1460 static const char *skip_user_manager(const char *p) {
1461         size_t n;
1462
1463         if (isempty(p))
1464                 return NULL;
1465
1466         p += strspn(p, "/");
1467
1468         n = strcspn(p, "/");
1469         if (n < strlen("user@x.service"))
1470                 return NULL;
1471
1472         if (memcmp(p, "user@", 5) == 0 && memcmp(p + n - 8, ".service", 8) == 0) {
1473                 char buf[n - 5 - 8 + 1];
1474
1475                 memcpy(buf, p + 5, n - 5 - 8);
1476                 buf[n - 5 - 8] = 0;
1477
1478                 /* Note that user manager services never need unescaping,
1479                  * since they cannot conflict with the kernel's own
1480                  * names, hence we don't need to call cg_unescape()
1481                  * here. */
1482
1483                 if (parse_uid(buf, NULL) < 0)
1484                         return NULL;
1485
1486                 p += n;
1487                 p += strspn(p, "/");
1488
1489                 return p;
1490         }
1491
1492         return NULL;
1493 }
1494
1495 static const char *skip_user_prefix(const char *path) {
1496         const char *e, *t;
1497
1498         assert(path);
1499
1500         /* Skip slices, if there are any */
1501         e = skip_slices(path);
1502
1503         /* Skip the user manager, if it's in the path now... */
1504         t = skip_user_manager(e);
1505         if (t)
1506                 return t;
1507
1508         /* Alternatively skip the user session if it is in the path... */
1509         return skip_session(e);
1510 }
1511
1512 int cg_path_get_user_unit(const char *path, char **ret) {
1513         const char *t;
1514
1515         assert(path);
1516         assert(ret);
1517
1518         t = skip_user_prefix(path);
1519         if (!t)
1520                 return -ENXIO;
1521
1522         /* And from here on it looks pretty much the same as for a
1523          * system unit, hence let's use the same parser from here
1524          * on. */
1525         return cg_path_get_unit(t, ret);
1526 }
1527
1528 int cg_pid_get_user_unit(pid_t pid, char **unit) {
1529         _cleanup_free_ char *cgroup = NULL;
1530         int r;
1531
1532         assert(unit);
1533
1534         r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1535         if (r < 0)
1536                 return r;
1537
1538         return cg_path_get_user_unit(cgroup, unit);
1539 }
1540
1541 int cg_path_get_machine_name(const char *path, char **machine) {
1542         _cleanup_free_ char *u = NULL;
1543         const char *sl;
1544         int r;
1545
1546         r = cg_path_get_unit(path, &u);
1547         if (r < 0)
1548                 return r;
1549
1550         sl = strjoina("/run/systemd/machines/unit:", u);
1551         return readlink_malloc(sl, machine);
1552 }
1553
1554 int cg_pid_get_machine_name(pid_t pid, char **machine) {
1555         _cleanup_free_ char *cgroup = NULL;
1556         int r;
1557
1558         assert(machine);
1559
1560         r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1561         if (r < 0)
1562                 return r;
1563
1564         return cg_path_get_machine_name(cgroup, machine);
1565 }
1566 #endif // 0
1567
1568 int cg_path_get_session(const char *path, char **session) {
1569 #if 0 /// UNNEEDED by elogind
1570         _cleanup_free_ char *unit = NULL;
1571         char *start, *end;
1572         int r;
1573
1574         assert(path);
1575
1576         r = cg_path_get_unit(path, &unit);
1577         if (r < 0)
1578                 return r;
1579
1580         start = startswith(unit, "session-");
1581         if (!start)
1582                 return -ENXIO;
1583         end = endswith(start, ".scope");
1584         if (!end)
1585                 return -ENXIO;
1586
1587         *end = 0;
1588         if (!session_id_valid(start))
1589                 return -ENXIO;
1590 #else
1591         /* Elogind uses a flat hierarchy, just "/SESSION".  The only
1592            wrinkle is that SESSION might be escaped.  */
1593         const char *e, *n, *start;
1594
1595         assert(path);
1596         log_debug_elogind("path is \"%s\"", path);
1597         assert(path[0] == '/');
1598
1599         e = path + 1;
1600         n = strchrnul(e, '/');
1601         if (e == n)
1602                 return -ENOENT;
1603
1604         start = strndupa(e, n - e);
1605         start = cg_unescape(start);
1606
1607         if (!start[0])
1608                 return -ENOENT;
1609 #endif // 0
1610
1611         if (session) {
1612                 char *rr;
1613
1614                 log_debug_elogind("found session: \"%s\"", start);
1615                 rr = strdup(start);
1616                 if (!rr)
1617                         return -ENOMEM;
1618
1619                 *session = rr;
1620         }
1621
1622         return 0;
1623 }
1624
1625 int cg_pid_get_session(pid_t pid, char **session) {
1626         _cleanup_free_ char *cgroup = NULL;
1627         int r;
1628
1629         r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1630         if (r < 0)
1631                 return r;
1632
1633         return cg_path_get_session(cgroup, session);
1634 }
1635
1636 #if 0 /// UNNEEDED by elogind
1637 int cg_path_get_owner_uid(const char *path, uid_t *uid) {
1638         _cleanup_free_ char *slice = NULL;
1639         char *start, *end;
1640         int r;
1641
1642         assert(path);
1643
1644         r = cg_path_get_slice(path, &slice);
1645         if (r < 0)
1646                 return r;
1647
1648         start = startswith(slice, "user-");
1649         if (!start)
1650                 return -ENXIO;
1651         end = endswith(start, ".slice");
1652         if (!end)
1653                 return -ENXIO;
1654
1655         *end = 0;
1656         if (parse_uid(start, uid) < 0)
1657                 return -ENXIO;
1658
1659         return 0;
1660 }
1661
1662 int cg_pid_get_owner_uid(pid_t pid, uid_t *uid) {
1663         _cleanup_free_ char *cgroup = NULL;
1664         int r;
1665
1666         r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1667         if (r < 0)
1668                 return r;
1669
1670         return cg_path_get_owner_uid(cgroup, uid);
1671 }
1672
1673 int cg_path_get_slice(const char *p, char **slice) {
1674         const char *e = NULL;
1675
1676         assert(p);
1677         assert(slice);
1678
1679         /* Finds the right-most slice unit from the beginning, but
1680          * stops before we come to the first non-slice unit. */
1681
1682         for (;;) {
1683                 size_t n;
1684
1685                 p += strspn(p, "/");
1686
1687                 n = strcspn(p, "/");
1688                 if (!valid_slice_name(p, n)) {
1689
1690                         if (!e) {
1691                                 char *s;
1692
1693                                 s = strdup("-.slice");
1694                                 if (!s)
1695                                         return -ENOMEM;
1696
1697                                 *slice = s;
1698                                 return 0;
1699                         }
1700
1701                         return cg_path_decode_unit(e, slice);
1702                 }
1703
1704                 e = p;
1705                 p += n;
1706         }
1707 }
1708
1709 int cg_pid_get_slice(pid_t pid, char **slice) {
1710         _cleanup_free_ char *cgroup = NULL;
1711         int r;
1712
1713         assert(slice);
1714
1715         r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1716         if (r < 0)
1717                 return r;
1718
1719         return cg_path_get_slice(cgroup, slice);
1720 }
1721
1722 int cg_path_get_user_slice(const char *p, char **slice) {
1723         const char *t;
1724         assert(p);
1725         assert(slice);
1726
1727         t = skip_user_prefix(p);
1728         if (!t)
1729                 return -ENXIO;
1730
1731         /* And now it looks pretty much the same as for a system
1732          * slice, so let's just use the same parser from here on. */
1733         return cg_path_get_slice(t, slice);
1734 }
1735
1736 int cg_pid_get_user_slice(pid_t pid, char **slice) {
1737         _cleanup_free_ char *cgroup = NULL;
1738         int r;
1739
1740         assert(slice);
1741
1742         r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1743         if (r < 0)
1744                 return r;
1745
1746         return cg_path_get_user_slice(cgroup, slice);
1747 }
1748 #endif // 0
1749
1750 char *cg_escape(const char *p) {
1751         bool need_prefix = false;
1752
1753         /* This implements very minimal escaping for names to be used
1754          * as file names in the cgroup tree: any name which might
1755          * conflict with a kernel name or is prefixed with '_' is
1756          * prefixed with a '_'. That way, when reading cgroup names it
1757          * is sufficient to remove a single prefixing underscore if
1758          * there is one. */
1759
1760         /* The return value of this function (unlike cg_unescape())
1761          * needs free()! */
1762
1763         if (p[0] == 0 ||
1764             p[0] == '_' ||
1765             p[0] == '.' ||
1766             streq(p, "notify_on_release") ||
1767             streq(p, "release_agent") ||
1768             streq(p, "tasks") ||
1769             startswith(p, "cgroup."))
1770                 need_prefix = true;
1771         else {
1772                 const char *dot;
1773
1774                 dot = strrchr(p, '.');
1775                 if (dot) {
1776                         CGroupController c;
1777                         size_t l = dot - p;
1778
1779                         for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1780                                 const char *n;
1781
1782                                 n = cgroup_controller_to_string(c);
1783
1784                                 if (l != strlen(n))
1785                                         continue;
1786
1787                                 if (memcmp(p, n, l) != 0)
1788                                         continue;
1789
1790                                 need_prefix = true;
1791                                 break;
1792                         }
1793                 }
1794         }
1795
1796         if (need_prefix)
1797                 return strappend("_", p);
1798
1799         return strdup(p);
1800 }
1801
1802 char *cg_unescape(const char *p) {
1803         assert(p);
1804
1805         /* The return value of this function (unlike cg_escape())
1806          * doesn't need free()! */
1807
1808         if (p[0] == '_')
1809                 return (char*) p+1;
1810
1811         return (char*) p;
1812 }
1813
1814 #define CONTROLLER_VALID                        \
1815         DIGITS LETTERS                          \
1816         "_"
1817
1818 bool cg_controller_is_valid(const char *p) {
1819         const char *t, *s;
1820
1821         if (!p)
1822                 return false;
1823
1824         s = startswith(p, "name=");
1825         if (s)
1826                 p = s;
1827
1828         if (*p == 0 || *p == '_')
1829                 return false;
1830
1831         for (t = p; *t; t++)
1832                 if (!strchr(CONTROLLER_VALID, *t))
1833                         return false;
1834
1835         if (t - p > FILENAME_MAX)
1836                 return false;
1837
1838         return true;
1839 }
1840
1841 #if 0 /// UNNEEDED by elogind
1842 int cg_slice_to_path(const char *unit, char **ret) {
1843         _cleanup_free_ char *p = NULL, *s = NULL, *e = NULL;
1844         const char *dash;
1845         int r;
1846
1847         assert(unit);
1848         assert(ret);
1849
1850         if (streq(unit, "-.slice")) {
1851                 char *x;
1852
1853                 x = strdup("");
1854                 if (!x)
1855                         return -ENOMEM;
1856                 *ret = x;
1857                 return 0;
1858         }
1859
1860         if (!unit_name_is_valid(unit, UNIT_NAME_PLAIN))
1861                 return -EINVAL;
1862
1863         if (!endswith(unit, ".slice"))
1864                 return -EINVAL;
1865
1866         r = unit_name_to_prefix(unit, &p);
1867         if (r < 0)
1868                 return r;
1869
1870         dash = strchr(p, '-');
1871
1872         /* Don't allow initial dashes */
1873         if (dash == p)
1874                 return -EINVAL;
1875
1876         while (dash) {
1877                 _cleanup_free_ char *escaped = NULL;
1878                 char n[dash - p + sizeof(".slice")];
1879
1880                 /* Don't allow trailing or double dashes */
1881                 if (dash[1] == 0 || dash[1] == '-')
1882                         return -EINVAL;
1883
1884                 strcpy(stpncpy(n, p, dash - p), ".slice");
1885                 if (!unit_name_is_valid(n, UNIT_NAME_PLAIN))
1886                         return -EINVAL;
1887
1888                 escaped = cg_escape(n);
1889                 if (!escaped)
1890                         return -ENOMEM;
1891
1892                 if (!strextend(&s, escaped, "/", NULL))
1893                         return -ENOMEM;
1894
1895                 dash = strchr(dash+1, '-');
1896         }
1897
1898         e = cg_escape(unit);
1899         if (!e)
1900                 return -ENOMEM;
1901
1902         if (!strextend(&s, e, NULL))
1903                 return -ENOMEM;
1904
1905         *ret = s;
1906         s = NULL;
1907
1908         return 0;
1909 }
1910 #endif // 0
1911
1912 int cg_set_attribute(const char *controller, const char *path, const char *attribute, const char *value) {
1913         _cleanup_free_ char *p = NULL;
1914         int r;
1915
1916         r = cg_get_path(controller, path, attribute, &p);
1917         if (r < 0)
1918                 return r;
1919
1920         return write_string_file(p, value, 0);
1921 }
1922
1923 #if 0 /// UNNEEDED by elogind
1924 int cg_get_attribute(const char *controller, const char *path, const char *attribute, char **ret) {
1925         _cleanup_free_ char *p = NULL;
1926         int r;
1927
1928         r = cg_get_path(controller, path, attribute, &p);
1929         if (r < 0)
1930                 return r;
1931
1932         return read_one_line_file(p, ret);
1933 }
1934
1935 int cg_create_everywhere(CGroupMask supported, CGroupMask mask, const char *path) {
1936         CGroupController c;
1937         int r, unified;
1938
1939         /* This one will create a cgroup in our private tree, but also
1940          * duplicate it in the trees specified in mask, and remove it
1941          * in all others */
1942
1943         /* First create the cgroup in our own hierarchy. */
1944         r = cg_create(SYSTEMD_CGROUP_CONTROLLER, path);
1945         if (r < 0)
1946                 return r;
1947
1948         /* If we are in the unified hierarchy, we are done now */
1949         unified = cg_unified();
1950         if (unified < 0)
1951                 return unified;
1952         if (unified > 0)
1953                 return 0;
1954
1955         /* Otherwise, do the same in the other hierarchies */
1956         for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1957                 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
1958                 const char *n;
1959
1960                 n = cgroup_controller_to_string(c);
1961
1962                 if (mask & bit)
1963                         (void) cg_create(n, path);
1964                 else if (supported & bit)
1965                         (void) cg_trim(n, path, true);
1966         }
1967
1968         return 0;
1969 }
1970
1971 int cg_attach_everywhere(CGroupMask supported, const char *path, pid_t pid, cg_migrate_callback_t path_callback, void *userdata) {
1972         CGroupController c;
1973         int r, unified;
1974
1975         r = cg_attach(SYSTEMD_CGROUP_CONTROLLER, path, pid);
1976         if (r < 0)
1977                 return r;
1978
1979         unified = cg_unified();
1980         if (unified < 0)
1981                 return unified;
1982         if (unified > 0)
1983                 return 0;
1984
1985         for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1986                 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
1987                 const char *p = NULL;
1988
1989                 if (!(supported & bit))
1990                         continue;
1991
1992                 if (path_callback)
1993                         p = path_callback(bit, userdata);
1994
1995                 if (!p)
1996                         p = path;
1997
1998                 (void) cg_attach_fallback(cgroup_controller_to_string(c), p, pid);
1999         }
2000
2001         return 0;
2002 }
2003
2004 int cg_attach_many_everywhere(CGroupMask supported, const char *path, Set* pids, cg_migrate_callback_t path_callback, void *userdata) {
2005         Iterator i;
2006         void *pidp;
2007         int r = 0;
2008
2009         SET_FOREACH(pidp, pids, i) {
2010                 pid_t pid = PTR_TO_PID(pidp);
2011                 int q;
2012
2013                 q = cg_attach_everywhere(supported, path, pid, path_callback, userdata);
2014                 if (q < 0 && r >= 0)
2015                         r = q;
2016         }
2017
2018         return r;
2019 }
2020
2021 int cg_migrate_everywhere(CGroupMask supported, const char *from, const char *to, cg_migrate_callback_t to_callback, void *userdata) {
2022         CGroupController c;
2023         int r = 0, unified;
2024
2025         if (!path_equal(from, to))  {
2026                 r = cg_migrate_recursive(SYSTEMD_CGROUP_CONTROLLER, from, SYSTEMD_CGROUP_CONTROLLER, to, CGROUP_REMOVE);
2027                 if (r < 0)
2028                         return r;
2029         }
2030
2031         unified = cg_unified();
2032         if (unified < 0)
2033                 return unified;
2034         if (unified > 0)
2035                 return r;
2036
2037         for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2038                 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2039                 const char *p = NULL;
2040
2041                 if (!(supported & bit))
2042                         continue;
2043
2044                 if (to_callback)
2045                         p = to_callback(bit, userdata);
2046
2047                 if (!p)
2048                         p = to;
2049
2050                 (void) cg_migrate_recursive_fallback(SYSTEMD_CGROUP_CONTROLLER, to, cgroup_controller_to_string(c), p, 0);
2051         }
2052
2053         return 0;
2054 }
2055
2056 int cg_trim_everywhere(CGroupMask supported, const char *path, bool delete_root) {
2057         CGroupController c;
2058         int r, unified;
2059
2060         r = cg_trim(SYSTEMD_CGROUP_CONTROLLER, path, delete_root);
2061         if (r < 0)
2062                 return r;
2063
2064         unified = cg_unified();
2065         if (unified < 0)
2066                 return unified;
2067         if (unified > 0)
2068                 return r;
2069
2070         for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2071                 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2072
2073                 if (!(supported & bit))
2074                         continue;
2075
2076                 (void) cg_trim(cgroup_controller_to_string(c), path, delete_root);
2077         }
2078
2079         return 0;
2080 }
2081 #endif // 0
2082
2083 int cg_mask_supported(CGroupMask *ret) {
2084         CGroupMask mask = 0;
2085         int r, unified;
2086
2087         /* Determines the mask of supported cgroup controllers. Only
2088          * includes controllers we can make sense of and that are
2089          * actually accessible. */
2090
2091         unified = cg_unified();
2092         if (unified < 0)
2093                 return unified;
2094         if (unified > 0) {
2095                 _cleanup_free_ char *root = NULL, *controllers = NULL, *path = NULL;
2096                 const char *c;
2097
2098                 /* In the unified hierarchy we can read the supported
2099                  * and accessible controllers from a the top-level
2100                  * cgroup attribute */
2101
2102                 r = cg_get_root_path(&root);
2103                 if (r < 0)
2104                         return r;
2105
2106                 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, root, "cgroup.controllers", &path);
2107                 if (r < 0)
2108                         return r;
2109
2110                 r = read_one_line_file(path, &controllers);
2111                 if (r < 0)
2112                         return r;
2113
2114                 c = controllers;
2115                 for (;;) {
2116                         _cleanup_free_ char *n = NULL;
2117                         CGroupController v;
2118
2119                         r = extract_first_word(&c, &n, NULL, 0);
2120                         if (r < 0)
2121                                 return r;
2122                         if (r == 0)
2123                                 break;
2124
2125                         v = cgroup_controller_from_string(n);
2126                         if (v < 0)
2127                                 continue;
2128
2129                         mask |= CGROUP_CONTROLLER_TO_MASK(v);
2130                 }
2131
2132                 /* Currently, we only support the memory, io and pids
2133                  * controller in the unified hierarchy, mask
2134                  * everything else off. */
2135                 mask &= CGROUP_MASK_MEMORY | CGROUP_MASK_IO | CGROUP_MASK_PIDS;
2136
2137         } else {
2138                 CGroupController c;
2139
2140                 /* In the legacy hierarchy, we check whether which
2141                  * hierarchies are mounted. */
2142
2143                 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2144                         const char *n;
2145
2146                         n = cgroup_controller_to_string(c);
2147                         if (controller_is_accessible(n) >= 0)
2148                                 mask |= CGROUP_CONTROLLER_TO_MASK(c);
2149                 }
2150         }
2151
2152         *ret = mask;
2153         return 0;
2154 }
2155
2156 #if 0 /// UNNEEDED by elogind
2157 int cg_kernel_controllers(Set *controllers) {
2158         _cleanup_fclose_ FILE *f = NULL;
2159         char buf[LINE_MAX];
2160         int r;
2161
2162         assert(controllers);
2163
2164         /* Determines the full list of kernel-known controllers. Might
2165          * include controllers we don't actually support, arbitrary
2166          * named hierarchies and controllers that aren't currently
2167          * accessible (because not mounted). */
2168
2169         f = fopen("/proc/cgroups", "re");
2170         if (!f) {
2171                 if (errno == ENOENT)
2172                         return 0;
2173                 return -errno;
2174         }
2175
2176         /* Ignore the header line */
2177         (void) fgets(buf, sizeof(buf), f);
2178
2179         for (;;) {
2180                 char *controller;
2181                 int enabled = 0;
2182
2183                 errno = 0;
2184                 if (fscanf(f, "%ms %*i %*i %i", &controller, &enabled) != 2) {
2185
2186                         if (feof(f))
2187                                 break;
2188
2189                         if (ferror(f) && errno > 0)
2190                                 return -errno;
2191
2192                         return -EBADMSG;
2193                 }
2194
2195                 if (!enabled) {
2196                         free(controller);
2197                         continue;
2198                 }
2199
2200                 if (!cg_controller_is_valid(controller)) {
2201                         free(controller);
2202                         return -EBADMSG;
2203                 }
2204
2205                 r = set_consume(controllers, controller);
2206                 if (r < 0)
2207                         return r;
2208         }
2209
2210         return 0;
2211 }
2212 #endif // 0
2213
2214 static thread_local int unified_cache = -1;
2215
2216 int cg_unified(void) {
2217         struct statfs fs;
2218
2219         /* Checks if we support the unified hierarchy. Returns an
2220          * error when the cgroup hierarchies aren't mounted yet or we
2221          * have any other trouble determining if the unified hierarchy
2222          * is supported. */
2223
2224         if (unified_cache >= 0)
2225                 return unified_cache;
2226
2227         if (statfs("/sys/fs/cgroup/", &fs) < 0)
2228                 return -errno;
2229
2230 #if 0 /// UNNEEDED by elogind
2231         if (F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC))
2232                 unified_cache = true;
2233         else if (F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC))
2234 #else
2235         /* elogind can not support the unified hierarchy as a controller,
2236          * so always assume a classical hierarchy.
2237          * If, ond only *if*, someone really wants to substitute systemd-login
2238          * in an environment managed by systemd with elogin, we might have to
2239          * add such a support. */
2240         if (F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC))
2241 #endif // 0
2242                 unified_cache = false;
2243         else
2244                 return -ENOMEDIUM;
2245
2246         return unified_cache;
2247 }
2248
2249 #if 0 /// UNNEEDED by elogind
2250 void cg_unified_flush(void) {
2251         unified_cache = -1;
2252 }
2253
2254 int cg_enable_everywhere(CGroupMask supported, CGroupMask mask, const char *p) {
2255         _cleanup_free_ char *fs = NULL;
2256         CGroupController c;
2257         int r, unified;
2258
2259         assert(p);
2260
2261         if (supported == 0)
2262                 return 0;
2263
2264         unified = cg_unified();
2265         if (unified < 0)
2266                 return unified;
2267         if (!unified) /* on the legacy hiearchy there's no joining of controllers defined */
2268                 return 0;
2269
2270         r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, p, "cgroup.subtree_control", &fs);
2271         if (r < 0)
2272                 return r;
2273
2274         for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2275                 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2276                 const char *n;
2277
2278                 if (!(supported & bit))
2279                         continue;
2280
2281                 n = cgroup_controller_to_string(c);
2282                 {
2283                         char s[1 + strlen(n) + 1];
2284
2285                         s[0] = mask & bit ? '+' : '-';
2286                         strcpy(s + 1, n);
2287
2288                         r = write_string_file(fs, s, 0);
2289                         if (r < 0)
2290                                 log_debug_errno(r, "Failed to enable controller %s for %s (%s): %m", n, p, fs);
2291                 }
2292         }
2293
2294         return 0;
2295 }
2296
2297 bool cg_is_unified_wanted(void) {
2298         static thread_local int wanted = -1;
2299         int r, unified;
2300
2301         /* If the hierarchy is already mounted, then follow whatever
2302          * was chosen for it. */
2303         unified = cg_unified();
2304         if (unified >= 0)
2305                 return unified;
2306
2307         /* Otherwise, let's see what the kernel command line has to
2308          * say. Since checking that is expensive, let's cache the
2309          * result. */
2310         if (wanted >= 0)
2311                 return wanted;
2312
2313         r = get_proc_cmdline_key("systemd.unified_cgroup_hierarchy", NULL);
2314         if (r > 0)
2315                 return (wanted = true);
2316         else {
2317                 _cleanup_free_ char *value = NULL;
2318
2319                 r = get_proc_cmdline_key("systemd.unified_cgroup_hierarchy=", &value);
2320                 if (r < 0)
2321                         return false;
2322                 if (r == 0)
2323                         return (wanted = false);
2324
2325                 return (wanted = parse_boolean(value) > 0);
2326         }
2327 }
2328
2329 bool cg_is_legacy_wanted(void) {
2330         return !cg_is_unified_wanted();
2331 }
2332 #else
2333 bool cg_is_legacy_wanted(void) {
2334         return true;
2335 }
2336 #endif // 0
2337
2338 #if 0 /// UNNEEDED by elogind
2339 int cg_weight_parse(const char *s, uint64_t *ret) {
2340         uint64_t u;
2341         int r;
2342
2343         if (isempty(s)) {
2344                 *ret = CGROUP_WEIGHT_INVALID;
2345                 return 0;
2346         }
2347
2348         r = safe_atou64(s, &u);
2349         if (r < 0)
2350                 return r;
2351
2352         if (u < CGROUP_WEIGHT_MIN || u > CGROUP_WEIGHT_MAX)
2353                 return -ERANGE;
2354
2355         *ret = u;
2356         return 0;
2357 }
2358
2359 const uint64_t cgroup_io_limit_defaults[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2360         [CGROUP_IO_RBPS_MAX]    = CGROUP_LIMIT_MAX,
2361         [CGROUP_IO_WBPS_MAX]    = CGROUP_LIMIT_MAX,
2362         [CGROUP_IO_RIOPS_MAX]   = CGROUP_LIMIT_MAX,
2363         [CGROUP_IO_WIOPS_MAX]   = CGROUP_LIMIT_MAX,
2364 };
2365
2366 static const char* const cgroup_io_limit_type_table[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2367         [CGROUP_IO_RBPS_MAX]    = "IOReadBandwidthMax",
2368         [CGROUP_IO_WBPS_MAX]    = "IOWriteBandwidthMax",
2369         [CGROUP_IO_RIOPS_MAX]   = "IOReadIOPSMax",
2370         [CGROUP_IO_WIOPS_MAX]   = "IOWriteIOPSMax",
2371 };
2372
2373 DEFINE_STRING_TABLE_LOOKUP(cgroup_io_limit_type, CGroupIOLimitType);
2374
2375 int cg_cpu_shares_parse(const char *s, uint64_t *ret) {
2376         uint64_t u;
2377         int r;
2378
2379         if (isempty(s)) {
2380                 *ret = CGROUP_CPU_SHARES_INVALID;
2381                 return 0;
2382         }
2383
2384         r = safe_atou64(s, &u);
2385         if (r < 0)
2386                 return r;
2387
2388         if (u < CGROUP_CPU_SHARES_MIN || u > CGROUP_CPU_SHARES_MAX)
2389                 return -ERANGE;
2390
2391         *ret = u;
2392         return 0;
2393 }
2394
2395 int cg_blkio_weight_parse(const char *s, uint64_t *ret) {
2396         uint64_t u;
2397         int r;
2398
2399         if (isempty(s)) {
2400                 *ret = CGROUP_BLKIO_WEIGHT_INVALID;
2401                 return 0;
2402         }
2403
2404         r = safe_atou64(s, &u);
2405         if (r < 0)
2406                 return r;
2407
2408         if (u < CGROUP_BLKIO_WEIGHT_MIN || u > CGROUP_BLKIO_WEIGHT_MAX)
2409                 return -ERANGE;
2410
2411         *ret = u;
2412         return 0;
2413 }
2414 #endif // 0
2415
2416 static const char *cgroup_controller_table[_CGROUP_CONTROLLER_MAX] = {
2417         [CGROUP_CONTROLLER_CPU] = "cpu",
2418         [CGROUP_CONTROLLER_CPUACCT] = "cpuacct",
2419         [CGROUP_CONTROLLER_IO] = "io",
2420         [CGROUP_CONTROLLER_BLKIO] = "blkio",
2421         [CGROUP_CONTROLLER_MEMORY] = "memory",
2422         [CGROUP_CONTROLLER_DEVICES] = "devices",
2423         [CGROUP_CONTROLLER_PIDS] = "pids",
2424 };
2425
2426 DEFINE_STRING_TABLE_LOOKUP(cgroup_controller, CGroupController);