3 * Copyright © 2014-2016 Canonical, Inc
4 * Author: Serge Hallyn <serge.hallyn@ubuntu.com>
6 * See COPYING file for details.
9 #define FUSE_USE_VERSION 26
25 #include <linux/sched.h>
26 #include <sys/epoll.h>
28 #include <sys/mount.h>
29 #include <sys/param.h>
30 #include <sys/socket.h>
31 #include <sys/syscall.h>
34 #include "config.h" // for VERSION
36 /* Define pivot_root() if missing from the C library */
37 #ifndef HAVE_PIVOT_ROOT
38 static int pivot_root(const char * new_root
, const char * put_old
)
40 #ifdef __NR_pivot_root
41 return syscall(__NR_pivot_root
, new_root
, put_old
);
48 extern int pivot_root(const char * new_root
, const char * put_old
);
52 #define lxcfs_debug(format, ...) \
54 fprintf(stderr, "%s: %d: %s: " format, __FILE__, __LINE__, \
55 __func__, __VA_ARGS__); \
58 #define lxcfs_debug(format, ...)
64 LXC_TYPE_PROC_MEMINFO
,
65 LXC_TYPE_PROC_CPUINFO
,
68 LXC_TYPE_PROC_DISKSTATS
,
77 char *buf
; // unused as of yet
79 int size
; //actual data size
83 /* reserve buffer size, for cpuall in /proc/stat */
84 #define BUF_RESERVE_SIZE 256
87 * A table caching which pid is init for a pid namespace.
88 * When looking up which pid is init for $qpid, we first
89 * 1. Stat /proc/$qpid/ns/pid.
90 * 2. Check whether the ino_t is in our store.
91 * a. if not, fork a child in qpid's ns to send us
92 * ucred.pid = 1, and read the initpid. Cache
93 * initpid and creation time for /proc/initpid
94 * in a new store entry.
95 * b. if so, verify that /proc/initpid still matches
96 * what we have saved. If not, clear the store
97 * entry and go back to a. If so, return the
100 struct pidns_init_store
{
101 ino_t ino
; // inode number for /proc/$pid/ns/pid
102 pid_t initpid
; // the pid of nit in that ns
103 long int ctime
; // the time at which /proc/$initpid was created
104 struct pidns_init_store
*next
;
108 /* lol - look at how they are allocated in the kernel */
109 #define PIDNS_HASH_SIZE 4096
110 #define HASH(x) ((x) % PIDNS_HASH_SIZE)
112 static struct pidns_init_store
*pidns_hash_table
[PIDNS_HASH_SIZE
];
113 static pthread_mutex_t pidns_store_mutex
= PTHREAD_MUTEX_INITIALIZER
;
114 static void lock_mutex(pthread_mutex_t
*l
)
118 if ((ret
= pthread_mutex_lock(l
)) != 0) {
119 fprintf(stderr
, "pthread_mutex_lock returned:%d %s\n", ret
, strerror(ret
));
124 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
125 * Number of hierarchies mounted. */
126 static int num_hierarchies
;
128 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
129 * Hierachies mounted {cpuset, blkio, ...}:
130 * Initialized via __constructor__ collect_and_mount_subsystems(). */
131 static char **hierarchies
;
133 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
134 * Open file descriptors:
135 * @fd_hierarchies[i] refers to cgroup @hierarchies[i]. They are mounted in a
136 * private mount namespace.
137 * Initialized via __constructor__ collect_and_mount_subsystems().
138 * @fd_hierarchies[i] can be used to perform file operations on the cgroup
139 * mounts and respective files in the private namespace even when located in
140 * another namespace using the *at() family of functions
141 * {openat(), fchownat(), ...}. */
142 static int *fd_hierarchies
;
144 static void unlock_mutex(pthread_mutex_t
*l
)
148 if ((ret
= pthread_mutex_unlock(l
)) != 0) {
149 fprintf(stderr
, "pthread_mutex_unlock returned:%d %s\n", ret
, strerror(ret
));
154 static void store_lock(void)
156 lock_mutex(&pidns_store_mutex
);
159 static void store_unlock(void)
161 unlock_mutex(&pidns_store_mutex
);
164 /* Must be called under store_lock */
165 static bool initpid_still_valid(struct pidns_init_store
*e
, struct stat
*nsfdsb
)
170 snprintf(fnam
, 100, "/proc/%d", e
->initpid
);
171 if (stat(fnam
, &initsb
) < 0)
174 lxcfs_debug("Comparing ctime %ld == %ld for pid %d.\n", e
->ctime
,
175 initsb
.st_ctime
, e
->initpid
);
177 if (e
->ctime
!= initsb
.st_ctime
)
182 /* Must be called under store_lock */
183 static void remove_initpid(struct pidns_init_store
*e
)
185 struct pidns_init_store
*tmp
;
188 lxcfs_debug("Remove_initpid: removing entry for %d.\n", e
->initpid
);
191 if (pidns_hash_table
[h
] == e
) {
192 pidns_hash_table
[h
] = e
->next
;
197 tmp
= pidns_hash_table
[h
];
199 if (tmp
->next
== e
) {
209 /* Must be called under store_lock */
210 static void prune_initpid_store(void)
212 static long int last_prune
= 0;
213 struct pidns_init_store
*e
, *prev
, *delme
;
214 long int now
, threshold
;
218 last_prune
= time(NULL
);
222 if (now
< last_prune
+ PURGE_SECS
)
225 lxcfs_debug("%s\n", "Pruning.");
228 threshold
= now
- 2 * PURGE_SECS
;
230 for (i
= 0; i
< PIDNS_HASH_SIZE
; i
++) {
231 for (prev
= NULL
, e
= pidns_hash_table
[i
]; e
; ) {
232 if (e
->lastcheck
< threshold
) {
234 lxcfs_debug("Removing cached entry for %d.\n", e
->initpid
);
238 prev
->next
= e
->next
;
240 pidns_hash_table
[i
] = e
->next
;
251 /* Must be called under store_lock */
252 static void save_initpid(struct stat
*sb
, pid_t pid
)
254 struct pidns_init_store
*e
;
259 lxcfs_debug("Save_initpid: adding entry for %d.\n", pid
);
261 snprintf(fpath
, 100, "/proc/%d", pid
);
262 if (stat(fpath
, &procsb
) < 0)
265 e
= malloc(sizeof(*e
));
269 e
->ctime
= procsb
.st_ctime
;
271 e
->next
= pidns_hash_table
[h
];
272 e
->lastcheck
= time(NULL
);
273 pidns_hash_table
[h
] = e
;
277 * Given the stat(2) info for a nsfd pid inode, lookup the init_pid_store
278 * entry for the inode number and creation time. Verify that the init pid
279 * is still valid. If not, remove it. Return the entry if valid, NULL
281 * Must be called under store_lock
283 static struct pidns_init_store
*lookup_verify_initpid(struct stat
*sb
)
285 int h
= HASH(sb
->st_ino
);
286 struct pidns_init_store
*e
= pidns_hash_table
[h
];
289 if (e
->ino
== sb
->st_ino
) {
290 if (initpid_still_valid(e
, sb
)) {
291 e
->lastcheck
= time(NULL
);
303 static int is_dir(const char *path
, int fd
)
306 int ret
= fstatat(fd
, path
, &statbuf
, fd
);
307 if (ret
== 0 && S_ISDIR(statbuf
.st_mode
))
312 static char *must_copy_string(const char *str
)
324 static inline void drop_trailing_newlines(char *s
)
328 for (l
=strlen(s
); l
>0 && s
[l
-1] == '\n'; l
--)
332 #define BATCH_SIZE 50
333 static void dorealloc(char **mem
, size_t oldlen
, size_t newlen
)
335 int newbatches
= (newlen
/ BATCH_SIZE
) + 1;
336 int oldbatches
= (oldlen
/ BATCH_SIZE
) + 1;
338 if (!*mem
|| newbatches
> oldbatches
) {
341 tmp
= realloc(*mem
, newbatches
* BATCH_SIZE
);
346 static void append_line(char **contents
, size_t *len
, char *line
, ssize_t linelen
)
348 size_t newlen
= *len
+ linelen
;
349 dorealloc(contents
, *len
, newlen
+ 1);
350 memcpy(*contents
+ *len
, line
, linelen
+1);
354 static char *slurp_file(const char *from
, int fd
)
357 char *contents
= NULL
;
358 FILE *f
= fdopen(fd
, "r");
359 size_t len
= 0, fulllen
= 0;
365 while ((linelen
= getline(&line
, &len
, f
)) != -1) {
366 append_line(&contents
, &fulllen
, line
, linelen
);
371 drop_trailing_newlines(contents
);
376 static bool write_string(const char *fnam
, const char *string
, int fd
)
381 if (!(f
= fdopen(fd
, "w")))
383 len
= strlen(string
);
384 ret
= fwrite(string
, 1, len
, f
);
386 fprintf(stderr
, "Error writing to file: %s\n", strerror(errno
));
391 fprintf(stderr
, "Error writing to file: %s\n", strerror(errno
));
404 static bool store_hierarchy(char *stridx
, char *h
)
406 if (num_hierarchies
% ALLOC_NUM
== 0) {
407 size_t n
= (num_hierarchies
/ ALLOC_NUM
) + 1;
409 char **tmp
= realloc(hierarchies
, n
* sizeof(char *));
411 fprintf(stderr
, "Out of memory\n");
417 hierarchies
[num_hierarchies
++] = must_copy_string(h
);
421 static void print_subsystems(void)
425 fprintf(stderr
, "hierarchies:\n");
426 for (i
= 0; i
< num_hierarchies
; i
++) {
428 fprintf(stderr
, " %d: %s\n", i
, hierarchies
[i
]);
432 static bool in_comma_list(const char *needle
, const char *haystack
)
434 const char *s
= haystack
, *e
;
435 size_t nlen
= strlen(needle
);
437 while (*s
&& (e
= strchr(s
, ','))) {
442 if (strncmp(needle
, s
, nlen
) == 0)
446 if (strcmp(needle
, s
) == 0)
451 /* do we need to do any massaging here? I'm not sure... */
452 /* Return the mounted controller and store the corresponding open file descriptor
453 * referring to the controller mountpoint in the private lxcfs namespace in
456 static char *find_mounted_controller(const char *controller
, int *cfd
)
460 for (i
= 0; i
< num_hierarchies
; i
++) {
463 if (strcmp(hierarchies
[i
], controller
) == 0) {
464 *cfd
= fd_hierarchies
[i
];
465 return hierarchies
[i
];
467 if (in_comma_list(controller
, hierarchies
[i
])) {
468 *cfd
= fd_hierarchies
[i
];
469 return hierarchies
[i
];
476 bool cgfs_set_value(const char *controller
, const char *cgroup
, const char *file
,
483 tmpc
= find_mounted_controller(controller
, &cfd
);
487 /* Make sure we pass a relative path to *at() family of functions.
488 * . + /cgroup + / + file + \0
490 len
= strlen(cgroup
) + strlen(file
) + 3;
492 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, file
);
493 if (ret
< 0 || (size_t)ret
>= len
)
496 fd
= openat(cfd
, fnam
, O_WRONLY
);
500 return write_string(fnam
, value
, fd
);
503 // Chown all the files in the cgroup directory. We do this when we create
504 // a cgroup on behalf of a user.
505 static void chown_all_cgroup_files(const char *dirname
, uid_t uid
, gid_t gid
, int fd
)
507 struct dirent
*direntp
;
508 char path
[MAXPATHLEN
];
513 len
= strlen(dirname
);
514 if (len
>= MAXPATHLEN
) {
515 fprintf(stderr
, "chown_all_cgroup_files: pathname too long: %s\n", dirname
);
519 fd1
= openat(fd
, dirname
, O_DIRECTORY
);
525 fprintf(stderr
, "chown_all_cgroup_files: failed to open %s\n", dirname
);
529 while ((direntp
= readdir(d
))) {
530 if (!strcmp(direntp
->d_name
, ".") || !strcmp(direntp
->d_name
, ".."))
532 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
533 if (ret
< 0 || ret
>= MAXPATHLEN
) {
534 fprintf(stderr
, "chown_all_cgroup_files: pathname too long under %s\n", dirname
);
537 if (fchownat(fd
, path
, uid
, gid
, 0) < 0)
538 fprintf(stderr
, "Failed to chown file %s to %u:%u", path
, uid
, gid
);
543 int cgfs_create(const char *controller
, const char *cg
, uid_t uid
, gid_t gid
)
549 tmpc
= find_mounted_controller(controller
, &cfd
);
553 /* Make sure we pass a relative path to *at() family of functions.
556 len
= strlen(cg
) + 2;
557 dirnam
= alloca(len
);
558 snprintf(dirnam
, len
, "%s%s", *cg
== '/' ? "." : "", cg
);
560 if (mkdirat(cfd
, dirnam
, 0755) < 0)
563 if (uid
== 0 && gid
== 0)
566 if (fchownat(cfd
, dirnam
, uid
, gid
, 0) < 0)
569 chown_all_cgroup_files(dirnam
, uid
, gid
, cfd
);
574 static bool recursive_rmdir(const char *dirname
, int fd
, const int cfd
)
576 struct dirent
*direntp
;
579 char pathname
[MAXPATHLEN
];
582 dupfd
= dup(fd
); // fdopendir() does bad things once it uses an fd.
586 dir
= fdopendir(dupfd
);
588 lxcfs_debug("Failed to open %s: %s.\n", dirname
, strerror(errno
));
593 while ((direntp
= readdir(dir
))) {
597 if (!strcmp(direntp
->d_name
, ".") ||
598 !strcmp(direntp
->d_name
, ".."))
601 rc
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
602 if (rc
< 0 || rc
>= MAXPATHLEN
) {
603 fprintf(stderr
, "pathname too long\n");
607 rc
= fstatat(cfd
, pathname
, &mystat
, AT_SYMLINK_NOFOLLOW
);
609 lxcfs_debug("Failed to stat %s: %s.\n", pathname
, strerror(errno
));
612 if (S_ISDIR(mystat
.st_mode
))
613 if (!recursive_rmdir(pathname
, fd
, cfd
))
614 lxcfs_debug("Error removing %s.\n", pathname
);
618 if (closedir(dir
) < 0) {
619 fprintf(stderr
, "%s: failed to close directory %s: %s\n", __func__
, dirname
, strerror(errno
));
623 if (unlinkat(cfd
, dirname
, AT_REMOVEDIR
) < 0) {
624 lxcfs_debug("Failed to delete %s: %s.\n", dirname
, strerror(errno
));
633 bool cgfs_remove(const char *controller
, const char *cg
)
640 tmpc
= find_mounted_controller(controller
, &cfd
);
644 /* Make sure we pass a relative path to *at() family of functions.
647 len
= strlen(cg
) + 2;
648 dirnam
= alloca(len
);
649 snprintf(dirnam
, len
, "%s%s", *cg
== '/' ? "." : "", cg
);
651 fd
= openat(cfd
, dirnam
, O_DIRECTORY
);
655 bret
= recursive_rmdir(dirnam
, fd
, cfd
);
660 bool cgfs_chmod_file(const char *controller
, const char *file
, mode_t mode
)
664 char *pathname
, *tmpc
;
666 tmpc
= find_mounted_controller(controller
, &cfd
);
670 /* Make sure we pass a relative path to *at() family of functions.
673 len
= strlen(file
) + 2;
674 pathname
= alloca(len
);
675 snprintf(pathname
, len
, "%s%s", *file
== '/' ? "." : "", file
);
676 if (fchmodat(cfd
, pathname
, mode
, 0) < 0)
681 static int chown_tasks_files(const char *dirname
, uid_t uid
, gid_t gid
, int fd
)
686 len
= strlen(dirname
) + strlen("/cgroup.procs") + 1;
688 snprintf(fname
, len
, "%s/tasks", dirname
);
689 if (fchownat(fd
, fname
, uid
, gid
, 0) != 0)
691 snprintf(fname
, len
, "%s/cgroup.procs", dirname
);
692 if (fchownat(fd
, fname
, uid
, gid
, 0) != 0)
697 int cgfs_chown_file(const char *controller
, const char *file
, uid_t uid
, gid_t gid
)
701 char *pathname
, *tmpc
;
703 tmpc
= find_mounted_controller(controller
, &cfd
);
707 /* Make sure we pass a relative path to *at() family of functions.
710 len
= strlen(file
) + 2;
711 pathname
= alloca(len
);
712 snprintf(pathname
, len
, "%s%s", *file
== '/' ? "." : "", file
);
713 if (fchownat(cfd
, pathname
, uid
, gid
, 0) < 0)
716 if (is_dir(pathname
, cfd
))
717 // like cgmanager did, we want to chown the tasks file as well
718 return chown_tasks_files(pathname
, uid
, gid
, cfd
);
723 FILE *open_pids_file(const char *controller
, const char *cgroup
)
727 char *pathname
, *tmpc
;
729 tmpc
= find_mounted_controller(controller
, &cfd
);
733 /* Make sure we pass a relative path to *at() family of functions.
734 * . + /cgroup + / "cgroup.procs" + \0
736 len
= strlen(cgroup
) + strlen("cgroup.procs") + 3;
737 pathname
= alloca(len
);
738 snprintf(pathname
, len
, "%s%s/cgroup.procs", *cgroup
== '/' ? "." : "", cgroup
);
740 fd
= openat(cfd
, pathname
, O_WRONLY
);
744 return fdopen(fd
, "w");
747 static bool cgfs_iterate_cgroup(const char *controller
, const char *cgroup
, bool directories
,
748 void ***list
, size_t typesize
,
749 void* (*iterator
)(const char*, const char*, const char*))
754 char pathname
[MAXPATHLEN
];
755 size_t sz
= 0, asz
= 0;
756 struct dirent
*dirent
;
759 tmpc
= find_mounted_controller(controller
, &cfd
);
764 /* Make sure we pass a relative path to *at() family of functions. */
765 len
= strlen(cgroup
) + 1 /* . */ + 1 /* \0 */;
767 ret
= snprintf(cg
, len
, "%s%s", *cgroup
== '/' ? "." : "", cgroup
);
768 if (ret
< 0 || (size_t)ret
>= len
) {
769 fprintf(stderr
, "%s: pathname too long under %s\n", __func__
, cgroup
);
773 fd
= openat(cfd
, cg
, O_DIRECTORY
);
781 while ((dirent
= readdir(dir
))) {
784 if (!strcmp(dirent
->d_name
, ".") ||
785 !strcmp(dirent
->d_name
, ".."))
788 ret
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", cg
, dirent
->d_name
);
789 if (ret
< 0 || ret
>= MAXPATHLEN
) {
790 fprintf(stderr
, "%s: pathname too long under %s\n", __func__
, cg
);
794 ret
= fstatat(cfd
, pathname
, &mystat
, AT_SYMLINK_NOFOLLOW
);
796 fprintf(stderr
, "%s: failed to stat %s: %s\n", __func__
, pathname
, strerror(errno
));
799 if ((!directories
&& !S_ISREG(mystat
.st_mode
)) ||
800 (directories
&& !S_ISDIR(mystat
.st_mode
)))
807 tmp
= realloc(*list
, asz
* typesize
);
811 (*list
)[sz
] = (*iterator
)(controller
, cg
, dirent
->d_name
);
812 (*list
)[sz
+1] = NULL
;
815 if (closedir(dir
) < 0) {
816 fprintf(stderr
, "%s: failed closedir for %s: %s\n", __func__
, cgroup
, strerror(errno
));
822 static void *make_children_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
826 dup
= strdup(dir_entry
);
831 bool cgfs_list_children(const char *controller
, const char *cgroup
, char ***list
)
833 return cgfs_iterate_cgroup(controller
, cgroup
, true, (void***)list
, sizeof(*list
), &make_children_list_entry
);
836 void free_key(struct cgfs_files
*k
)
844 void free_keys(struct cgfs_files
**keys
)
850 for (i
= 0; keys
[i
]; i
++) {
856 bool cgfs_get_value(const char *controller
, const char *cgroup
, const char *file
, char **value
)
862 tmpc
= find_mounted_controller(controller
, &cfd
);
866 /* Make sure we pass a relative path to *at() family of functions.
867 * . + /cgroup + / + file + \0
869 len
= strlen(cgroup
) + strlen(file
) + 3;
871 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, file
);
872 if (ret
< 0 || (size_t)ret
>= len
)
875 fd
= openat(cfd
, fnam
, O_RDONLY
);
879 *value
= slurp_file(fnam
, fd
);
880 return *value
!= NULL
;
883 struct cgfs_files
*cgfs_get_key(const char *controller
, const char *cgroup
, const char *file
)
889 struct cgfs_files
*newkey
;
891 tmpc
= find_mounted_controller(controller
, &cfd
);
895 if (file
&& *file
== '/')
898 if (file
&& strchr(file
, '/'))
901 /* Make sure we pass a relative path to *at() family of functions.
902 * . + /cgroup + / + file + \0
904 len
= strlen(cgroup
) + 3;
906 len
+= strlen(file
) + 1;
908 snprintf(fnam
, len
, "%s%s%s%s", *cgroup
== '/' ? "." : "", cgroup
,
909 file
? "/" : "", file
? file
: "");
911 ret
= fstatat(cfd
, fnam
, &sb
, 0);
916 newkey
= malloc(sizeof(struct cgfs_files
));
919 newkey
->name
= must_copy_string(file
);
920 else if (strrchr(cgroup
, '/'))
921 newkey
->name
= must_copy_string(strrchr(cgroup
, '/'));
923 newkey
->name
= must_copy_string(cgroup
);
924 newkey
->uid
= sb
.st_uid
;
925 newkey
->gid
= sb
.st_gid
;
926 newkey
->mode
= sb
.st_mode
;
931 static void *make_key_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
933 struct cgfs_files
*entry
= cgfs_get_key(controller
, cgroup
, dir_entry
);
935 fprintf(stderr
, "%s: Error getting files under %s:%s\n",
936 __func__
, controller
, cgroup
);
941 bool cgfs_list_keys(const char *controller
, const char *cgroup
, struct cgfs_files
***keys
)
943 return cgfs_iterate_cgroup(controller
, cgroup
, false, (void***)keys
, sizeof(*keys
), &make_key_list_entry
);
946 bool is_child_cgroup(const char *controller
, const char *cgroup
, const char *f
)
954 tmpc
= find_mounted_controller(controller
, &cfd
);
958 /* Make sure we pass a relative path to *at() family of functions.
959 * . + /cgroup + / + f + \0
961 len
= strlen(cgroup
) + strlen(f
) + 3;
963 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, f
);
964 if (ret
< 0 || (size_t)ret
>= len
)
967 ret
= fstatat(cfd
, fnam
, &sb
, 0);
968 if (ret
< 0 || !S_ISDIR(sb
.st_mode
))
974 #define SEND_CREDS_OK 0
975 #define SEND_CREDS_NOTSK 1
976 #define SEND_CREDS_FAIL 2
977 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
);
978 static int wait_for_pid(pid_t pid
);
979 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
);
980 static int send_creds_clone_wrapper(void *arg
);
983 * clone a task which switches to @task's namespace and writes '1'.
984 * over a unix sock so we can read the task's reaper's pid in our
987 * Note: glibc's fork() does not respect pidns, which can lead to failed
988 * assertions inside glibc (and thus failed forks) if the child's pid in
989 * the pidns and the parent pid outside are identical. Using clone prevents
992 static void write_task_init_pid_exit(int sock
, pid_t target
)
997 size_t stack_size
= sysconf(_SC_PAGESIZE
);
998 void *stack
= alloca(stack_size
);
1000 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", (int)target
);
1001 if (ret
< 0 || ret
>= sizeof(fnam
))
1004 fd
= open(fnam
, O_RDONLY
);
1006 perror("write_task_init_pid_exit open of ns/pid");
1010 perror("write_task_init_pid_exit setns 1");
1014 pid
= clone(send_creds_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &sock
);
1018 if (!wait_for_pid(pid
))
1024 static int send_creds_clone_wrapper(void *arg
) {
1027 int sock
= *(int *)arg
;
1029 /* we are the child */
1034 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
)
1039 static pid_t
get_init_pid_for_task(pid_t task
)
1047 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
1048 perror("socketpair");
1057 write_task_init_pid_exit(sock
[0], task
);
1061 if (!recv_creds(sock
[1], &cred
, &v
))
1073 static pid_t
lookup_initpid_in_store(pid_t qpid
)
1077 struct pidns_init_store
*e
;
1080 snprintf(fnam
, 100, "/proc/%d/ns/pid", qpid
);
1082 if (stat(fnam
, &sb
) < 0)
1084 e
= lookup_verify_initpid(&sb
);
1086 answer
= e
->initpid
;
1089 answer
= get_init_pid_for_task(qpid
);
1091 save_initpid(&sb
, answer
);
1094 /* we prune at end in case we are returning
1095 * the value we were about to return */
1096 prune_initpid_store();
1101 static int wait_for_pid(pid_t pid
)
1109 ret
= waitpid(pid
, &status
, 0);
1117 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
1124 * append pid to *src.
1125 * src: a pointer to a char* in which ot append the pid.
1126 * sz: the number of characters printed so far, minus trailing \0.
1127 * asz: the allocated size so far
1128 * pid: the pid to append
1130 static void must_strcat_pid(char **src
, size_t *sz
, size_t *asz
, pid_t pid
)
1134 int tmplen
= sprintf(tmp
, "%d\n", (int)pid
);
1136 if (!*src
|| tmplen
+ *sz
+ 1 >= *asz
) {
1139 tmp
= realloc(*src
, *asz
+ BUF_RESERVE_SIZE
);
1142 *asz
+= BUF_RESERVE_SIZE
;
1144 memcpy((*src
) +*sz
, tmp
, tmplen
+1); /* include the \0 */
1149 * Given a open file * to /proc/pid/{u,g}id_map, and an id
1150 * valid in the caller's namespace, return the id mapped into
1152 * Returns the mapped id, or -1 on error.
1155 convert_id_to_ns(FILE *idfile
, unsigned int in_id
)
1157 unsigned int nsuid
, // base id for a range in the idfile's namespace
1158 hostuid
, // base id for a range in the caller's namespace
1159 count
; // number of ids in this range
1163 fseek(idfile
, 0L, SEEK_SET
);
1164 while (fgets(line
, 400, idfile
)) {
1165 ret
= sscanf(line
, "%u %u %u\n", &nsuid
, &hostuid
, &count
);
1168 if (hostuid
+ count
< hostuid
|| nsuid
+ count
< nsuid
) {
1170 * uids wrapped around - unexpected as this is a procfile,
1173 fprintf(stderr
, "pid wrapparound at entry %u %u %u in %s\n",
1174 nsuid
, hostuid
, count
, line
);
1177 if (hostuid
<= in_id
&& hostuid
+count
> in_id
) {
1179 * now since hostuid <= in_id < hostuid+count, and
1180 * hostuid+count and nsuid+count do not wrap around,
1181 * we know that nsuid+(in_id-hostuid) which must be
1182 * less that nsuid+(count) must not wrap around
1184 return (in_id
- hostuid
) + nsuid
;
1193 * for is_privileged_over,
1194 * specify whether we require the calling uid to be root in his
1197 #define NS_ROOT_REQD true
1198 #define NS_ROOT_OPT false
1202 static bool is_privileged_over(pid_t pid
, uid_t uid
, uid_t victim
, bool req_ns_root
)
1204 char fpath
[PROCLEN
];
1206 bool answer
= false;
1209 if (victim
== -1 || uid
== -1)
1213 * If the request is one not requiring root in the namespace,
1214 * then having the same uid suffices. (i.e. uid 1000 has write
1215 * access to files owned by uid 1000
1217 if (!req_ns_root
&& uid
== victim
)
1220 ret
= snprintf(fpath
, PROCLEN
, "/proc/%d/uid_map", pid
);
1221 if (ret
< 0 || ret
>= PROCLEN
)
1223 FILE *f
= fopen(fpath
, "r");
1227 /* if caller's not root in his namespace, reject */
1228 nsuid
= convert_id_to_ns(f
, uid
);
1233 * If victim is not mapped into caller's ns, reject.
1234 * XXX I'm not sure this check is needed given that fuse
1235 * will be sending requests where the vfs has converted
1237 nsuid
= convert_id_to_ns(f
, victim
);
1248 static bool perms_include(int fmode
, mode_t req_mode
)
1252 switch (req_mode
& O_ACCMODE
) {
1260 r
= S_IROTH
| S_IWOTH
;
1265 return ((fmode
& r
) == r
);
1271 * querycg is /a/b/c/d/e
1274 static char *get_next_cgroup_dir(const char *taskcg
, const char *querycg
)
1278 if (strlen(taskcg
) <= strlen(querycg
)) {
1279 fprintf(stderr
, "%s: I was fed bad input\n", __func__
);
1283 if ((strcmp(querycg
, "/") == 0) || (strcmp(querycg
, "./") == 0))
1284 start
= strdup(taskcg
+ 1);
1286 start
= strdup(taskcg
+ strlen(querycg
) + 1);
1289 end
= strchr(start
, '/');
1295 static void stripnewline(char *x
)
1297 size_t l
= strlen(x
);
1298 if (l
&& x
[l
-1] == '\n')
1302 static char *get_pid_cgroup(pid_t pid
, const char *contrl
)
1307 char *answer
= NULL
;
1311 const char *h
= find_mounted_controller(contrl
, &cfd
);
1315 ret
= snprintf(fnam
, PROCLEN
, "/proc/%d/cgroup", pid
);
1316 if (ret
< 0 || ret
>= PROCLEN
)
1318 if (!(f
= fopen(fnam
, "r")))
1321 while (getline(&line
, &len
, f
) != -1) {
1325 c1
= strchr(line
, ':');
1329 c2
= strchr(c1
, ':');
1333 if (strcmp(c1
, h
) != 0)
1338 answer
= strdup(c2
);
1350 * check whether a fuse context may access a cgroup dir or file
1352 * If file is not null, it is a cgroup file to check under cg.
1353 * If file is null, then we are checking perms on cg itself.
1355 * For files we can check the mode of the list_keys result.
1356 * For cgroups, we must make assumptions based on the files under the
1357 * cgroup, because cgmanager doesn't tell us ownership/perms of cgroups
1360 static bool fc_may_access(struct fuse_context
*fc
, const char *contrl
, const char *cg
, const char *file
, mode_t mode
)
1362 struct cgfs_files
*k
= NULL
;
1365 k
= cgfs_get_key(contrl
, cg
, file
);
1369 if (is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
1370 if (perms_include(k
->mode
>> 6, mode
)) {
1375 if (fc
->gid
== k
->gid
) {
1376 if (perms_include(k
->mode
>> 3, mode
)) {
1381 ret
= perms_include(k
->mode
, mode
);
1388 #define INITSCOPE "/init.scope"
1389 static void prune_init_slice(char *cg
)
1392 size_t cg_len
= strlen(cg
), initscope_len
= strlen(INITSCOPE
);
1394 if (cg_len
< initscope_len
)
1397 point
= cg
+ cg_len
- initscope_len
;
1398 if (strcmp(point
, INITSCOPE
) == 0) {
1407 * If pid is in /a/b/c/d, he may only act on things under cg=/a/b/c/d.
1408 * If pid is in /a, he may act on /a/b, but not on /b.
1409 * if the answer is false and nextcg is not NULL, then *nextcg will point
1410 * to a string containing the next cgroup directory under cg, which must be
1411 * freed by the caller.
1413 static bool caller_is_in_ancestor(pid_t pid
, const char *contrl
, const char *cg
, char **nextcg
)
1415 bool answer
= false;
1416 char *c2
= get_pid_cgroup(pid
, contrl
);
1421 prune_init_slice(c2
);
1424 * callers pass in '/' or './' (openat()) for root cgroup, otherwise
1425 * they pass in a cgroup without leading '/'
1427 * The original line here was:
1428 * linecmp = *cg == '/' ? c2 : c2+1;
1429 * TODO: I'm not sure why you'd want to increment when *cg != '/'?
1430 * Serge, do you know?
1432 if (*cg
== '/' || !strncmp(cg
, "./", 2))
1436 if (strncmp(linecmp
, cg
, strlen(linecmp
)) != 0) {
1438 *nextcg
= get_next_cgroup_dir(linecmp
, cg
);
1450 * If pid is in /a/b/c, he may see that /a exists, but not /b or /a/c.
1452 static bool caller_may_see_dir(pid_t pid
, const char *contrl
, const char *cg
)
1454 bool answer
= false;
1456 size_t target_len
, task_len
;
1458 if (strcmp(cg
, "/") == 0 || strcmp(cg
, "./") == 0)
1461 c2
= get_pid_cgroup(pid
, contrl
);
1464 prune_init_slice(c2
);
1467 target_len
= strlen(cg
);
1468 task_len
= strlen(task_cg
);
1469 if (task_len
== 0) {
1470 /* Task is in the root cg, it can see everything. This case is
1471 * not handled by the strmcps below, since they test for the
1472 * last /, but that is the first / that we've chopped off
1478 if (strcmp(cg
, task_cg
) == 0) {
1482 if (target_len
< task_len
) {
1483 /* looking up a parent dir */
1484 if (strncmp(task_cg
, cg
, target_len
) == 0 && task_cg
[target_len
] == '/')
1488 if (target_len
> task_len
) {
1489 /* looking up a child dir */
1490 if (strncmp(task_cg
, cg
, task_len
) == 0 && cg
[task_len
] == '/')
1501 * given /cgroup/freezer/a/b, return "freezer".
1502 * the returned char* should NOT be freed.
1504 static char *pick_controller_from_path(struct fuse_context
*fc
, const char *path
)
1507 char *contr
, *slash
;
1509 if (strlen(path
) < 9) {
1513 if (*(path
+ 7) != '/') {
1518 contr
= strdupa(p1
);
1523 slash
= strstr(contr
, "/");
1528 for (i
= 0; i
< num_hierarchies
; i
++) {
1529 if (hierarchies
[i
] && strcmp(hierarchies
[i
], contr
) == 0)
1530 return hierarchies
[i
];
1537 * Find the start of cgroup in /cgroup/controller/the/cgroup/path
1538 * Note that the returned value may include files (keynames) etc
1540 static const char *find_cgroup_in_path(const char *path
)
1544 if (strlen(path
) < 9)
1546 p1
= strstr(path
+8, "/");
1553 * split the last path element from the path in @cg.
1554 * @dir is newly allocated and should be freed, @last not
1556 static void get_cgdir_and_path(const char *cg
, char **dir
, char **last
)
1563 *last
= strrchr(cg
, '/');
1568 p
= strrchr(*dir
, '/');
1573 * FUSE ops for /cgroup
1576 int cg_getattr(const char *path
, struct stat
*sb
)
1578 struct timespec now
;
1579 struct fuse_context
*fc
= fuse_get_context();
1580 char * cgdir
= NULL
;
1581 char *last
= NULL
, *path1
, *path2
;
1582 struct cgfs_files
*k
= NULL
;
1584 const char *controller
= NULL
;
1591 memset(sb
, 0, sizeof(struct stat
));
1593 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
1596 sb
->st_uid
= sb
->st_gid
= 0;
1597 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
1600 if (strcmp(path
, "/cgroup") == 0) {
1601 sb
->st_mode
= S_IFDIR
| 00755;
1606 controller
= pick_controller_from_path(fc
, path
);
1609 cgroup
= find_cgroup_in_path(path
);
1611 /* this is just /cgroup/controller, return it as a dir */
1612 sb
->st_mode
= S_IFDIR
| 00755;
1617 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
1627 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1630 /* check that cgcopy is either a child cgroup of cgdir, or listed in its keys.
1631 * Then check that caller's cgroup is under path if last is a child
1632 * cgroup, or cgdir if last is a file */
1634 if (is_child_cgroup(controller
, path1
, path2
)) {
1635 if (!caller_may_see_dir(initpid
, controller
, cgroup
)) {
1639 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
1640 /* this is just /cgroup/controller, return it as a dir */
1641 sb
->st_mode
= S_IFDIR
| 00555;
1646 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
)) {
1651 // get uid, gid, from '/tasks' file and make up a mode
1652 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
1653 sb
->st_mode
= S_IFDIR
| 00755;
1654 k
= cgfs_get_key(controller
, cgroup
, NULL
);
1656 sb
->st_uid
= sb
->st_gid
= 0;
1658 sb
->st_uid
= k
->uid
;
1659 sb
->st_gid
= k
->gid
;
1667 if ((k
= cgfs_get_key(controller
, path1
, path2
)) != NULL
) {
1668 sb
->st_mode
= S_IFREG
| k
->mode
;
1670 sb
->st_uid
= k
->uid
;
1671 sb
->st_gid
= k
->gid
;
1674 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
1678 if (!fc_may_access(fc
, controller
, path1
, path2
, O_RDONLY
)) {
1691 int cg_opendir(const char *path
, struct fuse_file_info
*fi
)
1693 struct fuse_context
*fc
= fuse_get_context();
1695 struct file_info
*dir_info
;
1696 char *controller
= NULL
;
1701 if (strcmp(path
, "/cgroup") == 0) {
1705 // return list of keys for the controller, and list of child cgroups
1706 controller
= pick_controller_from_path(fc
, path
);
1710 cgroup
= find_cgroup_in_path(path
);
1712 /* this is just /cgroup/controller, return its contents */
1717 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1721 if (!caller_may_see_dir(initpid
, controller
, cgroup
))
1723 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
))
1727 /* we'll free this at cg_releasedir */
1728 dir_info
= malloc(sizeof(*dir_info
));
1731 dir_info
->controller
= must_copy_string(controller
);
1732 dir_info
->cgroup
= must_copy_string(cgroup
);
1733 dir_info
->type
= LXC_TYPE_CGDIR
;
1734 dir_info
->buf
= NULL
;
1735 dir_info
->file
= NULL
;
1736 dir_info
->buflen
= 0;
1738 fi
->fh
= (unsigned long)dir_info
;
1742 int cg_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
1743 struct fuse_file_info
*fi
)
1745 struct file_info
*d
= (struct file_info
*)fi
->fh
;
1746 struct cgfs_files
**list
= NULL
;
1748 char *nextcg
= NULL
;
1749 struct fuse_context
*fc
= fuse_get_context();
1750 char **clist
= NULL
;
1752 if (filler(buf
, ".", NULL
, 0) != 0 || filler(buf
, "..", NULL
, 0) != 0)
1755 if (d
->type
!= LXC_TYPE_CGDIR
) {
1756 fprintf(stderr
, "Internal error: file cache info used in readdir\n");
1759 if (!d
->cgroup
&& !d
->controller
) {
1760 // ls /var/lib/lxcfs/cgroup - just show list of controllers
1763 for (i
= 0; i
< num_hierarchies
; i
++) {
1764 if (hierarchies
[i
] && filler(buf
, hierarchies
[i
], NULL
, 0) != 0) {
1771 if (!cgfs_list_keys(d
->controller
, d
->cgroup
, &list
)) {
1772 // not a valid cgroup
1777 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1780 if (!caller_is_in_ancestor(initpid
, d
->controller
, d
->cgroup
, &nextcg
)) {
1782 ret
= filler(buf
, nextcg
, NULL
, 0);
1793 for (i
= 0; list
[i
]; i
++) {
1794 if (filler(buf
, list
[i
]->name
, NULL
, 0) != 0) {
1800 // now get the list of child cgroups
1802 if (!cgfs_list_children(d
->controller
, d
->cgroup
, &clist
)) {
1807 for (i
= 0; clist
[i
]; i
++) {
1808 if (filler(buf
, clist
[i
], NULL
, 0) != 0) {
1819 for (i
= 0; clist
[i
]; i
++)
1826 static void do_release_file_info(struct fuse_file_info
*fi
)
1828 struct file_info
*f
= (struct file_info
*)fi
->fh
;
1835 free(f
->controller
);
1836 f
->controller
= NULL
;
1846 int cg_releasedir(const char *path
, struct fuse_file_info
*fi
)
1848 do_release_file_info(fi
);
1852 int cg_open(const char *path
, struct fuse_file_info
*fi
)
1855 char *last
= NULL
, *path1
, *path2
, * cgdir
= NULL
, *controller
;
1856 struct cgfs_files
*k
= NULL
;
1857 struct file_info
*file_info
;
1858 struct fuse_context
*fc
= fuse_get_context();
1864 controller
= pick_controller_from_path(fc
, path
);
1867 cgroup
= find_cgroup_in_path(path
);
1871 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
1880 k
= cgfs_get_key(controller
, path1
, path2
);
1887 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1890 if (!caller_may_see_dir(initpid
, controller
, path1
)) {
1894 if (!fc_may_access(fc
, controller
, path1
, path2
, fi
->flags
)) {
1899 /* we'll free this at cg_release */
1900 file_info
= malloc(sizeof(*file_info
));
1905 file_info
->controller
= must_copy_string(controller
);
1906 file_info
->cgroup
= must_copy_string(path1
);
1907 file_info
->file
= must_copy_string(path2
);
1908 file_info
->type
= LXC_TYPE_CGFILE
;
1909 file_info
->buf
= NULL
;
1910 file_info
->buflen
= 0;
1912 fi
->fh
= (unsigned long)file_info
;
1920 int cg_access(const char *path
, int mode
)
1924 char *path1
, *path2
, *controller
;
1925 char *last
= NULL
, *cgdir
= NULL
;
1926 struct cgfs_files
*k
= NULL
;
1927 struct fuse_context
*fc
= fuse_get_context();
1929 if (strcmp(path
, "/cgroup") == 0) {
1930 if ((mode
& W_OK
) == 0)
1938 controller
= pick_controller_from_path(fc
, path
);
1941 cgroup
= find_cgroup_in_path(path
);
1943 // access("/sys/fs/cgroup/systemd", mode) - rx allowed, w not
1944 if ((mode
& W_OK
) == 0)
1949 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
1958 k
= cgfs_get_key(controller
, path1
, path2
);
1960 if ((mode
& W_OK
) == 0)
1968 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1971 if (!caller_may_see_dir(initpid
, controller
, path1
)) {
1975 if (!fc_may_access(fc
, controller
, path1
, path2
, mode
)) {
1987 int cg_release(const char *path
, struct fuse_file_info
*fi
)
1989 do_release_file_info(fi
);
1993 #define POLLIN_SET ( EPOLLIN | EPOLLHUP | EPOLLRDHUP )
1995 static bool wait_for_sock(int sock
, int timeout
)
1997 struct epoll_event ev
;
1998 int epfd
, ret
, now
, starttime
, deltatime
, saved_errno
;
2000 if ((starttime
= time(NULL
)) < 0)
2003 if ((epfd
= epoll_create(1)) < 0) {
2004 fprintf(stderr
, "Failed to create epoll socket: %m\n");
2008 ev
.events
= POLLIN_SET
;
2010 if (epoll_ctl(epfd
, EPOLL_CTL_ADD
, sock
, &ev
) < 0) {
2011 fprintf(stderr
, "Failed adding socket to epoll: %m\n");
2017 if ((now
= time(NULL
)) < 0) {
2022 deltatime
= (starttime
+ timeout
) - now
;
2023 if (deltatime
< 0) { // timeout
2028 ret
= epoll_wait(epfd
, &ev
, 1, 1000*deltatime
+ 1);
2029 if (ret
< 0 && errno
== EINTR
)
2031 saved_errno
= errno
;
2035 errno
= saved_errno
;
2041 static int msgrecv(int sockfd
, void *buf
, size_t len
)
2043 if (!wait_for_sock(sockfd
, 2))
2045 return recv(sockfd
, buf
, len
, MSG_DONTWAIT
);
2048 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
)
2050 struct msghdr msg
= { 0 };
2052 struct cmsghdr
*cmsg
;
2053 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
2058 if (msgrecv(sock
, buf
, 1) != 1) {
2059 fprintf(stderr
, "%s: Error getting reply from server over socketpair\n",
2061 return SEND_CREDS_FAIL
;
2065 msg
.msg_control
= cmsgbuf
;
2066 msg
.msg_controllen
= sizeof(cmsgbuf
);
2068 cmsg
= CMSG_FIRSTHDR(&msg
);
2069 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct ucred
));
2070 cmsg
->cmsg_level
= SOL_SOCKET
;
2071 cmsg
->cmsg_type
= SCM_CREDENTIALS
;
2072 memcpy(CMSG_DATA(cmsg
), cred
, sizeof(*cred
));
2074 msg
.msg_name
= NULL
;
2075 msg
.msg_namelen
= 0;
2079 iov
.iov_len
= sizeof(buf
);
2083 if (sendmsg(sock
, &msg
, 0) < 0) {
2084 fprintf(stderr
, "%s: failed at sendmsg: %s\n", __func__
,
2087 return SEND_CREDS_NOTSK
;
2088 return SEND_CREDS_FAIL
;
2091 return SEND_CREDS_OK
;
2094 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
)
2096 struct msghdr msg
= { 0 };
2098 struct cmsghdr
*cmsg
;
2099 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
2110 if (setsockopt(sock
, SOL_SOCKET
, SO_PASSCRED
, &optval
, sizeof(optval
)) == -1) {
2111 fprintf(stderr
, "Failed to set passcred: %s\n", strerror(errno
));
2115 if (write(sock
, buf
, 1) != 1) {
2116 fprintf(stderr
, "Failed to start write on scm fd: %s\n", strerror(errno
));
2120 msg
.msg_name
= NULL
;
2121 msg
.msg_namelen
= 0;
2122 msg
.msg_control
= cmsgbuf
;
2123 msg
.msg_controllen
= sizeof(cmsgbuf
);
2126 iov
.iov_len
= sizeof(buf
);
2130 if (!wait_for_sock(sock
, 2)) {
2131 fprintf(stderr
, "Timed out waiting for scm_cred: %s\n",
2135 ret
= recvmsg(sock
, &msg
, MSG_DONTWAIT
);
2137 fprintf(stderr
, "Failed to receive scm_cred: %s\n",
2142 cmsg
= CMSG_FIRSTHDR(&msg
);
2144 if (cmsg
&& cmsg
->cmsg_len
== CMSG_LEN(sizeof(struct ucred
)) &&
2145 cmsg
->cmsg_level
== SOL_SOCKET
&&
2146 cmsg
->cmsg_type
== SCM_CREDENTIALS
) {
2147 memcpy(cred
, CMSG_DATA(cmsg
), sizeof(*cred
));
2154 struct pid_ns_clone_args
{
2158 int (*wrapped
) (int, pid_t
); // pid_from_ns or pid_to_ns
2162 * pid_ns_clone_wrapper - wraps pid_to_ns or pid_from_ns for usage
2163 * with clone(). This simply writes '1' as ACK back to the parent
2164 * before calling the actual wrapped function.
2166 static int pid_ns_clone_wrapper(void *arg
) {
2167 struct pid_ns_clone_args
* args
= (struct pid_ns_clone_args
*) arg
;
2170 close(args
->cpipe
[0]);
2171 if (write(args
->cpipe
[1], &b
, sizeof(char)) < 0) {
2172 fprintf(stderr
, "%s (child): error on write: %s\n",
2173 __func__
, strerror(errno
));
2175 close(args
->cpipe
[1]);
2176 return args
->wrapped(args
->sock
, args
->tpid
);
2180 * pid_to_ns - reads pids from a ucred over a socket, then writes the
2181 * int value back over the socket. This shifts the pid from the
2182 * sender's pidns into tpid's pidns.
2184 static int pid_to_ns(int sock
, pid_t tpid
)
2189 while (recv_creds(sock
, &cred
, &v
)) {
2192 if (write(sock
, &cred
.pid
, sizeof(pid_t
)) != sizeof(pid_t
))
2200 * pid_to_ns_wrapper: when you setns into a pidns, you yourself remain
2201 * in your old pidns. Only children which you clone will be in the target
2202 * pidns. So the pid_to_ns_wrapper does the setns, then clones a child to
2203 * actually convert pids.
2205 * Note: glibc's fork() does not respect pidns, which can lead to failed
2206 * assertions inside glibc (and thus failed forks) if the child's pid in
2207 * the pidns and the parent pid outside are identical. Using clone prevents
2210 static void pid_to_ns_wrapper(int sock
, pid_t tpid
)
2212 int newnsfd
= -1, ret
, cpipe
[2];
2217 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
2218 if (ret
< 0 || ret
>= sizeof(fnam
))
2220 newnsfd
= open(fnam
, O_RDONLY
);
2223 if (setns(newnsfd
, 0) < 0)
2227 if (pipe(cpipe
) < 0)
2230 struct pid_ns_clone_args args
= {
2234 .wrapped
= &pid_to_ns
2236 size_t stack_size
= sysconf(_SC_PAGESIZE
);
2237 void *stack
= alloca(stack_size
);
2239 cpid
= clone(pid_ns_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &args
);
2243 // give the child 1 second to be done forking and
2245 if (!wait_for_sock(cpipe
[0], 1))
2247 ret
= read(cpipe
[0], &v
, 1);
2248 if (ret
!= sizeof(char) || v
!= '1')
2251 if (!wait_for_pid(cpid
))
2257 * To read cgroup files with a particular pid, we will setns into the child
2258 * pidns, open a pipe, fork a child - which will be the first to really be in
2259 * the child ns - which does the cgfs_get_value and writes the data to the pipe.
2261 bool do_read_pids(pid_t tpid
, const char *contrl
, const char *cg
, const char *file
, char **d
)
2263 int sock
[2] = {-1, -1};
2264 char *tmpdata
= NULL
;
2266 pid_t qpid
, cpid
= -1;
2267 bool answer
= false;
2270 size_t sz
= 0, asz
= 0;
2272 if (!cgfs_get_value(contrl
, cg
, file
, &tmpdata
))
2276 * Now we read the pids from returned data one by one, pass
2277 * them into a child in the target namespace, read back the
2278 * translated pids, and put them into our to-return data
2281 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2282 perror("socketpair");
2291 if (!cpid
) // child - exits when done
2292 pid_to_ns_wrapper(sock
[1], tpid
);
2294 char *ptr
= tmpdata
;
2297 while (sscanf(ptr
, "%d\n", &qpid
) == 1) {
2299 ret
= send_creds(sock
[0], &cred
, v
, true);
2301 if (ret
== SEND_CREDS_NOTSK
)
2303 if (ret
== SEND_CREDS_FAIL
)
2306 // read converted results
2307 if (!wait_for_sock(sock
[0], 2)) {
2308 fprintf(stderr
, "%s: timed out waiting for pid from child: %s\n",
2309 __func__
, strerror(errno
));
2312 if (read(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2313 fprintf(stderr
, "%s: error reading pid from child: %s\n",
2314 __func__
, strerror(errno
));
2317 must_strcat_pid(d
, &sz
, &asz
, qpid
);
2319 ptr
= strchr(ptr
, '\n');
2325 cred
.pid
= getpid();
2327 if (send_creds(sock
[0], &cred
, v
, true) != SEND_CREDS_OK
) {
2328 // failed to ask child to exit
2329 fprintf(stderr
, "%s: failed to ask child to exit: %s\n",
2330 __func__
, strerror(errno
));
2340 if (sock
[0] != -1) {
2347 int cg_read(const char *path
, char *buf
, size_t size
, off_t offset
,
2348 struct fuse_file_info
*fi
)
2350 struct fuse_context
*fc
= fuse_get_context();
2351 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2352 struct cgfs_files
*k
= NULL
;
2357 if (f
->type
!= LXC_TYPE_CGFILE
) {
2358 fprintf(stderr
, "Internal error: directory cache info used in cg_read\n");
2371 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
2377 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_RDONLY
)) {
2382 if (strcmp(f
->file
, "tasks") == 0 ||
2383 strcmp(f
->file
, "/tasks") == 0 ||
2384 strcmp(f
->file
, "/cgroup.procs") == 0 ||
2385 strcmp(f
->file
, "cgroup.procs") == 0)
2386 // special case - we have to translate the pids
2387 r
= do_read_pids(fc
->pid
, f
->controller
, f
->cgroup
, f
->file
, &data
);
2389 r
= cgfs_get_value(f
->controller
, f
->cgroup
, f
->file
, &data
);
2403 memcpy(buf
, data
, s
);
2404 if (s
> 0 && s
< size
&& data
[s
-1] != '\n')
2414 static int pid_from_ns(int sock
, pid_t tpid
)
2424 if (!wait_for_sock(sock
, 2)) {
2425 fprintf(stderr
, "%s: timeout reading from parent\n", __func__
);
2428 if ((ret
= read(sock
, &vpid
, sizeof(pid_t
))) != sizeof(pid_t
)) {
2429 fprintf(stderr
, "%s: bad read from parent: %s\n",
2430 __func__
, strerror(errno
));
2433 if (vpid
== -1) // done
2437 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
) {
2439 cred
.pid
= getpid();
2440 if (send_creds(sock
, &cred
, v
, false) != SEND_CREDS_OK
)
2447 static void pid_from_ns_wrapper(int sock
, pid_t tpid
)
2449 int newnsfd
= -1, ret
, cpipe
[2];
2454 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
2455 if (ret
< 0 || ret
>= sizeof(fnam
))
2457 newnsfd
= open(fnam
, O_RDONLY
);
2460 if (setns(newnsfd
, 0) < 0)
2464 if (pipe(cpipe
) < 0)
2467 struct pid_ns_clone_args args
= {
2471 .wrapped
= &pid_from_ns
2473 size_t stack_size
= sysconf(_SC_PAGESIZE
);
2474 void *stack
= alloca(stack_size
);
2476 cpid
= clone(pid_ns_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &args
);
2480 // give the child 1 second to be done forking and
2482 if (!wait_for_sock(cpipe
[0], 1))
2484 ret
= read(cpipe
[0], &v
, 1);
2485 if (ret
!= sizeof(char) || v
!= '1')
2488 if (!wait_for_pid(cpid
))
2494 * Given host @uid, return the uid to which it maps in
2495 * @pid's user namespace, or -1 if none.
2497 bool hostuid_to_ns(uid_t uid
, pid_t pid
, uid_t
*answer
)
2502 sprintf(line
, "/proc/%d/uid_map", pid
);
2503 if ((f
= fopen(line
, "r")) == NULL
) {
2507 *answer
= convert_id_to_ns(f
, uid
);
2516 * get_pid_creds: get the real uid and gid of @pid from
2518 * (XXX should we use euid here?)
2520 void get_pid_creds(pid_t pid
, uid_t
*uid
, gid_t
*gid
)
2529 sprintf(line
, "/proc/%d/status", pid
);
2530 if ((f
= fopen(line
, "r")) == NULL
) {
2531 fprintf(stderr
, "Error opening %s: %s\n", line
, strerror(errno
));
2534 while (fgets(line
, 400, f
)) {
2535 if (strncmp(line
, "Uid:", 4) == 0) {
2536 if (sscanf(line
+4, "%u", &u
) != 1) {
2537 fprintf(stderr
, "bad uid line for pid %u\n", pid
);
2542 } else if (strncmp(line
, "Gid:", 4) == 0) {
2543 if (sscanf(line
+4, "%u", &g
) != 1) {
2544 fprintf(stderr
, "bad gid line for pid %u\n", pid
);
2555 * May the requestor @r move victim @v to a new cgroup?
2556 * This is allowed if
2557 * . they are the same task
2558 * . they are ownedy by the same uid
2559 * . @r is root on the host, or
2560 * . @v's uid is mapped into @r's where @r is root.
2562 bool may_move_pid(pid_t r
, uid_t r_uid
, pid_t v
)
2564 uid_t v_uid
, tmpuid
;
2571 get_pid_creds(v
, &v_uid
, &v_gid
);
2574 if (hostuid_to_ns(r_uid
, r
, &tmpuid
) && tmpuid
== 0
2575 && hostuid_to_ns(v_uid
, r
, &tmpuid
))
2580 static bool do_write_pids(pid_t tpid
, uid_t tuid
, const char *contrl
, const char *cg
,
2581 const char *file
, const char *buf
)
2583 int sock
[2] = {-1, -1};
2584 pid_t qpid
, cpid
= -1;
2585 FILE *pids_file
= NULL
;
2586 bool answer
= false, fail
= false;
2588 pids_file
= open_pids_file(contrl
, cg
);
2593 * write the pids to a socket, have helper in writer's pidns
2594 * call movepid for us
2596 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2597 perror("socketpair");
2605 if (!cpid
) { // child
2607 pid_from_ns_wrapper(sock
[1], tpid
);
2610 const char *ptr
= buf
;
2611 while (sscanf(ptr
, "%d", &qpid
) == 1) {
2615 if (write(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2616 fprintf(stderr
, "%s: error writing pid to child: %s\n",
2617 __func__
, strerror(errno
));
2621 if (recv_creds(sock
[0], &cred
, &v
)) {
2623 if (!may_move_pid(tpid
, tuid
, cred
.pid
)) {
2627 if (fprintf(pids_file
, "%d", (int) cred
.pid
) < 0)
2632 ptr
= strchr(ptr
, '\n');
2638 /* All good, write the value */
2640 if (write(sock
[0], &qpid
,sizeof(qpid
)) != sizeof(qpid
))
2641 fprintf(stderr
, "Warning: failed to ask child to exit\n");
2649 if (sock
[0] != -1) {
2654 if (fclose(pids_file
) != 0)
2660 int cg_write(const char *path
, const char *buf
, size_t size
, off_t offset
,
2661 struct fuse_file_info
*fi
)
2663 struct fuse_context
*fc
= fuse_get_context();
2664 char *localbuf
= NULL
;
2665 struct cgfs_files
*k
= NULL
;
2666 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2669 if (f
->type
!= LXC_TYPE_CGFILE
) {
2670 fprintf(stderr
, "Internal error: directory cache info used in cg_write\n");
2680 localbuf
= alloca(size
+1);
2681 localbuf
[size
] = '\0';
2682 memcpy(localbuf
, buf
, size
);
2684 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
2689 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_WRONLY
)) {
2694 if (strcmp(f
->file
, "tasks") == 0 ||
2695 strcmp(f
->file
, "/tasks") == 0 ||
2696 strcmp(f
->file
, "/cgroup.procs") == 0 ||
2697 strcmp(f
->file
, "cgroup.procs") == 0)
2698 // special case - we have to translate the pids
2699 r
= do_write_pids(fc
->pid
, fc
->uid
, f
->controller
, f
->cgroup
, f
->file
, localbuf
);
2701 r
= cgfs_set_value(f
->controller
, f
->cgroup
, f
->file
, localbuf
);
2711 int cg_chown(const char *path
, uid_t uid
, gid_t gid
)
2713 struct fuse_context
*fc
= fuse_get_context();
2714 char *cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
2715 struct cgfs_files
*k
= NULL
;
2722 if (strcmp(path
, "/cgroup") == 0)
2725 controller
= pick_controller_from_path(fc
, path
);
2728 cgroup
= find_cgroup_in_path(path
);
2730 /* this is just /cgroup/controller */
2733 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2743 if (is_child_cgroup(controller
, path1
, path2
)) {
2744 // get uid, gid, from '/tasks' file and make up a mode
2745 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
2746 k
= cgfs_get_key(controller
, cgroup
, "tasks");
2749 k
= cgfs_get_key(controller
, path1
, path2
);
2757 * This being a fuse request, the uid and gid must be valid
2758 * in the caller's namespace. So we can just check to make
2759 * sure that the caller is root in his uid, and privileged
2760 * over the file's current owner.
2762 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_REQD
)) {
2767 ret
= cgfs_chown_file(controller
, cgroup
, uid
, gid
);
2776 int cg_chmod(const char *path
, mode_t mode
)
2778 struct fuse_context
*fc
= fuse_get_context();
2779 char * cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
2780 struct cgfs_files
*k
= NULL
;
2787 if (strcmp(path
, "/cgroup") == 0)
2790 controller
= pick_controller_from_path(fc
, path
);
2793 cgroup
= find_cgroup_in_path(path
);
2795 /* this is just /cgroup/controller */
2798 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2808 if (is_child_cgroup(controller
, path1
, path2
)) {
2809 // get uid, gid, from '/tasks' file and make up a mode
2810 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
2811 k
= cgfs_get_key(controller
, cgroup
, "tasks");
2814 k
= cgfs_get_key(controller
, path1
, path2
);
2822 * This being a fuse request, the uid and gid must be valid
2823 * in the caller's namespace. So we can just check to make
2824 * sure that the caller is root in his uid, and privileged
2825 * over the file's current owner.
2827 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
2832 if (!cgfs_chmod_file(controller
, cgroup
, mode
)) {
2844 int cg_mkdir(const char *path
, mode_t mode
)
2846 struct fuse_context
*fc
= fuse_get_context();
2847 char *last
= NULL
, *path1
, *cgdir
= NULL
, *controller
, *next
= NULL
;
2855 controller
= pick_controller_from_path(fc
, path
);
2857 return errno
== ENOENT
? -EPERM
: -errno
;
2859 cgroup
= find_cgroup_in_path(path
);
2863 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2869 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2872 if (!caller_is_in_ancestor(initpid
, controller
, path1
, &next
)) {
2875 else if (last
&& strcmp(next
, last
) == 0)
2882 if (!fc_may_access(fc
, controller
, path1
, NULL
, O_RDWR
)) {
2886 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
2891 ret
= cgfs_create(controller
, cgroup
, fc
->uid
, fc
->gid
);
2899 int cg_rmdir(const char *path
)
2901 struct fuse_context
*fc
= fuse_get_context();
2902 char *last
= NULL
, *cgdir
= NULL
, *controller
, *next
= NULL
;
2909 controller
= pick_controller_from_path(fc
, path
);
2913 cgroup
= find_cgroup_in_path(path
);
2917 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2923 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2926 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, &next
)) {
2927 if (!last
|| strcmp(next
, last
) == 0)
2934 if (!fc_may_access(fc
, controller
, cgdir
, NULL
, O_WRONLY
)) {
2938 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
2943 if (!cgfs_remove(controller
, cgroup
)) {
2956 static bool startswith(const char *line
, const char *pref
)
2958 if (strncmp(line
, pref
, strlen(pref
)) == 0)
2963 static void parse_memstat(char *memstat
, unsigned long *cached
,
2964 unsigned long *active_anon
, unsigned long *inactive_anon
,
2965 unsigned long *active_file
, unsigned long *inactive_file
,
2966 unsigned long *unevictable
)
2971 if (startswith(memstat
, "cache")) {
2972 sscanf(memstat
+ 11, "%lu", cached
);
2974 } else if (startswith(memstat
, "active_anon")) {
2975 sscanf(memstat
+ 11, "%lu", active_anon
);
2976 *active_anon
/= 1024;
2977 } else if (startswith(memstat
, "inactive_anon")) {
2978 sscanf(memstat
+ 11, "%lu", inactive_anon
);
2979 *inactive_anon
/= 1024;
2980 } else if (startswith(memstat
, "active_file")) {
2981 sscanf(memstat
+ 11, "%lu", active_file
);
2982 *active_file
/= 1024;
2983 } else if (startswith(memstat
, "inactive_file")) {
2984 sscanf(memstat
+ 11, "%lu", inactive_file
);
2985 *inactive_file
/= 1024;
2986 } else if (startswith(memstat
, "unevictable")) {
2987 sscanf(memstat
+ 11, "%lu", unevictable
);
2988 *unevictable
/= 1024;
2990 eol
= strchr(memstat
, '\n');
2997 static void get_blkio_io_value(char *str
, unsigned major
, unsigned minor
, char *iotype
, unsigned long *v
)
3003 snprintf(key
, 32, "%u:%u %s", major
, minor
, iotype
);
3005 size_t len
= strlen(key
);
3009 if (startswith(str
, key
)) {
3010 sscanf(str
+ len
, "%lu", v
);
3013 eol
= strchr(str
, '\n');
3020 static int read_file(const char *path
, char *buf
, size_t size
,
3021 struct file_info
*d
)
3023 size_t linelen
= 0, total_len
= 0, rv
= 0;
3025 char *cache
= d
->buf
;
3026 size_t cache_size
= d
->buflen
;
3027 FILE *f
= fopen(path
, "r");
3031 while (getline(&line
, &linelen
, f
) != -1) {
3032 ssize_t l
= snprintf(cache
, cache_size
, "%s", line
);
3034 perror("Error writing to cache");
3038 if (l
>= cache_size
) {
3039 fprintf(stderr
, "Internal error: truncated write to cache\n");
3048 d
->size
= total_len
;
3049 if (total_len
> size
)
3052 /* read from off 0 */
3053 memcpy(buf
, d
->buf
, total_len
);
3062 * FUSE ops for /proc
3065 static unsigned long get_memlimit(const char *cgroup
)
3067 char *memlimit_str
= NULL
;
3068 unsigned long memlimit
= -1;
3070 if (cgfs_get_value("memory", cgroup
, "memory.limit_in_bytes", &memlimit_str
))
3071 memlimit
= strtoul(memlimit_str
, NULL
, 10);
3078 static unsigned long get_min_memlimit(const char *cgroup
)
3080 char *copy
= strdupa(cgroup
);
3081 unsigned long memlimit
= 0, retlimit
;
3083 retlimit
= get_memlimit(copy
);
3085 while (strcmp(copy
, "/") != 0) {
3086 copy
= dirname(copy
);
3087 memlimit
= get_memlimit(copy
);
3088 if (memlimit
!= -1 && memlimit
< retlimit
)
3089 retlimit
= memlimit
;
3095 static int proc_meminfo_read(char *buf
, size_t size
, off_t offset
,
3096 struct fuse_file_info
*fi
)
3098 struct fuse_context
*fc
= fuse_get_context();
3099 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3101 char *memusage_str
= NULL
, *memstat_str
= NULL
,
3102 *memswlimit_str
= NULL
, *memswusage_str
= NULL
,
3103 *memswlimit_default_str
= NULL
, *memswusage_default_str
= NULL
;
3104 unsigned long memlimit
= 0, memusage
= 0, memswlimit
= 0, memswusage
= 0,
3105 cached
= 0, hosttotal
= 0, active_anon
= 0, inactive_anon
= 0,
3106 active_file
= 0, inactive_file
= 0, unevictable
= 0;
3108 size_t linelen
= 0, total_len
= 0, rv
= 0;
3109 char *cache
= d
->buf
;
3110 size_t cache_size
= d
->buflen
;
3114 if (offset
> d
->size
)
3118 int left
= d
->size
- offset
;
3119 total_len
= left
> size
? size
: left
;
3120 memcpy(buf
, cache
+ offset
, total_len
);
3124 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3127 cg
= get_pid_cgroup(initpid
, "memory");
3129 return read_file("/proc/meminfo", buf
, size
, d
);
3130 prune_init_slice(cg
);
3132 memlimit
= get_min_memlimit(cg
);
3133 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
3135 if (!cgfs_get_value("memory", cg
, "memory.stat", &memstat_str
))
3138 // Following values are allowed to fail, because swapaccount might be turned
3139 // off for current kernel
3140 if(cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
) &&
3141 cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
))
3143 /* If swapaccounting is turned on, then default value is assumed to be that of cgroup / */
3144 if (!cgfs_get_value("memory", "/", "memory.memsw.limit_in_bytes", &memswlimit_default_str
))
3146 if (!cgfs_get_value("memory", "/", "memory.memsw.usage_in_bytes", &memswusage_default_str
))
3149 memswlimit
= strtoul(memswlimit_str
, NULL
, 10);
3150 memswusage
= strtoul(memswusage_str
, NULL
, 10);
3152 if (!strcmp(memswlimit_str
, memswlimit_default_str
))
3154 if (!strcmp(memswusage_str
, memswusage_default_str
))
3157 memswlimit
= memswlimit
/ 1024;
3158 memswusage
= memswusage
/ 1024;
3161 memusage
= strtoul(memusage_str
, NULL
, 10);
3165 parse_memstat(memstat_str
, &cached
, &active_anon
,
3166 &inactive_anon
, &active_file
, &inactive_file
,
3169 f
= fopen("/proc/meminfo", "r");
3173 while (getline(&line
, &linelen
, f
) != -1) {
3175 char *printme
, lbuf
[100];
3177 memset(lbuf
, 0, 100);
3178 if (startswith(line
, "MemTotal:")) {
3179 sscanf(line
+14, "%lu", &hosttotal
);
3180 if (hosttotal
< memlimit
)
3181 memlimit
= hosttotal
;
3182 snprintf(lbuf
, 100, "MemTotal: %8lu kB\n", memlimit
);
3184 } else if (startswith(line
, "MemFree:")) {
3185 snprintf(lbuf
, 100, "MemFree: %8lu kB\n", memlimit
- memusage
);
3187 } else if (startswith(line
, "MemAvailable:")) {
3188 snprintf(lbuf
, 100, "MemAvailable: %8lu kB\n", memlimit
- memusage
);
3190 } else if (startswith(line
, "SwapTotal:") && memswlimit
> 0) {
3191 snprintf(lbuf
, 100, "SwapTotal: %8lu kB\n", memswlimit
- memlimit
);
3193 } else if (startswith(line
, "SwapFree:") && memswlimit
> 0 && memswusage
> 0) {
3194 unsigned long swaptotal
= memswlimit
- memlimit
,
3195 swapusage
= memswusage
- memusage
,
3196 swapfree
= swapusage
< swaptotal
? swaptotal
- swapusage
: 0;
3197 snprintf(lbuf
, 100, "SwapFree: %8lu kB\n", swapfree
);
3199 } else if (startswith(line
, "Slab:")) {
3200 snprintf(lbuf
, 100, "Slab: %8lu kB\n", 0UL);
3202 } else if (startswith(line
, "Buffers:")) {
3203 snprintf(lbuf
, 100, "Buffers: %8lu kB\n", 0UL);
3205 } else if (startswith(line
, "Cached:")) {
3206 snprintf(lbuf
, 100, "Cached: %8lu kB\n", cached
);
3208 } else if (startswith(line
, "SwapCached:")) {
3209 snprintf(lbuf
, 100, "SwapCached: %8lu kB\n", 0UL);
3211 } else if (startswith(line
, "Active")) {
3212 snprintf(lbuf
, 100, "Active: %8lu kB\n",
3213 active_anon
+ active_file
);
3215 } else if (startswith(line
, "Inactive")) {
3216 snprintf(lbuf
, 100, "Inactive: %8lu kB\n",
3217 inactive_anon
+ inactive_file
);
3219 } else if (startswith(line
, "Active(anon)")) {
3220 snprintf(lbuf
, 100, "Active(anon): %8lu kB\n", active_anon
);
3222 } else if (startswith(line
, "Inactive(anon)")) {
3223 snprintf(lbuf
, 100, "Inactive(anon): %8lu kB\n", inactive_anon
);
3225 } else if (startswith(line
, "Active(file)")) {
3226 snprintf(lbuf
, 100, "Active(file): %8lu kB\n", active_file
);
3228 } else if (startswith(line
, "Inactive(file)")) {
3229 snprintf(lbuf
, 100, "Inactive(file): %8lu kB\n", inactive_file
);
3231 } else if (startswith(line
, "Unevictable")) {
3232 snprintf(lbuf
, 100, "Unevictable: %8lu kB\n", unevictable
);
3234 } else if (startswith(line
, "SReclaimable")) {
3235 snprintf(lbuf
, 100, "SReclaimable: %8lu kB\n", 0UL);
3237 } else if (startswith(line
, "SUnreclaim")) {
3238 snprintf(lbuf
, 100, "SUnreclaim: %8lu kB\n", 0UL);
3243 l
= snprintf(cache
, cache_size
, "%s", printme
);
3245 perror("Error writing to cache");
3250 if (l
>= cache_size
) {
3251 fprintf(stderr
, "Internal error: truncated write to cache\n");
3262 d
->size
= total_len
;
3263 if (total_len
> size
) total_len
= size
;
3264 memcpy(buf
, d
->buf
, total_len
);
3273 free(memswlimit_str
);
3274 free(memswusage_str
);
3276 free(memswlimit_default_str
);
3277 free(memswusage_default_str
);
3282 * Read the cpuset.cpus for cg
3283 * Return the answer in a newly allocated string which must be freed
3285 static char *get_cpuset(const char *cg
)
3289 if (!cgfs_get_value("cpuset", cg
, "cpuset.cpus", &answer
))
3294 bool cpu_in_cpuset(int cpu
, const char *cpuset
);
3296 static bool cpuline_in_cpuset(const char *line
, const char *cpuset
)
3300 if (sscanf(line
, "processor : %d", &cpu
) != 1)
3302 return cpu_in_cpuset(cpu
, cpuset
);
3306 * check whether this is a '^processor" line in /proc/cpuinfo
3308 static bool is_processor_line(const char *line
)
3312 if (sscanf(line
, "processor : %d", &cpu
) == 1)
3317 static int proc_cpuinfo_read(char *buf
, size_t size
, off_t offset
,
3318 struct fuse_file_info
*fi
)
3320 struct fuse_context
*fc
= fuse_get_context();
3321 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3323 char *cpuset
= NULL
;
3325 size_t linelen
= 0, total_len
= 0, rv
= 0;
3326 bool am_printing
= false, firstline
= true, is_s390x
= false;
3327 int curcpu
= -1, cpu
;
3328 char *cache
= d
->buf
;
3329 size_t cache_size
= d
->buflen
;
3333 if (offset
> d
->size
)
3337 int left
= d
->size
- offset
;
3338 total_len
= left
> size
? size
: left
;
3339 memcpy(buf
, cache
+ offset
, total_len
);
3343 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3346 cg
= get_pid_cgroup(initpid
, "cpuset");
3348 return read_file("proc/cpuinfo", buf
, size
, d
);
3349 prune_init_slice(cg
);
3351 cpuset
= get_cpuset(cg
);
3355 f
= fopen("/proc/cpuinfo", "r");
3359 while (getline(&line
, &linelen
, f
) != -1) {
3363 if (strstr(line
, "IBM/S390") != NULL
) {
3369 if (strncmp(line
, "# processors:", 12) == 0)
3371 if (is_processor_line(line
)) {
3372 am_printing
= cpuline_in_cpuset(line
, cpuset
);
3375 l
= snprintf(cache
, cache_size
, "processor : %d\n", curcpu
);
3377 perror("Error writing to cache");
3381 if (l
>= cache_size
) {
3382 fprintf(stderr
, "Internal error: truncated write to cache\n");
3391 } else if (is_s390x
&& sscanf(line
, "processor %d:", &cpu
) == 1) {
3393 if (!cpu_in_cpuset(cpu
, cpuset
))
3396 p
= strchr(line
, ':');
3400 l
= snprintf(cache
, cache_size
, "processor %d:%s", curcpu
, p
);
3402 perror("Error writing to cache");
3406 if (l
>= cache_size
) {
3407 fprintf(stderr
, "Internal error: truncated write to cache\n");
3418 l
= snprintf(cache
, cache_size
, "%s", line
);
3420 perror("Error writing to cache");
3424 if (l
>= cache_size
) {
3425 fprintf(stderr
, "Internal error: truncated write to cache\n");
3436 char *origcache
= d
->buf
;
3439 d
->buf
= malloc(d
->buflen
);
3442 cache_size
= d
->buflen
;
3444 l
= snprintf(cache
, cache_size
, "vendor_id : IBM/S390\n");
3445 if (l
< 0 || l
>= cache_size
) {
3452 l
= snprintf(cache
, cache_size
, "# processors : %d\n", curcpu
+ 1);
3453 if (l
< 0 || l
>= cache_size
) {
3460 l
= snprintf(cache
, cache_size
, "%s", origcache
);
3462 if (l
< 0 || l
>= cache_size
)
3468 d
->size
= total_len
;
3469 if (total_len
> size
) total_len
= size
;
3471 /* read from off 0 */
3472 memcpy(buf
, d
->buf
, total_len
);
3483 static int proc_stat_read(char *buf
, size_t size
, off_t offset
,
3484 struct fuse_file_info
*fi
)
3486 struct fuse_context
*fc
= fuse_get_context();
3487 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3489 char *cpuset
= NULL
;
3491 size_t linelen
= 0, total_len
= 0, rv
= 0;
3492 int curcpu
= -1; /* cpu numbering starts at 0 */
3493 unsigned long user
= 0, nice
= 0, system
= 0, idle
= 0, iowait
= 0, irq
= 0, softirq
= 0, steal
= 0, guest
= 0;
3494 unsigned long user_sum
= 0, nice_sum
= 0, system_sum
= 0, idle_sum
= 0, iowait_sum
= 0,
3495 irq_sum
= 0, softirq_sum
= 0, steal_sum
= 0, guest_sum
= 0;
3496 #define CPUALL_MAX_SIZE BUF_RESERVE_SIZE
3497 char cpuall
[CPUALL_MAX_SIZE
];
3498 /* reserve for cpu all */
3499 char *cache
= d
->buf
+ CPUALL_MAX_SIZE
;
3500 size_t cache_size
= d
->buflen
- CPUALL_MAX_SIZE
;
3504 if (offset
> d
->size
)
3508 int left
= d
->size
- offset
;
3509 total_len
= left
> size
? size
: left
;
3510 memcpy(buf
, d
->buf
+ offset
, total_len
);
3514 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3517 cg
= get_pid_cgroup(initpid
, "cpuset");
3519 return read_file("/proc/stat", buf
, size
, d
);
3520 prune_init_slice(cg
);
3522 cpuset
= get_cpuset(cg
);
3526 f
= fopen("/proc/stat", "r");
3531 if (getline(&line
, &linelen
, f
) < 0) {
3532 fprintf(stderr
, "proc_stat_read read first line failed\n");
3536 while (getline(&line
, &linelen
, f
) != -1) {
3539 char cpu_char
[10]; /* That's a lot of cores */
3542 if (strlen(line
) == 0)
3544 if (sscanf(line
, "cpu%9[^ ]", cpu_char
) != 1) {
3545 /* not a ^cpuN line containing a number N, just print it */
3546 l
= snprintf(cache
, cache_size
, "%s", line
);
3548 perror("Error writing to cache");
3552 if (l
>= cache_size
) {
3553 fprintf(stderr
, "Internal error: truncated write to cache\n");
3563 if (sscanf(cpu_char
, "%d", &cpu
) != 1)
3565 if (!cpu_in_cpuset(cpu
, cpuset
))
3569 c
= strchr(line
, ' ');
3572 l
= snprintf(cache
, cache_size
, "cpu%d%s", curcpu
, c
);
3574 perror("Error writing to cache");
3579 if (l
>= cache_size
) {
3580 fprintf(stderr
, "Internal error: truncated write to cache\n");
3589 if (sscanf(line
, "%*s %lu %lu %lu %lu %lu %lu %lu %lu %lu", &user
, &nice
, &system
, &idle
, &iowait
, &irq
,
3590 &softirq
, &steal
, &guest
) != 9)
3594 system_sum
+= system
;
3596 iowait_sum
+= iowait
;
3598 softirq_sum
+= softirq
;
3605 int cpuall_len
= snprintf(cpuall
, CPUALL_MAX_SIZE
, "%s %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
3606 "cpu ", user_sum
, nice_sum
, system_sum
, idle_sum
, iowait_sum
, irq_sum
, softirq_sum
, steal_sum
, guest_sum
);
3607 if (cpuall_len
> 0 && cpuall_len
< CPUALL_MAX_SIZE
){
3608 memcpy(cache
, cpuall
, cpuall_len
);
3609 cache
+= cpuall_len
;
3611 /* shouldn't happen */
3612 fprintf(stderr
, "proc_stat_read copy cpuall failed, cpuall_len=%d\n", cpuall_len
);
3616 memmove(cache
, d
->buf
+ CPUALL_MAX_SIZE
, total_len
);
3617 total_len
+= cpuall_len
;
3619 d
->size
= total_len
;
3620 if (total_len
> size
) total_len
= size
;
3622 memcpy(buf
, d
->buf
, total_len
);
3634 static long int getreaperage(pid_t pid
)
3641 qpid
= lookup_initpid_in_store(pid
);
3645 ret
= snprintf(fnam
, 100, "/proc/%d", qpid
);
3646 if (ret
< 0 || ret
>= 100)
3649 if (lstat(fnam
, &sb
) < 0)
3652 return time(NULL
) - sb
.st_ctime
;
3655 static unsigned long get_reaper_busy(pid_t task
)
3657 pid_t initpid
= lookup_initpid_in_store(task
);
3658 char *cgroup
= NULL
, *usage_str
= NULL
;
3659 unsigned long usage
= 0;
3664 cgroup
= get_pid_cgroup(initpid
, "cpuacct");
3667 prune_init_slice(cgroup
);
3668 if (!cgfs_get_value("cpuacct", cgroup
, "cpuacct.usage", &usage_str
))
3670 usage
= strtoul(usage_str
, NULL
, 10);
3671 usage
/= 1000000000;
3684 fd
= creat("/tmp/lxcfs-iwashere", 0644);
3691 * We read /proc/uptime and reuse its second field.
3692 * For the first field, we use the mtime for the reaper for
3693 * the calling pid as returned by getreaperage
3695 static int proc_uptime_read(char *buf
, size_t size
, off_t offset
,
3696 struct fuse_file_info
*fi
)
3698 struct fuse_context
*fc
= fuse_get_context();
3699 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3700 long int reaperage
= getreaperage(fc
->pid
);
3701 unsigned long int busytime
= get_reaper_busy(fc
->pid
), idletime
;
3702 char *cache
= d
->buf
;
3703 ssize_t total_len
= 0;
3710 if (offset
> d
->size
)
3714 int left
= d
->size
- offset
;
3715 total_len
= left
> size
? size
: left
;
3716 memcpy(buf
, cache
+ offset
, total_len
);
3720 idletime
= reaperage
- busytime
;
3721 if (idletime
> reaperage
)
3722 idletime
= reaperage
;
3724 total_len
= snprintf(d
->buf
, d
->size
, "%ld.0 %lu.0\n", reaperage
, idletime
);
3726 perror("Error writing to cache");
3730 d
->size
= (int)total_len
;
3733 if (total_len
> size
) total_len
= size
;
3735 memcpy(buf
, d
->buf
, total_len
);
3739 static int proc_diskstats_read(char *buf
, size_t size
, off_t offset
,
3740 struct fuse_file_info
*fi
)
3743 struct fuse_context
*fc
= fuse_get_context();
3744 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3746 char *io_serviced_str
= NULL
, *io_merged_str
= NULL
, *io_service_bytes_str
= NULL
,
3747 *io_wait_time_str
= NULL
, *io_service_time_str
= NULL
;
3748 unsigned long read
= 0, write
= 0;
3749 unsigned long read_merged
= 0, write_merged
= 0;
3750 unsigned long read_sectors
= 0, write_sectors
= 0;
3751 unsigned long read_ticks
= 0, write_ticks
= 0;
3752 unsigned long ios_pgr
= 0, tot_ticks
= 0, rq_ticks
= 0;
3753 unsigned long rd_svctm
= 0, wr_svctm
= 0, rd_wait
= 0, wr_wait
= 0;
3754 char *cache
= d
->buf
;
3755 size_t cache_size
= d
->buflen
;
3757 size_t linelen
= 0, total_len
= 0, rv
= 0;
3758 unsigned int major
= 0, minor
= 0;
3763 if (offset
> d
->size
)
3767 int left
= d
->size
- offset
;
3768 total_len
= left
> size
? size
: left
;
3769 memcpy(buf
, cache
+ offset
, total_len
);
3773 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3776 cg
= get_pid_cgroup(initpid
, "blkio");
3778 return read_file("/proc/diskstats", buf
, size
, d
);
3779 prune_init_slice(cg
);
3781 if (!cgfs_get_value("blkio", cg
, "blkio.io_serviced_recursive", &io_serviced_str
))
3783 if (!cgfs_get_value("blkio", cg
, "blkio.io_merged_recursive", &io_merged_str
))
3785 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_bytes_recursive", &io_service_bytes_str
))
3787 if (!cgfs_get_value("blkio", cg
, "blkio.io_wait_time_recursive", &io_wait_time_str
))
3789 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_time_recursive", &io_service_time_str
))
3793 f
= fopen("/proc/diskstats", "r");
3797 while (getline(&line
, &linelen
, f
) != -1) {
3801 i
= sscanf(line
, "%u %u %71s", &major
, &minor
, dev_name
);
3805 get_blkio_io_value(io_serviced_str
, major
, minor
, "Read", &read
);
3806 get_blkio_io_value(io_serviced_str
, major
, minor
, "Write", &write
);
3807 get_blkio_io_value(io_merged_str
, major
, minor
, "Read", &read_merged
);
3808 get_blkio_io_value(io_merged_str
, major
, minor
, "Write", &write_merged
);
3809 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Read", &read_sectors
);
3810 read_sectors
= read_sectors
/512;
3811 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Write", &write_sectors
);
3812 write_sectors
= write_sectors
/512;
3814 get_blkio_io_value(io_service_time_str
, major
, minor
, "Read", &rd_svctm
);
3815 rd_svctm
= rd_svctm
/1000000;
3816 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Read", &rd_wait
);
3817 rd_wait
= rd_wait
/1000000;
3818 read_ticks
= rd_svctm
+ rd_wait
;
3820 get_blkio_io_value(io_service_time_str
, major
, minor
, "Write", &wr_svctm
);
3821 wr_svctm
= wr_svctm
/1000000;
3822 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Write", &wr_wait
);
3823 wr_wait
= wr_wait
/1000000;
3824 write_ticks
= wr_svctm
+ wr_wait
;
3826 get_blkio_io_value(io_service_time_str
, major
, minor
, "Total", &tot_ticks
);
3827 tot_ticks
= tot_ticks
/1000000;
3829 memset(lbuf
, 0, 256);
3830 if (read
|| write
|| read_merged
|| write_merged
|| read_sectors
|| write_sectors
|| read_ticks
|| write_ticks
)
3831 snprintf(lbuf
, 256, "%u %u %s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
3832 major
, minor
, dev_name
, read
, read_merged
, read_sectors
, read_ticks
,
3833 write
, write_merged
, write_sectors
, write_ticks
, ios_pgr
, tot_ticks
, rq_ticks
);
3837 l
= snprintf(cache
, cache_size
, "%s", lbuf
);
3839 perror("Error writing to fuse buf");
3843 if (l
>= cache_size
) {
3844 fprintf(stderr
, "Internal error: truncated write to cache\n");
3854 d
->size
= total_len
;
3855 if (total_len
> size
) total_len
= size
;
3856 memcpy(buf
, d
->buf
, total_len
);
3864 free(io_serviced_str
);
3865 free(io_merged_str
);
3866 free(io_service_bytes_str
);
3867 free(io_wait_time_str
);
3868 free(io_service_time_str
);
3872 static int proc_swaps_read(char *buf
, size_t size
, off_t offset
,
3873 struct fuse_file_info
*fi
)
3875 struct fuse_context
*fc
= fuse_get_context();
3876 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3878 char *memswlimit_str
= NULL
, *memlimit_str
= NULL
, *memusage_str
= NULL
, *memswusage_str
= NULL
,
3879 *memswlimit_default_str
= NULL
, *memswusage_default_str
= NULL
;
3880 unsigned long memswlimit
= 0, memlimit
= 0, memusage
= 0, memswusage
= 0, swap_total
= 0, swap_free
= 0;
3881 ssize_t total_len
= 0, rv
= 0;
3883 char *cache
= d
->buf
;
3886 if (offset
> d
->size
)
3890 int left
= d
->size
- offset
;
3891 total_len
= left
> size
? size
: left
;
3892 memcpy(buf
, cache
+ offset
, total_len
);
3896 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3899 cg
= get_pid_cgroup(initpid
, "memory");
3901 return read_file("/proc/swaps", buf
, size
, d
);
3902 prune_init_slice(cg
);
3904 if (!cgfs_get_value("memory", cg
, "memory.limit_in_bytes", &memlimit_str
))
3907 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
3910 memlimit
= strtoul(memlimit_str
, NULL
, 10);
3911 memusage
= strtoul(memusage_str
, NULL
, 10);
3913 if (cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
) &&
3914 cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
)) {
3916 /* If swap accounting is turned on, then default value is assumed to be that of cgroup / */
3917 if (!cgfs_get_value("memory", "/", "memory.memsw.limit_in_bytes", &memswlimit_default_str
))
3919 if (!cgfs_get_value("memory", "/", "memory.memsw.usage_in_bytes", &memswusage_default_str
))
3922 memswlimit
= strtoul(memswlimit_str
, NULL
, 10);
3923 memswusage
= strtoul(memswusage_str
, NULL
, 10);
3925 if (!strcmp(memswlimit_str
, memswlimit_default_str
))
3927 if (!strcmp(memswusage_str
, memswusage_default_str
))
3930 swap_total
= (memswlimit
- memlimit
) / 1024;
3931 swap_free
= (memswusage
- memusage
) / 1024;
3934 total_len
= snprintf(d
->buf
, d
->size
, "Filename\t\t\t\tType\t\tSize\tUsed\tPriority\n");
3936 /* When no mem + swap limit is specified or swapaccount=0*/
3940 FILE *f
= fopen("/proc/meminfo", "r");
3945 while (getline(&line
, &linelen
, f
) != -1) {
3946 if (startswith(line
, "SwapTotal:")) {
3947 sscanf(line
, "SwapTotal: %8lu kB", &swap_total
);
3948 } else if (startswith(line
, "SwapFree:")) {
3949 sscanf(line
, "SwapFree: %8lu kB", &swap_free
);
3957 if (swap_total
> 0) {
3958 l
= snprintf(d
->buf
+ total_len
, d
->size
- total_len
,
3959 "none%*svirtual\t\t%lu\t%lu\t0\n", 36, " ",
3960 swap_total
, swap_free
);
3964 if (total_len
< 0 || l
< 0) {
3965 perror("Error writing to cache");
3971 d
->size
= (int)total_len
;
3973 if (total_len
> size
) total_len
= size
;
3974 memcpy(buf
, d
->buf
, total_len
);
3979 free(memswlimit_str
);
3982 free(memswusage_str
);
3983 free(memswusage_default_str
);
3984 free(memswlimit_default_str
);
3988 static off_t
get_procfile_size(const char *which
)
3990 FILE *f
= fopen(which
, "r");
3993 ssize_t sz
, answer
= 0;
3997 while ((sz
= getline(&line
, &len
, f
)) != -1)
4005 int proc_getattr(const char *path
, struct stat
*sb
)
4007 struct timespec now
;
4009 memset(sb
, 0, sizeof(struct stat
));
4010 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
4012 sb
->st_uid
= sb
->st_gid
= 0;
4013 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
4014 if (strcmp(path
, "/proc") == 0) {
4015 sb
->st_mode
= S_IFDIR
| 00555;
4019 if (strcmp(path
, "/proc/meminfo") == 0 ||
4020 strcmp(path
, "/proc/cpuinfo") == 0 ||
4021 strcmp(path
, "/proc/uptime") == 0 ||
4022 strcmp(path
, "/proc/stat") == 0 ||
4023 strcmp(path
, "/proc/diskstats") == 0 ||
4024 strcmp(path
, "/proc/swaps") == 0) {
4026 sb
->st_mode
= S_IFREG
| 00444;
4034 int proc_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
4035 struct fuse_file_info
*fi
)
4037 if (filler(buf
, ".", NULL
, 0) != 0 ||
4038 filler(buf
, "..", NULL
, 0) != 0 ||
4039 filler(buf
, "cpuinfo", NULL
, 0) != 0 ||
4040 filler(buf
, "meminfo", NULL
, 0) != 0 ||
4041 filler(buf
, "stat", NULL
, 0) != 0 ||
4042 filler(buf
, "uptime", NULL
, 0) != 0 ||
4043 filler(buf
, "diskstats", NULL
, 0) != 0 ||
4044 filler(buf
, "swaps", NULL
, 0) != 0)
4049 int proc_open(const char *path
, struct fuse_file_info
*fi
)
4052 struct file_info
*info
;
4054 if (strcmp(path
, "/proc/meminfo") == 0)
4055 type
= LXC_TYPE_PROC_MEMINFO
;
4056 else if (strcmp(path
, "/proc/cpuinfo") == 0)
4057 type
= LXC_TYPE_PROC_CPUINFO
;
4058 else if (strcmp(path
, "/proc/uptime") == 0)
4059 type
= LXC_TYPE_PROC_UPTIME
;
4060 else if (strcmp(path
, "/proc/stat") == 0)
4061 type
= LXC_TYPE_PROC_STAT
;
4062 else if (strcmp(path
, "/proc/diskstats") == 0)
4063 type
= LXC_TYPE_PROC_DISKSTATS
;
4064 else if (strcmp(path
, "/proc/swaps") == 0)
4065 type
= LXC_TYPE_PROC_SWAPS
;
4069 info
= malloc(sizeof(*info
));
4073 memset(info
, 0, sizeof(*info
));
4076 info
->buflen
= get_procfile_size(path
) + BUF_RESERVE_SIZE
;
4078 info
->buf
= malloc(info
->buflen
);
4079 } while (!info
->buf
);
4080 memset(info
->buf
, 0, info
->buflen
);
4081 /* set actual size to buffer size */
4082 info
->size
= info
->buflen
;
4084 fi
->fh
= (unsigned long)info
;
4088 int proc_access(const char *path
, int mask
)
4090 if (strcmp(path
, "/proc") == 0 && access(path
, R_OK
) == 0)
4093 /* these are all read-only */
4094 if ((mask
& ~R_OK
) != 0)
4099 int proc_release(const char *path
, struct fuse_file_info
*fi
)
4101 do_release_file_info(fi
);
4105 int proc_read(const char *path
, char *buf
, size_t size
, off_t offset
,
4106 struct fuse_file_info
*fi
)
4108 struct file_info
*f
= (struct file_info
*) fi
->fh
;
4111 case LXC_TYPE_PROC_MEMINFO
:
4112 return proc_meminfo_read(buf
, size
, offset
, fi
);
4113 case LXC_TYPE_PROC_CPUINFO
:
4114 return proc_cpuinfo_read(buf
, size
, offset
, fi
);
4115 case LXC_TYPE_PROC_UPTIME
:
4116 return proc_uptime_read(buf
, size
, offset
, fi
);
4117 case LXC_TYPE_PROC_STAT
:
4118 return proc_stat_read(buf
, size
, offset
, fi
);
4119 case LXC_TYPE_PROC_DISKSTATS
:
4120 return proc_diskstats_read(buf
, size
, offset
, fi
);
4121 case LXC_TYPE_PROC_SWAPS
:
4122 return proc_swaps_read(buf
, size
, offset
, fi
);
4129 * Functions needed to setup cgroups in the __constructor__.
4132 static bool mkdir_p(const char *dir
, mode_t mode
)
4134 const char *tmp
= dir
;
4135 const char *orig
= dir
;
4139 dir
= tmp
+ strspn(tmp
, "/");
4140 tmp
= dir
+ strcspn(dir
, "/");
4141 makeme
= strndup(orig
, dir
- orig
);
4144 if (mkdir(makeme
, mode
) && errno
!= EEXIST
) {
4145 fprintf(stderr
, "failed to create directory '%s': %s",
4146 makeme
, strerror(errno
));
4151 } while(tmp
!= dir
);
4156 static bool umount_if_mounted(void)
4158 if (umount2(BASEDIR
, MNT_DETACH
) < 0 && errno
!= EINVAL
) {
4159 fprintf(stderr
, "failed to unmount %s: %s.\n", BASEDIR
, strerror(errno
));
4165 static int pivot_enter(void)
4167 int ret
= -1, oldroot
= -1, newroot
= -1;
4169 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
);
4171 fprintf(stderr
, "%s: Failed to open old root for fchdir.\n", __func__
);
4175 newroot
= open(ROOTDIR
, O_DIRECTORY
| O_RDONLY
);
4177 fprintf(stderr
, "%s: Failed to open new root for fchdir.\n", __func__
);
4181 /* change into new root fs */
4182 if (fchdir(newroot
) < 0) {
4183 fprintf(stderr
, "%s: Failed to change directory to new rootfs: %s.\n", __func__
, ROOTDIR
);
4187 /* pivot_root into our new root fs */
4188 if (pivot_root(".", ".") < 0) {
4189 fprintf(stderr
, "%s: pivot_root() syscall failed: %s.\n", __func__
, strerror(errno
));
4194 * At this point the old-root is mounted on top of our new-root.
4195 * To unmounted it we must not be chdir'd into it, so escape back
4198 if (fchdir(oldroot
) < 0) {
4199 fprintf(stderr
, "%s: Failed to enter old root.\n", __func__
);
4202 if (umount2(".", MNT_DETACH
) < 0) {
4203 fprintf(stderr
, "%s: Failed to detach old root.\n", __func__
);
4207 if (fchdir(newroot
) < 0) {
4208 fprintf(stderr
, "%s: Failed to re-enter new root.\n", __func__
);
4222 /* Prepare our new clean root. */
4223 static int pivot_prepare(void)
4225 if (mkdir(ROOTDIR
, 0700) < 0 && errno
!= EEXIST
) {
4226 fprintf(stderr
, "%s: Failed to create directory for new root.\n", __func__
);
4230 if (mount("/", ROOTDIR
, NULL
, MS_BIND
, 0) < 0) {
4231 fprintf(stderr
, "%s: Failed to bind-mount / for new root: %s.\n", __func__
, strerror(errno
));
4235 if (mount(RUNTIME_PATH
, ROOTDIR RUNTIME_PATH
, NULL
, MS_BIND
, 0) < 0) {
4236 fprintf(stderr
, "%s: Failed to bind-mount /run into new root: %s.\n", __func__
, strerror(errno
));
4240 if (mount(BASEDIR
, ROOTDIR BASEDIR
, NULL
, MS_REC
| MS_MOVE
, 0) < 0) {
4241 printf("%s: failed to move " BASEDIR
" into new root: %s.\n", __func__
, strerror(errno
));
4248 static bool pivot_new_root(void)
4250 /* Prepare new root. */
4251 if (pivot_prepare() < 0)
4254 /* Pivot into new root. */
4255 if (pivot_enter() < 0)
4261 static bool setup_cgfs_dir(void)
4263 if (!mkdir_p(BASEDIR
, 0700)) {
4264 fprintf(stderr
, "Failed to create lxcfs cgroup mountpoint.\n");
4268 if (!umount_if_mounted()) {
4269 fprintf(stderr
, "Failed to clean up old lxcfs cgroup mountpoint.\n");
4273 if (unshare(CLONE_NEWNS
) < 0) {
4274 fprintf(stderr
, "%s: Failed to unshare mount namespace: %s.\n", __func__
, strerror(errno
));
4278 if (mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, 0) < 0) {
4279 fprintf(stderr
, "%s: Failed to remount / private: %s.\n", __func__
, strerror(errno
));
4283 if (mount("tmpfs", BASEDIR
, "tmpfs", 0, "size=100000,mode=700") < 0) {
4284 fprintf(stderr
, "Failed to mount tmpfs over lxcfs cgroup mountpoint.\n");
4291 static bool do_mount_cgroups(void)
4297 for (i
= 0; i
< num_hierarchies
; i
++) {
4298 char *controller
= hierarchies
[i
];
4299 clen
= strlen(controller
);
4300 len
= strlen(BASEDIR
) + clen
+ 2;
4301 target
= malloc(len
);
4304 ret
= snprintf(target
, len
, "%s/%s", BASEDIR
, controller
);
4305 if (ret
< 0 || ret
>= len
) {
4309 if (mkdir(target
, 0755) < 0 && errno
!= EEXIST
) {
4313 if (mount(controller
, target
, "cgroup", 0, controller
) < 0) {
4314 fprintf(stderr
, "Failed mounting cgroup %s\n", controller
);
4319 fd_hierarchies
[i
] = open(target
, O_DIRECTORY
);
4320 if (fd_hierarchies
[i
] < 0) {
4329 static bool cgfs_setup_controllers(void)
4331 if (!setup_cgfs_dir())
4334 if (!do_mount_cgroups()) {
4335 fprintf(stderr
, "Failed to set up private lxcfs cgroup mounts.\n");
4339 if (!pivot_new_root())
4345 static int preserve_ns(int pid
)
4348 size_t len
= 5 /* /proc */ + 21 /* /int_as_str */ + 7 /* /ns/mnt */ + 1 /* \0 */;
4351 ret
= snprintf(path
, len
, "/proc/%d/ns/mnt", pid
);
4352 if (ret
< 0 || (size_t)ret
>= len
)
4355 return open(path
, O_RDONLY
| O_CLOEXEC
);
4358 static void __attribute__((constructor
)) collect_and_mount_subsystems(void)
4363 int i
, init_ns
= -1;
4365 if ((f
= fopen("/proc/self/cgroup", "r")) == NULL
) {
4366 fprintf(stderr
, "Error opening /proc/self/cgroup: %s\n", strerror(errno
));
4369 while (getline(&line
, &len
, f
) != -1) {
4372 p
= strchr(line
, ':');
4377 p2
= strrchr(p
, ':');
4382 /* With cgroupv2 /proc/self/cgroup can contain entries of the
4383 * form: 0::/ This will cause lxcfs to fail the cgroup mounts
4384 * because it parses out the empty string "" and later on passes
4385 * it to mount(). Let's skip such entries.
4390 if (!store_hierarchy(line
, p
))
4394 /* Preserve initial namespace. */
4395 init_ns
= preserve_ns(getpid());
4399 fd_hierarchies
= malloc(sizeof(int *) * num_hierarchies
);
4400 if (!fd_hierarchies
)
4403 for (i
= 0; i
< num_hierarchies
; i
++)
4404 fd_hierarchies
[i
] = -1;
4406 /* This function calls unshare(CLONE_NEWNS) our initial mount namespace
4407 * to privately mount lxcfs cgroups. */
4408 if (!cgfs_setup_controllers())
4411 if (setns(init_ns
, 0) < 0)
4423 static void __attribute__((destructor
)) free_subsystems(void)
4427 for (i
= 0; i
< num_hierarchies
; i
++) {
4429 free(hierarchies
[i
]);
4430 if (fd_hierarchies
&& fd_hierarchies
[i
] >= 0)
4431 close(fd_hierarchies
[i
]);
4434 free(fd_hierarchies
);