chiark / gitweb /
Prep v228: Add remaining updates from upstream (3/3)
[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 /// UNNEEDED by elogind
751 #if 0
752 int cg_set_group_access(
753                 const char *controller,
754                 const char *path,
755                 mode_t mode,
756                 uid_t uid,
757                 gid_t gid) {
758
759         _cleanup_free_ char *fs = NULL;
760         int r;
761
762         if (mode == MODE_INVALID && uid == UID_INVALID && gid == GID_INVALID)
763                 return 0;
764
765         if (mode != MODE_INVALID)
766                 mode &= 0777;
767
768         r = cg_get_path(controller, path, NULL, &fs);
769         if (r < 0)
770                 return r;
771
772         return chmod_and_chown(fs, mode, uid, gid);
773 }
774
775 int cg_set_task_access(
776                 const char *controller,
777                 const char *path,
778                 mode_t mode,
779                 uid_t uid,
780                 gid_t gid) {
781
782         _cleanup_free_ char *fs = NULL, *procs = NULL;
783         int r, unified;
784
785         assert(path);
786
787         if (mode == MODE_INVALID && uid == UID_INVALID && gid == GID_INVALID)
788                 return 0;
789
790         if (mode != MODE_INVALID)
791                 mode &= 0666;
792
793         r = cg_get_path(controller, path, "cgroup.procs", &fs);
794         if (r < 0)
795                 return r;
796
797         r = chmod_and_chown(fs, mode, uid, gid);
798         if (r < 0)
799                 return r;
800
801         unified = cg_unified();
802         if (unified < 0)
803                 return unified;
804         if (unified)
805                 return 0;
806
807         /* Compatibility, Always keep values for "tasks" in sync with
808          * "cgroup.procs" */
809         if (cg_get_path(controller, path, "tasks", &procs) >= 0)
810                 (void) chmod_and_chown(procs, mode, uid, gid);
811
812         return 0;
813 }
814 #endif // 0
815
816 int cg_pid_get_path(const char *controller, pid_t pid, char **path) {
817         _cleanup_fclose_ FILE *f = NULL;
818         char line[LINE_MAX];
819         const char *fs;
820         size_t cs = 0;
821         int unified;
822
823         assert(path);
824         assert(pid >= 0);
825
826         unified = cg_unified();
827         if (unified < 0)
828                 return unified;
829         if (unified == 0) {
830                 if (controller) {
831                         if (!cg_controller_is_valid(controller))
832                                 return -EINVAL;
833                 } else
834                         controller = SYSTEMD_CGROUP_CONTROLLER;
835
836                 cs = strlen(controller);
837         }
838
839         fs = procfs_file_alloca(pid, "cgroup");
840         log_debug_elogind("Searching for PID %u in \"%s\" (controller \"%s\")",
841                           pid, fs, controller);
842         f = fopen(fs, "re");
843         if (!f)
844                 return errno == ENOENT ? -ESRCH : -errno;
845
846         FOREACH_LINE(line, f, return -errno) {
847                 char *e, *p;
848
849                 truncate_nl(line);
850
851                 if (unified) {
852                         e = startswith(line, "0:");
853                         if (!e)
854                                 continue;
855
856                         e = strchr(e, ':');
857                         if (!e)
858                                 continue;
859                 } else {
860                         char *l;
861                         size_t k;
862                         const char *word, *state;
863                         bool found = false;
864
865                         l = strchr(line, ':');
866                         if (!l)
867                                 continue;
868
869                         l++;
870                         e = strchr(l, ':');
871                         if (!e)
872                                 continue;
873
874                         *e = 0;
875                         FOREACH_WORD_SEPARATOR(word, k, l, ",", state) {
876                                 if (k == cs && memcmp(word, controller, cs) == 0) {
877                                         found = true;
878                                         break;
879                                 }
880                         }
881
882                         if (!found)
883                                 continue;
884                 }
885
886                 log_debug_elogind("Found %s:%s", line, e+1);
887                 p = strdup(e + 1);
888                 if (!p)
889                         return -ENOMEM;
890
891                 *path = p;
892                 return 0;
893         }
894
895         return -ENODATA;
896 }
897
898 int cg_install_release_agent(const char *controller, const char *agent) {
899         _cleanup_free_ char *fs = NULL, *contents = NULL;
900         const char *sc;
901         int r, unified;
902
903         assert(agent);
904
905         unified = cg_unified();
906         if (unified < 0)
907                 return unified;
908         if (unified) /* doesn't apply to unified hierarchy */
909                 return -EOPNOTSUPP;
910
911         r = cg_get_path(controller, NULL, "release_agent", &fs);
912         if (r < 0)
913                 return r;
914
915         r = read_one_line_file(fs, &contents);
916         if (r < 0)
917                 return r;
918
919         sc = strstrip(contents);
920         if (isempty(sc)) {
921                 r = write_string_file(fs, agent, 0);
922                 if (r < 0)
923                         return r;
924         } else if (!path_equal(sc, agent))
925                 return -EEXIST;
926
927         fs = mfree(fs);
928         r = cg_get_path(controller, NULL, "notify_on_release", &fs);
929         if (r < 0)
930                 return r;
931
932         contents = mfree(contents);
933         r = read_one_line_file(fs, &contents);
934         if (r < 0)
935                 return r;
936
937         sc = strstrip(contents);
938         if (streq(sc, "0")) {
939                 r = write_string_file(fs, "1", 0);
940                 if (r < 0)
941                         return r;
942
943                 return 1;
944         }
945
946         if (!streq(sc, "1"))
947                 return -EIO;
948
949         return 0;
950 }
951
952 int cg_uninstall_release_agent(const char *controller) {
953         _cleanup_free_ char *fs = NULL;
954         int r, unified;
955
956         unified = cg_unified();
957         if (unified < 0)
958                 return unified;
959         if (unified) /* Doesn't apply to unified hierarchy */
960                 return -EOPNOTSUPP;
961
962         r = cg_get_path(controller, NULL, "notify_on_release", &fs);
963         if (r < 0)
964                 return r;
965
966         r = write_string_file(fs, "0", 0);
967         if (r < 0)
968                 return r;
969
970         fs = mfree(fs);
971
972         r = cg_get_path(controller, NULL, "release_agent", &fs);
973         if (r < 0)
974                 return r;
975
976         r = write_string_file(fs, "", 0);
977         if (r < 0)
978                 return r;
979
980         return 0;
981 }
982
983 int cg_is_empty(const char *controller, const char *path) {
984         _cleanup_fclose_ FILE *f = NULL;
985         pid_t pid;
986         int r;
987
988         assert(path);
989
990         r = cg_enumerate_processes(controller, path, &f);
991         if (r == -ENOENT)
992                 return 1;
993         if (r < 0)
994                 return r;
995
996         r = cg_read_pid(f, &pid);
997         if (r < 0)
998                 return r;
999
1000         return r == 0;
1001 }
1002
1003 int cg_is_empty_recursive(const char *controller, const char *path) {
1004         int unified, r;
1005
1006         assert(path);
1007
1008         /* The root cgroup is always populated */
1009         if (controller && (isempty(path) || path_equal(path, "/")))
1010                 return false;
1011
1012         unified = cg_unified();
1013         if (unified < 0)
1014                 return unified;
1015
1016         if (unified > 0) {
1017                 _cleanup_free_ char *populated = NULL, *t = NULL;
1018
1019                 /* On the unified hierarchy we can check empty state
1020                  * via the "cgroup.populated" attribute. */
1021
1022                 r = cg_get_path(controller, path, "cgroup.populated", &populated);
1023                 if (r < 0)
1024                         return r;
1025
1026                 r = read_one_line_file(populated, &t);
1027                 if (r == -ENOENT)
1028                         return 1;
1029                 if (r < 0)
1030                         return r;
1031
1032                 return streq(t, "0");
1033         } else {
1034                 _cleanup_closedir_ DIR *d = NULL;
1035                 char *fn;
1036
1037                 r = cg_is_empty(controller, path);
1038                 if (r <= 0)
1039                         return r;
1040
1041                 r = cg_enumerate_subgroups(controller, path, &d);
1042                         if (r == -ENOENT)
1043                                 return 1;
1044                 if (r < 0)
1045                         return r;
1046
1047                 while ((r = cg_read_subgroup(d, &fn)) > 0) {
1048                         _cleanup_free_ char *p = NULL;
1049
1050                         p = strjoin(path, "/", fn, NULL);
1051                         free(fn);
1052                         if (!p)
1053                                 return -ENOMEM;
1054
1055                         r = cg_is_empty_recursive(controller, p);
1056                         if (r <= 0)
1057                                 return r;
1058                 }
1059                 if (r < 0)
1060                         return r;
1061
1062                 return true;
1063         }
1064 }
1065
1066 int cg_split_spec(const char *spec, char **controller, char **path) {
1067         char *t = NULL, *u = NULL;
1068         const char *e;
1069
1070         assert(spec);
1071
1072         if (*spec == '/') {
1073                 if (!path_is_safe(spec))
1074                         return -EINVAL;
1075
1076                 if (path) {
1077                         t = strdup(spec);
1078                         if (!t)
1079                                 return -ENOMEM;
1080
1081                         *path = path_kill_slashes(t);
1082                 }
1083
1084                 if (controller)
1085                         *controller = NULL;
1086
1087                 return 0;
1088         }
1089
1090         e = strchr(spec, ':');
1091         if (!e) {
1092                 if (!cg_controller_is_valid(spec))
1093                         return -EINVAL;
1094
1095                 if (controller) {
1096                         t = strdup(spec);
1097                         if (!t)
1098                                 return -ENOMEM;
1099
1100                         *controller = t;
1101                 }
1102
1103                 if (path)
1104                         *path = NULL;
1105
1106                 return 0;
1107         }
1108
1109         t = strndup(spec, e-spec);
1110         if (!t)
1111                 return -ENOMEM;
1112         if (!cg_controller_is_valid(t)) {
1113                 free(t);
1114                 return -EINVAL;
1115         }
1116
1117         if (isempty(e+1))
1118                 u = NULL;
1119         else {
1120                 u = strdup(e+1);
1121                 if (!u) {
1122                         free(t);
1123                         return -ENOMEM;
1124                 }
1125
1126                 if (!path_is_safe(u) ||
1127                     !path_is_absolute(u)) {
1128                         free(t);
1129                         free(u);
1130                         return -EINVAL;
1131                 }
1132
1133                 path_kill_slashes(u);
1134         }
1135
1136         if (controller)
1137                 *controller = t;
1138         else
1139                 free(t);
1140
1141         if (path)
1142                 *path = u;
1143         else
1144                 free(u);
1145
1146         return 0;
1147 }
1148
1149 int cg_mangle_path(const char *path, char **result) {
1150         _cleanup_free_ char *c = NULL, *p = NULL;
1151         char *t;
1152         int r;
1153
1154         assert(path);
1155         assert(result);
1156
1157         /* First, check if it already is a filesystem path */
1158         if (path_startswith(path, "/sys/fs/cgroup")) {
1159
1160                 t = strdup(path);
1161                 if (!t)
1162                         return -ENOMEM;
1163
1164                 *result = path_kill_slashes(t);
1165                 return 0;
1166         }
1167
1168         /* Otherwise, treat it as cg spec */
1169         r = cg_split_spec(path, &c, &p);
1170         if (r < 0)
1171                 return r;
1172
1173         return cg_get_path(c ?: SYSTEMD_CGROUP_CONTROLLER, p ?: "/", NULL, result);
1174 }
1175
1176 int cg_get_root_path(char **path) {
1177 /// elogind does not support systemd scopes and slices
1178 #if 0
1179         char *p, *e;
1180         int r;
1181
1182         assert(path);
1183
1184         r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, &p);
1185         if (r < 0)
1186                 return r;
1187
1188         e = endswith(p, "/" SPECIAL_INIT_SCOPE);
1189         if (!e)
1190                 e = endswith(p, "/" SPECIAL_SYSTEM_SLICE); /* legacy */
1191         if (!e)
1192                 e = endswith(p, "/system"); /* even more legacy */
1193         if (e)
1194                 *e = 0;
1195
1196         *path = p;
1197         return 0;
1198 #else
1199         assert(path);
1200         return cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, path);
1201 #endif // 0
1202 }
1203
1204 int cg_shift_path(const char *cgroup, const char *root, const char **shifted) {
1205         _cleanup_free_ char *rt = NULL;
1206         char *p;
1207         int r;
1208
1209         assert(cgroup);
1210         assert(shifted);
1211
1212         if (!root) {
1213                 /* If the root was specified let's use that, otherwise
1214                  * let's determine it from PID 1 */
1215
1216                 r = cg_get_root_path(&rt);
1217                 if (r < 0)
1218                         return r;
1219
1220                 root = rt;
1221                 log_debug_elogind("Determined root path: \"%s\"", root);
1222         }
1223
1224         p = path_startswith(cgroup, root);
1225         if (p && p[0] && (p > cgroup))
1226                 *shifted = p - 1;
1227         else
1228                 *shifted = cgroup;
1229
1230         return 0;
1231 }
1232
1233 int cg_pid_get_path_shifted(pid_t pid, const char *root, char **cgroup) {
1234         _cleanup_free_ char *raw = NULL;
1235         const char *c;
1236         int r;
1237
1238         assert(pid >= 0);
1239         assert(cgroup);
1240
1241         r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &raw);
1242         if (r < 0)
1243                 return r;
1244
1245         log_debug_elogind("Shifting path: \"%s\" (PID %u, root: \"%s\")",
1246                           raw, pid, root ? root : "NULL");
1247         r = cg_shift_path(raw, root, &c);
1248         if (r < 0)
1249                 return r;
1250
1251         if (c == raw) {
1252                 *cgroup = raw;
1253                 raw = NULL;
1254         } else {
1255                 char *n;
1256
1257                 n = strdup(c);
1258                 if (!n)
1259                         return -ENOMEM;
1260
1261                 *cgroup = n;
1262         }
1263         log_debug_elogind("Resulting cgroup:\"%s\"", *cgroup);
1264
1265         return 0;
1266 }
1267
1268 /// UNNEEDED by elogind
1269 #if 0
1270 int cg_path_decode_unit(const char *cgroup, char **unit){
1271         char *c, *s;
1272         size_t n;
1273
1274         assert(cgroup);
1275         assert(unit);
1276
1277         n = strcspn(cgroup, "/");
1278         if (n < 3)
1279                 return -ENXIO;
1280
1281         c = strndupa(cgroup, n);
1282         c = cg_unescape(c);
1283
1284         if (!unit_name_is_valid(c, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
1285                 return -ENXIO;
1286
1287         s = strdup(c);
1288         if (!s)
1289                 return -ENOMEM;
1290
1291         *unit = s;
1292         return 0;
1293 }
1294
1295 static bool valid_slice_name(const char *p, size_t n) {
1296
1297         if (!p)
1298                 return false;
1299
1300         if (n < strlen("x.slice"))
1301                 return false;
1302
1303         if (memcmp(p + n - 6, ".slice", 6) == 0) {
1304                 char buf[n+1], *c;
1305
1306                 memcpy(buf, p, n);
1307                 buf[n] = 0;
1308
1309                 c = cg_unescape(buf);
1310
1311                 return unit_name_is_valid(c, UNIT_NAME_PLAIN);
1312         }
1313
1314         return false;
1315 }
1316
1317 static const char *skip_slices(const char *p) {
1318         assert(p);
1319
1320         /* Skips over all slice assignments */
1321
1322         for (;;) {
1323                 size_t n;
1324
1325                 p += strspn(p, "/");
1326
1327                 n = strcspn(p, "/");
1328                 if (!valid_slice_name(p, n))
1329                         return p;
1330
1331                 p += n;
1332         }
1333 }
1334
1335 int cg_path_get_unit(const char *path, char **ret) {
1336         const char *e;
1337         char *unit;
1338         int r;
1339
1340         assert(path);
1341         assert(ret);
1342
1343         e = skip_slices(path);
1344
1345         r = cg_path_decode_unit(e, &unit);
1346         if (r < 0)
1347                 return r;
1348
1349         /* We skipped over the slices, don't accept any now */
1350         if (endswith(unit, ".slice")) {
1351                 free(unit);
1352                 return -ENXIO;
1353         }
1354
1355         *ret = unit;
1356         return 0;
1357 }
1358
1359 int cg_pid_get_unit(pid_t pid, char **unit) {
1360         _cleanup_free_ char *cgroup = NULL;
1361         int r;
1362
1363         assert(unit);
1364
1365         r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1366         if (r < 0)
1367                 return r;
1368
1369         return cg_path_get_unit(cgroup, unit);
1370 }
1371
1372 /**
1373  * Skip session-*.scope, but require it to be there.
1374  */
1375 static const char *skip_session(const char *p) {
1376         size_t n;
1377
1378         if (isempty(p))
1379                 return NULL;
1380
1381         p += strspn(p, "/");
1382
1383         n = strcspn(p, "/");
1384         if (n < strlen("session-x.scope"))
1385                 return NULL;
1386
1387         if (memcmp(p, "session-", 8) == 0 && memcmp(p + n - 6, ".scope", 6) == 0) {
1388                 char buf[n - 8 - 6 + 1];
1389
1390                 memcpy(buf, p + 8, n - 8 - 6);
1391                 buf[n - 8 - 6] = 0;
1392
1393                 /* Note that session scopes never need unescaping,
1394                  * since they cannot conflict with the kernel's own
1395                  * names, hence we don't need to call cg_unescape()
1396                  * here. */
1397
1398                 if (!session_id_valid(buf))
1399                         return false;
1400
1401                 p += n;
1402                 p += strspn(p, "/");
1403                 return p;
1404         }
1405
1406         return NULL;
1407 }
1408
1409 /**
1410  * Skip user@*.service, but require it to be there.
1411  */
1412 static const char *skip_user_manager(const char *p) {
1413         size_t n;
1414
1415         if (isempty(p))
1416                 return NULL;
1417
1418         p += strspn(p, "/");
1419
1420         n = strcspn(p, "/");
1421         if (n < strlen("user@x.service"))
1422                 return NULL;
1423
1424         if (memcmp(p, "user@", 5) == 0 && memcmp(p + n - 8, ".service", 8) == 0) {
1425                 char buf[n - 5 - 8 + 1];
1426
1427                 memcpy(buf, p + 5, n - 5 - 8);
1428                 buf[n - 5 - 8] = 0;
1429
1430                 /* Note that user manager services never need unescaping,
1431                  * since they cannot conflict with the kernel's own
1432                  * names, hence we don't need to call cg_unescape()
1433                  * here. */
1434
1435                 if (parse_uid(buf, NULL) < 0)
1436                         return NULL;
1437
1438                 p += n;
1439                 p += strspn(p, "/");
1440
1441                 return p;
1442         }
1443
1444         return NULL;
1445 }
1446
1447 static const char *skip_user_prefix(const char *path) {
1448         const char *e, *t;
1449
1450         assert(path);
1451
1452         /* Skip slices, if there are any */
1453         e = skip_slices(path);
1454
1455         /* Skip the user manager, if it's in the path now... */
1456         t = skip_user_manager(e);
1457         if (t)
1458                 return t;
1459
1460         /* Alternatively skip the user session if it is in the path... */
1461         return skip_session(e);
1462 }
1463
1464 int cg_path_get_user_unit(const char *path, char **ret) {
1465         const char *t;
1466
1467         assert(path);
1468         assert(ret);
1469
1470         t = skip_user_prefix(path);
1471         if (!t)
1472                 return -ENXIO;
1473
1474         /* And from here on it looks pretty much the same as for a
1475          * system unit, hence let's use the same parser from here
1476          * on. */
1477         return cg_path_get_unit(t, ret);
1478 }
1479
1480 int cg_pid_get_user_unit(pid_t pid, char **unit) {
1481         _cleanup_free_ char *cgroup = NULL;
1482         int r;
1483
1484         assert(unit);
1485
1486         r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1487         if (r < 0)
1488                 return r;
1489
1490         return cg_path_get_user_unit(cgroup, unit);
1491 }
1492
1493 int cg_path_get_machine_name(const char *path, char **machine) {
1494         _cleanup_free_ char *u = NULL;
1495         const char *sl;
1496         int r;
1497
1498         r = cg_path_get_unit(path, &u);
1499         if (r < 0)
1500                 return r;
1501
1502         sl = strjoina("/run/systemd/machines/unit:", u);
1503         return readlink_malloc(sl, machine);
1504 }
1505
1506 int cg_pid_get_machine_name(pid_t pid, char **machine) {
1507         _cleanup_free_ char *cgroup = NULL;
1508         int r;
1509
1510         assert(machine);
1511
1512         r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1513         if (r < 0)
1514                 return r;
1515
1516         return cg_path_get_machine_name(cgroup, machine);
1517 }
1518 #endif // 0
1519
1520 int cg_path_get_session(const char *path, char **session) {
1521         /* Elogind uses a flat hierarchy, just "/SESSION".  The only
1522            wrinkle is that SESSION might be escaped.  */
1523 #if 0
1524         _cleanup_free_ char *unit = NULL;
1525         char *start, *end;
1526         int r;
1527
1528         assert(path);
1529
1530         r = cg_path_get_unit(path, &unit);
1531         if (r < 0)
1532                 return r;
1533
1534         start = startswith(unit, "session-");
1535         if (!start)
1536                 return -ENXIO;
1537         end = endswith(start, ".scope");
1538         if (!end)
1539                 return -ENXIO;
1540
1541         *end = 0;
1542         if (!session_id_valid(start))
1543                 return -ENXIO;
1544 #else
1545         const char *e, *n, *start;
1546
1547         assert(path);
1548         log_debug_elogind("path is \"%s\"", path);
1549         assert(path[0] == '/');
1550
1551         e = path + 1;
1552         n = strchrnul(e, '/');
1553         if (e == n)
1554                 return -ENOENT;
1555
1556         start = strndupa(e, n - e);
1557         start = cg_unescape(start);
1558
1559         if (!start[0])
1560                 return -ENOENT;
1561 #endif // 0
1562
1563         if (session) {
1564                 char *rr;
1565
1566                 log_debug_elogind("found session: \"%s\"", start);
1567                 rr = strdup(start);
1568                 if (!rr)
1569                         return -ENOMEM;
1570
1571                 *session = rr;
1572         }
1573
1574         return 0;
1575 }
1576
1577 int cg_pid_get_session(pid_t pid, char **session) {
1578         _cleanup_free_ char *cgroup = NULL;
1579         int r;
1580
1581         r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1582         if (r < 0)
1583                 return r;
1584
1585         return cg_path_get_session(cgroup, session);
1586 }
1587
1588 /// UNNEEDED by elogind
1589 #if 0
1590 int cg_path_get_owner_uid(const char *path, uid_t *uid) {
1591         _cleanup_free_ char *slice = NULL;
1592         char *start, *end;
1593         int r;
1594
1595         assert(path);
1596
1597         r = cg_path_get_slice(path, &slice);
1598         if (r < 0)
1599                 return r;
1600
1601         start = startswith(slice, "user-");
1602         if (!start)
1603                 return -ENXIO;
1604         end = endswith(start, ".slice");
1605         if (!end)
1606                 return -ENXIO;
1607
1608         *end = 0;
1609         if (parse_uid(start, uid) < 0)
1610                 return -ENXIO;
1611
1612         return 0;
1613 }
1614
1615 int cg_pid_get_owner_uid(pid_t pid, uid_t *uid) {
1616         _cleanup_free_ char *cgroup = NULL;
1617         int r;
1618
1619         r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1620         if (r < 0)
1621                 return r;
1622
1623         return cg_path_get_owner_uid(cgroup, uid);
1624 }
1625
1626 int cg_path_get_slice(const char *p, char **slice) {
1627         const char *e = NULL;
1628
1629         assert(p);
1630         assert(slice);
1631
1632         /* Finds the right-most slice unit from the beginning, but
1633          * stops before we come to the first non-slice unit. */
1634
1635         for (;;) {
1636                 size_t n;
1637
1638                 p += strspn(p, "/");
1639
1640                 n = strcspn(p, "/");
1641                 if (!valid_slice_name(p, n)) {
1642
1643                         if (!e) {
1644                                 char *s;
1645
1646                                 s = strdup("-.slice");
1647                                 if (!s)
1648                                         return -ENOMEM;
1649
1650                                 *slice = s;
1651                                 return 0;
1652                         }
1653
1654                         return cg_path_decode_unit(e, slice);
1655                 }
1656
1657                 e = p;
1658                 p += n;
1659         }
1660 }
1661
1662 int cg_pid_get_slice(pid_t pid, char **slice) {
1663         _cleanup_free_ char *cgroup = NULL;
1664         int r;
1665
1666         assert(slice);
1667
1668         r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1669         if (r < 0)
1670                 return r;
1671
1672         return cg_path_get_slice(cgroup, slice);
1673 }
1674
1675 int cg_path_get_user_slice(const char *p, char **slice) {
1676         const char *t;
1677         assert(p);
1678         assert(slice);
1679
1680         t = skip_user_prefix(p);
1681         if (!t)
1682                 return -ENXIO;
1683
1684         /* And now it looks pretty much the same as for a system
1685          * slice, so let's just use the same parser from here on. */
1686         return cg_path_get_slice(t, slice);
1687 }
1688
1689 int cg_pid_get_user_slice(pid_t pid, char **slice) {
1690         _cleanup_free_ char *cgroup = NULL;
1691         int r;
1692
1693         assert(slice);
1694
1695         r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1696         if (r < 0)
1697                 return r;
1698
1699         return cg_path_get_user_slice(cgroup, slice);
1700 }
1701 #endif // 0
1702
1703 char *cg_escape(const char *p) {
1704         bool need_prefix = false;
1705
1706         /* This implements very minimal escaping for names to be used
1707          * as file names in the cgroup tree: any name which might
1708          * conflict with a kernel name or is prefixed with '_' is
1709          * prefixed with a '_'. That way, when reading cgroup names it
1710          * is sufficient to remove a single prefixing underscore if
1711          * there is one. */
1712
1713         /* The return value of this function (unlike cg_unescape())
1714          * needs free()! */
1715
1716         if (p[0] == 0 ||
1717             p[0] == '_' ||
1718             p[0] == '.' ||
1719             streq(p, "notify_on_release") ||
1720             streq(p, "release_agent") ||
1721             streq(p, "tasks") ||
1722             startswith(p, "cgroup."))
1723                 need_prefix = true;
1724         else {
1725                 const char *dot;
1726
1727                 dot = strrchr(p, '.');
1728                 if (dot) {
1729                         CGroupController c;
1730                         size_t l = dot - p;
1731
1732                         for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1733                                 const char *n;
1734
1735                                 n = cgroup_controller_to_string(c);
1736
1737                                 if (l != strlen(n))
1738                                         continue;
1739
1740                                 if (memcmp(p, n, l) != 0)
1741                                         continue;
1742
1743                                 need_prefix = true;
1744                                 break;
1745                         }
1746                 }
1747         }
1748
1749         if (need_prefix)
1750                 return strappend("_", p);
1751
1752         return strdup(p);
1753 }
1754
1755 char *cg_unescape(const char *p) {
1756         assert(p);
1757
1758         /* The return value of this function (unlike cg_escape())
1759          * doesn't need free()! */
1760
1761         if (p[0] == '_')
1762                 return (char*) p+1;
1763
1764         return (char*) p;
1765 }
1766
1767 #define CONTROLLER_VALID                        \
1768         DIGITS LETTERS                          \
1769         "_"
1770
1771 bool cg_controller_is_valid(const char *p) {
1772         const char *t, *s;
1773
1774         if (!p)
1775                 return false;
1776
1777         s = startswith(p, "name=");
1778         if (s)
1779                 p = s;
1780
1781         if (*p == 0 || *p == '_')
1782                 return false;
1783
1784         for (t = p; *t; t++)
1785                 if (!strchr(CONTROLLER_VALID, *t))
1786                         return false;
1787
1788         if (t - p > FILENAME_MAX)
1789                 return false;
1790
1791         return true;
1792 }
1793
1794 /// UNNEEDED by elogind
1795 #if 0
1796 int cg_slice_to_path(const char *unit, char **ret) {
1797         _cleanup_free_ char *p = NULL, *s = NULL, *e = NULL;
1798         const char *dash;
1799         int r;
1800
1801         assert(unit);
1802         assert(ret);
1803
1804         if (streq(unit, "-.slice")) {
1805                 char *x;
1806
1807                 x = strdup("");
1808                 if (!x)
1809                         return -ENOMEM;
1810                 *ret = x;
1811                 return 0;
1812         }
1813
1814         if (!unit_name_is_valid(unit, UNIT_NAME_PLAIN))
1815                 return -EINVAL;
1816
1817         if (!endswith(unit, ".slice"))
1818                 return -EINVAL;
1819
1820         r = unit_name_to_prefix(unit, &p);
1821         if (r < 0)
1822                 return r;
1823
1824         dash = strchr(p, '-');
1825
1826         /* Don't allow initial dashes */
1827         if (dash == p)
1828                 return -EINVAL;
1829
1830         while (dash) {
1831                 _cleanup_free_ char *escaped = NULL;
1832                 char n[dash - p + sizeof(".slice")];
1833
1834                 /* Don't allow trailing or double dashes */
1835                 if (dash[1] == 0 || dash[1] == '-')
1836                         return -EINVAL;
1837
1838                 strcpy(stpncpy(n, p, dash - p), ".slice");
1839                 if (!unit_name_is_valid(n, UNIT_NAME_PLAIN))
1840                         return -EINVAL;
1841
1842                 escaped = cg_escape(n);
1843                 if (!escaped)
1844                         return -ENOMEM;
1845
1846                 if (!strextend(&s, escaped, "/", NULL))
1847                         return -ENOMEM;
1848
1849                 dash = strchr(dash+1, '-');
1850         }
1851
1852         e = cg_escape(unit);
1853         if (!e)
1854                 return -ENOMEM;
1855
1856         if (!strextend(&s, e, NULL))
1857                 return -ENOMEM;
1858
1859         *ret = s;
1860         s = NULL;
1861
1862         return 0;
1863 }
1864 #endif // 0
1865
1866 int cg_set_attribute(const char *controller, const char *path, const char *attribute, const char *value) {
1867         _cleanup_free_ char *p = NULL;
1868         int r;
1869
1870         r = cg_get_path(controller, path, attribute, &p);
1871         if (r < 0)
1872                 return r;
1873
1874         return write_string_file(p, value, 0);
1875 }
1876
1877 /// UNNEEDED by elogind
1878 #if 0
1879 int cg_get_attribute(const char *controller, const char *path, const char *attribute, char **ret) {
1880         _cleanup_free_ char *p = NULL;
1881         int r;
1882
1883         r = cg_get_path(controller, path, attribute, &p);
1884         if (r < 0)
1885                 return r;
1886
1887         return read_one_line_file(p, ret);
1888 }
1889
1890 int cg_create_everywhere(CGroupMask supported, CGroupMask mask, const char *path) {
1891         CGroupController c;
1892         int r, unified;
1893
1894         /* This one will create a cgroup in our private tree, but also
1895          * duplicate it in the trees specified in mask, and remove it
1896          * in all others */
1897
1898         /* First create the cgroup in our own hierarchy. */
1899         r = cg_create(SYSTEMD_CGROUP_CONTROLLER, path);
1900         if (r < 0)
1901                 return r;
1902
1903         /* If we are in the unified hierarchy, we are done now */
1904         unified = cg_unified();
1905         if (unified < 0)
1906                 return unified;
1907         if (unified > 0)
1908                 return 0;
1909
1910         /* Otherwise, do the same in the other hierarchies */
1911         for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1912                 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
1913                 const char *n;
1914
1915                 n = cgroup_controller_to_string(c);
1916
1917                 if (mask & bit)
1918                         (void) cg_create(n, path);
1919                 else if (supported & bit)
1920                         (void) cg_trim(n, path, true);
1921         }
1922
1923         return 0;
1924 }
1925
1926 int cg_attach_everywhere(CGroupMask supported, const char *path, pid_t pid, cg_migrate_callback_t path_callback, void *userdata) {
1927         CGroupController c;
1928         int r, unified;
1929
1930         r = cg_attach(SYSTEMD_CGROUP_CONTROLLER, path, pid);
1931         if (r < 0)
1932                 return r;
1933
1934         unified = cg_unified();
1935         if (unified < 0)
1936                 return unified;
1937         if (unified > 0)
1938                 return 0;
1939
1940         for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1941                 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
1942                         const char *p = NULL;
1943
1944                 if (!(supported & bit))
1945                         continue;
1946
1947                         if (path_callback)
1948                                 p = path_callback(bit, userdata);
1949
1950                         if (!p)
1951                                 p = path;
1952
1953                 (void) cg_attach_fallback(cgroup_controller_to_string(c), p, pid);
1954         }
1955
1956         return 0;
1957 }
1958
1959 int cg_attach_many_everywhere(CGroupMask supported, const char *path, Set* pids, cg_migrate_callback_t path_callback, void *userdata) {
1960         Iterator i;
1961         void *pidp;
1962         int r = 0;
1963
1964         SET_FOREACH(pidp, pids, i) {
1965                 pid_t pid = PTR_TO_PID(pidp);
1966                 int q;
1967
1968                 q = cg_attach_everywhere(supported, path, pid, path_callback, userdata);
1969                 if (q < 0 && r >= 0)
1970                         r = q;
1971         }
1972
1973         return r;
1974 }
1975
1976 int cg_migrate_everywhere(CGroupMask supported, const char *from, const char *to, cg_migrate_callback_t to_callback, void *userdata) {
1977         CGroupController c;
1978         int r = 0, unified;
1979
1980         if (!path_equal(from, to))  {
1981                 r = cg_migrate_recursive(SYSTEMD_CGROUP_CONTROLLER, from, SYSTEMD_CGROUP_CONTROLLER, to, false, true);
1982                 if (r < 0)
1983                         return r;
1984         }
1985
1986         unified = cg_unified();
1987         if (unified < 0)
1988                 return unified;
1989         if (unified > 0)
1990                 return r;
1991
1992         for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1993                 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
1994                         const char *p = NULL;
1995
1996                 if (!(supported & bit))
1997                         continue;
1998
1999                         if (to_callback)
2000                                 p = to_callback(bit, userdata);
2001
2002                         if (!p)
2003                                 p = to;
2004
2005                 (void) cg_migrate_recursive_fallback(SYSTEMD_CGROUP_CONTROLLER, to, cgroup_controller_to_string(c), p, false, false);
2006         }
2007
2008         return 0;
2009 }
2010
2011 int cg_trim_everywhere(CGroupMask supported, const char *path, bool delete_root) {
2012         CGroupController c;
2013         int r, unified;
2014
2015         r = cg_trim(SYSTEMD_CGROUP_CONTROLLER, path, delete_root);
2016         if (r < 0)
2017                 return r;
2018
2019         unified = cg_unified();
2020         if (unified < 0)
2021                 return unified;
2022         if (unified > 0)
2023                 return r;
2024
2025         for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2026                 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2027
2028                 if (!(supported & bit))
2029                         continue;
2030
2031                 (void) cg_trim(cgroup_controller_to_string(c), path, delete_root);
2032         }
2033
2034         return 0;
2035 }
2036 #endif // 0
2037
2038 int cg_mask_supported(CGroupMask *ret) {
2039         CGroupMask mask = 0;
2040         int r, unified;
2041
2042         /* Determines the mask of supported cgroup controllers. Only
2043          * includes controllers we can make sense of and that are
2044          * actually accessible. */
2045
2046         unified = cg_unified();
2047         if (unified < 0)
2048                 return unified;
2049         if (unified > 0) {
2050                 _cleanup_free_ char *root = NULL, *controllers = NULL, *path = NULL;
2051                 const char *c;
2052
2053                 /* In the unified hierarchy we can read the supported
2054                  * and accessible controllers from a the top-level
2055                  * cgroup attribute */
2056
2057                 r = cg_get_root_path(&root);
2058                 if (r < 0)
2059                         return r;
2060
2061                 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, root, "cgroup.controllers", &path);
2062                 if (r < 0)
2063                         return r;
2064
2065                 r = read_one_line_file(path, &controllers);
2066                 if (r < 0)
2067                         return r;
2068
2069                 c = controllers;
2070                 for (;;) {
2071                         _cleanup_free_ char *n = NULL;
2072                         CGroupController v;
2073
2074                         r = extract_first_word(&c, &n, NULL, 0);
2075                         if (r < 0)
2076                                 return r;
2077                         if (r == 0)
2078                                 break;
2079
2080                         v = cgroup_controller_from_string(n);
2081                         if (v < 0)
2082                                 continue;
2083
2084                         mask |= CGROUP_CONTROLLER_TO_MASK(v);
2085         }
2086
2087                 /* Currently, we only support the memory and pids
2088                  * controller in the unified hierarchy, mask
2089                  * everything else off. */
2090                 mask &= CGROUP_MASK_MEMORY | CGROUP_MASK_PIDS;
2091
2092         } else {
2093                 CGroupController c;
2094
2095                 /* In the legacy hierarchy, we check whether which
2096                  * hierarchies are mounted. */
2097
2098                 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2099                         const char *n;
2100
2101                         n = cgroup_controller_to_string(c);
2102                         if (controller_is_accessible(n) >= 0)
2103                                 mask |= CGROUP_CONTROLLER_TO_MASK(c);
2104                 }
2105         }
2106
2107         *ret = mask;
2108         return 0;
2109 }
2110
2111 /// UNNEEDED by elogind
2112 #if 0
2113 int cg_kernel_controllers(Set *controllers) {
2114         _cleanup_fclose_ FILE *f = NULL;
2115         char buf[LINE_MAX];
2116         int r;
2117
2118         assert(controllers);
2119
2120         /* Determines the full list of kernel-known controllers. Might
2121          * include controllers we don't actually support, arbitrary
2122          * named hierarchies and controllers that aren't currently
2123          * accessible (because not mounted). */
2124
2125         f = fopen("/proc/cgroups", "re");
2126         if (!f) {
2127                 if (errno == ENOENT)
2128                         return 0;
2129                 return -errno;
2130         }
2131
2132         /* Ignore the header line */
2133         (void) fgets(buf, sizeof(buf), f);
2134
2135         for (;;) {
2136                 char *controller;
2137                 int enabled = 0;
2138
2139                 errno = 0;
2140                 if (fscanf(f, "%ms %*i %*i %i", &controller, &enabled) != 2) {
2141
2142                         if (feof(f))
2143                                 break;
2144
2145                         if (ferror(f) && errno != 0)
2146                                 return -errno;
2147
2148                         return -EBADMSG;
2149                 }
2150
2151                 if (!enabled) {
2152                         free(controller);
2153                         continue;
2154                 }
2155
2156                 if (!cg_controller_is_valid(controller)) {
2157                         free(controller);
2158                         return -EBADMSG;
2159                 }
2160
2161                 r = set_consume(controllers, controller);
2162                 if (r < 0)
2163                         return r;
2164         }
2165
2166         return 0;
2167 }
2168 #endif // 0
2169
2170 static thread_local int unified_cache = -1;
2171
2172 int cg_unified(void) {
2173         struct statfs fs;
2174
2175         /* Checks if we support the unified hierarchy. Returns an
2176          * error when the cgroup hierarchies aren't mounted yet or we
2177          * have any other trouble determining if the unified hierarchy
2178          * is supported. */
2179
2180         if (unified_cache >= 0)
2181                 return unified_cache;
2182
2183         if (statfs("/sys/fs/cgroup/", &fs) < 0)
2184                 return -errno;
2185
2186 /// elogind can not support the unified hierarchy as a controller,
2187 /// so always assume a classical hierarchy.
2188 /// If, ond only *if*, someone really wants to substitute systemd-login
2189 /// in an environment managed by systemd with elogin, we might have to
2190 /// add such a support.
2191 #if 0
2192         if (F_TYPE_EQUAL(fs.f_type, CGROUP_SUPER_MAGIC))
2193                 unified_cache = true;
2194         else if (F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC))
2195 #else
2196         if (F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC))
2197 #endif // 0
2198                 unified_cache = false;
2199         else
2200                 return -ENOEXEC;
2201
2202         return unified_cache;
2203 }
2204
2205 /// UNNEEDED by elogind
2206 #if 0
2207 void cg_unified_flush(void) {
2208         unified_cache = -1;
2209 }
2210
2211 int cg_enable_everywhere(CGroupMask supported, CGroupMask mask, const char *p) {
2212         _cleanup_free_ char *fs = NULL;
2213         CGroupController c;
2214         int r, unified;
2215
2216         assert(p);
2217
2218         if (supported == 0)
2219                 return 0;
2220
2221         unified = cg_unified();
2222         if (unified < 0)
2223                 return unified;
2224         if (!unified) /* on the legacy hiearchy there's no joining of controllers defined */
2225                 return 0;
2226
2227         r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, p, "cgroup.subtree_control", &fs);
2228         if (r < 0)
2229                 return r;
2230
2231         for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2232                 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2233                 const char *n;
2234
2235                 if (!(supported & bit))
2236                         continue;
2237
2238                 n = cgroup_controller_to_string(c);
2239                 {
2240                         char s[1 + strlen(n) + 1];
2241
2242                         s[0] = mask & bit ? '+' : '-';
2243                         strcpy(s + 1, n);
2244
2245                         r = write_string_file(fs, s, 0);
2246                         if (r < 0)
2247                                 log_debug_errno(r, "Failed to enable controller %s for %s (%s): %m", n, p, fs);
2248                 }
2249         }
2250
2251         return 0;
2252 }
2253
2254 bool cg_is_unified_wanted(void) {
2255         static thread_local int wanted = -1;
2256         int r, unified;
2257
2258         /* If the hierarchy is already mounted, then follow whatever
2259          * was chosen for it. */
2260         unified = cg_unified();
2261         if (unified >= 0)
2262                 return unified;
2263
2264         /* Otherwise, let's see what the kernel command line has to
2265          * say. Since checking that is expensive, let's cache the
2266          * result. */
2267         if (wanted >= 0)
2268                 return wanted;
2269
2270         r = get_proc_cmdline_key("systemd.unified_cgroup_hierarchy", NULL);
2271         if (r > 0)
2272                 return (wanted = true);
2273         else {
2274                 _cleanup_free_ char *value = NULL;
2275
2276                 r = get_proc_cmdline_key("systemd.unified_cgroup_hierarchy=", &value);
2277                 if (r < 0)
2278                         return false;
2279                 if (r == 0)
2280                         return (wanted = false);
2281
2282                 return (wanted = parse_boolean(value) > 0);
2283         }
2284 }
2285
2286 bool cg_is_legacy_wanted(void) {
2287         return !cg_is_unified_wanted();
2288 }
2289 #else
2290 bool cg_is_legacy_wanted(void) {
2291         return true;
2292 }
2293 #endif // 0
2294
2295 /// UNNEEDED by elogind
2296 #if 0
2297 int cg_cpu_shares_parse(const char *s, uint64_t *ret) {
2298         uint64_t u;
2299         int r;
2300
2301         if (isempty(s)) {
2302                 *ret = CGROUP_CPU_SHARES_INVALID;
2303                 return 0;
2304         }
2305
2306         r = safe_atou64(s, &u);
2307         if (r < 0)
2308                 return r;
2309
2310         if (u < CGROUP_CPU_SHARES_MIN || u > CGROUP_CPU_SHARES_MAX)
2311                 return -ERANGE;
2312
2313         *ret = u;
2314         return 0;
2315 }
2316
2317 int cg_blkio_weight_parse(const char *s, uint64_t *ret) {
2318         uint64_t u;
2319         int r;
2320
2321         if (isempty(s)) {
2322                 *ret = CGROUP_BLKIO_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_BLKIO_WEIGHT_MIN || u > CGROUP_BLKIO_WEIGHT_MAX)
2331                 return -ERANGE;
2332
2333         *ret = u;
2334         return 0;
2335 }
2336 #endif // 0
2337
2338 static const char *cgroup_controller_table[_CGROUP_CONTROLLER_MAX] = {
2339         [CGROUP_CONTROLLER_CPU] = "cpu",
2340         [CGROUP_CONTROLLER_CPUACCT] = "cpuacct",
2341         [CGROUP_CONTROLLER_BLKIO] = "blkio",
2342         [CGROUP_CONTROLLER_MEMORY] = "memory",
2343         [CGROUP_CONTROLLER_DEVICES] = "devices",
2344         [CGROUP_CONTROLLER_PIDS] = "pids",
2345         [CGROUP_CONTROLLER_NET_CLS] = "net_cls",
2346 };
2347
2348 DEFINE_STRING_TABLE_LOOKUP(cgroup_controller, CGroupController);