]>
git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/pam/pam_cgfs.c
3 * Copyright © 2016 Canonical, Inc
4 * Author: Serge Hallyn <serge.hallyn@ubuntu.com>
5 * Author: Christian Brauner <christian.brauner@ubuntu.com>
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.
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:
21 * user.slice/user-uid.slice/session-n.scope
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.
30 * All requested cgroups must be mounted under /sys/fs/cgroup/$controller,
31 * no messing around with finding mountpoints.
33 * See COPYING file for details.
49 #include <linux/unistd.h>
50 #include <sys/mount.h>
51 #include <sys/param.h>
53 #include <sys/types.h>
56 #define PAM_SM_SESSION
57 #include <security/_pam_macros.h>
58 #include <security/pam_modules.h>
62 #define pam_cgfs_debug_stream(stream, format, ...) \
64 fprintf(stream, "%s: %d: %s: " format, __FILE__, __LINE__, \
65 __func__, __VA_ARGS__); \
68 #define pam_cgfs_error(format, ...) pam_cgfs_debug_stream(stderr, format, __VA_ARGS__)
71 #define pam_cgfs_debug(format, ...) pam_cgfs_error(format, __VA_ARGS__)
73 #define pam_cgfs_debug(format, ...)
76 /* Taken over modified from the kernel sources. */
77 #define NBITS 32 /* bits in uint32_t */
78 #define DIV_ROUND_UP(n, d) (((n) + (d)-1) / (d))
79 #define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr, NBITS)
81 static enum cg_mount_mode
{
86 CGROUP_UNINITIALIZED
= 3,
87 } cg_mount_mode
= CGROUP_UNINITIALIZED
;
89 /* Common helper functions. Most of these have been taken from LXC. */
90 static void append_line(char **dest
, size_t oldlen
, char *new, size_t newlen
);
91 static int append_null_to_list(void ***list
);
92 static void batch_realloc(char **mem
, size_t oldlen
, size_t newlen
);
93 static inline void clear_bit(unsigned bit
, uint32_t *bitarr
)
95 bitarr
[bit
/ NBITS
] &= ~(1 << (bit
% NBITS
));
97 static char *copy_to_eol(char *s
);
98 static void free_string_list(char **list
);
99 static char *get_mountpoint(char *line
);
100 static bool get_uid_gid(const char *user
, uid_t
*uid
, gid_t
*gid
);
101 static int handle_login(const char *user
, uid_t uid
, gid_t gid
);
102 static inline bool is_set(unsigned bit
, uint32_t *bitarr
)
104 return (bitarr
[bit
/ NBITS
] & (1 << (bit
% NBITS
))) != 0;
106 static bool is_lxcfs(const char *line
);
107 static bool is_cgv1(char *line
);
108 static bool is_cgv2(char *line
);
109 static void *must_alloc(size_t sz
);
110 static void must_add_to_list(char ***clist
, char *entry
);
111 static void must_append_controller(char **klist
, char **nlist
, char ***clist
,
113 static void must_append_string(char ***list
, char *entry
);
114 static void mysyslog(int err
, const char *format
, ...) __attribute__((sentinel
));
115 static char *read_file(char *fnam
);
116 static int read_from_file(const char *filename
, void* buf
, size_t count
);
117 static int recursive_rmdir(char *dirname
);
118 static inline void set_bit(unsigned bit
, uint32_t *bitarr
)
120 bitarr
[bit
/ NBITS
] |= (1 << (bit
% NBITS
));
122 static bool string_in_list(char **list
, const char *entry
);
123 static char *string_join(const char *sep
, const char **parts
, bool use_as_prefix
);
124 static void trim(char *s
);
125 static bool write_int(char *path
, int v
);
126 static ssize_t
write_nointr(int fd
, const void* buf
, size_t count
);
127 static int write_to_file(const char *filename
, const void *buf
, size_t count
,
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(char **list
);
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
,
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 static bool is_lxcfs(const char *line
);
156 /* cgroupfs v1 prototypes. */
157 struct cgv1_hierarchy
{
163 bool create_rw_cgroup
;
164 bool systemd_user_slice
;
167 static struct cgv1_hierarchy
**cgv1_hierarchies
;
169 static void cgv1_add_controller(char **clist
, char *mountpoint
,
170 char *base_cgroup
, char *init_cgroup
);
171 static bool cgv1_controller_in_clist(char *cgline
, char *c
);
172 static bool cgv1_controller_lists_intersect(char **l1
, char **l2
);
173 static bool cgv1_controller_list_is_dup(struct cgv1_hierarchy
**hlist
,
175 static bool cgv1_create(const char *cgroup
, uid_t uid
, gid_t gid
,
177 static bool cgv1_create_one(struct cgv1_hierarchy
*h
, const char *cgroup
,
178 uid_t uid
, gid_t gid
, bool *existed
);
179 static bool cgv1_enter(const char *cgroup
);
180 static void cgv1_escape(void);
181 static bool cgv1_get_controllers(char ***klist
, char ***nlist
);
182 static char *cgv1_get_current_cgroup(char *basecginfo
, char *controller
);
183 static char **cgv1_get_proc_mountinfo_controllers(char **klist
, char **nlist
,
185 static bool cgv1_handle_cpuset_hierarchy(struct cgv1_hierarchy
*h
,
187 static bool cgv1_handle_root_cpuset_hierarchy(struct cgv1_hierarchy
*h
);
188 static bool cgv1_init(uid_t uid
, gid_t gid
);
189 static void cgv1_mark_to_make_rw(char **clist
);
190 static char *cgv1_must_prefix_named(char *entry
);
191 static bool cgv1_prune_empty_cgroups(const char *user
);
192 static bool cgv1_remove_one(struct cgv1_hierarchy
*h
, const char *cgroup
);
193 static bool is_cgv1(char *line
);
195 /* cgroupfs v2 prototypes. */
196 struct cgv2_hierarchy
{
202 bool create_rw_cgroup
;
203 bool systemd_user_slice
;
206 /* Actually this should only be a single hierarchy. But for the sake of
207 * parallelism and because the layout of the cgroupfs v2 is still somewhat
208 * changing, we'll leave it as an array of structs.
210 static struct cgv2_hierarchy
**cgv2_hierarchies
;
212 static void cgv2_add_controller(char **clist
, char *mountpoint
,
213 char *base_cgroup
, char *init_cgroup
,
214 bool systemd_user_slice
);
215 static bool cgv2_create(const char *cgroup
, uid_t uid
, gid_t gid
,
217 static bool cgv2_enter(const char *cgroup
);
218 static void cgv2_escape(void);
219 static char *cgv2_get_current_cgroup(int pid
);
220 static bool cgv2_init(uid_t uid
, gid_t gid
);
221 static void cgv2_mark_to_make_rw(char **clist
);
222 static bool cgv2_prune_empty_cgroups(const char *user
);
223 static bool cgv2_remove(const char *cgroup
);
224 static bool is_cgv2(char *line
);
226 static int do_mkdir(const char *path
, mode_t mode
)
233 r
= mkdir(path
, mode
);
240 /* Create directory and (if necessary) its parents. */
241 static bool mkdir_parent(const char *root
, char *path
)
245 if (strlen(path
) < strlen(root
))
248 if (strlen(path
) == strlen(root
))
251 b
= path
+ strlen(root
) + 1;
253 while (*b
&& (*b
== '/'))
259 while (*e
&& *e
!= '/')
266 if (file_exists(path
))
269 if (do_mkdir(path
, 0755) < 0) {
270 pam_cgfs_debug("Failed to create %s: %s.\n", path
, strerror(errno
));
285 /* Common helper functions. Most of these have been taken from LXC. */
286 static void mysyslog(int err
, const char *format
, ...)
290 va_start(args
, format
);
291 openlog("PAM-CGFS", LOG_CONS
| LOG_PID
, LOG_AUTH
);
292 vsyslog(err
, format
, args
);
297 /* realloc() pointer in batch sizes; do not fail. */
298 #define BATCH_SIZE 50
299 static void batch_realloc(char **mem
, size_t oldlen
, size_t newlen
)
301 int newbatches
= (newlen
/ BATCH_SIZE
) + 1;
302 int oldbatches
= (oldlen
/ BATCH_SIZE
) + 1;
304 if (!*mem
|| newbatches
> oldbatches
)
305 *mem
= must_realloc(*mem
, newbatches
* BATCH_SIZE
);
308 /* Append lines as is to pointer; do not fail. */
309 static void append_line(char **dest
, size_t oldlen
, char *new, size_t newlen
)
311 size_t full
= oldlen
+ newlen
;
313 batch_realloc(dest
, oldlen
, full
+ 1);
315 memcpy(*dest
+ oldlen
, new, newlen
+ 1);
318 /* Read in whole file and return allocated pointer. */
319 static char *read_file(char *fnam
)
323 char *line
= NULL
, *buf
= NULL
;
324 size_t len
= 0, fulllen
= 0;
326 f
= fopen(fnam
, "r");
330 while ((linelen
= getline(&line
, &len
, f
)) != -1) {
331 append_line(&buf
, fulllen
, line
, linelen
);
341 /* Given a pointer to a null-terminated array of pointers, realloc to add one
342 * entry, and point the new entry to NULL. Do not fail. Return the index to the
343 * second-to-last entry - that is, the one which is now available for use
344 * (keeping the list null-terminated).
346 static int append_null_to_list(void ***list
)
351 for (; (*list
)[newentry
]; newentry
++) {
355 *list
= must_realloc(*list
, (newentry
+ 2) * sizeof(void **));
356 (*list
)[newentry
+ 1] = NULL
;
361 /* Append new entry to null-terminated array of pointer; make sure that array of
362 * pointers will still be null-terminated.
364 static void must_append_string(char ***list
, char *entry
)
369 newentry
= append_null_to_list((void ***)list
);
370 copy
= must_copy_string(entry
);
371 (*list
)[newentry
] = copy
;
374 /* Remove newlines from string. */
375 static void trim(char *s
)
377 size_t len
= strlen(s
);
379 while ((len
> 0) && s
[len
- 1] == '\n')
383 /* Allocate pointer; do not fail. */
384 static void *must_alloc(size_t sz
)
386 return must_realloc(NULL
, sz
);
389 /* Make allocated copy of string. End of string is taken to be '\n'. */
390 static char *copy_to_eol(char *s
)
392 char *newline
, *sret
;
395 newline
= strchr(s
, '\n');
400 sret
= must_alloc(len
+ 1);
401 memcpy(sret
, s
, len
);
407 /* Check if given entry under /proc/<pid>/mountinfo is a fuse.lxcfs mount. */
408 static bool is_lxcfs(const char *line
)
410 char *p
= strstr(line
, " - ");
414 return strncmp(p
, " - fuse.lxcfs ", 14) == 0;
417 /* Check if given entry under /proc/<pid>/mountinfo is a cgroupfs v1 mount. */
418 static bool is_cgv1(char *line
)
420 char *p
= strstr(line
, " - ");
424 return strncmp(p
, " - cgroup ", 10) == 0;
427 /* Check if given entry under /proc/<pid>/mountinfo is a cgroupfs v2 mount. */
428 static bool is_cgv2(char *line
)
430 char *p
= strstr(line
, " - ");
434 return strncmp(p
, " - cgroup2 ", 11) == 0;
437 /* Given a null-terminated array of strings, check whether @entry is one of the
440 static bool string_in_list(char **list
, const char *entry
)
444 for (it
= list
; it
&& *it
; it
++)
445 if (strcmp(*it
, entry
) == 0)
452 * Creates a null-terminated array of strings, made by splitting the entries in
453 * @str on each @sep. Caller is responsible for calling free_string_list.
455 static char **make_string_list(const char *str
, const char *sep
)
458 char *saveptr
= NULL
;
461 copy
= must_copy_string(str
);
463 for (tok
= strtok_r(copy
, sep
, &saveptr
); tok
;
464 tok
= strtok_r(NULL
, sep
, &saveptr
))
465 must_add_to_list(&clist
, tok
);
472 /* Gets the length of a null-terminated array of strings. */
473 static size_t string_list_length(char **list
)
478 for (it
= list
; it
&& *it
; it
++)
484 /* Free null-terminated array of strings. */
485 static void free_string_list(char **list
)
489 for (it
= list
; it
&& *it
; it
++)
494 /* Write single integer to file. */
495 static bool write_int(char *path
, int v
)
500 f
= fopen(path
, "w");
504 if (fprintf(f
, "%d\n", v
) < 0)
513 /* Recursively remove directory and its parents. */
514 static int recursive_rmdir(char *dirname
)
516 struct dirent
*direntp
;
520 dir
= opendir(dirname
);
524 while ((direntp
= readdir(dir
))) {
528 if (!strcmp(direntp
->d_name
, ".") ||
529 !strcmp(direntp
->d_name
, ".."))
532 pathname
= must_make_path(dirname
, direntp
->d_name
, NULL
);
534 if (lstat(pathname
, &st
)) {
536 pam_cgfs_debug("Failed to stat %s.\n", pathname
);
541 if (!S_ISDIR(st
.st_mode
))
544 if (recursive_rmdir(pathname
) < 0)
550 if (rmdir(dirname
) < 0) {
552 pam_cgfs_debug("Failed to delete %s: %s.\n", dirname
, strerror(errno
));
556 if (closedir(dir
) < 0) {
558 pam_cgfs_debug("Failed to delete %s: %s.\n", dirname
, strerror(errno
));
565 /* Add new entry to null-terminated array of pointers. Make sure array is still
568 static void must_add_to_list(char ***clist
, char *entry
)
572 newentry
= append_null_to_list((void ***)clist
);
573 (*clist
)[newentry
] = must_copy_string(entry
);
576 /* Get mountpoint from a /proc/<pid>/mountinfo line. */
577 static char *get_mountpoint(char *line
)
585 for (i
= 0; i
< 4; i
++) {
597 sret
= must_alloc(len
+ 1);
598 memcpy(sret
, p
, len
);
604 /* Create list of cgroupfs v1 controller found under /proc/self/cgroup. Skips
605 * the 0::/some/path cgroupfs v2 hierarchy listed. Splits controllers into
606 * kernel controllers (@klist) and named controllers (@nlist).
608 static bool cgv1_get_controllers(char ***klist
, char ***nlist
)
614 f
= fopen("/proc/self/cgroup", "r");
618 while (getline(&line
, &len
, f
) != -1) {
620 char *saveptr
= NULL
;
622 p
= strchr(line
, ':');
632 /* Skip the v2 hierarchy. */
636 for (tok
= strtok_r(p
, ",", &saveptr
); tok
;
637 tok
= strtok_r(NULL
, ",", &saveptr
)) {
638 if (strncmp(tok
, "name=", 5) == 0)
639 must_append_string(nlist
, tok
);
641 must_append_string(klist
, tok
);
651 /* Get list of controllers for cgroupfs v2 hierarchy by looking at
652 * cgroup.controllers and/or cgroup.subtree_control of a given (parent) cgroup.
653 static bool cgv2_get_controllers(char ***klist)
659 /* Get current cgroup from /proc/self/cgroup for the cgroupfs v2 hierarchy. */
660 static char *cgv2_get_current_cgroup(int pid
)
664 char *current_cgroup
;
666 /* The largest integer that can fit into long int is 2^64. This is a
667 * 20-digit number. */
668 #define __PIDLEN /* /proc */ 5 + /* /pid-to-str */ 21 + /* /cgroup */ 7 + /* \0 */ 1
671 ret
= snprintf(path
, __PIDLEN
, "/proc/%d/cgroup", pid
);
672 if (ret
< 0 || ret
>= __PIDLEN
)
675 cgroups_v2
= read_file(path
);
679 current_cgroup
= strstr(cgroups_v2
, "0::/");
683 current_cgroup
= current_cgroup
+ 3;
684 copy
= copy_to_eol(current_cgroup
);
696 /* Given two null-terminated lists of strings, return true if any string is in
699 static bool cgv1_controller_lists_intersect(char **l1
, char **l2
)
706 for (it
= l1
; it
&& *it
; it
++)
707 if (string_in_list(l2
, *it
))
713 /* For a null-terminated list of controllers @clist, return true if any of those
714 * controllers is already listed the null-terminated list of hierarchies @hlist.
715 * Realistically, if one is present, all must be present.
717 static bool cgv1_controller_list_is_dup(struct cgv1_hierarchy
**hlist
, char **clist
)
719 struct cgv1_hierarchy
**it
;
721 for (it
= hlist
; it
&& *it
; it
++)
722 if ((*it
)->controllers
)
723 if (cgv1_controller_lists_intersect((*it
)->controllers
, clist
))
729 /* Set boolean to mark controllers under which we are supposed create a
732 static void cgv1_mark_to_make_rw(char **clist
)
734 struct cgv1_hierarchy
**it
;
736 for (it
= cgv1_hierarchies
; it
&& *it
; it
++)
737 if ((*it
)->controllers
)
738 if (cgv1_controller_lists_intersect((*it
)->controllers
, clist
) ||
739 string_in_list(clist
, "all"))
740 (*it
)->create_rw_cgroup
= true;
743 /* Set boolean to mark whether we are supposed to create a writeable cgroup in
744 * the cgroupfs v2 hierarchy.
746 static void cgv2_mark_to_make_rw(char **clist
)
748 if (string_in_list(clist
, "unified") || string_in_list(clist
, "all"))
749 if (cgv2_hierarchies
)
750 (*cgv2_hierarchies
)->create_rw_cgroup
= true;
753 /* Wrapper around cgv{1,2}_mark_to_make_rw(). */
754 static void cg_mark_to_make_rw(char **clist
)
756 cgv1_mark_to_make_rw(clist
);
757 cgv2_mark_to_make_rw(clist
);
760 /* Prefix any named controllers with "name=", e.g. "name=systemd". */
761 static char *cgv1_must_prefix_named(char *entry
)
768 s
= must_alloc(len
+ 6);
770 ret
= snprintf(s
, len
+ 6, "name=%s", entry
);
771 if (ret
< 0 || (size_t)ret
>= (len
+ 6))
777 /* Append kernel controller in @klist or named controller in @nlist to @clist */
778 static void must_append_controller(char **klist
, char **nlist
, char ***clist
, char *entry
)
783 if (string_in_list(klist
, entry
) && string_in_list(nlist
, entry
))
786 newentry
= append_null_to_list((void ***)clist
);
788 if (strncmp(entry
, "name=", 5) == 0)
789 copy
= must_copy_string(entry
);
790 else if (string_in_list(klist
, entry
))
791 copy
= must_copy_string(entry
);
793 copy
= cgv1_must_prefix_named(entry
);
795 (*clist
)[newentry
] = copy
;
798 /* Get the controllers from a mountinfo line. There are other ways we could get
799 * this info. For lxcfs, field 3 is /cgroup/controller-list. For cgroupfs, we
800 * could parse the mount options. But we simply assume that the mountpoint must
801 * be /sys/fs/cgroup/controller-list
803 static char **cgv1_get_proc_mountinfo_controllers(char **klist
, char **nlist
, char *line
)
807 char *saveptr
= NULL
;
812 for (i
= 0; i
< 4; i
++) {
821 if (strncmp(p
, "/sys/fs/cgroup/", 15) != 0)
831 for (tok
= strtok_r(p
, ",", &saveptr
); tok
;
832 tok
= strtok_r(NULL
, ",", &saveptr
))
833 must_append_controller(klist
, nlist
, &aret
, tok
);
838 /* Check if a cgroupfs v2 controller is present in the string @cgline. */
839 static bool cgv1_controller_in_clist(char *cgline
, char *c
)
842 char *tok
, *eol
, *tmp
;
843 char *saveptr
= NULL
;
845 eol
= strchr(cgline
, ':');
850 tmp
= alloca(len
+ 1);
851 memcpy(tmp
, cgline
, len
);
854 for (tok
= strtok_r(tmp
, ",", &saveptr
); tok
;
855 tok
= strtok_r(NULL
, ",", &saveptr
)) {
856 if (strcmp(tok
, c
) == 0)
862 /* Get current cgroup from the /proc/<pid>/cgroup file passed in via @basecginfo
863 * of a given cgv1 controller passed in via @controller.
865 static char *cgv1_get_current_cgroup(char *basecginfo
, char *controller
)
877 if (cgv1_controller_in_clist(p
, controller
)) {
883 return copy_to_eol(p
);
895 /* Remove /init.scope from string @cg. This will mostly affect systemd-based
898 #define INIT_SCOPE "/init.scope"
899 static void cg_systemd_prune_init_scope(char *cg
)
906 point
= cg
+ strlen(cg
) - strlen(INIT_SCOPE
);
910 if (strcmp(point
, INIT_SCOPE
) == 0) {
918 /* Add new info about a mounted cgroupfs v1 hierarchy. Includes the controllers
919 * mounted into that hierarchy (e.g. cpu,cpuacct), the mountpoint of that
920 * hierarchy (/sys/fs/cgroup/<controller>, the base cgroup of the current
921 * process gathered from /proc/self/cgroup, and the init cgroup of PID1 gathered
922 * from /proc/1/cgroup.
924 static void cgv1_add_controller(char **clist
, char *mountpoint
, char *base_cgroup
, char *init_cgroup
)
926 struct cgv1_hierarchy
*new;
929 new = must_alloc(sizeof(*new));
930 new->controllers
= clist
;
931 new->mountpoint
= mountpoint
;
932 new->base_cgroup
= base_cgroup
;
933 new->fullcgpath
= NULL
;
934 new->create_rw_cgroup
= false;
935 new->init_cgroup
= init_cgroup
;
936 new->systemd_user_slice
= false;
938 newentry
= append_null_to_list((void ***)&cgv1_hierarchies
);
939 cgv1_hierarchies
[newentry
] = new;
942 /* Add new info about the mounted cgroupfs v2 hierarchy. Can (but doesn't
943 * currently) include the controllers mounted into the hierarchy (e.g. memory,
944 * pids, blkio), the mountpoint of that hierarchy (Should usually be
945 * /sys/fs/cgroup but some init systems seems to think it might be a good idea
946 * to also mount empty cgroupfs v2 hierarchies at /sys/fs/cgroup/systemd.), the
947 * base cgroup of the current process gathered from /proc/self/cgroup, and the
948 * init cgroup of PID1 gathered from /proc/1/cgroup.
950 static void cgv2_add_controller(char **clist
, char *mountpoint
, char *base_cgroup
, char *init_cgroup
, bool systemd_user_slice
)
952 struct cgv2_hierarchy
*new;
955 new = must_alloc(sizeof(*new));
956 new->controllers
= clist
;
957 new->mountpoint
= mountpoint
;
958 new->base_cgroup
= base_cgroup
;
959 new->fullcgpath
= NULL
;
960 new->create_rw_cgroup
= false;
961 new->init_cgroup
= init_cgroup
;
962 new->systemd_user_slice
= systemd_user_slice
;
964 newentry
= append_null_to_list((void ***)&cgv2_hierarchies
);
965 cgv2_hierarchies
[newentry
] = new;
968 /* In Ubuntu 14.04, the paths created for us were
969 * '/user/$uid.user/$something.session' This can be merged better with
970 * systemd_created_slice_for_us(), but keeping it separate makes it easier to
971 * reason about the correctness.
973 static bool cg_systemd_under_user_slice_1(const char *in
, uid_t uid
)
981 copy
= must_copy_string(in
);
982 if (strlen(copy
) < strlen("/user/1.user/1.session"))
984 p
= copy
+ strlen(copy
) - 1;
986 /* skip any trailing '/' (shouldn't be any, but be sure) */
987 while (p
>= copy
&& *p
== '/')
992 /* Get last path element */
993 while (p
>= copy
&& *p
!= '/')
997 /* make sure it is something.session */
999 if (len
< strlen("1.session") ||
1000 strncmp(p
+ 1 + len
- 8, ".session", 8) != 0)
1003 /* ok last path piece checks out, now check the second to last */
1005 while (p
>= copy
&& *(--p
) != '/')
1007 if (sscanf(p
+ 1, "%d.user/", &id
) != 1)
1020 /* So long as our path relative to init starts with /user.slice/user-$uid.slice,
1021 * assume it belongs to $uid and chown it
1023 static bool cg_systemd_under_user_slice_2(const char *base_cgroup
,
1024 const char *init_cgroup
, uid_t uid
)
1028 size_t curlen
, initlen
;
1030 curlen
= strlen(base_cgroup
);
1031 initlen
= strlen(init_cgroup
);
1032 if (curlen
<= initlen
)
1035 if (strncmp(base_cgroup
, init_cgroup
, initlen
) != 0)
1038 ret
= snprintf(buf
, 100, "/user.slice/user-%d.slice/", (int)uid
);
1039 if (ret
< 0 || ret
>= 100)
1043 initlen
= 0; // skip the '/'
1045 return strncmp(base_cgroup
+ initlen
, buf
, strlen(buf
)) == 0;
1048 /* The systemd-created path is: user-$uid.slice/session-c$session.scope. If that
1049 * is not the end of our systemd path, then we're not part of the PAM call that
1050 * created that path.
1052 * The last piece is chowned to $uid, the user- part not.
1053 * Note: If the user creates paths that look like what we're looking for to
1055 * - they fool us, we create new cgroups, and they get auto-logged-out.
1056 * - they fool a root sudo, systemd cgroup is not changed but chowned, and they
1057 * lose ownership of their cgroups
1059 static bool cg_systemd_created_user_slice(const char *base_cgroup
,
1060 const char *init_cgroup
,
1061 const char *in
, uid_t uid
)
1069 copy
= must_copy_string(in
);
1071 /* An old version of systemd has already created a cgroup for us. */
1072 if (cg_systemd_under_user_slice_1(in
, uid
))
1075 /* A new version of systemd has already created a cgroup for us. */
1076 if (cg_systemd_under_user_slice_2(base_cgroup
, init_cgroup
, uid
))
1079 if (strlen(copy
) < strlen("/user-0.slice/session-0.scope"))
1082 p
= copy
+ strlen(copy
) - 1;
1083 /* Skip any trailing '/' (shouldn't be any, but be sure). */
1084 while (p
>= copy
&& *p
== '/')
1090 /* Get last path element */
1091 while (p
>= copy
&& *p
!= '/')
1097 /* Make sure it is session-something.scope. */
1098 len
= strlen(p
+ 1);
1099 if (strncmp(p
+ 1, "session-", strlen("session-")) != 0 ||
1100 strncmp(p
+ 1 + len
- 6, ".scope", 6) != 0)
1103 /* Ok last path piece checks out, now check the second to last. */
1105 while (p
>= copy
&& *(--p
) != '/')
1108 if (sscanf(p
+ 1, "user-%d.slice/", &id
) != 1)
1121 /* Chown existing cgroup that systemd has already created for us. */
1122 static bool cg_systemd_chown_existing_cgroup(const char *mountpoint
,
1123 const char *base_cgroup
, uid_t uid
,
1124 gid_t gid
, bool systemd_user_slice
)
1128 if (!systemd_user_slice
)
1131 path
= must_make_path(mountpoint
, base_cgroup
, NULL
);
1133 /* A cgroup within name=systemd has already been created. So we only
1136 if (chown(path
, uid
, gid
) < 0)
1137 mysyslog(LOG_WARNING
, "Failed to chown %s to %d:%d: %s.\n",
1138 path
, (int)uid
, (int)gid
, strerror(errno
), NULL
);
1139 pam_cgfs_debug("Chowned %s to %d:%d.\n", path
, (int)uid
, (int)gid
);
1145 /* Detect and store information about cgroupfs v1 hierarchies. */
1146 static bool cgv1_init(uid_t uid
, gid_t gid
)
1149 struct cgv1_hierarchy
**it
;
1152 char **klist
= NULL
, **nlist
= NULL
;
1155 basecginfo
= read_file("/proc/self/cgroup");
1159 f
= fopen("/proc/self/mountinfo", "r");
1165 cgv1_get_controllers(&klist
, &nlist
);
1167 while (getline(&line
, &len
, f
) != -1) {
1168 char **controller_list
= NULL
;
1169 char *mountpoint
, *base_cgroup
;
1171 if (is_lxcfs(line
) || !is_cgv1(line
))
1174 controller_list
= cgv1_get_proc_mountinfo_controllers(klist
, nlist
, line
);
1175 if (!controller_list
)
1178 if (cgv1_controller_list_is_dup(cgv1_hierarchies
,
1180 free(controller_list
);
1184 mountpoint
= get_mountpoint(line
);
1186 free_string_list(controller_list
);
1190 base_cgroup
= cgv1_get_current_cgroup(basecginfo
, controller_list
[0]);
1192 free_string_list(controller_list
);
1197 pam_cgfs_debug("Detected cgroupfs v1 controller \"%s\" with "
1198 "mountpoint \"%s\" and cgroup \"%s\".\n",
1199 controller_list
[0], mountpoint
, base_cgroup
);
1200 cgv1_add_controller(controller_list
, mountpoint
, base_cgroup
,
1203 free_string_list(klist
);
1204 free_string_list(nlist
);
1209 /* Retrieve init cgroup path for all controllers. */
1210 basecginfo
= read_file("/proc/1/cgroup");
1214 for (it
= cgv1_hierarchies
; it
&& *it
; it
++) {
1215 if ((*it
)->controllers
) {
1216 char *init_cgroup
, *user_slice
;
1217 /* We've already stored the controller and received its
1218 * current cgroup. If we now fail to retrieve its init
1219 * cgroup, we should probably fail.
1221 init_cgroup
= cgv1_get_current_cgroup(basecginfo
, (*it
)->controllers
[0]);
1226 cg_systemd_prune_init_scope(init_cgroup
);
1227 (*it
)->init_cgroup
= init_cgroup
;
1228 pam_cgfs_debug("cgroupfs v1 controller \"%s\" has init "
1230 (*(*it
)->controllers
), init_cgroup
);
1231 /* Check whether systemd has already created a cgroup
1234 user_slice
= must_make_path((*it
)->mountpoint
, (*it
)->base_cgroup
, NULL
);
1235 if (cg_systemd_created_user_slice((*it
)->base_cgroup
, (*it
)->init_cgroup
, user_slice
, uid
))
1236 (*it
)->systemd_user_slice
= true;
1244 /* Check whether @path is a cgroupfs v1 or cgroupfs v2 mount. Returns -1 if
1245 * statfs fails. If @path is null /sys/fs/cgroup is checked.
1247 static inline int cg_get_version_of_mntpt(const char *path
)
1249 if (has_fs_type(path
, CGROUP_SUPER_MAGIC
))
1252 if (has_fs_type(path
, CGROUP2_SUPER_MAGIC
))
1258 /* Detect and store information about the cgroupfs v2 hierarchy. Currently only
1259 * deals with the empty v2 hierachy as we do not retrieve enabled controllers.
1261 static bool cgv2_init(uid_t uid
, gid_t gid
)
1265 char *current_cgroup
= NULL
, *init_cgroup
= NULL
;
1270 current_cgroup
= cgv2_get_current_cgroup(getpid());
1271 if (!current_cgroup
) {
1272 /* No v2 hierarchy present. We're done. */
1277 init_cgroup
= cgv2_get_current_cgroup(1);
1279 /* If we're here and didn't fail already above, then something's
1280 * certainly wrong, so error this time.
1284 cg_systemd_prune_init_scope(init_cgroup
);
1286 /* Check if the v2 hierarchy is mounted at its standard location.
1287 * If so we can skip the rest of the work here. Although the unified
1288 * hierarchy can be mounted multiple times, each of those mountpoints
1289 * will expose identical information.
1291 if (cg_get_version_of_mntpt("/sys/fs/cgroup") == 2) {
1293 bool has_user_slice
= false;
1295 mountpoint
= must_copy_string("/sys/fs/cgroup");
1299 user_slice
= must_make_path(mountpoint
, current_cgroup
, NULL
);
1300 if (cg_systemd_created_user_slice(current_cgroup
, init_cgroup
, user_slice
, uid
))
1301 has_user_slice
= true;
1304 cgv2_add_controller(NULL
, mountpoint
, current_cgroup
, init_cgroup
, has_user_slice
);
1310 f
= fopen("/proc/self/mountinfo", "r");
1314 /* we support simple cgroup mounts and lxcfs mounts */
1315 while (getline(&line
, &len
, f
) != -1) {
1317 bool has_user_slice
= false;
1321 mountpoint
= get_mountpoint(line
);
1325 user_slice
= must_make_path(mountpoint
, current_cgroup
, NULL
);
1326 if (cg_systemd_created_user_slice(current_cgroup
, init_cgroup
, user_slice
, uid
))
1327 has_user_slice
= true;
1330 cgv2_add_controller(NULL
, mountpoint
, current_cgroup
, init_cgroup
, has_user_slice
);
1331 /* Although the unified hierarchy can be mounted multiple times,
1332 * each of those mountpoints will expose identical information.
1333 * So let the first mountpoint we find, win.
1339 pam_cgfs_debug("Detected cgroupfs v2 hierarchy at mountpoint \"%s\" with "
1340 "current cgroup \"%s\" and init cgroup \"%s\".\n",
1341 mountpoint
, current_cgroup
, init_cgroup
);
1351 /* Detect and store information about mounted cgroupfs v1 hierarchies and the
1352 * cgroupfs v2 hierarchy.
1353 * Detect whether we are on a pure cgroupfs v1, cgroupfs v2, or mixed system,
1354 * where some controllers are mounted into their standard cgroupfs v1 locations
1355 * (/sys/fs/cgroup/<controller>) and others are mounted into the cgroupfs v2
1356 * hierarchy (/sys/fs/cgroup).
1358 static bool cg_init(uid_t uid
, gid_t gid
)
1360 if (!cgv1_init(uid
, gid
))
1363 if (!cgv2_init(uid
, gid
))
1366 if (cgv1_hierarchies
&& cgv2_hierarchies
) {
1367 cg_mount_mode
= CGROUP_MIXED
;
1368 pam_cgfs_debug("%s\n", "Detected cgroupfs v1 and v2 hierarchies.");
1369 } else if (cgv1_hierarchies
&& !cgv2_hierarchies
) {
1370 cg_mount_mode
= CGROUP_PURE_V1
;
1371 pam_cgfs_debug("%s\n", "Detected cgroupfs v1 hierarchies.");
1372 } else if (cgv2_hierarchies
&& !cgv1_hierarchies
) {
1373 cg_mount_mode
= CGROUP_PURE_V2
;
1374 pam_cgfs_debug("%s\n", "Detected cgroupfs v2 hierarchies.");
1376 cg_mount_mode
= CGROUP_UNKNOWN
;
1377 mysyslog(LOG_ERR
, "Could not detect cgroupfs hierarchy.\n", NULL
);
1380 if (cg_mount_mode
== CGROUP_UNKNOWN
)
1386 /* Try to move/migrate us into @cgroup in a cgroupfs v1 hierarchy. */
1387 static bool cgv1_enter(const char *cgroup
)
1389 struct cgv1_hierarchy
**it
;
1391 for (it
= cgv1_hierarchies
; it
&& *it
; it
++) {
1393 bool entered
= false;
1395 if (!(*it
)->controllers
|| !(*it
)->mountpoint
||
1396 !(*it
)->init_cgroup
|| !(*it
)->create_rw_cgroup
)
1399 for (controller
= (*it
)->controllers
; controller
&& *controller
;
1403 /* We've already been placed in a user slice, so we
1404 * don't need to enter the cgroup again.
1406 if ((*it
)->systemd_user_slice
) {
1411 path
= must_make_path((*it
)->mountpoint
,
1416 if (!file_exists(path
)) {
1418 path
= must_make_path((*it
)->mountpoint
,
1424 pam_cgfs_debug("Attempting to enter cgroupfs v1 hierarchy in \"%s\" cgroup.\n", path
);
1425 entered
= write_int(path
, (int)getpid());
1430 pam_cgfs_debug("Failed to enter cgroupfs v1 hierarchy in \"%s\" cgroup.\n", path
);
1440 /* Try to move/migrate us into @cgroup in the cgroupfs v2 hierarchy. */
1441 static bool cgv2_enter(const char *cgroup
)
1443 struct cgv2_hierarchy
*v2
;
1445 bool entered
= false;
1447 if (!cgv2_hierarchies
)
1450 v2
= *cgv2_hierarchies
;
1452 if (!v2
->mountpoint
|| !v2
->base_cgroup
)
1455 if (!v2
->create_rw_cgroup
|| v2
->systemd_user_slice
)
1458 path
= must_make_path(v2
->mountpoint
, v2
->base_cgroup
, cgroup
, "/cgroup.procs", NULL
);
1459 pam_cgfs_debug("Attempting to enter cgroupfs v2 hierarchy in cgroup \"%s\".\n", path
);
1460 entered
= write_int(path
, (int)getpid());
1462 pam_cgfs_debug("Failed to enter cgroupfs v2 hierarchy in cgroup \"%s\".\n", path
);
1472 /* Wrapper around cgv{1,2}_enter(). */
1473 static bool cg_enter(const char *cgroup
)
1475 if (!cgv1_enter(cgroup
)) {
1476 mysyslog(LOG_WARNING
, "cgroupfs v1: Failed to enter cgroups.\n", NULL
);
1480 if (!cgv2_enter(cgroup
)) {
1481 mysyslog(LOG_WARNING
, "cgroupfs v2: Failed to enter cgroups.\n", NULL
);
1488 /* Escape to root cgroup in all detected cgroupfs v1 hierarchies. */
1489 static void cgv1_escape(void)
1491 struct cgv1_hierarchy
**it
;
1493 /* In case systemd hasn't already placed us in a user slice for the
1494 * cpuset v1 controller we will reside in the root cgroup. This means
1495 * that cgroup.clone_children will not have been initialized for us so
1498 for (it
= cgv1_hierarchies
; it
&& *it
; it
++)
1499 if (!cgv1_handle_root_cpuset_hierarchy(*it
))
1500 mysyslog(LOG_WARNING
, "cgroupfs v1: Failed to initialize cpuset.\n", NULL
);
1502 if (!cgv1_enter("/"))
1503 mysyslog(LOG_WARNING
, "cgroupfs v1: Failed to escape to init's cgroup.\n", NULL
);
1506 /* Escape to root cgroup in the cgroupfs v2 hierarchy. */
1507 static void cgv2_escape(void)
1509 if (!cgv2_enter("/"))
1510 mysyslog(LOG_WARNING
, "cgroupfs v2: Failed to escape to init's cgroup.\n", NULL
);
1513 /* Wrapper around cgv{1,2}_escape(). */
1514 static void cg_escape(void)
1520 /* Get uid and gid for @user. */
1521 static bool get_uid_gid(const char *user
, uid_t
*uid
, gid_t
*gid
)
1523 struct passwd
*pwent
;
1525 pwent
= getpwnam(user
);
1529 *uid
= pwent
->pw_uid
;
1530 *gid
= pwent
->pw_gid
;
1535 /* Check if cgroup belongs to our uid and gid. If so, reuse it. */
1536 static bool cg_belongs_to_uid_gid(const char *path
, uid_t uid
, gid_t gid
)
1538 struct stat statbuf
;
1540 if (stat(path
, &statbuf
) < 0)
1543 if (!(statbuf
.st_uid
== uid
) || !(statbuf
.st_gid
== gid
))
1549 /* Create cpumask from cpulist aka turn:
1557 static uint32_t *cg_cpumask(char *buf
, size_t nbits
)
1560 char *saveptr
= NULL
;
1561 size_t arrlen
= BITS_TO_LONGS(nbits
);
1562 uint32_t *bitarr
= calloc(arrlen
, sizeof(uint32_t));
1566 for (; (token
= strtok_r(buf
, ",", &saveptr
)); buf
= NULL
) {
1568 unsigned start
= strtoul(token
, NULL
, 0);
1569 unsigned end
= start
;
1571 char *range
= strchr(token
, '-');
1573 end
= strtoul(range
+ 1, NULL
, 0);
1574 if (!(start
<= end
)) {
1584 while (start
<= end
)
1585 set_bit(start
++, bitarr
);
1591 static char *string_join(const char *sep
, const char **parts
, bool use_as_prefix
)
1595 size_t sep_len
= strlen(sep
);
1596 size_t result_len
= use_as_prefix
* sep_len
;
1601 /* calculate new string length */
1602 for (p
= (char **)parts
; *p
; p
++)
1603 result_len
+= (p
> (char **)parts
) * sep_len
+ strlen(*p
);
1605 result
= calloc(result_len
+ 1, sizeof(char));
1610 strcpy(result
, sep
);
1611 for (p
= (char **)parts
; *p
; p
++) {
1612 if (p
> (char **)parts
)
1613 strcat(result
, sep
);
1620 /* The largest integer that can fit into long int is 2^64. This is a
1623 #define __IN_TO_STR_LEN 21
1624 /* Turn cpumask into simple, comma-separated cpulist. */
1625 static char *cg_cpumask_to_cpulist(uint32_t *bitarr
, size_t nbits
)
1629 char numstr
[__IN_TO_STR_LEN
] = {0};
1630 char **cpulist
= NULL
;
1632 for (i
= 0; i
<= nbits
; i
++) {
1633 if (is_set(i
, bitarr
)) {
1634 ret
= snprintf(numstr
, __IN_TO_STR_LEN
, "%zu", i
);
1635 if (ret
< 0 || (size_t)ret
>= __IN_TO_STR_LEN
) {
1636 free_string_list(cpulist
);
1639 must_append_string(&cpulist
, numstr
);
1642 return string_join(",", (const char **)cpulist
, false);
1645 static ssize_t
cg_get_max_cpus(char *cpulist
)
1648 char *maxcpus
= cpulist
;
1651 c1
= strrchr(maxcpus
, ',');
1655 c2
= strrchr(maxcpus
, '-');
1664 /* If the above logic is correct, c1 should always hold a valid string
1669 cpus
= strtoul(c1
, NULL
, 0);
1676 static ssize_t
write_nointr(int fd
, const void* buf
, size_t count
)
1680 ret
= write(fd
, buf
, count
);
1681 if (ret
< 0 && errno
== EINTR
)
1686 static int write_to_file(const char *filename
, const void* buf
, size_t count
, bool add_newline
)
1688 int fd
, saved_errno
;
1691 fd
= open(filename
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_CLOEXEC
, 0666);
1694 ret
= write_nointr(fd
, buf
, count
);
1697 if ((size_t)ret
!= count
)
1700 ret
= write_nointr(fd
, "\n", 1);
1708 saved_errno
= errno
;
1710 errno
= saved_errno
;
1714 #define __ISOL_CPUS "/sys/devices/system/cpu/isolated"
1715 static bool cg_filter_and_set_cpus(char *path
, bool am_initialized
)
1717 char *lastslash
, *fpath
, oldv
;
1721 ssize_t maxposs
= 0, maxisol
= 0;
1722 char *cpulist
= NULL
, *posscpus
= NULL
, *isolcpus
= NULL
;
1723 uint32_t *possmask
= NULL
, *isolmask
= NULL
;
1724 bool bret
= false, flipped_bit
= false;
1726 lastslash
= strrchr(path
, '/');
1727 if (!lastslash
) { // bug... this shouldn't be possible
1728 pam_cgfs_debug("Invalid path: %s.\n", path
);
1733 fpath
= must_make_path(path
, "cpuset.cpus", NULL
);
1734 posscpus
= read_file(fpath
);
1736 pam_cgfs_debug("Could not read file: %s.\n", fpath
);
1740 /* Get maximum number of cpus found in possible cpuset. */
1741 maxposs
= cg_get_max_cpus(posscpus
);
1745 if (!file_exists(__ISOL_CPUS
)) {
1746 /* This system doesn't expose isolated cpus. */
1747 pam_cgfs_debug("%s", "Path: "__ISOL_CPUS
" to read isolated cpus from does not exist.\n");
1749 /* No isolated cpus but we weren't already initialized by
1750 * someone. We should simply copy the parents cpuset.cpus
1753 if (!am_initialized
) {
1754 pam_cgfs_debug("%s", "Copying cpuset of parent cgroup.\n");
1757 /* No isolated cpus but we were already initialized by someone.
1758 * Nothing more to do for us.
1763 isolcpus
= read_file(__ISOL_CPUS
);
1765 pam_cgfs_debug("%s", "Could not read file "__ISOL_CPUS
"\n");
1768 if (!isdigit(isolcpus
[0])) {
1769 pam_cgfs_debug("%s", "No isolated cpus detected.\n");
1771 /* No isolated cpus but we weren't already initialized by
1772 * someone. We should simply copy the parents cpuset.cpus
1775 if (!am_initialized
) {
1776 pam_cgfs_debug("%s", "Copying cpuset of parent cgroup.\n");
1779 /* No isolated cpus but we were already initialized by someone.
1780 * Nothing more to do for us.
1785 /* Get maximum number of cpus found in isolated cpuset. */
1786 maxisol
= cg_get_max_cpus(isolcpus
);
1790 if (maxposs
< maxisol
)
1794 possmask
= cg_cpumask(posscpus
, maxposs
);
1796 pam_cgfs_debug("%s", "Could not create cpumask for all possible cpus.\n");
1800 isolmask
= cg_cpumask(isolcpus
, maxposs
);
1802 pam_cgfs_debug("%s", "Could not create cpumask for all isolated cpus.\n");
1806 for (i
= 0; i
<= maxposs
; i
++) {
1807 if (is_set(i
, isolmask
) && is_set(i
, possmask
)) {
1809 clear_bit(i
, possmask
);
1814 pam_cgfs_debug("%s", "No isolated cpus present in cpuset.\n");
1817 pam_cgfs_debug("%s", "Removed isolated cpus from cpuset.\n");
1819 cpulist
= cg_cpumask_to_cpulist(possmask
, maxposs
);
1821 pam_cgfs_debug("%s", "Could not create cpu list.\n");
1827 fpath
= must_make_path(path
, "cpuset.cpus", NULL
);
1828 ret
= write_to_file(fpath
, cpulist
, strlen(cpulist
), false);
1830 pam_cgfs_debug("Could not write cpu list to: %s.\n", fpath
);
1843 if (posscpus
!= cpulist
)
1851 int read_from_file(const char *filename
, void* buf
, size_t count
)
1853 int fd
= -1, saved_errno
;
1856 fd
= open(filename
, O_RDONLY
| O_CLOEXEC
);
1860 if (!buf
|| !count
) {
1863 while ((ret
= read(fd
, buf2
, 100)) > 0)
1868 memset(buf
, 0, count
);
1869 ret
= read(fd
, buf
, count
);
1873 pam_cgfs_debug("read %s: %s", filename
, strerror(errno
));
1875 saved_errno
= errno
;
1877 errno
= saved_errno
;
1881 /* Copy contents of parent(@path)/@file to @path/@file */
1882 static bool cg_copy_parent_file(char *path
, char *file
)
1884 char *lastslash
, *value
= NULL
, *fpath
, oldv
;
1888 lastslash
= strrchr(path
, '/');
1889 if (!lastslash
) { // bug... this shouldn't be possible
1890 pam_cgfs_debug("cgfsng:copy_parent_file: bad path %s", path
);
1895 fpath
= must_make_path(path
, file
, NULL
);
1896 len
= read_from_file(fpath
, NULL
, 0);
1899 value
= must_alloc(len
+ 1);
1900 if (read_from_file(fpath
, value
, len
) != len
)
1904 fpath
= must_make_path(path
, file
, NULL
);
1905 ret
= write_to_file(fpath
, value
, len
, false);
1907 pam_cgfs_debug("Unable to write %s to %s", value
, fpath
);
1913 pam_cgfs_debug("Error reading '%s'", fpath
);
1919 /* In case systemd hasn't already placed us in a user slice for the cpuset v1
1920 * controller we will reside in the root cgroup. This means that
1921 * cgroup.clone_children will not have been initialized for us so we need to do
1924 static bool cgv1_handle_root_cpuset_hierarchy(struct cgv1_hierarchy
*h
)
1926 char *clonechildrenpath
, v
;
1928 if (!string_in_list(h
->controllers
, "cpuset"))
1931 clonechildrenpath
= must_make_path(h
->mountpoint
, "cgroup.clone_children", NULL
);
1933 if (read_from_file(clonechildrenpath
, &v
, 1) < 0) {
1934 pam_cgfs_debug("Failed to read '%s'", clonechildrenpath
);
1935 free(clonechildrenpath
);
1939 if (v
== '1') { /* already set for us by someone else */
1940 free(clonechildrenpath
);
1944 if (write_to_file(clonechildrenpath
, "1", 1, false) < 0) {
1945 /* Set clone_children so children inherit our settings */
1946 pam_cgfs_debug("Failed to write 1 to %s", clonechildrenpath
);
1947 free(clonechildrenpath
);
1950 free(clonechildrenpath
);
1955 * Initialize the cpuset hierarchy in first directory of @gname and
1956 * set cgroup.clone_children so that children inherit settings.
1957 * Since the h->base_path is populated by init or ourselves, we know
1958 * it is already initialized.
1960 static bool cgv1_handle_cpuset_hierarchy(struct cgv1_hierarchy
*h
,
1963 char *cgpath
, *clonechildrenpath
, v
, *slash
;
1965 if (!string_in_list(h
->controllers
, "cpuset"))
1970 slash
= strchr(cgroup
, '/');
1974 cgpath
= must_make_path(h
->mountpoint
, h
->base_cgroup
, cgroup
, NULL
);
1977 if (do_mkdir(cgpath
, 0755) < 0 && errno
!= EEXIST
) {
1978 pam_cgfs_debug("Failed to create '%s'", cgpath
);
1982 clonechildrenpath
= must_make_path(cgpath
, "cgroup.clone_children", NULL
);
1983 if (!file_exists(clonechildrenpath
)) { /* unified hierarchy doesn't have clone_children */
1984 free(clonechildrenpath
);
1988 if (read_from_file(clonechildrenpath
, &v
, 1) < 0) {
1989 pam_cgfs_debug("Failed to read '%s'", clonechildrenpath
);
1990 free(clonechildrenpath
);
1995 /* Make sure any isolated cpus are removed from cpuset.cpus. */
1996 if (!cg_filter_and_set_cpus(cgpath
, v
== '1')) {
1997 pam_cgfs_debug("%s", "Failed to remove isolated cpus.\n");
1998 free(clonechildrenpath
);
2003 if (v
== '1') { /* already set for us by someone else */
2004 pam_cgfs_debug("%s", "\"cgroup.clone_children\" was already set to \"1\".\n");
2005 free(clonechildrenpath
);
2010 /* copy parent's settings */
2011 if (!cg_copy_parent_file(cgpath
, "cpuset.mems")) {
2012 pam_cgfs_debug("%s", "Failed to copy \"cpuset.mems\" settings.\n");
2014 free(clonechildrenpath
);
2019 if (write_to_file(clonechildrenpath
, "1", 1, false) < 0) {
2020 /* Set clone_children so children inherit our settings */
2021 pam_cgfs_debug("Failed to write 1 to %s", clonechildrenpath
);
2022 free(clonechildrenpath
);
2025 free(clonechildrenpath
);
2029 /* Create and chown @cgroup for all given controllers in a cgroupfs v1 hierarchy
2030 * (For example, create @cgroup for the cpu and cpuacct controller mounted into
2031 * /sys/fs/cgroup/cpu,cpuacct). Check if the path already exists and report back
2032 * to the caller in @existed.
2034 #define __PAM_CGFS_USER "/user/"
2035 #define __PAM_CGFS_USER_LEN 6
2036 static bool cgv1_create_one(struct cgv1_hierarchy
*h
, const char *cgroup
, uid_t uid
, gid_t gid
, bool *existed
)
2038 char *clean_base_cgroup
, *path
;
2040 struct cgv1_hierarchy
*it
;
2041 bool created
= false;
2045 for (controller
= it
->controllers
; controller
&& *controller
;
2047 if (!cgv1_handle_cpuset_hierarchy(it
, cgroup
))
2050 /* If systemd has already created a cgroup for us, keep using
2053 if (cg_systemd_chown_existing_cgroup(it
->mountpoint
,
2054 it
->base_cgroup
, uid
, gid
,
2055 it
->systemd_user_slice
)) {
2059 /* We need to make sure that we do not create an endless chain
2060 * of sub-cgroups. So we check if we have already logged in
2061 * somehow (sudo -i, su, etc.) and have created a
2062 * /user/PAM_user/idx cgroup. If so, we skip that part. For most
2063 * cgroups this is unnecessary since we use the init_cgroup
2064 * anyway, but for controllers which have an existing systemd
2065 * cgroup that does not match the current uid, this is pretty
2068 if (strncmp(it
->base_cgroup
, __PAM_CGFS_USER
, __PAM_CGFS_USER_LEN
) == 0) {
2069 free(it
->base_cgroup
);
2070 it
->base_cgroup
= must_copy_string("/");
2073 strstr(it
->base_cgroup
, __PAM_CGFS_USER
);
2074 if (clean_base_cgroup
)
2075 *clean_base_cgroup
= '\0';
2078 path
= must_make_path(it
->mountpoint
, it
->init_cgroup
, cgroup
, NULL
);
2079 pam_cgfs_debug("Constructing path: %s.\n", path
);
2080 if (file_exists(path
)) {
2081 bool our_cg
= cg_belongs_to_uid_gid(path
, uid
, gid
);
2082 pam_cgfs_debug("%s existed and does %shave our uid: %d and gid: %d.\n", path
, our_cg
? "" : "not ", uid
, gid
);
2090 created
= mkdir_parent(it
->mountpoint
, path
);
2095 if (chown(path
, uid
, gid
) < 0)
2096 mysyslog(LOG_WARNING
,
2097 "Failed to chown %s to %d:%d: %s.\n", path
,
2098 (int)uid
, (int)gid
, strerror(errno
), NULL
);
2099 pam_cgfs_debug("Chowned %s to %d:%d.\n", path
, (int)uid
, (int)gid
);
2107 /* Try to remove @cgroup for all given controllers in a cgroupfs v1 hierarchy
2108 * (For example, try to remove @cgroup for the cpu and cpuacct controller
2109 * mounted into /sys/fs/cgroup/cpu,cpuacct). Ignores failures.
2111 static bool cgv1_remove_one(struct cgv1_hierarchy
*h
, const char *cgroup
)
2116 /* Better safe than sorry. */
2117 if (!h
->controllers
)
2120 /* Cgroups created by systemd for us which we re-use won't be removed
2121 * here, since we're using init_cgroup + cgroup as path instead of
2122 * base_cgroup + cgroup.
2124 path
= must_make_path(h
->mountpoint
, h
->init_cgroup
, cgroup
, NULL
);
2125 (void)recursive_rmdir(path
);
2131 /* Try to remove @cgroup the cgroupfs v2 hierarchy. */
2132 static bool cgv2_remove(const char *cgroup
)
2134 struct cgv2_hierarchy
*v2
;
2137 if (!cgv2_hierarchies
)
2140 v2
= *cgv2_hierarchies
;
2142 /* If we reused an already existing cgroup, don't bother trying to
2143 * remove (a potentially wrong)/the path.
2144 * Cgroups created by systemd for us which we re-use would be removed
2145 * here, since we're using base_cgroup + cgroup as path.
2147 if (v2
->systemd_user_slice
)
2150 path
= must_make_path(v2
->mountpoint
, v2
->base_cgroup
, cgroup
, NULL
);
2151 (void)recursive_rmdir(path
);
2157 /* Create @cgroup in all detected cgroupfs v1 hierarchy. If the creation fails
2158 * for any cgroupfs v1 hierarchy, remove all we have created so far. Report
2159 * back, to the caller if the creation failed due to @cgroup already existing
2162 static bool cgv1_create(const char *cgroup
, uid_t uid
, gid_t gid
, bool *existed
)
2164 struct cgv1_hierarchy
**it
, **rev_it
;
2165 bool all_created
= true;
2167 for (it
= cgv1_hierarchies
; it
&& *it
; it
++) {
2168 if (!(*it
)->controllers
|| !(*it
)->mountpoint
||
2169 !(*it
)->init_cgroup
|| !(*it
)->create_rw_cgroup
)
2172 if (!cgv1_create_one(*it
, cgroup
, uid
, gid
, existed
)) {
2173 all_created
= false;
2181 for (rev_it
= cgv1_hierarchies
; rev_it
&& *rev_it
&& (*rev_it
!= *it
);
2183 cgv1_remove_one(*rev_it
, cgroup
);
2188 /* Create @cgroup in the cgroupfs v2 hierarchy. Report back, to the caller if
2189 * the creation failed due to @cgroup already existing via @existed.
2191 static bool cgv2_create(const char *cgroup
, uid_t uid
, gid_t gid
, bool *existed
)
2194 char *clean_base_cgroup
;
2196 struct cgv2_hierarchy
*v2
;
2197 bool our_cg
= false, created
= false;
2201 if (!cgv2_hierarchies
|| !(*cgv2_hierarchies
)->create_rw_cgroup
)
2204 v2
= *cgv2_hierarchies
;
2206 /* We can't be placed under init's cgroup for the v2 hierarchy. We need
2207 * to be placed under our current cgroup.
2209 if (cg_systemd_chown_existing_cgroup(v2
->mountpoint
, v2
->base_cgroup
,
2210 uid
, gid
, v2
->systemd_user_slice
))
2211 goto delegate_files
;
2213 /* We need to make sure that we do not create an endless chain of
2214 * sub-cgroups. So we check if we have already logged in somehow (sudo
2215 * -i, su, etc.) and have created a /user/PAM_user/idx cgroup. If so, we
2218 if (strncmp(v2
->base_cgroup
, __PAM_CGFS_USER
, __PAM_CGFS_USER_LEN
) == 0) {
2219 free(v2
->base_cgroup
);
2220 v2
->base_cgroup
= must_copy_string("/");
2222 clean_base_cgroup
= strstr(v2
->base_cgroup
, __PAM_CGFS_USER
);
2223 if (clean_base_cgroup
)
2224 *clean_base_cgroup
= '\0';
2227 path
= must_make_path(v2
->mountpoint
, v2
->base_cgroup
, cgroup
, NULL
);
2228 pam_cgfs_debug("Constructing path \"%s\".\n", path
);
2229 if (file_exists(path
)) {
2230 our_cg
= cg_belongs_to_uid_gid(path
, uid
, gid
);
2232 "%s existed and does %shave our uid: %d and gid: %d.\n",
2233 path
, our_cg
? "" : "not ", uid
, gid
);
2237 goto delegate_files
;
2244 created
= mkdir_parent(v2
->mountpoint
, path
);
2250 /* chown cgroup to user */
2251 if (chown(path
, uid
, gid
) < 0)
2252 mysyslog(LOG_WARNING
, "Failed to chown %s to %d:%d: %s.\n",
2253 path
, (int)uid
, (int)gid
, strerror(errno
), NULL
);
2255 pam_cgfs_debug("Chowned %s to %d:%d.\n", path
, (int)uid
, (int)gid
);
2259 /* chown cgroup.procs to user */
2260 if (v2
->systemd_user_slice
)
2261 path
= must_make_path(v2
->mountpoint
, v2
->base_cgroup
,
2262 "/cgroup.procs", NULL
);
2264 path
= must_make_path(v2
->mountpoint
, v2
->base_cgroup
, cgroup
,
2265 "/cgroup.procs", NULL
);
2266 ret
= chown(path
, uid
, gid
);
2268 mysyslog(LOG_WARNING
, "Failed to chown %s to %d:%d: %s.\n",
2269 path
, (int)uid
, (int)gid
, strerror(errno
), NULL
);
2271 pam_cgfs_debug("Chowned %s to %d:%d.\n", path
, (int)uid
, (int)gid
);
2274 /* chown cgroup.subtree_control to user */
2275 if (v2
->systemd_user_slice
)
2276 path
= must_make_path(v2
->mountpoint
, v2
->base_cgroup
,
2277 "/cgroup.subtree_control", NULL
);
2279 path
= must_make_path(v2
->mountpoint
, v2
->base_cgroup
, cgroup
,
2280 "/cgroup.subtree_control", NULL
);
2281 ret
= chown(path
, uid
, gid
);
2283 mysyslog(LOG_WARNING
, "Failed to chown %s to %d:%d: %s.\n",
2284 path
, (int)uid
, (int)gid
, strerror(errno
), NULL
);
2287 /* chown cgroup.threads to user */
2288 if (v2
->systemd_user_slice
)
2289 path
= must_make_path(v2
->mountpoint
, v2
->base_cgroup
,
2290 "/cgroup.threads", NULL
);
2292 path
= must_make_path(v2
->mountpoint
, v2
->base_cgroup
, cgroup
,
2293 "/cgroup.threads", NULL
);
2294 ret
= chown(path
, uid
, gid
);
2295 if (ret
< 0 && errno
!= ENOENT
)
2296 mysyslog(LOG_WARNING
, "Failed to chown %s to %d:%d: %s.\n",
2297 path
, (int)uid
, (int)gid
, strerror(errno
), NULL
);
2303 /* Create writeable cgroups for @user at login. Details can be found in the
2304 * preamble/license at the top of this file.
2306 static int handle_login(const char *user
, uid_t uid
, gid_t gid
)
2310 char cg
[MAXPATHLEN
];
2315 ret
= snprintf(cg
, MAXPATHLEN
, "/user/%s/%d", user
, idx
);
2316 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2317 mysyslog(LOG_ERR
, "Username too long.\n", NULL
);
2318 return PAM_SESSION_ERR
;
2322 if (!cgv2_create(cg
, uid
, gid
, &existed
)) {
2328 mysyslog(LOG_ERR
, "Failed to create a cgroup for user %s.\n", user
, NULL
);
2329 return PAM_SESSION_ERR
;
2333 if (!cgv1_create(cg
, uid
, gid
, &existed
)) {
2339 mysyslog(LOG_ERR
, "Failed to create a cgroup for user %s.\n", user
, NULL
);
2340 return PAM_SESSION_ERR
;
2343 if (!cg_enter(cg
)) {
2344 mysyslog( LOG_ERR
, "Failed to enter user cgroup %s for user %s.\n", cg
, user
, NULL
);
2345 return PAM_SESSION_ERR
;
2353 /* Try to prune cgroups we created and that now are empty from all cgroupfs v1
2356 static bool cgv1_prune_empty_cgroups(const char *user
)
2358 bool controller_removed
= true;
2359 bool all_removed
= true;
2360 struct cgv1_hierarchy
**it
;
2362 for (it
= cgv1_hierarchies
; it
&& *it
; it
++) {
2364 char *path_base
, *path_init
;
2367 if (!(*it
)->controllers
|| !(*it
)->mountpoint
||
2368 !(*it
)->init_cgroup
|| !(*it
)->create_rw_cgroup
)
2371 for (controller
= (*it
)->controllers
; controller
&& *controller
;
2373 bool path_base_rm
, path_init_rm
;
2375 path_base
= must_make_path((*it
)->mountpoint
, (*it
)->base_cgroup
, "/user", user
, NULL
);
2376 pam_cgfs_debug("cgroupfs v1: Trying to prune \"%s\".\n", path_base
);
2377 ret
= recursive_rmdir(path_base
);
2378 if (ret
== -ENOENT
|| ret
>= 0)
2379 path_base_rm
= true;
2381 path_base_rm
= false;
2384 path_init
= must_make_path((*it
)->mountpoint
, (*it
)->init_cgroup
, "/user", user
, NULL
);
2385 pam_cgfs_debug("cgroupfs v1: Trying to prune \"%s\".\n", path_init
);
2386 ret
= recursive_rmdir(path_init
);
2387 if (ret
== -ENOENT
|| ret
>= 0)
2388 path_init_rm
= true;
2390 path_init_rm
= false;
2393 if (!path_base_rm
&& !path_init_rm
) {
2394 controller_removed
= false;
2398 controller_removed
= true;
2401 if (!controller_removed
)
2402 all_removed
= false;
2408 /* Try to prune cgroup we created and that now is empty from the cgroupfs v2
2411 static bool cgv2_prune_empty_cgroups(const char *user
)
2414 struct cgv2_hierarchy
*v2
;
2415 char *path_base
, *path_init
;
2416 bool path_base_rm
, path_init_rm
;
2418 if (!cgv2_hierarchies
)
2421 v2
= *cgv2_hierarchies
;
2423 path_base
= must_make_path(v2
->mountpoint
, v2
->base_cgroup
, "/user", user
, NULL
);
2424 pam_cgfs_debug("cgroupfs v2: Trying to prune \"%s\".\n", path_base
);
2425 ret
= recursive_rmdir(path_base
);
2426 if (ret
== -ENOENT
|| ret
>= 0)
2427 path_base_rm
= true;
2429 path_base_rm
= false;
2432 path_init
= must_make_path(v2
->mountpoint
, v2
->init_cgroup
, "/user", user
, NULL
);
2433 pam_cgfs_debug("cgroupfs v2: Trying to prune \"%s\".\n", path_init
);
2434 ret
= recursive_rmdir(path_init
);
2435 if (ret
== -ENOENT
|| ret
>= 0)
2436 path_init_rm
= true;
2438 path_init_rm
= false;
2441 if (!path_base_rm
&& !path_init_rm
)
2447 /* Wrapper around cgv{1,2}_prune_empty_cgroups(). */
2448 static void cg_prune_empty_cgroups(const char *user
)
2450 (void)cgv1_prune_empty_cgroups(user
);
2451 (void)cgv2_prune_empty_cgroups(user
);
2454 /* Free allocated information for detected cgroupfs v1 hierarchies. */
2455 static void cgv1_free_hierarchies(void)
2457 struct cgv1_hierarchy
**it
;
2459 if (!cgv1_hierarchies
)
2462 for (it
= cgv1_hierarchies
; it
&& *it
; it
++) {
2463 if ((*it
)->controllers
) {
2465 for (tmp
= (*it
)->controllers
; tmp
&& *tmp
; tmp
++)
2468 free((*it
)->controllers
);
2470 free((*it
)->mountpoint
);
2471 free((*it
)->base_cgroup
);
2472 free((*it
)->fullcgpath
);
2473 free((*it
)->init_cgroup
);
2475 free(cgv1_hierarchies
);
2478 /* Free allocated information for the detected cgroupfs v2 hierarchy. */
2479 static void cgv2_free_hierarchies(void)
2481 struct cgv2_hierarchy
**it
;
2483 if (!cgv2_hierarchies
)
2486 for (it
= cgv2_hierarchies
; it
&& *it
; it
++) {
2487 if ((*it
)->controllers
) {
2489 for (tmp
= (*it
)->controllers
; tmp
&& *tmp
; tmp
++)
2492 free((*it
)->controllers
);
2494 free((*it
)->mountpoint
);
2495 free((*it
)->base_cgroup
);
2496 free((*it
)->fullcgpath
);
2497 free((*it
)->init_cgroup
);
2499 free(cgv2_hierarchies
);
2502 /* Wrapper around cgv{1,2}_free_hierarchies(). */
2503 static void cg_exit(void)
2505 cgv1_free_hierarchies();
2506 cgv2_free_hierarchies();
2509 int pam_sm_open_session(pam_handle_t
*pamh
, int flags
, int argc
,
2515 const char *PAM_user
= NULL
;
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
;
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
;
2528 if (!cg_init(uid
, gid
)) {
2529 mysyslog(LOG_ERR
, "Failed to get list of controllers\n", NULL
);
2530 return PAM_SESSION_ERR
;
2533 /* Try to prune cgroups, that are actually empty but were still marked
2534 * as busy by the kernel so we couldn't remove them on session close.
2536 cg_prune_empty_cgroups(PAM_user
);
2538 if (cg_mount_mode
== CGROUP_UNKNOWN
)
2539 return PAM_SESSION_ERR
;
2541 if (argc
> 1 && !strcmp(argv
[0], "-c")) {
2542 char **clist
= make_string_list(argv
[1], ",");
2545 * We don't allow using "all" and other controllers explicitly because
2546 * that simply doesn't make any sense.
2548 if (string_list_length(clist
) > 1 && string_in_list(clist
, "all")) {
2549 mysyslog(LOG_ERR
, "Invalid -c option, cannot specify individual controllers alongside 'all'.\n", NULL
);
2550 free_string_list(clist
);
2551 return PAM_SESSION_ERR
;
2554 cg_mark_to_make_rw(clist
);
2555 free_string_list(clist
);
2558 return handle_login(PAM_user
, uid
, gid
);
2561 int pam_sm_close_session(pam_handle_t
*pamh
, int flags
, int argc
,
2567 const char *PAM_user
= NULL
;
2569 ret
= pam_get_user(pamh
, &PAM_user
, NULL
);
2570 if (ret
!= PAM_SUCCESS
) {
2571 mysyslog(LOG_ERR
, "PAM-CGFS: couldn't get user\n", NULL
);
2572 return PAM_SESSION_ERR
;
2575 if (!get_uid_gid(PAM_user
, &uid
, &gid
)) {
2576 mysyslog(LOG_ERR
, "Failed to get uid and gid for %s.\n", PAM_user
, NULL
);
2577 return PAM_SESSION_ERR
;
2580 if (cg_mount_mode
== CGROUP_UNINITIALIZED
) {
2581 if (!cg_init(uid
, gid
))
2582 mysyslog(LOG_ERR
, "Failed to get list of controllers\n", NULL
);
2584 if (argc
> 1 && !strcmp(argv
[0], "-c")) {
2585 char **clist
= make_string_list(argv
[1], ",");
2588 * We don't allow using "all" and other controllers explicitly because
2589 * that simply doesn't make any sense.
2591 if (string_list_length(clist
) > 1 && string_in_list(clist
, "all")) {
2592 mysyslog(LOG_ERR
, "Invalid -c option, cannot specify individual controllers alongside 'all'.\n", NULL
);
2593 free_string_list(clist
);
2594 return PAM_SESSION_ERR
;
2597 cg_mark_to_make_rw(clist
);
2598 free_string_list(clist
);
2602 cg_prune_empty_cgroups(PAM_user
);