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