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