]> git.proxmox.com Git - mirror_lxcfs.git/blob - pam/pam_cgfs.c
pam_cgfs: handle cgroupfs v1 cpuset controller
[mirror_lxcfs.git] / pam / pam_cgfs.c
1 /* pam-cgfs
2 *
3 * Copyright © 2016 Canonical, Inc
4 * Author: Serge Hallyn <serge.hallyn@ubuntu.com>
5 * Author: Christian Brauner <christian.brauner@ubuntu.com>
6 *
7 * When a user logs in, this pam module will create cgroups which the user may
8 * administer. It handles both pure cgroupfs v1 and pure cgroupfs v2, as well as
9 * mixed mounts, where some controllers are mounted in a standard cgroupfs v1
10 * hierarchy location (/sys/fs/cgroup/<controller>) and others are in the
11 * cgroupfs v2 hierarchy.
12 * Writeable cgroups are either created for all controllers or, if specified,
13 * for any controllers listed on the command line.
14 * The cgroup created will be "user/$user/0" for the first session,
15 * "user/$user/1" for the second, etc.
16 *
17 * Systems with a systemd init system are treated specially, both with respect
18 * to cgroupfs v1 and cgroupfs v2. For both, cgroupfs v1 and cgroupfs v2, We
19 * check whether systemd already placed us in a cgroup it created:
20 *
21 * user.slice/user-uid.slice/session-n.scope
22 *
23 * by checking whether uid == our uid. If it did, we simply chown the last
24 * part (session-n.scope). If it did not we create a cgroup as outlined above
25 * (user/$user/n) and chown it to our uid.
26 * The same holds for cgroupfs v2 where this assumptions becomes crucial:
27 * We __have to__ be placed in our under the cgroup systemd created for us on
28 * login, otherwise things like starting an xserver or similar will not work.
29 *
30 * All requested cgroups must be mounted under /sys/fs/cgroup/$controller,
31 * no messing around with finding mountpoints.
32 *
33 * See COPYING file for details.
34 */
35
36 #include <ctype.h>
37 #include <dirent.h>
38 #include <errno.h>
39 #include <fcntl.h>
40 #include <pwd.h>
41 #include <stdarg.h>
42 #include <stdbool.h>
43 #include <stdint.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <syslog.h>
48 #include <unistd.h>
49 #include <linux/unistd.h>
50 #include <sys/mount.h>
51 #include <sys/param.h>
52 #include <sys/stat.h>
53 #include <sys/types.h>
54 #include <sys/vfs.h>
55
56 #define PAM_SM_SESSION
57 #include <security/_pam_macros.h>
58 #include <security/pam_modules.h>
59
60 #include "macro.h"
61
62 #ifndef CGROUP_SUPER_MAGIC
63 #define CGROUP_SUPER_MAGIC 0x27e0eb
64 #endif
65
66 #ifndef CGROUP2_SUPER_MAGIC
67 #define CGROUP2_SUPER_MAGIC 0x63677270
68 #endif
69
70 /* Taken over modified from the kernel sources. */
71 #define NBITS 32 /* bits in uint32_t */
72 #define DIV_ROUND_UP(n, d) (((n) + (d)-1) / (d))
73 #define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr, NBITS)
74
75 static enum cg_mount_mode {
76 CGROUP_UNKNOWN = -1,
77 CGROUP_MIXED = 0,
78 CGROUP_PURE_V1 = 1,
79 CGROUP_PURE_V2 = 2,
80 CGROUP_UNINITIALIZED = 3,
81 } cg_mount_mode = CGROUP_UNINITIALIZED;
82
83 /* Common helper prototypes. */
84 static void append_line(char **dest, size_t oldlen, char *new, size_t newlen);
85 static int append_null_to_list(void ***list);
86 static void batch_realloc(char **mem, size_t oldlen, size_t newlen);
87 static inline void clear_bit(unsigned bit, uint32_t *bitarr)
88 {
89 bitarr[bit / NBITS] &= ~(1 << (bit % NBITS));
90 }
91 static char *copy_to_eol(char *s);
92 static bool file_exists(const char *f);
93 static void free_string_list(char **list);
94 static char *get_mountpoint(char *line);
95 static bool get_uid_gid(const char *user, uid_t *uid, gid_t *gid);
96 static int handle_login(const char *user, uid_t uid, gid_t gid);
97 static inline bool is_set(unsigned bit, uint32_t *bitarr)
98 {
99 return (bitarr[bit / NBITS] & (1 << (bit % NBITS))) != 0;
100 }
101 /* __typeof__ should be safe to use with all compilers. */
102 typedef __typeof__(((struct statfs *)NULL)->f_type) fs_type_magic;
103 static bool has_fs_type(const struct statfs *fs, fs_type_magic magic_val);
104 static bool is_lxcfs(const char *line);
105 static bool is_cgv1(char *line);
106 static bool is_cgv2(char *line);
107 static bool mkdir_p(const char *root, char *path);
108 static void *must_alloc(size_t sz);
109 static void must_add_to_list(char ***clist, char *entry);
110 static void must_append_controller(char **klist, char **nlist, char ***clist,
111 char *entry);
112 static void must_append_string(char ***list, char *entry);
113 static char *must_copy_string(const char *entry);
114 static char *must_make_path(const char *first, ...) __attribute__((sentinel));
115 static void *must_realloc(void *orig, size_t sz);
116 static void mysyslog(int err, const char *format, ...) __attribute__((sentinel));
117 static char *read_file(char *fnam);
118 static int read_from_file(const char *filename, void* buf, size_t count);
119 static int recursive_rmdir(char *dirname);
120 static inline void set_bit(unsigned bit, uint32_t *bitarr)
121 {
122 bitarr[bit / NBITS] |= (1 << (bit % NBITS));
123 }
124 static bool string_in_list(char **list, const char *entry);
125 char *string_join(const char *sep, const char **parts, bool use_as_prefix);
126 static void trim(char *s);
127 static bool write_int(char *path, int v);
128 ssize_t write_nointr(int fd, const void* buf, size_t count);
129
130 /* cgroupfs prototypes. */
131 static bool cg_belongs_to_uid_gid(const char *path, uid_t uid, gid_t gid);
132 static uint32_t *cg_cpumask(char *buf, size_t nbits);
133 static bool cg_copy_parent_file(char *path, char *file);
134 static char *cg_cpumask_to_cpulist(uint32_t *bitarr, size_t nbits);
135 static bool cg_enter(const char *cgroup);
136 static void cg_escape(void);
137 static bool cg_filter_and_set_cpus(char *path, bool am_initialized);
138 static ssize_t cg_get_max_cpus(char *cpulist);
139 static int cg_get_version_of_mntpt(const char *path);
140 static bool cg_init(uid_t uid, gid_t gid);
141 static void cg_mark_to_make_rw(const char *cstring);
142 static void cg_prune_empty_cgroups(const char *user);
143 static bool cg_systemd_created_user_slice(const char *base_cgroup,
144 const char *init_cgroup,
145 const char *in, uid_t uid);
146 static bool cg_systemd_chown_existing_cgroup(const char *mountpoint,
147 const char *base_cgroup, uid_t uid,
148 gid_t gid,
149 bool systemd_user_slice);
150 static bool cg_systemd_under_user_slice_1(const char *in, uid_t uid);
151 static bool cg_systemd_under_user_slice_2(const char *base_cgroup,
152 const char *init_cgroup, uid_t uid);
153 static void cg_systemd_prune_init_scope(char *cg);
154 int cg_write_to_file(const char *filename, const void *buf, size_t count,
155 bool add_newline);
156 static bool is_lxcfs(const char *line);
157
158 /* cgroupfs v1 prototypes. */
159 struct cgv1_hierarchy {
160 char **controllers;
161 char *mountpoint;
162 char *base_cgroup;
163 char *fullcgpath;
164 char *init_cgroup;
165 bool create_rw_cgroup;
166 bool systemd_user_slice;
167 };
168
169 static struct cgv1_hierarchy **cgv1_hierarchies;
170
171 static void cgv1_add_controller(char **clist, char *mountpoint,
172 char *base_cgroup, char *init_cgroup);
173 static bool cgv1_controller_in_clist(char *cgline, char *c);
174 static bool cgv1_controller_lists_intersect(char **l1, char **l2);
175 static bool cgv1_controller_list_is_dup(struct cgv1_hierarchy **hlist,
176 char **clist);
177 static bool cgv1_create(const char *cgroup, uid_t uid, gid_t gid,
178 bool *existed);
179 static bool cgv1_create_one(struct cgv1_hierarchy *h, const char *cgroup,
180 uid_t uid, gid_t gid, bool *existed);
181 static bool cgv1_enter(const char *cgroup);
182 static void cgv1_escape(void);
183 static bool cgv1_get_controllers(char ***klist, char ***nlist);
184 static char *cgv1_get_current_cgroup(char *basecginfo, char *controller);
185 static char **cgv1_get_proc_mountinfo_controllers(char **klist, char **nlist,
186 char *line);
187 static bool cgv1_handle_cpuset_hierarchy(struct cgv1_hierarchy *h,
188 const char *cgroup);
189 static bool cgv1_handle_root_cpuset_hierarchy(struct cgv1_hierarchy *h);
190 static bool cgv1_init(uid_t uid, gid_t gid);
191 static void cgv1_mark_to_make_rw(char **clist);
192 static char *cgv1_must_prefix_named(char *entry);
193 static bool cgv1_prune_empty_cgroups(const char *user);
194 static bool cgv1_remove_one(struct cgv1_hierarchy *h, const char *cgroup);
195 static bool is_cgv1(char *line);
196
197 /* cgroupfs v2 prototypes. */
198 struct cgv2_hierarchy {
199 char **controllers;
200 char *mountpoint;
201 char *base_cgroup;
202 char *fullcgpath;
203 char *init_cgroup;
204 bool create_rw_cgroup;
205 bool systemd_user_slice;
206 };
207
208 /* Actually this should only be a single hierarchy. But for the sake of
209 * parallelism and because the layout of the cgroupfs v2 is still somewhat
210 * changing, we'll leave it as an array of structs.
211 */
212 static struct cgv2_hierarchy **cgv2_hierarchies;
213
214 static void cgv2_add_controller(char **clist, char *mountpoint,
215 char *base_cgroup, char *init_cgroup,
216 bool systemd_user_slice);
217 static bool cgv2_create(const char *cgroup, uid_t uid, gid_t gid,
218 bool *existed);
219 static bool cgv2_enter(const char *cgroup);
220 static void cgv2_escape(void);
221 static char *cgv2_get_current_cgroup(int pid);
222 static bool cgv2_init(uid_t uid, gid_t gid);
223 static void cgv2_mark_to_make_rw(char **clist);
224 static bool cgv2_prune_empty_cgroups(const char *user);
225 static bool cgv2_remove(const char *cgroup);
226 static bool is_cgv2(char *line);
227
228 /* Common helper functions. */
229 static void mysyslog(int err, const char *format, ...)
230 {
231 va_list args;
232
233 va_start(args, format);
234 openlog("PAM-CGFS", LOG_CONS | LOG_PID, LOG_AUTH);
235 vsyslog(err, format, args);
236 va_end(args);
237 closelog();
238 }
239
240 /* realloc() pointer; do not fail. */
241 static void *must_realloc(void *orig, size_t sz)
242 {
243 void *ret;
244
245 do {
246 ret = realloc(orig, sz);
247 } while (!ret);
248
249 return ret;
250 }
251
252 /* realloc() pointer in batch sizes; do not fail. */
253 #define BATCH_SIZE 50
254 static void batch_realloc(char **mem, size_t oldlen, size_t newlen)
255 {
256 int newbatches = (newlen / BATCH_SIZE) + 1;
257 int oldbatches = (oldlen / BATCH_SIZE) + 1;
258
259 if (!*mem || newbatches > oldbatches)
260 *mem = must_realloc(*mem, newbatches * BATCH_SIZE);
261 }
262
263 /* Append lines as is to pointer; do not fail. */
264 static void append_line(char **dest, size_t oldlen, char *new, size_t newlen)
265 {
266 size_t full = oldlen + newlen;
267
268 batch_realloc(dest, oldlen, full + 1);
269
270 memcpy(*dest + oldlen, new, newlen + 1);
271 }
272
273 /* Read in whole file and return allocated pointer. */
274 static char *read_file(char *fnam)
275 {
276 FILE *f;
277 int linelen;
278 char *line = NULL, *buf = NULL;
279 size_t len = 0, fulllen = 0;
280
281 f = fopen(fnam, "r");
282 if (!f)
283 return NULL;
284
285 while ((linelen = getline(&line, &len, f)) != -1) {
286 append_line(&buf, fulllen, line, linelen);
287 fulllen += linelen;
288 }
289
290 fclose(f);
291 free(line);
292
293 return buf;
294 }
295
296 /* Given a pointer to a null-terminated array of pointers, realloc to add one
297 * entry, and point the new entry to NULL. Do not fail. Return the index to the
298 * second-to-last entry - that is, the one which is now available for use
299 * (keeping the list null-terminated).
300 */
301 static int append_null_to_list(void ***list)
302 {
303 int newentry = 0;
304
305 if (*list)
306 for (; (*list)[newentry]; newentry++) {
307 ;
308 }
309
310 *list = must_realloc(*list, (newentry + 2) * sizeof(void **));
311 (*list)[newentry + 1] = NULL;
312
313 return newentry;
314 }
315
316 /* Make allocated copy of string; do not fail. */
317 static char *must_copy_string(const char *entry)
318 {
319 char *ret;
320
321 if (!entry)
322 return NULL;
323
324 do {
325 ret = strdup(entry);
326 } while (!ret);
327
328 return ret;
329 }
330
331 /* Append new entry to null-terminated array of pointer; make sure that array of
332 * pointers will still be null-terminated.
333 */
334 static void must_append_string(char ***list, char *entry)
335 {
336 int newentry;
337 char *copy;
338
339 newentry = append_null_to_list((void ***)list);
340 copy = must_copy_string(entry);
341 (*list)[newentry] = copy;
342 }
343
344 /* Remove newlines from string. */
345 static void trim(char *s)
346 {
347 size_t len = strlen(s);
348
349 while (s[len - 1] == '\n')
350 s[--len] = '\0';
351 }
352
353 /* Allocate pointer; do not fail. */
354 static void *must_alloc(size_t sz)
355 {
356 return must_realloc(NULL, sz);
357 }
358
359 /* Make allocated copy of string. End of string is taken to be '\n'. */
360 static char *copy_to_eol(char *s)
361 {
362 char *newline, *sret;
363 size_t len;
364
365 newline = strchr(s, '\n');
366 if (!newline)
367 return NULL;
368
369 len = newline - s;
370 sret = must_alloc(len + 1);
371 memcpy(sret, s, len);
372 sret[len] = '\0';
373
374 return sret;
375 }
376
377 /* Check if given entry under /proc/<pid>/mountinfo is a fuse.lxcfs mount. */
378 static bool is_lxcfs(const char *line)
379 {
380 char *p = strstr(line, " - ");
381 if (!p)
382 return false;
383
384 return strncmp(p, " - fuse.lxcfs ", 14) == 0;
385 }
386
387 /* Check if given entry under /proc/<pid>/mountinfo is a cgroupfs v1 mount. */
388 static bool is_cgv1(char *line)
389 {
390 char *p = strstr(line, " - ");
391 if (!p)
392 return false;
393
394 return strncmp(p, " - cgroup ", 10) == 0;
395 }
396
397 /* Check if given entry under /proc/<pid>/mountinfo is a cgroupfs v2 mount. */
398 static bool is_cgv2(char *line)
399 {
400 char *p = strstr(line, " - ");
401 if (!p)
402 return false;
403
404 return strncmp(p, " - cgroup2 ", 11) == 0;
405 }
406
407 /* Given a null-terminated array of strings, check whether @entry is one of the
408 * strings
409 */
410 static bool string_in_list(char **list, const char *entry)
411 {
412 char **it;
413
414 for (it = list; it && *it; it++)
415 if (strcmp(*it, entry) == 0)
416 return true;
417
418 return false;
419 }
420
421 /* Free null-terminated array of strings. */
422 static void free_string_list(char **list)
423 {
424 char **it;
425
426 for (it = list; it && *it; it++)
427 free(*it);
428 free(list);
429 }
430
431 /* Concatenate all passed-in strings into one path. Do not fail. If any piece
432 * is not prefixed with '/', add a '/'. Does not remove duplicate '///' from the
433 * created path.
434 */
435 static char *must_make_path(const char *first, ...)
436 {
437 va_list args;
438 char *cur, *dest;
439 size_t full_len;
440
441 full_len = strlen(first);
442
443 dest = must_copy_string(first);
444
445 va_start(args, first);
446 while ((cur = va_arg(args, char *)) != NULL) {
447 full_len += strlen(cur);
448
449 if (cur[0] != '/')
450 full_len++;
451
452 dest = must_realloc(dest, full_len + 1);
453
454 if (cur[0] != '/')
455 strcat(dest, "/");
456
457 strcat(dest, cur);
458 }
459 va_end(args);
460
461 return dest;
462 }
463
464 /* Write single integer to file. */
465 static bool write_int(char *path, int v)
466 {
467 FILE *f;
468 bool ret = true;
469
470 f = fopen(path, "w");
471 if (!f)
472 return false;
473
474 if (fprintf(f, "%d\n", v) < 0)
475 ret = false;
476
477 if (fclose(f) != 0)
478 ret = false;
479
480 return ret;
481 }
482
483 /* Check if a given file exists. */
484 static bool file_exists(const char *f)
485 {
486 struct stat statbuf;
487
488 return stat(f, &statbuf) == 0;
489 }
490
491 /* Create directory and (if necessary) its parents. */
492 static bool mkdir_p(const char *root, char *path)
493 {
494 char *b, orig, *e;
495
496 if (strlen(path) < strlen(root))
497 return false;
498
499 if (strlen(path) == strlen(root))
500 return true;
501
502 b = path + strlen(root) + 1;
503 while (true) {
504 while (*b && (*b == '/'))
505 b++;
506 if (!*b)
507 return true;
508
509 e = b + 1;
510 while (*e && *e != '/')
511 e++;
512
513 orig = *e;
514 if (orig)
515 *e = '\0';
516
517 if (file_exists(path))
518 goto next;
519
520 if (mkdir(path, 0755) < 0) {
521 lxcfs_debug("Failed to create %s: %m.\n", path);
522 return false;
523 }
524
525 next:
526 if (!orig)
527 return true;
528
529 *e = orig;
530 b = e + 1;
531 }
532
533 return false;
534 }
535
536 /* Recursively remove directory and its parents. */
537 static int recursive_rmdir(char *dirname)
538 {
539 struct dirent *direntp;
540 DIR *dir;
541 int r = 0;
542
543 dir = opendir(dirname);
544 if (!dir)
545 return -ENOENT;
546
547 while ((direntp = readdir(dir))) {
548 struct stat st;
549 char *pathname;
550
551 if (!direntp)
552 break;
553
554 if (!strcmp(direntp->d_name, ".") ||
555 !strcmp(direntp->d_name, ".."))
556 continue;
557
558 pathname = must_make_path(dirname, direntp->d_name, NULL);
559
560 if (lstat(pathname, &st)) {
561 if (!r)
562 lxcfs_debug("Failed to stat %s.\n", pathname);
563 r = -1;
564 goto next;
565 }
566
567 if (!S_ISDIR(st.st_mode))
568 goto next;
569
570 if (recursive_rmdir(pathname) < 0)
571 r = -1;
572 next:
573 free(pathname);
574 }
575
576 if (rmdir(dirname) < 0) {
577 if (!r)
578 lxcfs_debug("Failed to delete %s: %m.\n", dirname);
579 r = -1;
580 }
581
582 if (closedir(dir) < 0) {
583 if (!r)
584 lxcfs_debug("Failed to delete %s: %m.\n", dirname);
585 r = -1;
586 }
587
588 return r;
589 }
590
591 /* Add new entry to null-terminated array of pointers. Make sure array is still
592 * null-terminated.
593 */
594 static void must_add_to_list(char ***clist, char *entry)
595 {
596 int newentry;
597
598 newentry = append_null_to_list((void ***)clist);
599 (*clist)[newentry] = must_copy_string(entry);
600 }
601
602 /* Get mountpoint from a /proc/<pid>/mountinfo line. */
603 static char *get_mountpoint(char *line)
604 {
605 int i;
606 char *p, *sret, *p2;
607 size_t len;
608
609 p = line;
610
611 for (i = 0; i < 4; i++) {
612 p = strchr(p, ' ');
613 if (!p)
614 return NULL;
615 p++;
616 }
617
618 p2 = strchr(p, ' ');
619 if (p2)
620 *p2 = '\0';
621
622 len = strlen(p);
623 sret = must_alloc(len + 1);
624 memcpy(sret, p, len);
625 sret[len] = '\0';
626
627 return sret;
628 }
629
630 /* Create list of cgroupfs v1 controller found under /proc/self/cgroup. Skips
631 * the 0::/some/path cgroupfs v2 hierarchy listed. Splits controllers into
632 * kernel controllers (@klist) and named controllers (@nlist).
633 */
634 static bool cgv1_get_controllers(char ***klist, char ***nlist)
635 {
636 FILE *f;
637 char *line = NULL;
638 size_t len = 0;
639
640 f = fopen("/proc/self/cgroup", "r");
641 if (!f)
642 return false;
643
644 while (getline(&line, &len, f) != -1) {
645 char *p, *p2, *tok;
646 char *saveptr = NULL;
647
648 p = strchr(line, ':');
649 if (!p)
650 continue;
651 p++;
652
653 p2 = strchr(p, ':');
654 if (!p2)
655 continue;
656 *p2 = '\0';
657
658 /* Skip the v2 hierarchy. */
659 if ((p2 - p) == 0)
660 continue;
661
662 for (tok = strtok_r(p, ",", &saveptr); tok;
663 tok = strtok_r(NULL, ",", &saveptr)) {
664 if (strncmp(tok, "name=", 5) == 0)
665 must_append_string(nlist, tok);
666 else
667 must_append_string(klist, tok);
668 }
669 }
670
671 free(line);
672 fclose(f);
673
674 return true;
675 }
676
677 /* Get list of controllers for cgroupfs v2 hierarchy by looking at
678 * cgroup.controllers and/or cgroup.subtree_control of a given (parent) cgroup.
679 static bool cgv2_get_controllers(char ***klist)
680 {
681 return -ENOSYS;
682 }
683 */
684
685 /* Get current cgroup from /proc/self/cgroup for the cgroupfs v2 hierarchy. */
686 static char *cgv2_get_current_cgroup(int pid)
687 {
688 int ret;
689 char *cgroups_v2;
690 char *current_cgroup;
691 char *copy = NULL;
692 /* The largest integer that can fit into long int is 2^64. This is a
693 * 20-digit number. */
694 #define __PIDLEN /* /proc */ 5 + /* /pid-to-str */ 21 + /* /cgroup */ 7 + /* \0 */ 1
695 char path[__PIDLEN];
696
697 ret = snprintf(path, __PIDLEN, "/proc/%d/cgroup", pid);
698 if (ret < 0 || ret >= __PIDLEN)
699 return NULL;
700
701 cgroups_v2 = read_file(path);
702 if (!cgroups_v2)
703 return NULL;
704
705 current_cgroup = strstr(cgroups_v2, "0::/");
706 if (!current_cgroup)
707 goto cleanup_on_err;
708
709 current_cgroup = current_cgroup + 3;
710 copy = copy_to_eol(current_cgroup);
711 if (!copy)
712 goto cleanup_on_err;
713
714 cleanup_on_err:
715 free(cgroups_v2);
716 if (copy)
717 trim(copy);
718
719 return copy;
720 }
721
722 /* Given two null-terminated lists of strings, return true if any string is in
723 * both.
724 */
725 static bool cgv1_controller_lists_intersect(char **l1, char **l2)
726 {
727 char **it;
728
729 if (!l2)
730 return false;
731
732 for (it = l1; it && *it; it++)
733 if (string_in_list(l2, *it))
734 return true;
735
736 return false;
737 }
738
739 /* For a null-terminated list of controllers @clist, return true if any of those
740 * controllers is already listed the null-terminated list of hierarchies @hlist.
741 * Realistically, if one is present, all must be present.
742 */
743 static bool cgv1_controller_list_is_dup(struct cgv1_hierarchy **hlist, char **clist)
744 {
745 struct cgv1_hierarchy **it;
746
747 for (it = hlist; it && *it; it++)
748 if ((*it)->controllers)
749 if (cgv1_controller_lists_intersect((*it)->controllers, clist))
750 return true;
751 return false;
752
753 }
754
755 /* Set boolean to mark controllers under which we are supposed create a
756 * writeable cgroup.
757 */
758 static void cgv1_mark_to_make_rw(char **clist)
759 {
760 struct cgv1_hierarchy **it;
761
762 for (it = cgv1_hierarchies; it && *it; it++)
763 if ((*it)->controllers)
764 if (cgv1_controller_lists_intersect((*it)->controllers, clist))
765 (*it)->create_rw_cgroup = true;
766 }
767
768 /* Set boolean to mark whether we are supposed to create a writeable cgroup in
769 * the cgroupfs v2 hierarchy.
770 */
771 static void cgv2_mark_to_make_rw(char **clist)
772 {
773 if (string_in_list(clist, "unified"))
774 if (cgv2_hierarchies)
775 (*cgv2_hierarchies)->create_rw_cgroup = true;
776 }
777
778 /* Wrapper around cgv{1,2}_mark_to_make_rw(). */
779 static void cg_mark_to_make_rw(const char *cstring)
780 {
781 char *copy, *tok;
782 char *saveptr = NULL;
783 char **clist = NULL;
784
785 copy = must_copy_string(cstring);
786
787 for (tok = strtok_r(copy, ",", &saveptr); tok;
788 tok = strtok_r(NULL, ",", &saveptr))
789 must_add_to_list(&clist, tok);
790
791 free(copy);
792
793 cgv1_mark_to_make_rw(clist);
794 cgv2_mark_to_make_rw(clist);
795
796 free_string_list(clist);
797 }
798
799 /* Prefix any named controllers with "name=", e.g. "name=systemd". */
800 static char *cgv1_must_prefix_named(char *entry)
801 {
802 char *s;
803 int ret;
804 size_t len;
805
806 len = strlen(entry);
807 s = must_alloc(len + 6);
808
809 ret = snprintf(s, len + 6, "name=%s", entry);
810 if (ret < 0 || (size_t)ret >= (len + 6))
811 return NULL;
812
813 return s;
814 }
815
816 /* Append kernel controller in @klist or named controller in @nlist to @clist */
817 static void must_append_controller(char **klist, char **nlist, char ***clist, char *entry)
818 {
819 int newentry;
820 char *copy;
821
822 if (string_in_list(klist, entry) && string_in_list(nlist, entry))
823 return;
824
825 newentry = append_null_to_list((void ***)clist);
826
827 if (strncmp(entry, "name=", 5) == 0)
828 copy = must_copy_string(entry);
829 else if (string_in_list(klist, entry))
830 copy = must_copy_string(entry);
831 else
832 copy = cgv1_must_prefix_named(entry);
833
834 (*clist)[newentry] = copy;
835 }
836
837 /* Get the controllers from a mountinfo line. There are other ways we could get
838 * this info. For lxcfs, field 3 is /cgroup/controller-list. For cgroupfs, we
839 * could parse the mount options. But we simply assume that the mountpoint must
840 * be /sys/fs/cgroup/controller-list
841 */
842 static char **cgv1_get_proc_mountinfo_controllers(char **klist, char **nlist, char *line)
843 {
844 int i;
845 char *p, *p2, *tok;
846 char *saveptr = NULL;
847 char **aret = NULL;
848
849 p = line;
850
851 for (i = 0; i < 4; i++) {
852 p = strchr(p, ' ');
853 if (!p)
854 return NULL;
855 p++;
856 }
857 if (!p)
858 return NULL;
859
860 if (strncmp(p, "/sys/fs/cgroup/", 15) != 0)
861 return NULL;
862
863 p += 15;
864
865 p2 = strchr(p, ' ');
866 if (!p2)
867 return NULL;
868 *p2 = '\0';
869
870 for (tok = strtok_r(p, ",", &saveptr); tok;
871 tok = strtok_r(NULL, ",", &saveptr))
872 must_append_controller(klist, nlist, &aret, tok);
873
874 return aret;
875 }
876
877 /* Check if a cgroupfs v2 controller is present in the string @cgline. */
878 static bool cgv1_controller_in_clist(char *cgline, char *c)
879 {
880 size_t len;
881 char *tok, *eol, *tmp;
882 char *saveptr = NULL;
883
884 eol = strchr(cgline, ':');
885 if (!eol)
886 return false;
887
888 len = eol - cgline;
889 tmp = alloca(len + 1);
890 memcpy(tmp, cgline, len);
891 tmp[len] = '\0';
892
893 for (tok = strtok_r(tmp, ",", &saveptr); tok;
894 tok = strtok_r(NULL, ",", &saveptr)) {
895 if (strcmp(tok, c) == 0)
896 return true;
897 }
898 return false;
899 }
900
901 /* Get current cgroup from the /proc/<pid>/cgroup file passed in via @basecginfo
902 * of a given cgv1 controller passed in via @controller.
903 */
904 static char *cgv1_get_current_cgroup(char *basecginfo, char *controller)
905 {
906 char *p;
907
908 p = basecginfo;
909
910 while (true) {
911 p = strchr(p, ':');
912 if (!p)
913 return NULL;
914 p++;
915
916 if (cgv1_controller_in_clist(p, controller)) {
917 p = strchr(p, ':');
918 if (!p)
919 return NULL;
920 p++;
921
922 return copy_to_eol(p);
923 }
924
925 p = strchr(p, '\n');
926 if (!p)
927 return NULL;
928 p++;
929 }
930
931 return NULL;
932 }
933
934 /* Remove /init.scope from string @cg. This will mostly affect systemd-based
935 * systems.
936 */
937 #define INIT_SCOPE "/init.scope"
938 static void cg_systemd_prune_init_scope(char *cg)
939 {
940 char *point;
941
942 if (!cg)
943 return;
944
945 point = cg + strlen(cg) - strlen(INIT_SCOPE);
946 if (point < cg)
947 return;
948
949 if (strcmp(point, INIT_SCOPE) == 0) {
950 if (point == cg)
951 *(point + 1) = '\0';
952 else
953 *point = '\0';
954 }
955 }
956
957 /* Add new info about a mounted cgroupfs v1 hierarchy. Includes the controllers
958 * mounted into that hierarchy (e.g. cpu,cpuacct), the mountpoint of that
959 * hierarchy (/sys/fs/cgroup/<controller>, the base cgroup of the current
960 * process gathered from /proc/self/cgroup, and the init cgroup of PID1 gathered
961 * from /proc/1/cgroup.
962 */
963 static void cgv1_add_controller(char **clist, char *mountpoint, char *base_cgroup, char *init_cgroup)
964 {
965 struct cgv1_hierarchy *new;
966 int newentry;
967
968 new = must_alloc(sizeof(*new));
969 new->controllers = clist;
970 new->mountpoint = mountpoint;
971 new->base_cgroup = base_cgroup;
972 new->fullcgpath = NULL;
973 new->create_rw_cgroup = false;
974 new->init_cgroup = init_cgroup;
975 new->systemd_user_slice = false;
976
977 newentry = append_null_to_list((void ***)&cgv1_hierarchies);
978 cgv1_hierarchies[newentry] = new;
979 }
980
981 /* Add new info about the mounted cgroupfs v2 hierarchy. Can (but doesn't
982 * currently) include the controllers mounted into the hierarchy (e.g. memory,
983 * pids, blkio), the mountpoint of that hierarchy (Should usually be
984 * /sys/fs/cgroup but some init systems seems to think it might be a good idea
985 * to also mount empty cgroupfs v2 hierarchies at /sys/fs/cgroup/systemd.), the
986 * base cgroup of the current process gathered from /proc/self/cgroup, and the
987 * init cgroup of PID1 gathered from /proc/1/cgroup.
988 */
989 static void cgv2_add_controller(char **clist, char *mountpoint, char *base_cgroup, char *init_cgroup, bool systemd_user_slice)
990 {
991 struct cgv2_hierarchy *new;
992 int newentry;
993
994 new = must_alloc(sizeof(*new));
995 new->controllers = clist;
996 new->mountpoint = mountpoint;
997 new->base_cgroup = base_cgroup;
998 new->fullcgpath = NULL;
999 new->create_rw_cgroup = false;
1000 new->init_cgroup = init_cgroup;
1001 new->systemd_user_slice = systemd_user_slice;
1002
1003 newentry = append_null_to_list((void ***)&cgv2_hierarchies);
1004 cgv2_hierarchies[newentry] = new;
1005 }
1006
1007 /* In Ubuntu 14.04, the paths created for us were
1008 * '/user/$uid.user/$something.session' This can be merged better with
1009 * systemd_created_slice_for_us(), but keeping it separate makes it easier to
1010 * reason about the correctness.
1011 */
1012 static bool cg_systemd_under_user_slice_1(const char *in, uid_t uid)
1013 {
1014 char *p;
1015 size_t len;
1016 int id;
1017 char *copy = NULL;
1018 bool bret = false;
1019
1020 copy = must_copy_string(in);
1021 if (strlen(copy) < strlen("/user/1.user/1.session"))
1022 goto cleanup;
1023 p = copy + strlen(copy) - 1;
1024
1025 /* skip any trailing '/' (shouldn't be any, but be sure) */
1026 while (p >= copy && *p == '/')
1027 *(p--) = '\0';
1028 if (p < copy)
1029 goto cleanup;
1030
1031 /* Get last path element */
1032 while (p >= copy && *p != '/')
1033 p--;
1034 if (p < copy)
1035 goto cleanup;
1036 /* make sure it is something.session */
1037 len = strlen(p + 1);
1038 if (len < strlen("1.session") ||
1039 strncmp(p + 1 + len - 8, ".session", 8) != 0)
1040 goto cleanup;
1041
1042 /* ok last path piece checks out, now check the second to last */
1043 *(p + 1) = '\0';
1044 while (p >= copy && *(--p) != '/')
1045 ;
1046 if (sscanf(p + 1, "%d.user/", &id) != 1)
1047 goto cleanup;
1048
1049 if (id != (int)uid)
1050 goto cleanup;
1051
1052 bret = true;
1053
1054 cleanup:
1055 free(copy);
1056 return bret;
1057 }
1058
1059 /* So long as our path relative to init starts with /user.slice/user-$uid.slice,
1060 * assume it belongs to $uid and chown it
1061 */
1062 static bool cg_systemd_under_user_slice_2(const char *base_cgroup,
1063 const char *init_cgroup, uid_t uid)
1064 {
1065 int ret;
1066 char buf[100];
1067 size_t curlen, initlen;
1068
1069 curlen = strlen(base_cgroup);
1070 initlen = strlen(init_cgroup);
1071 if (curlen <= initlen)
1072 return false;
1073
1074 if (strncmp(base_cgroup, init_cgroup, initlen) != 0)
1075 return false;
1076
1077 ret = snprintf(buf, 100, "/user.slice/user-%d.slice/", (int)uid);
1078 if (ret < 0 || ret >= 100)
1079 return false;
1080
1081 if (initlen == 1)
1082 initlen = 0; // skip the '/'
1083
1084 return strncmp(base_cgroup + initlen, buf, strlen(buf)) == 0;
1085 }
1086
1087 /* The systemd-created path is: user-$uid.slice/session-c$session.scope. If that
1088 * is not the end of our systemd path, then we're not part of the PAM call that
1089 * created that path.
1090 *
1091 * The last piece is chowned to $uid, the user- part not.
1092 * Note: If the user creates paths that look like what we're looking for to
1093 * 'fool' us, either
1094 * - they fool us, we create new cgroups, and they get auto-logged-out.
1095 * - they fool a root sudo, systemd cgroup is not changed but chowned, and they
1096 * lose ownership of their cgroups
1097 */
1098 static bool cg_systemd_created_user_slice(const char *base_cgroup,
1099 const char *init_cgroup,
1100 const char *in, uid_t uid)
1101 {
1102 char *p;
1103 size_t len;
1104 int id;
1105 char *copy = NULL;
1106 bool bret = false;
1107
1108 copy = must_copy_string(in);
1109
1110 /* An old version of systemd has already created a cgroup for us. */
1111 if (cg_systemd_under_user_slice_1(in, uid))
1112 goto succeed;
1113
1114 /* A new version of systemd has already created a cgroup for us. */
1115 if (cg_systemd_under_user_slice_2(base_cgroup, init_cgroup, uid))
1116 goto succeed;
1117
1118 if (strlen(copy) < strlen("/user-0.slice/session-0.scope"))
1119 goto cleanup;
1120
1121 p = copy + strlen(copy) - 1;
1122 /* Skip any trailing '/' (shouldn't be any, but be sure). */
1123 while (p >= copy && *p == '/')
1124 *(p--) = '\0';
1125
1126 if (p < copy)
1127 goto cleanup;
1128
1129 /* Get last path element */
1130 while (p >= copy && *p != '/')
1131 p--;
1132
1133 if (p < copy)
1134 goto cleanup;
1135
1136 /* Make sure it is session-something.scope. */
1137 len = strlen(p + 1);
1138 if (strncmp(p + 1, "session-", strlen("session-")) != 0 ||
1139 strncmp(p + 1 + len - 6, ".scope", 6) != 0)
1140 goto cleanup;
1141
1142 /* Ok last path piece checks out, now check the second to last. */
1143 *(p + 1) = '\0';
1144 while (p >= copy && *(--p) != '/')
1145 ;
1146
1147 if (sscanf(p + 1, "user-%d.slice/", &id) != 1)
1148 goto cleanup;
1149
1150 if (id != (int)uid)
1151 goto cleanup;
1152
1153 succeed:
1154 bret = true;
1155 cleanup:
1156 free(copy);
1157 return bret;
1158 }
1159
1160 /* Chown existing cgroup that systemd has already created for us. */
1161 static bool cg_systemd_chown_existing_cgroup(const char *mountpoint,
1162 const char *base_cgroup, uid_t uid,
1163 gid_t gid, bool systemd_user_slice)
1164 {
1165 char *path;
1166
1167 if (!systemd_user_slice)
1168 return false;
1169
1170 path = must_make_path(mountpoint, base_cgroup, NULL);
1171
1172 /* A cgroup within name=systemd has already been created. So we only
1173 * need to chown it.
1174 */
1175 if (chown(path, uid, gid) < 0)
1176 mysyslog(LOG_WARNING, "Failed to chown %s to %d:%d: %m.\n",
1177 path, (int)uid, (int)gid, NULL);
1178
1179 free(path);
1180 return true;
1181 }
1182
1183 /* Detect and store information about cgroupfs v1 hierarchies. */
1184 static bool cgv1_init(uid_t uid, gid_t gid)
1185 {
1186 FILE *f;
1187 struct cgv1_hierarchy **it;
1188 char *basecginfo;
1189 char *line = NULL;
1190 char **klist = NULL, **nlist = NULL;
1191 size_t len = 0;
1192
1193 basecginfo = read_file("/proc/self/cgroup");
1194 if (!basecginfo)
1195 return false;
1196
1197 f = fopen("/proc/self/mountinfo", "r");
1198 if (!f) {
1199 free(basecginfo);
1200 return false;
1201 }
1202
1203 cgv1_get_controllers(&klist, &nlist);
1204
1205 while (getline(&line, &len, f) != -1) {
1206 char **controller_list = NULL;
1207 char *mountpoint, *base_cgroup;
1208
1209 if (is_lxcfs(line) || !is_cgv1(line))
1210 continue;
1211
1212 controller_list = cgv1_get_proc_mountinfo_controllers(klist, nlist, line);
1213 if (!controller_list)
1214 continue;
1215
1216 if (cgv1_controller_list_is_dup(cgv1_hierarchies,
1217 controller_list)) {
1218 free(controller_list);
1219 continue;
1220 }
1221
1222 mountpoint = get_mountpoint(line);
1223 if (!mountpoint) {
1224 free_string_list(controller_list);
1225 continue;
1226 }
1227
1228 base_cgroup = cgv1_get_current_cgroup(basecginfo, controller_list[0]);
1229 if (!base_cgroup) {
1230 free_string_list(controller_list);
1231 free(mountpoint);
1232 continue;
1233 }
1234 trim(base_cgroup);
1235 lxcfs_debug("Detected cgroupfs v1 controller \"%s\" with "
1236 "mountpoint \"%s\" and cgroup \"%s\".\n",
1237 controller_list[0], mountpoint, base_cgroup);
1238 cgv1_add_controller(controller_list, mountpoint, base_cgroup,
1239 NULL);
1240 }
1241 free_string_list(klist);
1242 free_string_list(nlist);
1243 free(basecginfo);
1244 fclose(f);
1245 free(line);
1246
1247 /* Retrieve init cgroup path for all controllers. */
1248 basecginfo = read_file("/proc/1/cgroup");
1249 if (!basecginfo)
1250 return false;
1251
1252 for (it = cgv1_hierarchies; it && *it; it++) {
1253 if ((*it)->controllers) {
1254 char *init_cgroup, *user_slice;
1255 /* We've already stored the controller and received its
1256 * current cgroup. If we now fail to retrieve its init
1257 * cgroup, we should probably fail.
1258 */
1259 init_cgroup = cgv1_get_current_cgroup(basecginfo, (*it)->controllers[0]);
1260 if (!init_cgroup) {
1261 free(basecginfo);
1262 return false;
1263 }
1264 cg_systemd_prune_init_scope(init_cgroup);
1265 (*it)->init_cgroup = init_cgroup;
1266 lxcfs_debug("cgroupfs v1 controller \"%s\" has init "
1267 "cgroup \"%s\".\n",
1268 (*(*it)->controllers), init_cgroup);
1269 /* Check whether systemd has already created a cgroup
1270 * for us.
1271 */
1272 user_slice = must_make_path((*it)->mountpoint, (*it)->base_cgroup, NULL);
1273 if (cg_systemd_created_user_slice((*it)->base_cgroup, (*it)->init_cgroup, user_slice, uid))
1274 (*it)->systemd_user_slice = true;
1275 }
1276 }
1277 free(basecginfo);
1278
1279 return true;
1280 }
1281
1282 /* __typeof__ should be safe to use with all compilers. */
1283 typedef __typeof__(((struct statfs *)NULL)->f_type) fs_type_magic;
1284 /* Check whether given mountpoint has mount type specified via @magic_val. */
1285 static bool has_fs_type(const struct statfs *fs, fs_type_magic magic_val)
1286 {
1287 return (fs->f_type == (fs_type_magic)magic_val);
1288 }
1289
1290 /* Check whether @path is a cgroupfs v1 or cgroupfs v2 mount. Returns -1 if
1291 * statfs fails. If @path is null /sys/fs/cgroup is checked.
1292 */
1293 static int cg_get_version_of_mntpt(const char *path)
1294 {
1295 int ret;
1296 struct statfs sb;
1297
1298 if (path)
1299 ret = statfs(path, &sb);
1300 else
1301 ret = statfs("/sys/fs/cgroup", &sb);
1302
1303 if (ret < 0)
1304 return -1;
1305
1306 if (has_fs_type(&sb, CGROUP_SUPER_MAGIC))
1307 return 1;
1308 else if (has_fs_type(&sb, CGROUP2_SUPER_MAGIC))
1309 return 2;
1310
1311 return 0;
1312 }
1313
1314 /* Detect and store information about the cgroupfs v2 hierarchy. Currently only
1315 * deals with the empty v2 hierachy as we do not retrieve enabled controllers.
1316 */
1317 static bool cgv2_init(uid_t uid, gid_t gid)
1318 {
1319 char *mountpoint;
1320 bool ret = false;
1321 FILE *f = NULL;
1322 char *current_cgroup = NULL, *init_cgroup = NULL;
1323 char * line = NULL;
1324 size_t len = 0;
1325
1326 current_cgroup = cgv2_get_current_cgroup(getpid());
1327 if (!current_cgroup) {
1328 /* No v2 hierarchy present. We're done. */
1329 ret = true;
1330 goto cleanup;
1331 }
1332
1333 init_cgroup = cgv2_get_current_cgroup(1);
1334 if (!init_cgroup) {
1335 /* If we're here and didn't fail already above, then something's
1336 * certainly wrong, so error this time.
1337 */
1338 goto cleanup;
1339 }
1340 cg_systemd_prune_init_scope(init_cgroup);
1341
1342 /* Check if the v2 hierarchy is mounted at its standard location.
1343 * If so we can skip the rest of the work here. Although the unified
1344 * hierarchy can be mounted multiple times, each of those mountpoints
1345 * will expose identical information.
1346 */
1347 if (cg_get_version_of_mntpt("/sys/fs/cgroup") == 2) {
1348 char *user_slice;
1349 bool has_user_slice = false;
1350
1351 mountpoint = must_copy_string("/sys/fs/cgroup");
1352 if (!mountpoint)
1353 goto cleanup;
1354
1355 user_slice = must_make_path(mountpoint, current_cgroup, NULL);
1356 if (cg_systemd_created_user_slice(current_cgroup, init_cgroup, user_slice, uid))
1357 has_user_slice = true;
1358 free(user_slice);
1359
1360 cgv2_add_controller(NULL, mountpoint, current_cgroup, init_cgroup, has_user_slice);
1361
1362 ret = true;
1363 goto cleanup;
1364 }
1365
1366 f = fopen("/proc/self/mountinfo", "r");
1367 if (!f)
1368 return false;
1369
1370 /* we support simple cgroup mounts and lxcfs mounts */
1371 while (getline(&line, &len, f) != -1) {
1372 char *user_slice;
1373 bool has_user_slice = false;
1374 if (!is_cgv2(line))
1375 continue;
1376
1377 mountpoint = get_mountpoint(line);
1378 if (!mountpoint)
1379 continue;
1380
1381 user_slice = must_make_path(mountpoint, current_cgroup, NULL);
1382 if (cg_systemd_created_user_slice(current_cgroup, init_cgroup, user_slice, uid))
1383 has_user_slice = true;
1384 free(user_slice);
1385
1386 cgv2_add_controller(NULL, mountpoint, current_cgroup, init_cgroup, has_user_slice);
1387 /* Although the unified hierarchy can be mounted multiple times,
1388 * each of those mountpoints will expose identical information.
1389 * So let the first mountpoint we find, win.
1390 */
1391 break;
1392 }
1393
1394 lxcfs_debug("Detected cgroupfs v2 hierarchy at mountpoint \"%s\" with "
1395 "current cgroup \"%s\" and init cgroup \"%s\".\n",
1396 mountpoint, current_cgroup, init_cgroup);
1397
1398 cleanup:
1399 if (f)
1400 fclose(f);
1401 free(line);
1402
1403 return true;
1404 }
1405
1406 /* Detect and store information about mounted cgroupfs v1 hierarchies and the
1407 * cgroupfs v2 hierarchy.
1408 * Detect whether we are on a pure cgroupfs v1, cgroupfs v2, or mixed system,
1409 * where some controllers are mounted into their standard cgroupfs v1 locations
1410 * (/sys/fs/cgroup/<controller>) and others are mounted into the cgroupfs v2
1411 * hierarchy (/sys/fs/cgroup).
1412 */
1413 static bool cg_init(uid_t uid, gid_t gid)
1414 {
1415 if (!cgv1_init(uid, gid))
1416 return false;
1417
1418 if (!cgv2_init(uid, gid))
1419 return false;
1420
1421 if (cgv1_hierarchies && cgv2_hierarchies) {
1422 cg_mount_mode = CGROUP_MIXED;
1423 lxcfs_debug("%s\n", "Detected cgroupfs v1 and v2 hierarchies.");
1424 } else if (cgv1_hierarchies && !cgv2_hierarchies) {
1425 cg_mount_mode = CGROUP_PURE_V1;
1426 lxcfs_debug("%s\n", "Detected cgroupfs v1 hierarchies.");
1427 } else if (cgv2_hierarchies && !cgv1_hierarchies) {
1428 cg_mount_mode = CGROUP_PURE_V2;
1429 lxcfs_debug("%s\n", "Detected cgroupfs v2 hierarchies.");
1430 } else {
1431 cg_mount_mode = CGROUP_UNKNOWN;
1432 mysyslog(LOG_ERR, "Could not detect cgroupfs hierarchy.\n", NULL);
1433 }
1434
1435 if (cg_mount_mode == CGROUP_UNKNOWN)
1436 return false;
1437
1438 return true;
1439 }
1440
1441 /* Try to move/migrate us into @cgroup in a cgroupfs v1 hierarchy. */
1442 static bool cgv1_enter(const char *cgroup)
1443 {
1444 struct cgv1_hierarchy **it;
1445
1446 for (it = cgv1_hierarchies; it && *it; it++) {
1447 char **controller;
1448 bool entered = false;
1449
1450 if (!(*it)->controllers || !(*it)->mountpoint ||
1451 !(*it)->init_cgroup || !(*it)->create_rw_cgroup)
1452 continue;
1453
1454 for (controller = (*it)->controllers; controller && *controller;
1455 controller++) {
1456 char *path;
1457
1458 /* We've already been placed in a user slice, so we
1459 * don't need to enter the cgroup again.
1460 */
1461 if ((*it)->systemd_user_slice) {
1462 entered = true;
1463 break;
1464 }
1465
1466 path = must_make_path((*it)->mountpoint,
1467 (*it)->init_cgroup,
1468 cgroup,
1469 "/cgroup.procs",
1470 NULL);
1471 if (!file_exists(path)) {
1472 free(path);
1473 path = must_make_path((*it)->mountpoint,
1474 (*it)->init_cgroup,
1475 cgroup,
1476 "/tasks",
1477 NULL);
1478 }
1479 lxcfs_debug("Attempting to enter cgroupfs v1 hierarchy in \"%s\" cgroup.\n", path);
1480 entered = write_int(path, (int)getpid());
1481 if (entered) {
1482 free(path);
1483 break;
1484 }
1485 lxcfs_debug("Failed to enter cgroupfs v1 hierarchy in \"%s\" cgroup.\n", path);
1486 free(path);
1487 }
1488 if (!entered)
1489 return false;
1490 }
1491
1492 return true;
1493 }
1494
1495 /* Try to move/migrate us into @cgroup in the cgroupfs v2 hierarchy. */
1496 static bool cgv2_enter(const char *cgroup)
1497 {
1498 struct cgv2_hierarchy *v2;
1499 char *path;
1500 bool entered = false;
1501
1502 if (!cgv2_hierarchies)
1503 return true;
1504
1505 v2 = *cgv2_hierarchies;
1506
1507 if (!v2->mountpoint || !v2->base_cgroup)
1508 return false;
1509
1510 if (!v2->create_rw_cgroup || v2->systemd_user_slice)
1511 return true;
1512
1513 path = must_make_path(v2->mountpoint, v2->base_cgroup, cgroup,
1514 "/cgroup.procs", NULL);
1515 lxcfs_debug("Attempting to enter cgroupfs v2 hierarchy in cgroup \"%s\".\n", path);
1516 entered = write_int(path, (int)getpid());
1517 if (!entered) {
1518 lxcfs_debug("Failed to enter cgroupfs v2 hierarchy in cgroup \"%s\".\n", path);
1519 free(path);
1520 return false;
1521 }
1522
1523 free(path);
1524
1525 return true;
1526 }
1527
1528 /* Wrapper around cgv{1,2}_enter(). */
1529 static bool cg_enter(const char *cgroup)
1530 {
1531 if (!cgv1_enter(cgroup)) {
1532 mysyslog(LOG_WARNING, "cgroupfs v1: Failed to enter cgroups.\n", NULL);
1533 return false;
1534 }
1535
1536 if (!cgv2_enter(cgroup)) {
1537 mysyslog(LOG_WARNING, "cgroupfs v2: Failed to enter cgroups.\n", NULL);
1538 return false;
1539 }
1540
1541 return true;
1542 }
1543
1544 /* Escape to root cgroup in all detected cgroupfs v1 hierarchies. */
1545 static void cgv1_escape(void)
1546 {
1547 struct cgv1_hierarchy **it;
1548
1549 /* In case systemd hasn't already placed us in a user slice for the
1550 * cpuset v1 controller we will reside in the root cgroup. This means
1551 * that cgroup.clone_children will not have been initialized for us so
1552 * we need to do it.
1553 */
1554 for (it = cgv1_hierarchies; it && *it; it++)
1555 if (!cgv1_handle_root_cpuset_hierarchy(*it))
1556 mysyslog(LOG_WARNING, "cgroupfs v1: Failed to initialize cpuset.\n", NULL);
1557
1558 if (!cgv1_enter("/"))
1559 mysyslog(LOG_WARNING, "cgroupfs v1: Failed to escape to init's cgroup.\n", NULL);
1560 }
1561
1562 /* Escape to root cgroup in the cgroupfs v2 hierarchy. */
1563 static void cgv2_escape(void)
1564 {
1565 if (!cgv2_enter("/"))
1566 mysyslog(LOG_WARNING, "cgroupfs v2: Failed to escape to init's cgroup.\n", NULL);
1567 }
1568
1569 /* Wrapper around cgv{1,2}_escape(). */
1570 static void cg_escape(void)
1571 {
1572 cgv1_escape();
1573 cgv2_escape();
1574 }
1575
1576 /* Get uid and gid for @user. */
1577 static bool get_uid_gid(const char *user, uid_t *uid, gid_t *gid)
1578 {
1579 struct passwd *pwent;
1580
1581 pwent = getpwnam(user);
1582 if (!pwent)
1583 return false;
1584
1585 *uid = pwent->pw_uid;
1586 *gid = pwent->pw_gid;
1587
1588 return true;
1589 }
1590
1591 /* Check if cgroup belongs to our uid and gid. If so, reuse it. */
1592 static bool cg_belongs_to_uid_gid(const char *path, uid_t uid, gid_t gid)
1593 {
1594 struct stat statbuf;
1595
1596 if (stat(path, &statbuf) < 0)
1597 return false;
1598
1599 if (!(statbuf.st_uid == uid) || !(statbuf.st_gid == gid))
1600 return false;
1601
1602 return true;
1603 }
1604
1605 /* Create cpumask from cpulist aka turn:
1606 *
1607 * 0,2-3
1608 *
1609 * into bit array
1610 *
1611 * 1 0 1 1
1612 */
1613 static uint32_t *cg_cpumask(char *buf, size_t nbits)
1614 {
1615 char *token;
1616 char *saveptr = NULL;
1617 size_t arrlen = BITS_TO_LONGS(nbits);
1618 uint32_t *bitarr = calloc(arrlen, sizeof(uint32_t));
1619 if (!bitarr)
1620 return NULL;
1621
1622 for (; (token = strtok_r(buf, ",", &saveptr)); buf = NULL) {
1623 errno = 0;
1624 unsigned start = strtoul(token, NULL, 0);
1625 unsigned end = start;
1626
1627 char *range = strchr(token, '-');
1628 if (range)
1629 end = strtoul(range + 1, NULL, 0);
1630 if (!(start <= end)) {
1631 free(bitarr);
1632 return NULL;
1633 }
1634
1635 if (end >= nbits) {
1636 free(bitarr);
1637 return NULL;
1638 }
1639
1640 while (start <= end)
1641 set_bit(start++, bitarr);
1642 }
1643
1644 return bitarr;
1645 }
1646
1647 char *string_join(const char *sep, const char **parts, bool use_as_prefix)
1648 {
1649 char *result;
1650 char **p;
1651 size_t sep_len = strlen(sep);
1652 size_t result_len = use_as_prefix * sep_len;
1653
1654 /* calculate new string length */
1655 for (p = (char **)parts; *p; p++)
1656 result_len += (p > (char **)parts) * sep_len + strlen(*p);
1657
1658 result = calloc(result_len + 1, 1);
1659 if (!result)
1660 return NULL;
1661
1662 if (use_as_prefix)
1663 strcpy(result, sep);
1664 for (p = (char **)parts; *p; p++) {
1665 if (p > (char **)parts)
1666 strcat(result, sep);
1667 strcat(result, *p);
1668 }
1669
1670 return result;
1671 }
1672
1673 /* The largest integer that can fit into long int is 2^64. This is a
1674 * 20-digit number.
1675 */
1676 #define __IN_TO_STR_LEN 21
1677 /* Turn cpumask into simple, comma-separated cpulist. */
1678 static char *cg_cpumask_to_cpulist(uint32_t *bitarr, size_t nbits)
1679 {
1680 size_t i;
1681 int ret;
1682 char numstr[__IN_TO_STR_LEN] = {0};
1683 char **cpulist = NULL;
1684
1685 for (i = 0; i <= nbits; i++) {
1686 if (is_set(i, bitarr)) {
1687 ret = snprintf(numstr, __IN_TO_STR_LEN, "%zu", i);
1688 if (ret < 0 || (size_t)ret >= __IN_TO_STR_LEN) {
1689 free_string_list(cpulist);
1690 return NULL;
1691 }
1692 must_append_string(&cpulist, numstr);
1693 }
1694 }
1695 return string_join(",", (const char **)cpulist, false);
1696 }
1697
1698 static ssize_t cg_get_max_cpus(char *cpulist)
1699 {
1700 char *c1, *c2;
1701 char *maxcpus = cpulist;
1702 size_t cpus = 0;
1703
1704 c1 = strrchr(maxcpus, ',');
1705 if (c1)
1706 c1++;
1707
1708 c2 = strrchr(maxcpus, '-');
1709 if (c2)
1710 c2++;
1711
1712 if (!c1 && !c2)
1713 c1 = maxcpus;
1714 else if (c1 > c2)
1715 c2 = c1;
1716 else if (c1 < c2)
1717 c1 = c2;
1718 else if (!c1 && c2) // The reverse case is obvs. not needed.
1719 c1 = c2;
1720
1721 /* If the above logic is correct, c1 should always hold a valid string
1722 * here.
1723 */
1724
1725 errno = 0;
1726 cpus = strtoul(c1, NULL, 0);
1727 if (errno != 0)
1728 return -1;
1729
1730 return cpus;
1731 }
1732
1733 ssize_t write_nointr(int fd, const void* buf, size_t count)
1734 {
1735 ssize_t ret;
1736 again:
1737 ret = write(fd, buf, count);
1738 if (ret < 0 && errno == EINTR)
1739 goto again;
1740 return ret;
1741 }
1742
1743 int cg_write_to_file(const char *filename, const void* buf, size_t count, bool add_newline)
1744 {
1745 int fd, saved_errno;
1746 ssize_t ret;
1747
1748 fd = open(filename, O_WRONLY | O_TRUNC | O_CREAT | O_CLOEXEC, 0666);
1749 if (fd < 0)
1750 return -1;
1751 ret = write_nointr(fd, buf, count);
1752 if (ret < 0)
1753 goto out_error;
1754 if ((size_t)ret != count)
1755 goto out_error;
1756 if (add_newline) {
1757 ret = write_nointr(fd, "\n", 1);
1758 if (ret != 1)
1759 goto out_error;
1760 }
1761 close(fd);
1762 return 0;
1763
1764 out_error:
1765 saved_errno = errno;
1766 close(fd);
1767 errno = saved_errno;
1768 return -1;
1769 }
1770
1771 static bool cg_filter_and_set_cpus(char *path, bool am_initialized)
1772 {
1773 char *lastslash, *fpath, oldv;
1774 int ret;
1775 ssize_t i;
1776
1777 ssize_t maxposs = 0, maxisol = 0;
1778 char *cpulist = NULL, *posscpus = NULL, *isolcpus = NULL;
1779 uint32_t *possmask = NULL, *isolmask = NULL;
1780 bool bret = false;
1781
1782 lastslash = strrchr(path, '/');
1783 if (!lastslash) { // bug... this shouldn't be possible
1784 lxcfs_debug("cgfsng:copy_parent_file: bad path %s", path);
1785 return bret;
1786 }
1787 oldv = *lastslash;
1788 *lastslash = '\0';
1789 fpath = must_make_path(path, "cpuset.cpus", NULL);
1790 posscpus = read_file(fpath);
1791 if (!posscpus)
1792 goto cleanup;
1793
1794 /* Get maximum number of cpus found in possible cpuset. */
1795 maxposs = cg_get_max_cpus(posscpus);
1796 if (maxposs < 0)
1797 goto cleanup;
1798
1799 isolcpus = read_file("/sys/devices/system/cpu/isolated");
1800 if (!isolcpus)
1801 goto cleanup;
1802 if (!isdigit(isolcpus[0])) {
1803 cpulist = posscpus;
1804 /* No isolated cpus but we weren't already initialized by
1805 * someone. We should simply copy the parents cpuset.cpus
1806 * values.
1807 */
1808 if (!am_initialized)
1809 goto copy_parent;
1810 /* No isolated cpus but we were already initialized by someone.
1811 * Nothing more to do for us.
1812 */
1813 bret = true;
1814 goto cleanup;
1815 }
1816
1817 /* Get maximum number of cpus found in isolated cpuset. */
1818 maxisol = cg_get_max_cpus(isolcpus);
1819 if (maxisol < 0)
1820 goto cleanup;
1821
1822 if (maxposs < maxisol)
1823 maxposs = maxisol;
1824 maxposs++;
1825
1826 possmask = cg_cpumask(posscpus, maxposs);
1827 if (!possmask)
1828 goto cleanup;
1829
1830 isolmask = cg_cpumask(isolcpus, maxposs);
1831 if (!isolmask)
1832 goto cleanup;
1833
1834 for (i = 0; i <= maxposs; i++) {
1835 if (is_set(i, isolmask) && is_set(i, possmask)) {
1836 clear_bit(i, possmask);
1837 }
1838 }
1839
1840 cpulist = cg_cpumask_to_cpulist(possmask, maxposs);
1841 if (!cpulist) /* Bug */
1842 goto cleanup;
1843
1844 copy_parent:
1845 *lastslash = oldv;
1846 fpath = must_make_path(path, "cpuset.cpus", NULL);
1847 ret = cg_write_to_file(fpath, cpulist, strlen(cpulist), false);
1848 if (!ret)
1849 bret = true;
1850
1851 cleanup:
1852 free(fpath);
1853
1854 free(isolcpus);
1855 free(isolmask);
1856
1857 if (posscpus != cpulist)
1858 free(posscpus);
1859 free(possmask);
1860
1861 free(cpulist);
1862 return bret;
1863 }
1864
1865 int read_from_file(const char *filename, void* buf, size_t count)
1866 {
1867 int fd = -1, saved_errno;
1868 ssize_t ret;
1869
1870 fd = open(filename, O_RDONLY | O_CLOEXEC);
1871 if (fd < 0)
1872 return -1;
1873
1874 if (!buf || !count) {
1875 char buf2[100];
1876 size_t count2 = 0;
1877 while ((ret = read(fd, buf2, 100)) > 0)
1878 count2 += ret;
1879 if (ret >= 0)
1880 ret = count2;
1881 } else {
1882 memset(buf, 0, count);
1883 ret = read(fd, buf, count);
1884 }
1885
1886 if (ret < 0)
1887 lxcfs_debug("read %s: %s", filename, strerror(errno));
1888
1889 saved_errno = errno;
1890 close(fd);
1891 errno = saved_errno;
1892 return ret;
1893 }
1894
1895 /* Copy contents of parent(@path)/@file to @path/@file */
1896 static bool cg_copy_parent_file(char *path, char *file)
1897 {
1898 char *lastslash, *value = NULL, *fpath, oldv;
1899 int len = 0;
1900 int ret;
1901
1902 lastslash = strrchr(path, '/');
1903 if (!lastslash) { // bug... this shouldn't be possible
1904 lxcfs_debug("cgfsng:copy_parent_file: bad path %s", path);
1905 return false;
1906 }
1907 oldv = *lastslash;
1908 *lastslash = '\0';
1909 fpath = must_make_path(path, file, NULL);
1910 len = read_from_file(fpath, NULL, 0);
1911 if (len <= 0)
1912 goto bad;
1913 value = must_alloc(len + 1);
1914 if (read_from_file(fpath, value, len) != len)
1915 goto bad;
1916 free(fpath);
1917 *lastslash = oldv;
1918 fpath = must_make_path(path, file, NULL);
1919 ret = cg_write_to_file(fpath, value, len, false);
1920 if (ret < 0)
1921 lxcfs_debug("Unable to write %s to %s", value, fpath);
1922 free(fpath);
1923 free(value);
1924 return ret >= 0;
1925
1926 bad:
1927 lxcfs_debug("Error reading '%s'", fpath);
1928 free(fpath);
1929 free(value);
1930 return false;
1931 }
1932
1933 /* In case systemd hasn't already placed us in a user slice for the cpuset v1
1934 * controller we will reside in the root cgroup. This means that
1935 * cgroup.clone_children will not have been initialized for us so we need to do
1936 * it.
1937 */
1938 static bool cgv1_handle_root_cpuset_hierarchy(struct cgv1_hierarchy *h)
1939 {
1940 char *clonechildrenpath, v;
1941
1942 if (!string_in_list(h->controllers, "cpuset"))
1943 return true;
1944
1945 clonechildrenpath = must_make_path(h->mountpoint, "cgroup.clone_children", NULL);
1946
1947 if (read_from_file(clonechildrenpath, &v, 1) < 0) {
1948 lxcfs_debug("Failed to read '%s'", clonechildrenpath);
1949 free(clonechildrenpath);
1950 return false;
1951 }
1952
1953 if (v == '1') { /* already set for us by someone else */
1954 free(clonechildrenpath);
1955 return true;
1956 }
1957
1958 if (cg_write_to_file(clonechildrenpath, "1", 1, false) < 0) {
1959 /* Set clone_children so children inherit our settings */
1960 lxcfs_debug("Failed to write 1 to %s", clonechildrenpath);
1961 free(clonechildrenpath);
1962 return false;
1963 }
1964 free(clonechildrenpath);
1965 return true;
1966 }
1967
1968 /*
1969 * Initialize the cpuset hierarchy in first directory of @gname and
1970 * set cgroup.clone_children so that children inherit settings.
1971 * Since the h->base_path is populated by init or ourselves, we know
1972 * it is already initialized.
1973 */
1974 static bool cgv1_handle_cpuset_hierarchy(struct cgv1_hierarchy *h,
1975 const char *cgroup)
1976 {
1977 char *cgpath, *clonechildrenpath, v, *slash;
1978
1979 if (!string_in_list(h->controllers, "cpuset"))
1980 return true;
1981
1982 if (*cgroup == '/')
1983 cgroup++;
1984 slash = strchr(cgroup, '/');
1985 if (slash)
1986 *slash = '\0';
1987
1988 cgpath = must_make_path(h->mountpoint, h->base_cgroup, cgroup, NULL);
1989 if (slash)
1990 *slash = '/';
1991 if (mkdir(cgpath, 0755) < 0 && errno != EEXIST) {
1992 lxcfs_debug("Failed to create '%s'", cgpath);
1993 free(cgpath);
1994 return false;
1995 }
1996 clonechildrenpath = must_make_path(cgpath, "cgroup.clone_children", NULL);
1997 if (!file_exists(clonechildrenpath)) { /* unified hierarchy doesn't have clone_children */
1998 free(clonechildrenpath);
1999 free(cgpath);
2000 return true;
2001 }
2002 if (read_from_file(clonechildrenpath, &v, 1) < 0) {
2003 lxcfs_debug("Failed to read '%s'", clonechildrenpath);
2004 free(clonechildrenpath);
2005 free(cgpath);
2006 return false;
2007 }
2008
2009 /* Make sure any isolated cpus are removed from cpuset.cpus. */
2010 if (!cg_filter_and_set_cpus(cgpath, v == '1'))
2011 return false;
2012
2013 if (v == '1') { /* already set for us by someone else */
2014 free(clonechildrenpath);
2015 free(cgpath);
2016 return true;
2017 }
2018
2019 /* copy parent's settings */
2020 if (!cg_copy_parent_file(cgpath, "cpuset.mems")) {
2021 free(cgpath);
2022 free(clonechildrenpath);
2023 return false;
2024 }
2025 free(cgpath);
2026
2027 if (cg_write_to_file(clonechildrenpath, "1", 1, false) < 0) {
2028 /* Set clone_children so children inherit our settings */
2029 lxcfs_debug("Failed to write 1 to %s", clonechildrenpath);
2030 free(clonechildrenpath);
2031 return false;
2032 }
2033 free(clonechildrenpath);
2034 return true;
2035 }
2036
2037 /* Create and chown @cgroup for all given controllers in a cgroupfs v1 hierarchy
2038 * (For example, create @cgroup for the cpu and cpuacct controller mounted into
2039 * /sys/fs/cgroup/cpu,cpuacct). Check if the path already exists and report back
2040 * to the caller in @existed.
2041 */
2042 #define __PAM_CGFS_USER "/user/"
2043 #define __PAM_CGFS_USER_LEN 6
2044 static bool cgv1_create_one(struct cgv1_hierarchy *h, const char *cgroup, uid_t uid, gid_t gid, bool *existed)
2045 {
2046 char *clean_base_cgroup, *path;
2047 char **controller;
2048 struct cgv1_hierarchy *it;
2049 bool created = false;
2050
2051 *existed = false;
2052 it = h;
2053 for (controller = it->controllers; controller && *controller;
2054 controller++) {
2055 created = false;
2056
2057 if (!cgv1_handle_cpuset_hierarchy(it, cgroup))
2058 return false;
2059
2060 /* If systemd has already created a cgroup for us, keep using
2061 * it.
2062 */
2063 if (cg_systemd_chown_existing_cgroup(it->mountpoint,
2064 it->base_cgroup, uid, gid,
2065 it->systemd_user_slice)) {
2066 return true;
2067 }
2068
2069 /* We need to make sure that we do not create an endless chain
2070 * of sub-cgroups. So we check if we have already logged in
2071 * somehow (sudo -i, su, etc.) and have created a
2072 * /user/PAM_user/idx cgroup. If so, we skip that part. For most
2073 * cgroups this is unnecessary since we use the init_cgroup
2074 * anyway, but for controllers which have an existing systemd
2075 * cgroup that does not match the current uid, this is pretty
2076 * useful.
2077 */
2078 if (strncmp(it->base_cgroup, __PAM_CGFS_USER, __PAM_CGFS_USER_LEN) == 0) {
2079 free(it->base_cgroup);
2080 it->base_cgroup = must_copy_string("/");
2081 } else {
2082 clean_base_cgroup =
2083 strstr(it->base_cgroup, __PAM_CGFS_USER);
2084 if (clean_base_cgroup)
2085 *clean_base_cgroup = '\0';
2086 }
2087
2088 path = must_make_path(it->mountpoint, it->init_cgroup, cgroup, NULL);
2089 lxcfs_debug("Constructing path: %s.\n", path);
2090 if (file_exists(path)) {
2091 bool our_cg = cg_belongs_to_uid_gid(path, uid, gid);
2092 lxcfs_debug("%s existed and does %s have our uid and gid.\n", path, our_cg ? "" : "not");
2093 free(path);
2094 if (our_cg)
2095 *existed = false;
2096 else
2097 *existed = true;
2098 return our_cg;
2099 }
2100 created = mkdir_p(it->mountpoint, path);
2101 if (!created) {
2102 free(path);
2103 continue;
2104 }
2105 if (chown(path, uid, gid) < 0)
2106 lxcfs_debug("Failed to chown %s to %d:%d: %m.\n", path,
2107 (int)uid, (int)gid);
2108 free(path);
2109 break;
2110 }
2111
2112 if (!created)
2113 return false;
2114
2115 return true;
2116 }
2117
2118 /* Try to remove @cgroup for all given controllers in a cgroupfs v1 hierarchy
2119 * (For example, try to remove @cgroup for the cpu and cpuacct controller
2120 * mounted into /sys/fs/cgroup/cpu,cpuacct). Ignores failures.
2121 */
2122 static bool cgv1_remove_one(struct cgv1_hierarchy *h, const char *cgroup)
2123 {
2124
2125 char *path;
2126
2127 /* Better safe than sorry. */
2128 if (!h->controllers)
2129 return true;
2130
2131 /* Cgroups created by systemd for us which we re-use won't be removed
2132 * here, since we're using init_cgroup + cgroup as path instead of
2133 * base_cgroup + cgroup.
2134 */
2135 path = must_make_path(h->mountpoint, h->init_cgroup, cgroup, NULL);
2136 (void)recursive_rmdir(path);
2137 free(path);
2138
2139 return true;
2140 }
2141
2142 /* Try to remove @cgroup the cgroupfs v2 hierarchy. */
2143 static bool cgv2_remove(const char *cgroup)
2144 {
2145 struct cgv2_hierarchy *v2;
2146 char *path;
2147
2148 if (!cgv2_hierarchies)
2149 return true;
2150
2151 v2 = *cgv2_hierarchies;
2152
2153 /* If we reused an already existing cgroup, don't bother trying to
2154 * remove (a potentially wrong)/the path.
2155 * Cgroups created by systemd for us which we re-use would be removed
2156 * here, since we're using base_cgroup + cgroup as path.
2157 */
2158 if (v2->systemd_user_slice)
2159 return true;
2160
2161 path = must_make_path(v2->mountpoint, v2->base_cgroup, cgroup, NULL);
2162 (void)recursive_rmdir(path);
2163 free(path);
2164
2165 return true;
2166 }
2167
2168 /* Create @cgroup in all detected cgroupfs v1 hierarchy. If the creation fails
2169 * for any cgroupfs v1 hierarchy, remove all we have created so far. Report
2170 * back, to the caller if the creation failed due to @cgroup already existing
2171 * via @existed.
2172 */
2173 static bool cgv1_create(const char *cgroup, uid_t uid, gid_t gid, bool *existed)
2174 {
2175 struct cgv1_hierarchy **it, **rev_it;
2176 bool all_created = true;
2177
2178 for (it = cgv1_hierarchies; it && *it; it++) {
2179 if (!(*it)->controllers || !(*it)->mountpoint ||
2180 !(*it)->init_cgroup || !(*it)->create_rw_cgroup)
2181 continue;
2182
2183 if (!cgv1_create_one(*it, cgroup, uid, gid, existed)) {
2184 all_created = false;
2185 break;
2186 }
2187 }
2188
2189 if (all_created)
2190 return true;
2191
2192 for (rev_it = cgv1_hierarchies; rev_it && *rev_it && (*rev_it != *it);
2193 rev_it++)
2194 cgv1_remove_one(*rev_it, cgroup);
2195
2196 return false;
2197 }
2198
2199 /* Create @cgroup in the cgroupfs v2 hierarchy. Report back, to the caller if
2200 * the creation failed due to @cgroup already existing via @existed.
2201 */
2202 static bool cgv2_create(const char *cgroup, uid_t uid, gid_t gid, bool *existed)
2203 {
2204 char *clean_base_cgroup;
2205 char *path;
2206 struct cgv2_hierarchy *v2;
2207 bool created = false;
2208
2209 *existed = false;
2210
2211 if (!cgv2_hierarchies || !(*cgv2_hierarchies)->create_rw_cgroup)
2212 return true;
2213
2214 v2 = *cgv2_hierarchies;
2215
2216 /* We can't be placed under init's cgroup for the v2 hierarchy. We need
2217 * to be placed under our current cgroup.
2218 */
2219 if (cg_systemd_chown_existing_cgroup(v2->mountpoint,
2220 v2->base_cgroup, uid, gid,
2221 v2->systemd_user_slice))
2222 return true;
2223
2224 /* We need to make sure that we do not create an endless chaing of
2225 * sub-cgroups. So we check if we have already logged in somehow (sudo
2226 * -i, su, etc.) and have created a /user/PAM_user/idx cgroup. If so, we
2227 * skip that part.
2228 */
2229 if (strncmp(v2->base_cgroup, __PAM_CGFS_USER, __PAM_CGFS_USER_LEN) == 0) {
2230 free(v2->base_cgroup);
2231 v2->base_cgroup = must_copy_string("/");
2232 } else {
2233 clean_base_cgroup = strstr(v2->base_cgroup, __PAM_CGFS_USER);
2234 if (clean_base_cgroup)
2235 *clean_base_cgroup = '\0';
2236 }
2237
2238 path = must_make_path(v2->mountpoint, v2->base_cgroup, cgroup, NULL);
2239 lxcfs_debug("Constructing path \"%s\".\n", path);
2240 if (file_exists(path)) {
2241 bool our_cg = cg_belongs_to_uid_gid(path, uid, gid);
2242 lxcfs_debug("%s existed and does %s have our uid and gid.\n", path, our_cg ? "" : "not");
2243 free(path);
2244 if (our_cg)
2245 *existed = false;
2246 else
2247 *existed = true;
2248 return our_cg;
2249 }
2250
2251 created = mkdir_p(v2->mountpoint, path);
2252 if (!created) {
2253 free(path);
2254 return false;
2255 }
2256
2257 if (chown(path, uid, gid) < 0)
2258 mysyslog(LOG_WARNING, "Failed to chown %s to %d:%d: %m.\n",
2259 path, (int)uid, (int)gid, NULL);
2260 free(path);
2261
2262 return true;
2263 }
2264
2265 /* Create writeable cgroups for @user at login. Details can be found in the
2266 * preamble/license at the top of this file.
2267 */
2268 static int handle_login(const char *user, uid_t uid, gid_t gid)
2269 {
2270 int idx = 0, ret;
2271 bool existed;
2272 char cg[MAXPATHLEN];
2273
2274 cg_escape();
2275
2276 while (idx >= 0) {
2277 ret = snprintf(cg, MAXPATHLEN, "/user/%s/%d", user, idx);
2278 if (ret < 0 || ret >= MAXPATHLEN) {
2279 mysyslog(LOG_ERR, "Username too long.\n", NULL);
2280 return PAM_SESSION_ERR;
2281 }
2282
2283 existed = false;
2284 if (!cgv2_create(cg, uid, gid, &existed)) {
2285 if (existed) {
2286 cgv2_remove(cg);
2287 idx++;
2288 continue;
2289 }
2290 mysyslog(LOG_ERR, "Failed to create a cgroup for user %s.\n", user, NULL);
2291 return PAM_SESSION_ERR;
2292 }
2293
2294 existed = false;
2295 if (!cgv1_create(cg, uid, gid, &existed)) {
2296 if (existed) {
2297 cgv2_remove(cg);
2298 idx++;
2299 continue;
2300 }
2301 mysyslog(LOG_ERR, "Failed to create a cgroup for user %s.\n", user, NULL);
2302 return PAM_SESSION_ERR;
2303 }
2304
2305 if (!cg_enter(cg)) {
2306 mysyslog( LOG_ERR, "Failed to enter user cgroup %s for user %s.\n", cg, user, NULL);
2307 return PAM_SESSION_ERR;
2308 }
2309 break;
2310 }
2311
2312 return PAM_SUCCESS;
2313 }
2314
2315 /* Try to prune cgroups we created and that now are empty from all cgroupfs v1
2316 * hierarchies.
2317 */
2318 static bool cgv1_prune_empty_cgroups(const char *user)
2319 {
2320 bool controller_removed = true;
2321 bool all_removed = true;
2322 struct cgv1_hierarchy **it;
2323
2324 for (it = cgv1_hierarchies; it && *it; it++) {
2325 int ret;
2326 char *path_base, *path_init;
2327 char **controller;
2328
2329 if (!(*it)->controllers || !(*it)->mountpoint ||
2330 !(*it)->init_cgroup || !(*it)->create_rw_cgroup)
2331 continue;
2332
2333 for (controller = (*it)->controllers; controller && *controller;
2334 controller++) {
2335 bool path_base_rm, path_init_rm;
2336
2337 path_base = must_make_path((*it)->mountpoint, (*it)->base_cgroup, "/user", user, NULL);
2338 lxcfs_debug("cgroupfs v1: Trying to prune \"%s\".\n", path_base);
2339 ret = recursive_rmdir(path_base);
2340 if (ret == -ENOENT || ret >= 0)
2341 path_base_rm = true;
2342 else
2343 path_base_rm = false;
2344 free(path_base);
2345
2346 path_init = must_make_path((*it)->mountpoint, (*it)->init_cgroup, "/user", user, NULL);
2347 lxcfs_debug("cgroupfs v1: Trying to prune \"%s\".\n", path_init);
2348 ret = recursive_rmdir(path_init);
2349 if (ret == -ENOENT || ret >= 0)
2350 path_init_rm = true;
2351 else
2352 path_init_rm = false;
2353 free(path_init);
2354
2355 if (!path_base_rm && !path_init_rm) {
2356 controller_removed = false;
2357 continue;
2358 }
2359
2360 controller_removed = true;
2361 break;
2362 }
2363 if (!controller_removed)
2364 all_removed = false;
2365 }
2366
2367 return all_removed;
2368 }
2369
2370 /* Try to prune cgroup we created and that now is empty from the cgroupfs v2
2371 * hierarchy.
2372 */
2373 static bool cgv2_prune_empty_cgroups(const char *user)
2374 {
2375 int ret;
2376 struct cgv2_hierarchy *v2;
2377 char *path_base, *path_init;
2378 bool path_base_rm, path_init_rm;
2379
2380 if (!cgv2_hierarchies)
2381 return true;
2382
2383 v2 = *cgv2_hierarchies;
2384
2385 path_base = must_make_path(v2->mountpoint, v2->base_cgroup, "/user", user, NULL);
2386 lxcfs_debug("cgroupfs v2: Trying to prune \"%s\".\n", path_base);
2387 ret = recursive_rmdir(path_base);
2388 if (ret == -ENOENT || ret >= 0)
2389 path_base_rm = true;
2390 else
2391 path_base_rm = false;
2392 free(path_base);
2393
2394 path_init = must_make_path(v2->mountpoint, v2->init_cgroup, "/user", user, NULL);
2395 lxcfs_debug("cgroupfs v2: Trying to prune \"%s\".\n", path_init);
2396 ret = recursive_rmdir(path_init);
2397 if (ret == -ENOENT || ret >= 0)
2398 path_init_rm = true;
2399 else
2400 path_init_rm = false;
2401 free(path_init);
2402
2403 if (!path_base_rm && !path_init_rm)
2404 return false;
2405
2406 return true;
2407 }
2408
2409 /* Wrapper around cgv{1,2}_prune_empty_cgroups(). */
2410 static void cg_prune_empty_cgroups(const char *user)
2411 {
2412 (void)cgv1_prune_empty_cgroups(user);
2413 (void)cgv2_prune_empty_cgroups(user);
2414 }
2415
2416 /* Free allocated information for detected cgroupfs v1 hierarchies. */
2417 static void cgv1_free_hierarchies(void)
2418 {
2419 struct cgv1_hierarchy **it;
2420
2421 if (!cgv1_hierarchies)
2422 return;
2423
2424 for (it = cgv1_hierarchies; it && *it; it++) {
2425 if ((*it)->controllers) {
2426 char **tmp;
2427 for (tmp = (*it)->controllers; tmp && *tmp; tmp++)
2428 free(*tmp);
2429
2430 free((*it)->controllers);
2431 }
2432 free((*it)->mountpoint);
2433 free((*it)->base_cgroup);
2434 free((*it)->fullcgpath);
2435 free((*it)->init_cgroup);
2436 }
2437 free(cgv1_hierarchies);
2438 }
2439
2440 /* Free allocated information for the detected cgroupfs v2 hierarchy. */
2441 static void cgv2_free_hierarchies(void)
2442 {
2443 struct cgv2_hierarchy **it;
2444
2445 if (!cgv2_hierarchies)
2446 return;
2447
2448 for (it = cgv2_hierarchies; it && *it; it++) {
2449 if ((*it)->controllers) {
2450 char **tmp;
2451 for (tmp = (*it)->controllers; tmp && *tmp; tmp++)
2452 free(*tmp);
2453
2454 free((*it)->controllers);
2455 }
2456 free((*it)->mountpoint);
2457 free((*it)->base_cgroup);
2458 free((*it)->fullcgpath);
2459 free((*it)->init_cgroup);
2460 }
2461 free(cgv2_hierarchies);
2462 }
2463
2464 /* Wrapper around cgv{1,2}_free_hierarchies(). */
2465 static void cg_exit(void)
2466 {
2467 cgv1_free_hierarchies();
2468 cgv2_free_hierarchies();
2469 }
2470
2471 int pam_sm_open_session(pam_handle_t *pamh, int flags, int argc,
2472 const char **argv)
2473 {
2474 int ret;
2475 uid_t uid = 0;
2476 gid_t gid = 0;
2477 const char *PAM_user = NULL;
2478
2479 ret = pam_get_user(pamh, &PAM_user, NULL);
2480 if (ret != PAM_SUCCESS) {
2481 mysyslog(LOG_ERR, "PAM-CGFS: couldn't get user\n", NULL);
2482 return PAM_SESSION_ERR;
2483 }
2484
2485 if (!get_uid_gid(PAM_user, &uid, &gid)) {
2486 mysyslog(LOG_ERR, "Failed to get uid and gid for %s.\n", PAM_user, NULL);
2487 return PAM_SESSION_ERR;
2488 }
2489
2490 if (!cg_init(uid, gid)) {
2491 mysyslog(LOG_ERR, "Failed to get list of controllers\n", NULL);
2492 return PAM_SESSION_ERR;
2493 }
2494
2495 /* Try to prune cgroups, that are actually empty but were still marked
2496 * as busy by the kernel so we couldn't remove them on session close.
2497 */
2498 cg_prune_empty_cgroups(PAM_user);
2499
2500 if (cg_mount_mode == CGROUP_UNKNOWN)
2501 return PAM_SESSION_ERR;
2502
2503 if (argc > 1 && strcmp(argv[0], "-c") == 0)
2504 cg_mark_to_make_rw(argv[1]);
2505
2506 return handle_login(PAM_user, uid, gid);
2507 }
2508
2509 int pam_sm_close_session(pam_handle_t *pamh, int flags, int argc,
2510 const char **argv)
2511 {
2512 int ret;
2513 uid_t uid = 0;
2514 gid_t gid = 0;
2515 const char *PAM_user = NULL;
2516
2517 ret = pam_get_user(pamh, &PAM_user, NULL);
2518 if (ret != PAM_SUCCESS) {
2519 mysyslog(LOG_ERR, "PAM-CGFS: couldn't get user\n", NULL);
2520 return PAM_SESSION_ERR;
2521 }
2522
2523 if (!get_uid_gid(PAM_user, &uid, &gid)) {
2524 mysyslog(LOG_ERR, "Failed to get uid and gid for %s.\n", PAM_user, NULL);
2525 return PAM_SESSION_ERR;
2526 }
2527
2528 if (cg_mount_mode == CGROUP_UNINITIALIZED) {
2529 if (!cg_init(uid, gid))
2530 mysyslog(LOG_ERR, "Failed to get list of controllers\n", NULL);
2531
2532 if (argc > 1 && strcmp(argv[0], "-c") == 0)
2533 cg_mark_to_make_rw(argv[1]);
2534 }
2535
2536 cg_prune_empty_cgroups(PAM_user);
2537 cg_exit();
2538
2539 return PAM_SUCCESS;
2540 }