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/magic.h>
26 #include <linux/sched.h>
27 #include <sys/epoll.h>
29 #include <sys/mount.h>
30 #include <sys/param.h>
31 #include <sys/socket.h>
32 #include <sys/syscall.h>
36 #include "config.h" // for VERSION
38 /* Define pivot_root() if missing from the C library */
39 #ifndef HAVE_PIVOT_ROOT
40 static int pivot_root(const char * new_root
, const char * put_old
)
42 #ifdef __NR_pivot_root
43 return syscall(__NR_pivot_root
, new_root
, put_old
);
50 extern int pivot_root(const char * new_root
, const char * put_old
);
56 LXC_TYPE_PROC_MEMINFO
,
57 LXC_TYPE_PROC_CPUINFO
,
60 LXC_TYPE_PROC_DISKSTATS
,
69 char *buf
; // unused as of yet
71 int size
; //actual data size
75 /* reserve buffer size, for cpuall in /proc/stat */
76 #define BUF_RESERVE_SIZE 256
79 * A table caching which pid is init for a pid namespace.
80 * When looking up which pid is init for $qpid, we first
81 * 1. Stat /proc/$qpid/ns/pid.
82 * 2. Check whether the ino_t is in our store.
83 * a. if not, fork a child in qpid's ns to send us
84 * ucred.pid = 1, and read the initpid. Cache
85 * initpid and creation time for /proc/initpid
86 * in a new store entry.
87 * b. if so, verify that /proc/initpid still matches
88 * what we have saved. If not, clear the store
89 * entry and go back to a. If so, return the
92 struct pidns_init_store
{
93 ino_t ino
; // inode number for /proc/$pid/ns/pid
94 pid_t initpid
; // the pid of nit in that ns
95 long int ctime
; // the time at which /proc/$initpid was created
96 struct pidns_init_store
*next
;
100 /* lol - look at how they are allocated in the kernel */
101 #define PIDNS_HASH_SIZE 4096
102 #define HASH(x) ((x) % PIDNS_HASH_SIZE)
104 static struct pidns_init_store
*pidns_hash_table
[PIDNS_HASH_SIZE
];
105 static pthread_mutex_t pidns_store_mutex
= PTHREAD_MUTEX_INITIALIZER
;
106 static void lock_mutex(pthread_mutex_t
*l
)
110 if ((ret
= pthread_mutex_lock(l
)) != 0) {
111 lxcfs_error("returned:%d %s\n", ret
, strerror(ret
));
116 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
117 * Number of hierarchies mounted. */
118 static int num_hierarchies
;
120 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
121 * Hierachies mounted {cpuset, blkio, ...}:
122 * Initialized via __constructor__ collect_and_mount_subsystems(). */
123 static char **hierarchies
;
125 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
126 * Open file descriptors:
127 * @fd_hierarchies[i] refers to cgroup @hierarchies[i]. They are mounted in a
128 * private mount namespace.
129 * Initialized via __constructor__ collect_and_mount_subsystems().
130 * @fd_hierarchies[i] can be used to perform file operations on the cgroup
131 * mounts and respective files in the private namespace even when located in
132 * another namespace using the *at() family of functions
133 * {openat(), fchownat(), ...}. */
134 static int *fd_hierarchies
;
136 static void unlock_mutex(pthread_mutex_t
*l
)
140 if ((ret
= pthread_mutex_unlock(l
)) != 0) {
141 lxcfs_error("returned:%d %s\n", ret
, strerror(ret
));
146 static void store_lock(void)
148 lock_mutex(&pidns_store_mutex
);
151 static void store_unlock(void)
153 unlock_mutex(&pidns_store_mutex
);
156 /* Must be called under store_lock */
157 static bool initpid_still_valid(struct pidns_init_store
*e
, struct stat
*nsfdsb
)
162 snprintf(fnam
, 100, "/proc/%d", e
->initpid
);
163 if (stat(fnam
, &initsb
) < 0)
166 lxcfs_debug("Comparing ctime %ld == %ld for pid %d.\n", e
->ctime
,
167 initsb
.st_ctime
, e
->initpid
);
169 if (e
->ctime
!= initsb
.st_ctime
)
174 /* Must be called under store_lock */
175 static void remove_initpid(struct pidns_init_store
*e
)
177 struct pidns_init_store
*tmp
;
180 lxcfs_debug("Remove_initpid: removing entry for %d.\n", e
->initpid
);
183 if (pidns_hash_table
[h
] == e
) {
184 pidns_hash_table
[h
] = e
->next
;
189 tmp
= pidns_hash_table
[h
];
191 if (tmp
->next
== e
) {
201 /* Must be called under store_lock */
202 static void prune_initpid_store(void)
204 static long int last_prune
= 0;
205 struct pidns_init_store
*e
, *prev
, *delme
;
206 long int now
, threshold
;
210 last_prune
= time(NULL
);
214 if (now
< last_prune
+ PURGE_SECS
)
217 lxcfs_debug("%s\n", "Pruning.");
220 threshold
= now
- 2 * PURGE_SECS
;
222 for (i
= 0; i
< PIDNS_HASH_SIZE
; i
++) {
223 for (prev
= NULL
, e
= pidns_hash_table
[i
]; e
; ) {
224 if (e
->lastcheck
< threshold
) {
226 lxcfs_debug("Removing cached entry for %d.\n", e
->initpid
);
230 prev
->next
= e
->next
;
232 pidns_hash_table
[i
] = e
->next
;
243 /* Must be called under store_lock */
244 static void save_initpid(struct stat
*sb
, pid_t pid
)
246 struct pidns_init_store
*e
;
251 lxcfs_debug("Save_initpid: adding entry for %d.\n", pid
);
253 snprintf(fpath
, 100, "/proc/%d", pid
);
254 if (stat(fpath
, &procsb
) < 0)
257 e
= malloc(sizeof(*e
));
261 e
->ctime
= procsb
.st_ctime
;
263 e
->next
= pidns_hash_table
[h
];
264 e
->lastcheck
= time(NULL
);
265 pidns_hash_table
[h
] = e
;
269 * Given the stat(2) info for a nsfd pid inode, lookup the init_pid_store
270 * entry for the inode number and creation time. Verify that the init pid
271 * is still valid. If not, remove it. Return the entry if valid, NULL
273 * Must be called under store_lock
275 static struct pidns_init_store
*lookup_verify_initpid(struct stat
*sb
)
277 int h
= HASH(sb
->st_ino
);
278 struct pidns_init_store
*e
= pidns_hash_table
[h
];
281 if (e
->ino
== sb
->st_ino
) {
282 if (initpid_still_valid(e
, sb
)) {
283 e
->lastcheck
= time(NULL
);
295 static int is_dir(const char *path
, int fd
)
298 int ret
= fstatat(fd
, path
, &statbuf
, fd
);
299 if (ret
== 0 && S_ISDIR(statbuf
.st_mode
))
304 static char *must_copy_string(const char *str
)
316 static inline void drop_trailing_newlines(char *s
)
320 for (l
=strlen(s
); l
>0 && s
[l
-1] == '\n'; l
--)
324 #define BATCH_SIZE 50
325 static void dorealloc(char **mem
, size_t oldlen
, size_t newlen
)
327 int newbatches
= (newlen
/ BATCH_SIZE
) + 1;
328 int oldbatches
= (oldlen
/ BATCH_SIZE
) + 1;
330 if (!*mem
|| newbatches
> oldbatches
) {
333 tmp
= realloc(*mem
, newbatches
* BATCH_SIZE
);
338 static void append_line(char **contents
, size_t *len
, char *line
, ssize_t linelen
)
340 size_t newlen
= *len
+ linelen
;
341 dorealloc(contents
, *len
, newlen
+ 1);
342 memcpy(*contents
+ *len
, line
, linelen
+1);
346 static char *slurp_file(const char *from
, int fd
)
349 char *contents
= NULL
;
350 FILE *f
= fdopen(fd
, "r");
351 size_t len
= 0, fulllen
= 0;
357 while ((linelen
= getline(&line
, &len
, f
)) != -1) {
358 append_line(&contents
, &fulllen
, line
, linelen
);
363 drop_trailing_newlines(contents
);
368 static bool write_string(const char *fnam
, const char *string
, int fd
)
373 if (!(f
= fdopen(fd
, "w")))
375 len
= strlen(string
);
376 ret
= fwrite(string
, 1, len
, f
);
378 lxcfs_error("Error writing to file: %s\n", strerror(errno
));
383 lxcfs_error("Error writing to file: %s\n", strerror(errno
));
396 static bool store_hierarchy(char *stridx
, char *h
)
398 if (num_hierarchies
% ALLOC_NUM
== 0) {
399 size_t n
= (num_hierarchies
/ ALLOC_NUM
) + 1;
401 char **tmp
= realloc(hierarchies
, n
* sizeof(char *));
403 lxcfs_error("%s\n", strerror(errno
));
409 hierarchies
[num_hierarchies
++] = must_copy_string(h
);
413 static void print_subsystems(void)
417 fprintf(stderr
, "hierarchies:\n");
418 for (i
= 0; i
< num_hierarchies
; i
++) {
420 fprintf(stderr
, " %2d: fd: %3d: %s\n", i
,
421 fd_hierarchies
[i
], hierarchies
[i
]);
425 static bool in_comma_list(const char *needle
, const char *haystack
)
427 const char *s
= haystack
, *e
;
428 size_t nlen
= strlen(needle
);
430 while (*s
&& (e
= strchr(s
, ','))) {
435 if (strncmp(needle
, s
, nlen
) == 0)
439 if (strcmp(needle
, s
) == 0)
444 /* do we need to do any massaging here? I'm not sure... */
445 /* Return the mounted controller and store the corresponding open file descriptor
446 * referring to the controller mountpoint in the private lxcfs namespace in
449 static char *find_mounted_controller(const char *controller
, int *cfd
)
453 for (i
= 0; i
< num_hierarchies
; i
++) {
456 if (strcmp(hierarchies
[i
], controller
) == 0) {
457 *cfd
= fd_hierarchies
[i
];
458 return hierarchies
[i
];
460 if (in_comma_list(controller
, hierarchies
[i
])) {
461 *cfd
= fd_hierarchies
[i
];
462 return hierarchies
[i
];
469 bool cgfs_set_value(const char *controller
, const char *cgroup
, const char *file
,
476 tmpc
= find_mounted_controller(controller
, &cfd
);
480 /* Make sure we pass a relative path to *at() family of functions.
481 * . + /cgroup + / + file + \0
483 len
= strlen(cgroup
) + strlen(file
) + 3;
485 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, file
);
486 if (ret
< 0 || (size_t)ret
>= len
)
489 fd
= openat(cfd
, fnam
, O_WRONLY
);
493 return write_string(fnam
, value
, fd
);
496 // Chown all the files in the cgroup directory. We do this when we create
497 // a cgroup on behalf of a user.
498 static void chown_all_cgroup_files(const char *dirname
, uid_t uid
, gid_t gid
, int fd
)
500 struct dirent
*direntp
;
501 char path
[MAXPATHLEN
];
506 len
= strlen(dirname
);
507 if (len
>= MAXPATHLEN
) {
508 lxcfs_error("Pathname too long: %s\n", dirname
);
512 fd1
= openat(fd
, dirname
, O_DIRECTORY
);
518 lxcfs_error("Failed to open %s\n", dirname
);
522 while ((direntp
= readdir(d
))) {
523 if (!strcmp(direntp
->d_name
, ".") || !strcmp(direntp
->d_name
, ".."))
525 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
526 if (ret
< 0 || ret
>= MAXPATHLEN
) {
527 lxcfs_error("Pathname too long under %s\n", dirname
);
530 if (fchownat(fd
, path
, uid
, gid
, 0) < 0)
531 lxcfs_error("Failed to chown file %s to %u:%u", path
, uid
, gid
);
536 int cgfs_create(const char *controller
, const char *cg
, uid_t uid
, gid_t gid
)
542 tmpc
= find_mounted_controller(controller
, &cfd
);
546 /* Make sure we pass a relative path to *at() family of functions.
549 len
= strlen(cg
) + 2;
550 dirnam
= alloca(len
);
551 snprintf(dirnam
, len
, "%s%s", *cg
== '/' ? "." : "", cg
);
553 if (mkdirat(cfd
, dirnam
, 0755) < 0)
556 if (uid
== 0 && gid
== 0)
559 if (fchownat(cfd
, dirnam
, uid
, gid
, 0) < 0)
562 chown_all_cgroup_files(dirnam
, uid
, gid
, cfd
);
567 static bool recursive_rmdir(const char *dirname
, int fd
, const int cfd
)
569 struct dirent
*direntp
;
572 char pathname
[MAXPATHLEN
];
575 dupfd
= dup(fd
); // fdopendir() does bad things once it uses an fd.
579 dir
= fdopendir(dupfd
);
581 lxcfs_debug("Failed to open %s: %s.\n", dirname
, strerror(errno
));
586 while ((direntp
= readdir(dir
))) {
590 if (!strcmp(direntp
->d_name
, ".") ||
591 !strcmp(direntp
->d_name
, ".."))
594 rc
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
595 if (rc
< 0 || rc
>= MAXPATHLEN
) {
596 lxcfs_error("%s\n", "Pathname too long.");
600 rc
= fstatat(cfd
, pathname
, &mystat
, AT_SYMLINK_NOFOLLOW
);
602 lxcfs_debug("Failed to stat %s: %s.\n", pathname
, strerror(errno
));
605 if (S_ISDIR(mystat
.st_mode
))
606 if (!recursive_rmdir(pathname
, fd
, cfd
))
607 lxcfs_debug("Error removing %s.\n", pathname
);
611 if (closedir(dir
) < 0) {
612 lxcfs_error("Failed to close directory %s: %s\n", dirname
, strerror(errno
));
616 if (unlinkat(cfd
, dirname
, AT_REMOVEDIR
) < 0) {
617 lxcfs_debug("Failed to delete %s: %s.\n", dirname
, strerror(errno
));
626 bool cgfs_remove(const char *controller
, const char *cg
)
633 tmpc
= find_mounted_controller(controller
, &cfd
);
637 /* Make sure we pass a relative path to *at() family of functions.
640 len
= strlen(cg
) + 2;
641 dirnam
= alloca(len
);
642 snprintf(dirnam
, len
, "%s%s", *cg
== '/' ? "." : "", cg
);
644 fd
= openat(cfd
, dirnam
, O_DIRECTORY
);
648 bret
= recursive_rmdir(dirnam
, fd
, cfd
);
653 bool cgfs_chmod_file(const char *controller
, const char *file
, mode_t mode
)
657 char *pathname
, *tmpc
;
659 tmpc
= find_mounted_controller(controller
, &cfd
);
663 /* Make sure we pass a relative path to *at() family of functions.
666 len
= strlen(file
) + 2;
667 pathname
= alloca(len
);
668 snprintf(pathname
, len
, "%s%s", *file
== '/' ? "." : "", file
);
669 if (fchmodat(cfd
, pathname
, mode
, 0) < 0)
674 static int chown_tasks_files(const char *dirname
, uid_t uid
, gid_t gid
, int fd
)
679 len
= strlen(dirname
) + strlen("/cgroup.procs") + 1;
681 snprintf(fname
, len
, "%s/tasks", dirname
);
682 if (fchownat(fd
, fname
, uid
, gid
, 0) != 0)
684 snprintf(fname
, len
, "%s/cgroup.procs", dirname
);
685 if (fchownat(fd
, fname
, uid
, gid
, 0) != 0)
690 int cgfs_chown_file(const char *controller
, const char *file
, uid_t uid
, gid_t gid
)
694 char *pathname
, *tmpc
;
696 tmpc
= find_mounted_controller(controller
, &cfd
);
700 /* Make sure we pass a relative path to *at() family of functions.
703 len
= strlen(file
) + 2;
704 pathname
= alloca(len
);
705 snprintf(pathname
, len
, "%s%s", *file
== '/' ? "." : "", file
);
706 if (fchownat(cfd
, pathname
, uid
, gid
, 0) < 0)
709 if (is_dir(pathname
, cfd
))
710 // like cgmanager did, we want to chown the tasks file as well
711 return chown_tasks_files(pathname
, uid
, gid
, cfd
);
716 FILE *open_pids_file(const char *controller
, const char *cgroup
)
720 char *pathname
, *tmpc
;
722 tmpc
= find_mounted_controller(controller
, &cfd
);
726 /* Make sure we pass a relative path to *at() family of functions.
727 * . + /cgroup + / "cgroup.procs" + \0
729 len
= strlen(cgroup
) + strlen("cgroup.procs") + 3;
730 pathname
= alloca(len
);
731 snprintf(pathname
, len
, "%s%s/cgroup.procs", *cgroup
== '/' ? "." : "", cgroup
);
733 fd
= openat(cfd
, pathname
, O_WRONLY
);
737 return fdopen(fd
, "w");
740 static bool cgfs_iterate_cgroup(const char *controller
, const char *cgroup
, bool directories
,
741 void ***list
, size_t typesize
,
742 void* (*iterator
)(const char*, const char*, const char*))
747 char pathname
[MAXPATHLEN
];
748 size_t sz
= 0, asz
= 0;
749 struct dirent
*dirent
;
752 tmpc
= find_mounted_controller(controller
, &cfd
);
757 /* Make sure we pass a relative path to *at() family of functions. */
758 len
= strlen(cgroup
) + 1 /* . */ + 1 /* \0 */;
760 ret
= snprintf(cg
, len
, "%s%s", *cgroup
== '/' ? "." : "", cgroup
);
761 if (ret
< 0 || (size_t)ret
>= len
) {
762 lxcfs_error("Pathname too long under %s\n", cgroup
);
766 fd
= openat(cfd
, cg
, O_DIRECTORY
);
774 while ((dirent
= readdir(dir
))) {
777 if (!strcmp(dirent
->d_name
, ".") ||
778 !strcmp(dirent
->d_name
, ".."))
781 ret
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", cg
, dirent
->d_name
);
782 if (ret
< 0 || ret
>= MAXPATHLEN
) {
783 lxcfs_error("Pathname too long under %s\n", cg
);
787 ret
= fstatat(cfd
, pathname
, &mystat
, AT_SYMLINK_NOFOLLOW
);
789 lxcfs_error("Failed to stat %s: %s\n", pathname
, strerror(errno
));
792 if ((!directories
&& !S_ISREG(mystat
.st_mode
)) ||
793 (directories
&& !S_ISDIR(mystat
.st_mode
)))
800 tmp
= realloc(*list
, asz
* typesize
);
804 (*list
)[sz
] = (*iterator
)(controller
, cg
, dirent
->d_name
);
805 (*list
)[sz
+1] = NULL
;
808 if (closedir(dir
) < 0) {
809 lxcfs_error("Failed closedir for %s: %s\n", cgroup
, strerror(errno
));
815 static void *make_children_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
819 dup
= strdup(dir_entry
);
824 bool cgfs_list_children(const char *controller
, const char *cgroup
, char ***list
)
826 return cgfs_iterate_cgroup(controller
, cgroup
, true, (void***)list
, sizeof(*list
), &make_children_list_entry
);
829 void free_key(struct cgfs_files
*k
)
837 void free_keys(struct cgfs_files
**keys
)
843 for (i
= 0; keys
[i
]; i
++) {
849 bool cgfs_get_value(const char *controller
, const char *cgroup
, const char *file
, char **value
)
855 tmpc
= find_mounted_controller(controller
, &cfd
);
859 /* Make sure we pass a relative path to *at() family of functions.
860 * . + /cgroup + / + file + \0
862 len
= strlen(cgroup
) + strlen(file
) + 3;
864 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, file
);
865 if (ret
< 0 || (size_t)ret
>= len
)
868 fd
= openat(cfd
, fnam
, O_RDONLY
);
872 *value
= slurp_file(fnam
, fd
);
873 return *value
!= NULL
;
876 struct cgfs_files
*cgfs_get_key(const char *controller
, const char *cgroup
, const char *file
)
882 struct cgfs_files
*newkey
;
884 tmpc
= find_mounted_controller(controller
, &cfd
);
888 if (file
&& *file
== '/')
891 if (file
&& strchr(file
, '/'))
894 /* Make sure we pass a relative path to *at() family of functions.
895 * . + /cgroup + / + file + \0
897 len
= strlen(cgroup
) + 3;
899 len
+= strlen(file
) + 1;
901 snprintf(fnam
, len
, "%s%s%s%s", *cgroup
== '/' ? "." : "", cgroup
,
902 file
? "/" : "", file
? file
: "");
904 ret
= fstatat(cfd
, fnam
, &sb
, 0);
909 newkey
= malloc(sizeof(struct cgfs_files
));
912 newkey
->name
= must_copy_string(file
);
913 else if (strrchr(cgroup
, '/'))
914 newkey
->name
= must_copy_string(strrchr(cgroup
, '/'));
916 newkey
->name
= must_copy_string(cgroup
);
917 newkey
->uid
= sb
.st_uid
;
918 newkey
->gid
= sb
.st_gid
;
919 newkey
->mode
= sb
.st_mode
;
924 static void *make_key_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
926 struct cgfs_files
*entry
= cgfs_get_key(controller
, cgroup
, dir_entry
);
928 lxcfs_error("Error getting files under %s:%s\n", controller
,
934 bool cgfs_list_keys(const char *controller
, const char *cgroup
, struct cgfs_files
***keys
)
936 return cgfs_iterate_cgroup(controller
, cgroup
, false, (void***)keys
, sizeof(*keys
), &make_key_list_entry
);
939 bool is_child_cgroup(const char *controller
, const char *cgroup
, const char *f
)
947 tmpc
= find_mounted_controller(controller
, &cfd
);
951 /* Make sure we pass a relative path to *at() family of functions.
952 * . + /cgroup + / + f + \0
954 len
= strlen(cgroup
) + strlen(f
) + 3;
956 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, f
);
957 if (ret
< 0 || (size_t)ret
>= len
)
960 ret
= fstatat(cfd
, fnam
, &sb
, 0);
961 if (ret
< 0 || !S_ISDIR(sb
.st_mode
))
967 #define SEND_CREDS_OK 0
968 #define SEND_CREDS_NOTSK 1
969 #define SEND_CREDS_FAIL 2
970 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
);
971 static int wait_for_pid(pid_t pid
);
972 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
);
973 static int send_creds_clone_wrapper(void *arg
);
976 * clone a task which switches to @task's namespace and writes '1'.
977 * over a unix sock so we can read the task's reaper's pid in our
980 * Note: glibc's fork() does not respect pidns, which can lead to failed
981 * assertions inside glibc (and thus failed forks) if the child's pid in
982 * the pidns and the parent pid outside are identical. Using clone prevents
985 static void write_task_init_pid_exit(int sock
, pid_t target
)
990 size_t stack_size
= sysconf(_SC_PAGESIZE
);
991 void *stack
= alloca(stack_size
);
993 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", (int)target
);
994 if (ret
< 0 || ret
>= sizeof(fnam
))
997 fd
= open(fnam
, O_RDONLY
);
999 perror("write_task_init_pid_exit open of ns/pid");
1003 perror("write_task_init_pid_exit setns 1");
1007 pid
= clone(send_creds_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &sock
);
1011 if (!wait_for_pid(pid
))
1017 static int send_creds_clone_wrapper(void *arg
) {
1020 int sock
= *(int *)arg
;
1022 /* we are the child */
1027 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
)
1032 static pid_t
get_init_pid_for_task(pid_t task
)
1040 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
1041 perror("socketpair");
1050 write_task_init_pid_exit(sock
[0], task
);
1054 if (!recv_creds(sock
[1], &cred
, &v
))
1066 static pid_t
lookup_initpid_in_store(pid_t qpid
)
1070 struct pidns_init_store
*e
;
1073 snprintf(fnam
, 100, "/proc/%d/ns/pid", qpid
);
1075 if (stat(fnam
, &sb
) < 0)
1077 e
= lookup_verify_initpid(&sb
);
1079 answer
= e
->initpid
;
1082 answer
= get_init_pid_for_task(qpid
);
1084 save_initpid(&sb
, answer
);
1087 /* we prune at end in case we are returning
1088 * the value we were about to return */
1089 prune_initpid_store();
1094 static int wait_for_pid(pid_t pid
)
1102 ret
= waitpid(pid
, &status
, 0);
1110 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
1117 * append pid to *src.
1118 * src: a pointer to a char* in which ot append the pid.
1119 * sz: the number of characters printed so far, minus trailing \0.
1120 * asz: the allocated size so far
1121 * pid: the pid to append
1123 static void must_strcat_pid(char **src
, size_t *sz
, size_t *asz
, pid_t pid
)
1127 int tmplen
= sprintf(tmp
, "%d\n", (int)pid
);
1129 if (!*src
|| tmplen
+ *sz
+ 1 >= *asz
) {
1132 tmp
= realloc(*src
, *asz
+ BUF_RESERVE_SIZE
);
1135 *asz
+= BUF_RESERVE_SIZE
;
1137 memcpy((*src
) +*sz
, tmp
, tmplen
+1); /* include the \0 */
1142 * Given a open file * to /proc/pid/{u,g}id_map, and an id
1143 * valid in the caller's namespace, return the id mapped into
1145 * Returns the mapped id, or -1 on error.
1148 convert_id_to_ns(FILE *idfile
, unsigned int in_id
)
1150 unsigned int nsuid
, // base id for a range in the idfile's namespace
1151 hostuid
, // base id for a range in the caller's namespace
1152 count
; // number of ids in this range
1156 fseek(idfile
, 0L, SEEK_SET
);
1157 while (fgets(line
, 400, idfile
)) {
1158 ret
= sscanf(line
, "%u %u %u\n", &nsuid
, &hostuid
, &count
);
1161 if (hostuid
+ count
< hostuid
|| nsuid
+ count
< nsuid
) {
1163 * uids wrapped around - unexpected as this is a procfile,
1166 lxcfs_error("pid wrapparound at entry %u %u %u in %s\n",
1167 nsuid
, hostuid
, count
, line
);
1170 if (hostuid
<= in_id
&& hostuid
+count
> in_id
) {
1172 * now since hostuid <= in_id < hostuid+count, and
1173 * hostuid+count and nsuid+count do not wrap around,
1174 * we know that nsuid+(in_id-hostuid) which must be
1175 * less that nsuid+(count) must not wrap around
1177 return (in_id
- hostuid
) + nsuid
;
1186 * for is_privileged_over,
1187 * specify whether we require the calling uid to be root in his
1190 #define NS_ROOT_REQD true
1191 #define NS_ROOT_OPT false
1195 static bool is_privileged_over(pid_t pid
, uid_t uid
, uid_t victim
, bool req_ns_root
)
1197 char fpath
[PROCLEN
];
1199 bool answer
= false;
1202 if (victim
== -1 || uid
== -1)
1206 * If the request is one not requiring root in the namespace,
1207 * then having the same uid suffices. (i.e. uid 1000 has write
1208 * access to files owned by uid 1000
1210 if (!req_ns_root
&& uid
== victim
)
1213 ret
= snprintf(fpath
, PROCLEN
, "/proc/%d/uid_map", pid
);
1214 if (ret
< 0 || ret
>= PROCLEN
)
1216 FILE *f
= fopen(fpath
, "r");
1220 /* if caller's not root in his namespace, reject */
1221 nsuid
= convert_id_to_ns(f
, uid
);
1226 * If victim is not mapped into caller's ns, reject.
1227 * XXX I'm not sure this check is needed given that fuse
1228 * will be sending requests where the vfs has converted
1230 nsuid
= convert_id_to_ns(f
, victim
);
1241 static bool perms_include(int fmode
, mode_t req_mode
)
1245 switch (req_mode
& O_ACCMODE
) {
1253 r
= S_IROTH
| S_IWOTH
;
1258 return ((fmode
& r
) == r
);
1264 * querycg is /a/b/c/d/e
1267 static char *get_next_cgroup_dir(const char *taskcg
, const char *querycg
)
1271 if (strlen(taskcg
) <= strlen(querycg
)) {
1272 lxcfs_error("%s\n", "I was fed bad input.");
1276 if ((strcmp(querycg
, "/") == 0) || (strcmp(querycg
, "./") == 0))
1277 start
= strdup(taskcg
+ 1);
1279 start
= strdup(taskcg
+ strlen(querycg
) + 1);
1282 end
= strchr(start
, '/');
1288 static void stripnewline(char *x
)
1290 size_t l
= strlen(x
);
1291 if (l
&& x
[l
-1] == '\n')
1295 static char *get_pid_cgroup(pid_t pid
, const char *contrl
)
1300 char *answer
= NULL
;
1304 const char *h
= find_mounted_controller(contrl
, &cfd
);
1308 ret
= snprintf(fnam
, PROCLEN
, "/proc/%d/cgroup", pid
);
1309 if (ret
< 0 || ret
>= PROCLEN
)
1311 if (!(f
= fopen(fnam
, "r")))
1314 while (getline(&line
, &len
, f
) != -1) {
1318 c1
= strchr(line
, ':');
1322 c2
= strchr(c1
, ':');
1326 if (strcmp(c1
, h
) != 0)
1331 answer
= strdup(c2
);
1343 * check whether a fuse context may access a cgroup dir or file
1345 * If file is not null, it is a cgroup file to check under cg.
1346 * If file is null, then we are checking perms on cg itself.
1348 * For files we can check the mode of the list_keys result.
1349 * For cgroups, we must make assumptions based on the files under the
1350 * cgroup, because cgmanager doesn't tell us ownership/perms of cgroups
1353 static bool fc_may_access(struct fuse_context
*fc
, const char *contrl
, const char *cg
, const char *file
, mode_t mode
)
1355 struct cgfs_files
*k
= NULL
;
1358 k
= cgfs_get_key(contrl
, cg
, file
);
1362 if (is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
1363 if (perms_include(k
->mode
>> 6, mode
)) {
1368 if (fc
->gid
== k
->gid
) {
1369 if (perms_include(k
->mode
>> 3, mode
)) {
1374 ret
= perms_include(k
->mode
, mode
);
1381 #define INITSCOPE "/init.scope"
1382 static void prune_init_slice(char *cg
)
1385 size_t cg_len
= strlen(cg
), initscope_len
= strlen(INITSCOPE
);
1387 if (cg_len
< initscope_len
)
1390 point
= cg
+ cg_len
- initscope_len
;
1391 if (strcmp(point
, INITSCOPE
) == 0) {
1400 * If pid is in /a/b/c/d, he may only act on things under cg=/a/b/c/d.
1401 * If pid is in /a, he may act on /a/b, but not on /b.
1402 * if the answer is false and nextcg is not NULL, then *nextcg will point
1403 * to a string containing the next cgroup directory under cg, which must be
1404 * freed by the caller.
1406 static bool caller_is_in_ancestor(pid_t pid
, const char *contrl
, const char *cg
, char **nextcg
)
1408 bool answer
= false;
1409 char *c2
= get_pid_cgroup(pid
, contrl
);
1414 prune_init_slice(c2
);
1417 * callers pass in '/' or './' (openat()) for root cgroup, otherwise
1418 * they pass in a cgroup without leading '/'
1420 * The original line here was:
1421 * linecmp = *cg == '/' ? c2 : c2+1;
1422 * TODO: I'm not sure why you'd want to increment when *cg != '/'?
1423 * Serge, do you know?
1425 if (*cg
== '/' || !strncmp(cg
, "./", 2))
1429 if (strncmp(linecmp
, cg
, strlen(linecmp
)) != 0) {
1431 *nextcg
= get_next_cgroup_dir(linecmp
, cg
);
1443 * If pid is in /a/b/c, he may see that /a exists, but not /b or /a/c.
1445 static bool caller_may_see_dir(pid_t pid
, const char *contrl
, const char *cg
)
1447 bool answer
= false;
1449 size_t target_len
, task_len
;
1451 if (strcmp(cg
, "/") == 0 || strcmp(cg
, "./") == 0)
1454 c2
= get_pid_cgroup(pid
, contrl
);
1457 prune_init_slice(c2
);
1460 target_len
= strlen(cg
);
1461 task_len
= strlen(task_cg
);
1462 if (task_len
== 0) {
1463 /* Task is in the root cg, it can see everything. This case is
1464 * not handled by the strmcps below, since they test for the
1465 * last /, but that is the first / that we've chopped off
1471 if (strcmp(cg
, task_cg
) == 0) {
1475 if (target_len
< task_len
) {
1476 /* looking up a parent dir */
1477 if (strncmp(task_cg
, cg
, target_len
) == 0 && task_cg
[target_len
] == '/')
1481 if (target_len
> task_len
) {
1482 /* looking up a child dir */
1483 if (strncmp(task_cg
, cg
, task_len
) == 0 && cg
[task_len
] == '/')
1494 * given /cgroup/freezer/a/b, return "freezer".
1495 * the returned char* should NOT be freed.
1497 static char *pick_controller_from_path(struct fuse_context
*fc
, const char *path
)
1500 char *contr
, *slash
;
1502 if (strlen(path
) < 9) {
1506 if (*(path
+ 7) != '/') {
1511 contr
= strdupa(p1
);
1516 slash
= strstr(contr
, "/");
1521 for (i
= 0; i
< num_hierarchies
; i
++) {
1522 if (hierarchies
[i
] && strcmp(hierarchies
[i
], contr
) == 0)
1523 return hierarchies
[i
];
1530 * Find the start of cgroup in /cgroup/controller/the/cgroup/path
1531 * Note that the returned value may include files (keynames) etc
1533 static const char *find_cgroup_in_path(const char *path
)
1537 if (strlen(path
) < 9) {
1541 p1
= strstr(path
+ 8, "/");
1551 * split the last path element from the path in @cg.
1552 * @dir is newly allocated and should be freed, @last not
1554 static void get_cgdir_and_path(const char *cg
, char **dir
, char **last
)
1561 *last
= strrchr(cg
, '/');
1566 p
= strrchr(*dir
, '/');
1571 * FUSE ops for /cgroup
1574 int cg_getattr(const char *path
, struct stat
*sb
)
1576 struct timespec now
;
1577 struct fuse_context
*fc
= fuse_get_context();
1578 char * cgdir
= NULL
;
1579 char *last
= NULL
, *path1
, *path2
;
1580 struct cgfs_files
*k
= NULL
;
1582 const char *controller
= NULL
;
1589 memset(sb
, 0, sizeof(struct stat
));
1591 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
1594 sb
->st_uid
= sb
->st_gid
= 0;
1595 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
1598 if (strcmp(path
, "/cgroup") == 0) {
1599 sb
->st_mode
= S_IFDIR
| 00755;
1604 controller
= pick_controller_from_path(fc
, path
);
1607 cgroup
= find_cgroup_in_path(path
);
1609 /* this is just /cgroup/controller, return it as a dir */
1610 sb
->st_mode
= S_IFDIR
| 00755;
1615 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
1625 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1628 /* check that cgcopy is either a child cgroup of cgdir, or listed in its keys.
1629 * Then check that caller's cgroup is under path if last is a child
1630 * cgroup, or cgdir if last is a file */
1632 if (is_child_cgroup(controller
, path1
, path2
)) {
1633 if (!caller_may_see_dir(initpid
, controller
, cgroup
)) {
1637 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
1638 /* this is just /cgroup/controller, return it as a dir */
1639 sb
->st_mode
= S_IFDIR
| 00555;
1644 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
)) {
1649 // get uid, gid, from '/tasks' file and make up a mode
1650 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
1651 sb
->st_mode
= S_IFDIR
| 00755;
1652 k
= cgfs_get_key(controller
, cgroup
, NULL
);
1654 sb
->st_uid
= sb
->st_gid
= 0;
1656 sb
->st_uid
= k
->uid
;
1657 sb
->st_gid
= k
->gid
;
1665 if ((k
= cgfs_get_key(controller
, path1
, path2
)) != NULL
) {
1666 sb
->st_mode
= S_IFREG
| k
->mode
;
1668 sb
->st_uid
= k
->uid
;
1669 sb
->st_gid
= k
->gid
;
1672 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
1684 int cg_opendir(const char *path
, struct fuse_file_info
*fi
)
1686 struct fuse_context
*fc
= fuse_get_context();
1688 struct file_info
*dir_info
;
1689 char *controller
= NULL
;
1694 if (strcmp(path
, "/cgroup") == 0) {
1698 // return list of keys for the controller, and list of child cgroups
1699 controller
= pick_controller_from_path(fc
, path
);
1703 cgroup
= find_cgroup_in_path(path
);
1705 /* this is just /cgroup/controller, return its contents */
1710 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1714 if (!caller_may_see_dir(initpid
, controller
, cgroup
))
1716 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
))
1720 /* we'll free this at cg_releasedir */
1721 dir_info
= malloc(sizeof(*dir_info
));
1724 dir_info
->controller
= must_copy_string(controller
);
1725 dir_info
->cgroup
= must_copy_string(cgroup
);
1726 dir_info
->type
= LXC_TYPE_CGDIR
;
1727 dir_info
->buf
= NULL
;
1728 dir_info
->file
= NULL
;
1729 dir_info
->buflen
= 0;
1731 fi
->fh
= (unsigned long)dir_info
;
1735 int cg_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
1736 struct fuse_file_info
*fi
)
1738 struct file_info
*d
= (struct file_info
*)fi
->fh
;
1739 struct cgfs_files
**list
= NULL
;
1741 char *nextcg
= NULL
;
1742 struct fuse_context
*fc
= fuse_get_context();
1743 char **clist
= NULL
;
1745 if (filler(buf
, ".", NULL
, 0) != 0 || filler(buf
, "..", NULL
, 0) != 0)
1748 if (d
->type
!= LXC_TYPE_CGDIR
) {
1749 lxcfs_error("%s\n", "Internal error: file cache info used in readdir.");
1752 if (!d
->cgroup
&& !d
->controller
) {
1753 // ls /var/lib/lxcfs/cgroup - just show list of controllers
1756 for (i
= 0; i
< num_hierarchies
; i
++) {
1757 if (hierarchies
[i
] && filler(buf
, hierarchies
[i
], NULL
, 0) != 0) {
1764 if (!cgfs_list_keys(d
->controller
, d
->cgroup
, &list
)) {
1765 // not a valid cgroup
1770 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1773 if (!caller_is_in_ancestor(initpid
, d
->controller
, d
->cgroup
, &nextcg
)) {
1775 ret
= filler(buf
, nextcg
, NULL
, 0);
1786 for (i
= 0; list
[i
]; i
++) {
1787 if (filler(buf
, list
[i
]->name
, NULL
, 0) != 0) {
1793 // now get the list of child cgroups
1795 if (!cgfs_list_children(d
->controller
, d
->cgroup
, &clist
)) {
1800 for (i
= 0; clist
[i
]; i
++) {
1801 if (filler(buf
, clist
[i
], NULL
, 0) != 0) {
1812 for (i
= 0; clist
[i
]; i
++)
1819 static void do_release_file_info(struct fuse_file_info
*fi
)
1821 struct file_info
*f
= (struct file_info
*)fi
->fh
;
1828 free(f
->controller
);
1829 f
->controller
= NULL
;
1839 int cg_releasedir(const char *path
, struct fuse_file_info
*fi
)
1841 do_release_file_info(fi
);
1845 int cg_open(const char *path
, struct fuse_file_info
*fi
)
1848 char *last
= NULL
, *path1
, *path2
, * cgdir
= NULL
, *controller
;
1849 struct cgfs_files
*k
= NULL
;
1850 struct file_info
*file_info
;
1851 struct fuse_context
*fc
= fuse_get_context();
1857 controller
= pick_controller_from_path(fc
, path
);
1860 cgroup
= find_cgroup_in_path(path
);
1864 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
1873 k
= cgfs_get_key(controller
, path1
, path2
);
1880 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1883 if (!caller_may_see_dir(initpid
, controller
, path1
)) {
1887 if (!fc_may_access(fc
, controller
, path1
, path2
, fi
->flags
)) {
1892 /* we'll free this at cg_release */
1893 file_info
= malloc(sizeof(*file_info
));
1898 file_info
->controller
= must_copy_string(controller
);
1899 file_info
->cgroup
= must_copy_string(path1
);
1900 file_info
->file
= must_copy_string(path2
);
1901 file_info
->type
= LXC_TYPE_CGFILE
;
1902 file_info
->buf
= NULL
;
1903 file_info
->buflen
= 0;
1905 fi
->fh
= (unsigned long)file_info
;
1913 int cg_access(const char *path
, int mode
)
1917 char *path1
, *path2
, *controller
;
1918 char *last
= NULL
, *cgdir
= NULL
;
1919 struct cgfs_files
*k
= NULL
;
1920 struct fuse_context
*fc
= fuse_get_context();
1922 if (strcmp(path
, "/cgroup") == 0)
1928 controller
= pick_controller_from_path(fc
, path
);
1931 cgroup
= find_cgroup_in_path(path
);
1933 // access("/sys/fs/cgroup/systemd", mode) - rx allowed, w not
1934 if ((mode
& W_OK
) == 0)
1939 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
1948 k
= cgfs_get_key(controller
, path1
, path2
);
1950 if ((mode
& W_OK
) == 0)
1958 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1961 if (!caller_may_see_dir(initpid
, controller
, path1
)) {
1965 if (!fc_may_access(fc
, controller
, path1
, path2
, mode
)) {
1977 int cg_release(const char *path
, struct fuse_file_info
*fi
)
1979 do_release_file_info(fi
);
1983 #define POLLIN_SET ( EPOLLIN | EPOLLHUP | EPOLLRDHUP )
1985 static bool wait_for_sock(int sock
, int timeout
)
1987 struct epoll_event ev
;
1988 int epfd
, ret
, now
, starttime
, deltatime
, saved_errno
;
1990 if ((starttime
= time(NULL
)) < 0)
1993 if ((epfd
= epoll_create(1)) < 0) {
1994 lxcfs_error("%s\n", "Failed to create epoll socket: %m.");
1998 ev
.events
= POLLIN_SET
;
2000 if (epoll_ctl(epfd
, EPOLL_CTL_ADD
, sock
, &ev
) < 0) {
2001 lxcfs_error("%s\n", "Failed adding socket to epoll: %m.");
2007 if ((now
= time(NULL
)) < 0) {
2012 deltatime
= (starttime
+ timeout
) - now
;
2013 if (deltatime
< 0) { // timeout
2018 ret
= epoll_wait(epfd
, &ev
, 1, 1000*deltatime
+ 1);
2019 if (ret
< 0 && errno
== EINTR
)
2021 saved_errno
= errno
;
2025 errno
= saved_errno
;
2031 static int msgrecv(int sockfd
, void *buf
, size_t len
)
2033 if (!wait_for_sock(sockfd
, 2))
2035 return recv(sockfd
, buf
, len
, MSG_DONTWAIT
);
2038 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
)
2040 struct msghdr msg
= { 0 };
2042 struct cmsghdr
*cmsg
;
2043 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
2048 if (msgrecv(sock
, buf
, 1) != 1) {
2049 lxcfs_error("%s\n", "Error getting reply from server over socketpair.");
2050 return SEND_CREDS_FAIL
;
2054 msg
.msg_control
= cmsgbuf
;
2055 msg
.msg_controllen
= sizeof(cmsgbuf
);
2057 cmsg
= CMSG_FIRSTHDR(&msg
);
2058 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct ucred
));
2059 cmsg
->cmsg_level
= SOL_SOCKET
;
2060 cmsg
->cmsg_type
= SCM_CREDENTIALS
;
2061 memcpy(CMSG_DATA(cmsg
), cred
, sizeof(*cred
));
2063 msg
.msg_name
= NULL
;
2064 msg
.msg_namelen
= 0;
2068 iov
.iov_len
= sizeof(buf
);
2072 if (sendmsg(sock
, &msg
, 0) < 0) {
2073 lxcfs_error("Failed at sendmsg: %s.\n",strerror(errno
));
2075 return SEND_CREDS_NOTSK
;
2076 return SEND_CREDS_FAIL
;
2079 return SEND_CREDS_OK
;
2082 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
)
2084 struct msghdr msg
= { 0 };
2086 struct cmsghdr
*cmsg
;
2087 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
2098 if (setsockopt(sock
, SOL_SOCKET
, SO_PASSCRED
, &optval
, sizeof(optval
)) == -1) {
2099 lxcfs_error("Failed to set passcred: %s\n", strerror(errno
));
2103 if (write(sock
, buf
, 1) != 1) {
2104 lxcfs_error("Failed to start write on scm fd: %s\n", strerror(errno
));
2108 msg
.msg_name
= NULL
;
2109 msg
.msg_namelen
= 0;
2110 msg
.msg_control
= cmsgbuf
;
2111 msg
.msg_controllen
= sizeof(cmsgbuf
);
2114 iov
.iov_len
= sizeof(buf
);
2118 if (!wait_for_sock(sock
, 2)) {
2119 lxcfs_error("Timed out waiting for scm_cred: %s\n", strerror(errno
));
2122 ret
= recvmsg(sock
, &msg
, MSG_DONTWAIT
);
2124 lxcfs_error("Failed to receive scm_cred: %s\n", strerror(errno
));
2128 cmsg
= CMSG_FIRSTHDR(&msg
);
2130 if (cmsg
&& cmsg
->cmsg_len
== CMSG_LEN(sizeof(struct ucred
)) &&
2131 cmsg
->cmsg_level
== SOL_SOCKET
&&
2132 cmsg
->cmsg_type
== SCM_CREDENTIALS
) {
2133 memcpy(cred
, CMSG_DATA(cmsg
), sizeof(*cred
));
2140 struct pid_ns_clone_args
{
2144 int (*wrapped
) (int, pid_t
); // pid_from_ns or pid_to_ns
2148 * pid_ns_clone_wrapper - wraps pid_to_ns or pid_from_ns for usage
2149 * with clone(). This simply writes '1' as ACK back to the parent
2150 * before calling the actual wrapped function.
2152 static int pid_ns_clone_wrapper(void *arg
) {
2153 struct pid_ns_clone_args
* args
= (struct pid_ns_clone_args
*) arg
;
2156 close(args
->cpipe
[0]);
2157 if (write(args
->cpipe
[1], &b
, sizeof(char)) < 0)
2158 lxcfs_error("(child): error on write: %s.\n", strerror(errno
));
2159 close(args
->cpipe
[1]);
2160 return args
->wrapped(args
->sock
, args
->tpid
);
2164 * pid_to_ns - reads pids from a ucred over a socket, then writes the
2165 * int value back over the socket. This shifts the pid from the
2166 * sender's pidns into tpid's pidns.
2168 static int pid_to_ns(int sock
, pid_t tpid
)
2173 while (recv_creds(sock
, &cred
, &v
)) {
2176 if (write(sock
, &cred
.pid
, sizeof(pid_t
)) != sizeof(pid_t
))
2184 * pid_to_ns_wrapper: when you setns into a pidns, you yourself remain
2185 * in your old pidns. Only children which you clone will be in the target
2186 * pidns. So the pid_to_ns_wrapper does the setns, then clones a child to
2187 * actually convert pids.
2189 * Note: glibc's fork() does not respect pidns, which can lead to failed
2190 * assertions inside glibc (and thus failed forks) if the child's pid in
2191 * the pidns and the parent pid outside are identical. Using clone prevents
2194 static void pid_to_ns_wrapper(int sock
, pid_t tpid
)
2196 int newnsfd
= -1, ret
, cpipe
[2];
2201 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
2202 if (ret
< 0 || ret
>= sizeof(fnam
))
2204 newnsfd
= open(fnam
, O_RDONLY
);
2207 if (setns(newnsfd
, 0) < 0)
2211 if (pipe(cpipe
) < 0)
2214 struct pid_ns_clone_args args
= {
2218 .wrapped
= &pid_to_ns
2220 size_t stack_size
= sysconf(_SC_PAGESIZE
);
2221 void *stack
= alloca(stack_size
);
2223 cpid
= clone(pid_ns_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &args
);
2227 // give the child 1 second to be done forking and
2229 if (!wait_for_sock(cpipe
[0], 1))
2231 ret
= read(cpipe
[0], &v
, 1);
2232 if (ret
!= sizeof(char) || v
!= '1')
2235 if (!wait_for_pid(cpid
))
2241 * To read cgroup files with a particular pid, we will setns into the child
2242 * pidns, open a pipe, fork a child - which will be the first to really be in
2243 * the child ns - which does the cgfs_get_value and writes the data to the pipe.
2245 bool do_read_pids(pid_t tpid
, const char *contrl
, const char *cg
, const char *file
, char **d
)
2247 int sock
[2] = {-1, -1};
2248 char *tmpdata
= NULL
;
2250 pid_t qpid
, cpid
= -1;
2251 bool answer
= false;
2254 size_t sz
= 0, asz
= 0;
2256 if (!cgfs_get_value(contrl
, cg
, file
, &tmpdata
))
2260 * Now we read the pids from returned data one by one, pass
2261 * them into a child in the target namespace, read back the
2262 * translated pids, and put them into our to-return data
2265 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2266 perror("socketpair");
2275 if (!cpid
) // child - exits when done
2276 pid_to_ns_wrapper(sock
[1], tpid
);
2278 char *ptr
= tmpdata
;
2281 while (sscanf(ptr
, "%d\n", &qpid
) == 1) {
2283 ret
= send_creds(sock
[0], &cred
, v
, true);
2285 if (ret
== SEND_CREDS_NOTSK
)
2287 if (ret
== SEND_CREDS_FAIL
)
2290 // read converted results
2291 if (!wait_for_sock(sock
[0], 2)) {
2292 lxcfs_error("Timed out waiting for pid from child: %s.\n", strerror(errno
));
2295 if (read(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2296 lxcfs_error("Error reading pid from child: %s.\n", strerror(errno
));
2299 must_strcat_pid(d
, &sz
, &asz
, qpid
);
2301 ptr
= strchr(ptr
, '\n');
2307 cred
.pid
= getpid();
2309 if (send_creds(sock
[0], &cred
, v
, true) != SEND_CREDS_OK
) {
2310 // failed to ask child to exit
2311 lxcfs_error("Failed to ask child to exit: %s.\n", strerror(errno
));
2321 if (sock
[0] != -1) {
2328 int cg_read(const char *path
, char *buf
, size_t size
, off_t offset
,
2329 struct fuse_file_info
*fi
)
2331 struct fuse_context
*fc
= fuse_get_context();
2332 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2333 struct cgfs_files
*k
= NULL
;
2338 if (f
->type
!= LXC_TYPE_CGFILE
) {
2339 lxcfs_error("%s\n", "Internal error: directory cache info used in cg_read.");
2352 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
2358 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_RDONLY
)) {
2363 if (strcmp(f
->file
, "tasks") == 0 ||
2364 strcmp(f
->file
, "/tasks") == 0 ||
2365 strcmp(f
->file
, "/cgroup.procs") == 0 ||
2366 strcmp(f
->file
, "cgroup.procs") == 0)
2367 // special case - we have to translate the pids
2368 r
= do_read_pids(fc
->pid
, f
->controller
, f
->cgroup
, f
->file
, &data
);
2370 r
= cgfs_get_value(f
->controller
, f
->cgroup
, f
->file
, &data
);
2384 memcpy(buf
, data
, s
);
2385 if (s
> 0 && s
< size
&& data
[s
-1] != '\n')
2395 static int pid_from_ns(int sock
, pid_t tpid
)
2405 if (!wait_for_sock(sock
, 2)) {
2406 lxcfs_error("%s\n", "Timeout reading from parent.");
2409 if ((ret
= read(sock
, &vpid
, sizeof(pid_t
))) != sizeof(pid_t
)) {
2410 lxcfs_error("Bad read from parent: %s.\n", strerror(errno
));
2413 if (vpid
== -1) // done
2417 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
) {
2419 cred
.pid
= getpid();
2420 if (send_creds(sock
, &cred
, v
, false) != SEND_CREDS_OK
)
2427 static void pid_from_ns_wrapper(int sock
, pid_t tpid
)
2429 int newnsfd
= -1, ret
, cpipe
[2];
2434 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
2435 if (ret
< 0 || ret
>= sizeof(fnam
))
2437 newnsfd
= open(fnam
, O_RDONLY
);
2440 if (setns(newnsfd
, 0) < 0)
2444 if (pipe(cpipe
) < 0)
2447 struct pid_ns_clone_args args
= {
2451 .wrapped
= &pid_from_ns
2453 size_t stack_size
= sysconf(_SC_PAGESIZE
);
2454 void *stack
= alloca(stack_size
);
2456 cpid
= clone(pid_ns_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &args
);
2460 // give the child 1 second to be done forking and
2462 if (!wait_for_sock(cpipe
[0], 1))
2464 ret
= read(cpipe
[0], &v
, 1);
2465 if (ret
!= sizeof(char) || v
!= '1')
2468 if (!wait_for_pid(cpid
))
2474 * Given host @uid, return the uid to which it maps in
2475 * @pid's user namespace, or -1 if none.
2477 bool hostuid_to_ns(uid_t uid
, pid_t pid
, uid_t
*answer
)
2482 sprintf(line
, "/proc/%d/uid_map", pid
);
2483 if ((f
= fopen(line
, "r")) == NULL
) {
2487 *answer
= convert_id_to_ns(f
, uid
);
2496 * get_pid_creds: get the real uid and gid of @pid from
2498 * (XXX should we use euid here?)
2500 void get_pid_creds(pid_t pid
, uid_t
*uid
, gid_t
*gid
)
2509 sprintf(line
, "/proc/%d/status", pid
);
2510 if ((f
= fopen(line
, "r")) == NULL
) {
2511 lxcfs_error("Error opening %s: %s\n", line
, strerror(errno
));
2514 while (fgets(line
, 400, f
)) {
2515 if (strncmp(line
, "Uid:", 4) == 0) {
2516 if (sscanf(line
+4, "%u", &u
) != 1) {
2517 lxcfs_error("bad uid line for pid %u\n", pid
);
2522 } else if (strncmp(line
, "Gid:", 4) == 0) {
2523 if (sscanf(line
+4, "%u", &g
) != 1) {
2524 lxcfs_error("bad gid line for pid %u\n", pid
);
2535 * May the requestor @r move victim @v to a new cgroup?
2536 * This is allowed if
2537 * . they are the same task
2538 * . they are ownedy by the same uid
2539 * . @r is root on the host, or
2540 * . @v's uid is mapped into @r's where @r is root.
2542 bool may_move_pid(pid_t r
, uid_t r_uid
, pid_t v
)
2544 uid_t v_uid
, tmpuid
;
2551 get_pid_creds(v
, &v_uid
, &v_gid
);
2554 if (hostuid_to_ns(r_uid
, r
, &tmpuid
) && tmpuid
== 0
2555 && hostuid_to_ns(v_uid
, r
, &tmpuid
))
2560 static bool do_write_pids(pid_t tpid
, uid_t tuid
, const char *contrl
, const char *cg
,
2561 const char *file
, const char *buf
)
2563 int sock
[2] = {-1, -1};
2564 pid_t qpid
, cpid
= -1;
2565 FILE *pids_file
= NULL
;
2566 bool answer
= false, fail
= false;
2568 pids_file
= open_pids_file(contrl
, cg
);
2573 * write the pids to a socket, have helper in writer's pidns
2574 * call movepid for us
2576 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2577 perror("socketpair");
2585 if (!cpid
) { // child
2587 pid_from_ns_wrapper(sock
[1], tpid
);
2590 const char *ptr
= buf
;
2591 while (sscanf(ptr
, "%d", &qpid
) == 1) {
2595 if (write(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2596 lxcfs_error("Error writing pid to child: %s.\n", strerror(errno
));
2600 if (recv_creds(sock
[0], &cred
, &v
)) {
2602 if (!may_move_pid(tpid
, tuid
, cred
.pid
)) {
2606 if (fprintf(pids_file
, "%d", (int) cred
.pid
) < 0)
2611 ptr
= strchr(ptr
, '\n');
2617 /* All good, write the value */
2619 if (write(sock
[0], &qpid
,sizeof(qpid
)) != sizeof(qpid
))
2620 lxcfs_error("%s\n", "Warning: failed to ask child to exit.");
2628 if (sock
[0] != -1) {
2633 if (fclose(pids_file
) != 0)
2639 int cg_write(const char *path
, const char *buf
, size_t size
, off_t offset
,
2640 struct fuse_file_info
*fi
)
2642 struct fuse_context
*fc
= fuse_get_context();
2643 char *localbuf
= NULL
;
2644 struct cgfs_files
*k
= NULL
;
2645 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2648 if (f
->type
!= LXC_TYPE_CGFILE
) {
2649 lxcfs_error("%s\n", "Internal error: directory cache info used in cg_write.");
2659 localbuf
= alloca(size
+1);
2660 localbuf
[size
] = '\0';
2661 memcpy(localbuf
, buf
, size
);
2663 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
2668 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_WRONLY
)) {
2673 if (strcmp(f
->file
, "tasks") == 0 ||
2674 strcmp(f
->file
, "/tasks") == 0 ||
2675 strcmp(f
->file
, "/cgroup.procs") == 0 ||
2676 strcmp(f
->file
, "cgroup.procs") == 0)
2677 // special case - we have to translate the pids
2678 r
= do_write_pids(fc
->pid
, fc
->uid
, f
->controller
, f
->cgroup
, f
->file
, localbuf
);
2680 r
= cgfs_set_value(f
->controller
, f
->cgroup
, f
->file
, localbuf
);
2690 int cg_chown(const char *path
, uid_t uid
, gid_t gid
)
2692 struct fuse_context
*fc
= fuse_get_context();
2693 char *cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
2694 struct cgfs_files
*k
= NULL
;
2701 if (strcmp(path
, "/cgroup") == 0)
2704 controller
= pick_controller_from_path(fc
, path
);
2706 return errno
== ENOENT
? -EPERM
: -errno
;
2708 cgroup
= find_cgroup_in_path(path
);
2710 /* this is just /cgroup/controller */
2713 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2723 if (is_child_cgroup(controller
, path1
, path2
)) {
2724 // get uid, gid, from '/tasks' file and make up a mode
2725 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
2726 k
= cgfs_get_key(controller
, cgroup
, "tasks");
2729 k
= cgfs_get_key(controller
, path1
, path2
);
2737 * This being a fuse request, the uid and gid must be valid
2738 * in the caller's namespace. So we can just check to make
2739 * sure that the caller is root in his uid, and privileged
2740 * over the file's current owner.
2742 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_REQD
)) {
2747 ret
= cgfs_chown_file(controller
, cgroup
, uid
, gid
);
2756 int cg_chmod(const char *path
, mode_t mode
)
2758 struct fuse_context
*fc
= fuse_get_context();
2759 char * cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
2760 struct cgfs_files
*k
= NULL
;
2767 if (strcmp(path
, "/cgroup") == 0)
2770 controller
= pick_controller_from_path(fc
, path
);
2772 return errno
== ENOENT
? -EPERM
: -errno
;
2774 cgroup
= find_cgroup_in_path(path
);
2776 /* this is just /cgroup/controller */
2779 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2789 if (is_child_cgroup(controller
, path1
, path2
)) {
2790 // get uid, gid, from '/tasks' file and make up a mode
2791 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
2792 k
= cgfs_get_key(controller
, cgroup
, "tasks");
2795 k
= cgfs_get_key(controller
, path1
, path2
);
2803 * This being a fuse request, the uid and gid must be valid
2804 * in the caller's namespace. So we can just check to make
2805 * sure that the caller is root in his uid, and privileged
2806 * over the file's current owner.
2808 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
2813 if (!cgfs_chmod_file(controller
, cgroup
, mode
)) {
2825 int cg_mkdir(const char *path
, mode_t mode
)
2827 struct fuse_context
*fc
= fuse_get_context();
2828 char *last
= NULL
, *path1
, *cgdir
= NULL
, *controller
, *next
= NULL
;
2835 controller
= pick_controller_from_path(fc
, path
);
2837 return errno
== ENOENT
? -EPERM
: -errno
;
2839 cgroup
= find_cgroup_in_path(path
);
2843 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2849 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2852 if (!caller_is_in_ancestor(initpid
, controller
, path1
, &next
)) {
2855 else if (last
&& strcmp(next
, last
) == 0)
2862 if (!fc_may_access(fc
, controller
, path1
, NULL
, O_RDWR
)) {
2866 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
2871 ret
= cgfs_create(controller
, cgroup
, fc
->uid
, fc
->gid
);
2879 int cg_rmdir(const char *path
)
2881 struct fuse_context
*fc
= fuse_get_context();
2882 char *last
= NULL
, *cgdir
= NULL
, *controller
, *next
= NULL
;
2889 controller
= pick_controller_from_path(fc
, path
);
2890 if (!controller
) /* Someone's trying to delete "/cgroup". */
2893 cgroup
= find_cgroup_in_path(path
);
2894 if (!cgroup
) /* Someone's trying to delete a controller e.g. "/blkio". */
2897 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2899 /* Someone's trying to delete a cgroup on the same level as the
2900 * "/lxc" cgroup e.g. rmdir "/cgroup/blkio/lxc" or
2901 * rmdir "/cgroup/blkio/init.slice".
2907 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2910 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, &next
)) {
2911 if (!last
|| (next
&& (strcmp(next
, last
) == 0)))
2918 if (!fc_may_access(fc
, controller
, cgdir
, NULL
, O_WRONLY
)) {
2922 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
2927 if (!cgfs_remove(controller
, cgroup
)) {
2940 static bool startswith(const char *line
, const char *pref
)
2942 if (strncmp(line
, pref
, strlen(pref
)) == 0)
2947 static void parse_memstat(char *memstat
, unsigned long *cached
,
2948 unsigned long *active_anon
, unsigned long *inactive_anon
,
2949 unsigned long *active_file
, unsigned long *inactive_file
,
2950 unsigned long *unevictable
)
2955 if (startswith(memstat
, "cache")) {
2956 sscanf(memstat
+ 5, "%lu", cached
);
2958 } else if (startswith(memstat
, "active_anon")) {
2959 sscanf(memstat
+ 11, "%lu", active_anon
);
2960 *active_anon
/= 1024;
2961 } else if (startswith(memstat
, "inactive_anon")) {
2962 sscanf(memstat
+ 13, "%lu", inactive_anon
);
2963 *inactive_anon
/= 1024;
2964 } else if (startswith(memstat
, "active_file")) {
2965 sscanf(memstat
+ 11, "%lu", active_file
);
2966 *active_file
/= 1024;
2967 } else if (startswith(memstat
, "inactive_file")) {
2968 sscanf(memstat
+ 13, "%lu", inactive_file
);
2969 *inactive_file
/= 1024;
2970 } else if (startswith(memstat
, "unevictable")) {
2971 sscanf(memstat
+ 11, "%lu", unevictable
);
2972 *unevictable
/= 1024;
2974 eol
= strchr(memstat
, '\n');
2981 static void get_blkio_io_value(char *str
, unsigned major
, unsigned minor
, char *iotype
, unsigned long *v
)
2987 snprintf(key
, 32, "%u:%u %s", major
, minor
, iotype
);
2989 size_t len
= strlen(key
);
2993 if (startswith(str
, key
)) {
2994 sscanf(str
+ len
, "%lu", v
);
2997 eol
= strchr(str
, '\n');
3004 static int read_file(const char *path
, char *buf
, size_t size
,
3005 struct file_info
*d
)
3007 size_t linelen
= 0, total_len
= 0, rv
= 0;
3009 char *cache
= d
->buf
;
3010 size_t cache_size
= d
->buflen
;
3011 FILE *f
= fopen(path
, "r");
3015 while (getline(&line
, &linelen
, f
) != -1) {
3016 ssize_t l
= snprintf(cache
, cache_size
, "%s", line
);
3018 perror("Error writing to cache");
3022 if (l
>= cache_size
) {
3023 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3032 d
->size
= total_len
;
3033 if (total_len
> size
)
3036 /* read from off 0 */
3037 memcpy(buf
, d
->buf
, total_len
);
3046 * FUSE ops for /proc
3049 static unsigned long get_memlimit(const char *cgroup
, const char *file
)
3051 char *memlimit_str
= NULL
;
3052 unsigned long memlimit
= -1;
3054 if (cgfs_get_value("memory", cgroup
, file
, &memlimit_str
))
3055 memlimit
= strtoul(memlimit_str
, NULL
, 10);
3062 static unsigned long get_min_memlimit(const char *cgroup
, const char *file
)
3064 char *copy
= strdupa(cgroup
);
3065 unsigned long memlimit
= 0, retlimit
;
3067 retlimit
= get_memlimit(copy
, file
);
3069 while (strcmp(copy
, "/") != 0) {
3070 copy
= dirname(copy
);
3071 memlimit
= get_memlimit(copy
, file
);
3072 if (memlimit
!= -1 && memlimit
< retlimit
)
3073 retlimit
= memlimit
;
3079 static int proc_meminfo_read(char *buf
, size_t size
, off_t offset
,
3080 struct fuse_file_info
*fi
)
3082 struct fuse_context
*fc
= fuse_get_context();
3083 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3085 char *memusage_str
= NULL
, *memstat_str
= NULL
,
3086 *memswlimit_str
= NULL
, *memswusage_str
= NULL
;
3087 unsigned long memlimit
= 0, memusage
= 0, memswlimit
= 0, memswusage
= 0,
3088 cached
= 0, hosttotal
= 0, active_anon
= 0, inactive_anon
= 0,
3089 active_file
= 0, inactive_file
= 0, unevictable
= 0;
3091 size_t linelen
= 0, total_len
= 0, rv
= 0;
3092 char *cache
= d
->buf
;
3093 size_t cache_size
= d
->buflen
;
3097 if (offset
> d
->size
)
3101 int left
= d
->size
- offset
;
3102 total_len
= left
> size
? size
: left
;
3103 memcpy(buf
, cache
+ offset
, total_len
);
3107 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3110 cg
= get_pid_cgroup(initpid
, "memory");
3112 return read_file("/proc/meminfo", buf
, size
, d
);
3113 prune_init_slice(cg
);
3115 memlimit
= get_min_memlimit(cg
, "memory.limit_in_bytes");
3116 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
3118 if (!cgfs_get_value("memory", cg
, "memory.stat", &memstat_str
))
3121 // Following values are allowed to fail, because swapaccount might be turned
3122 // off for current kernel
3123 if(cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
) &&
3124 cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
))
3126 memswlimit
= get_min_memlimit(cg
, "memory.memsw.limit_in_bytes");
3127 memswusage
= strtoul(memswusage_str
, NULL
, 10);
3129 memswlimit
= memswlimit
/ 1024;
3130 memswusage
= memswusage
/ 1024;
3133 memusage
= strtoul(memusage_str
, NULL
, 10);
3137 parse_memstat(memstat_str
, &cached
, &active_anon
,
3138 &inactive_anon
, &active_file
, &inactive_file
,
3141 f
= fopen("/proc/meminfo", "r");
3145 while (getline(&line
, &linelen
, f
) != -1) {
3147 char *printme
, lbuf
[100];
3149 memset(lbuf
, 0, 100);
3150 if (startswith(line
, "MemTotal:")) {
3151 sscanf(line
+14, "%lu", &hosttotal
);
3152 if (hosttotal
< memlimit
)
3153 memlimit
= hosttotal
;
3154 snprintf(lbuf
, 100, "MemTotal: %8lu kB\n", memlimit
);
3156 } else if (startswith(line
, "MemFree:")) {
3157 snprintf(lbuf
, 100, "MemFree: %8lu kB\n", memlimit
- memusage
);
3159 } else if (startswith(line
, "MemAvailable:")) {
3160 snprintf(lbuf
, 100, "MemAvailable: %8lu kB\n", memlimit
- memusage
);
3162 } else if (startswith(line
, "SwapTotal:") && memswlimit
> 0) {
3163 snprintf(lbuf
, 100, "SwapTotal: %8lu kB\n", memswlimit
- memlimit
);
3165 } else if (startswith(line
, "SwapFree:") && memswlimit
> 0 && memswusage
> 0) {
3166 unsigned long swaptotal
= memswlimit
- memlimit
,
3167 swapusage
= memswusage
- memusage
,
3168 swapfree
= swapusage
< swaptotal
? swaptotal
- swapusage
: 0;
3169 snprintf(lbuf
, 100, "SwapFree: %8lu kB\n", swapfree
);
3171 } else if (startswith(line
, "Slab:")) {
3172 snprintf(lbuf
, 100, "Slab: %8lu kB\n", 0UL);
3174 } else if (startswith(line
, "Buffers:")) {
3175 snprintf(lbuf
, 100, "Buffers: %8lu kB\n", 0UL);
3177 } else if (startswith(line
, "Cached:")) {
3178 snprintf(lbuf
, 100, "Cached: %8lu kB\n", cached
);
3180 } else if (startswith(line
, "SwapCached:")) {
3181 snprintf(lbuf
, 100, "SwapCached: %8lu kB\n", 0UL);
3183 } else if (startswith(line
, "Active:")) {
3184 snprintf(lbuf
, 100, "Active: %8lu kB\n",
3185 active_anon
+ active_file
);
3187 } else if (startswith(line
, "Inactive:")) {
3188 snprintf(lbuf
, 100, "Inactive: %8lu kB\n",
3189 inactive_anon
+ inactive_file
);
3191 } else if (startswith(line
, "Active(anon)")) {
3192 snprintf(lbuf
, 100, "Active(anon): %8lu kB\n", active_anon
);
3194 } else if (startswith(line
, "Inactive(anon)")) {
3195 snprintf(lbuf
, 100, "Inactive(anon): %8lu kB\n", inactive_anon
);
3197 } else if (startswith(line
, "Active(file)")) {
3198 snprintf(lbuf
, 100, "Active(file): %8lu kB\n", active_file
);
3200 } else if (startswith(line
, "Inactive(file)")) {
3201 snprintf(lbuf
, 100, "Inactive(file): %8lu kB\n", inactive_file
);
3203 } else if (startswith(line
, "Unevictable")) {
3204 snprintf(lbuf
, 100, "Unevictable: %8lu kB\n", unevictable
);
3206 } else if (startswith(line
, "SReclaimable")) {
3207 snprintf(lbuf
, 100, "SReclaimable: %8lu kB\n", 0UL);
3209 } else if (startswith(line
, "SUnreclaim")) {
3210 snprintf(lbuf
, 100, "SUnreclaim: %8lu kB\n", 0UL);
3215 l
= snprintf(cache
, cache_size
, "%s", printme
);
3217 perror("Error writing to cache");
3222 if (l
>= cache_size
) {
3223 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3234 d
->size
= total_len
;
3235 if (total_len
> size
) total_len
= size
;
3236 memcpy(buf
, d
->buf
, total_len
);
3245 free(memswlimit_str
);
3246 free(memswusage_str
);
3252 * Read the cpuset.cpus for cg
3253 * Return the answer in a newly allocated string which must be freed
3255 static char *get_cpuset(const char *cg
)
3259 if (!cgfs_get_value("cpuset", cg
, "cpuset.cpus", &answer
))
3264 bool cpu_in_cpuset(int cpu
, const char *cpuset
);
3266 static bool cpuline_in_cpuset(const char *line
, const char *cpuset
)
3270 if (sscanf(line
, "processor : %d", &cpu
) != 1)
3272 return cpu_in_cpuset(cpu
, cpuset
);
3276 * check whether this is a '^processor" line in /proc/cpuinfo
3278 static bool is_processor_line(const char *line
)
3282 if (sscanf(line
, "processor : %d", &cpu
) == 1)
3287 static int proc_cpuinfo_read(char *buf
, size_t size
, off_t offset
,
3288 struct fuse_file_info
*fi
)
3290 struct fuse_context
*fc
= fuse_get_context();
3291 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3293 char *cpuset
= NULL
;
3295 size_t linelen
= 0, total_len
= 0, rv
= 0;
3296 bool am_printing
= false, firstline
= true, is_s390x
= false;
3297 int curcpu
= -1, cpu
;
3298 char *cache
= d
->buf
;
3299 size_t cache_size
= d
->buflen
;
3303 if (offset
> d
->size
)
3307 int left
= d
->size
- offset
;
3308 total_len
= left
> size
? size
: left
;
3309 memcpy(buf
, cache
+ offset
, total_len
);
3313 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3316 cg
= get_pid_cgroup(initpid
, "cpuset");
3318 return read_file("proc/cpuinfo", buf
, size
, d
);
3319 prune_init_slice(cg
);
3321 cpuset
= get_cpuset(cg
);
3325 f
= fopen("/proc/cpuinfo", "r");
3329 while (getline(&line
, &linelen
, f
) != -1) {
3333 if (strstr(line
, "IBM/S390") != NULL
) {
3339 if (strncmp(line
, "# processors:", 12) == 0)
3341 if (is_processor_line(line
)) {
3342 am_printing
= cpuline_in_cpuset(line
, cpuset
);
3345 l
= snprintf(cache
, cache_size
, "processor : %d\n", curcpu
);
3347 perror("Error writing to cache");
3351 if (l
>= cache_size
) {
3352 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3361 } else if (is_s390x
&& sscanf(line
, "processor %d:", &cpu
) == 1) {
3363 if (!cpu_in_cpuset(cpu
, cpuset
))
3366 p
= strchr(line
, ':');
3370 l
= snprintf(cache
, cache_size
, "processor %d:%s", curcpu
, p
);
3372 perror("Error writing to cache");
3376 if (l
>= cache_size
) {
3377 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3388 l
= snprintf(cache
, cache_size
, "%s", line
);
3390 perror("Error writing to cache");
3394 if (l
>= cache_size
) {
3395 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3406 char *origcache
= d
->buf
;
3409 d
->buf
= malloc(d
->buflen
);
3412 cache_size
= d
->buflen
;
3414 l
= snprintf(cache
, cache_size
, "vendor_id : IBM/S390\n");
3415 if (l
< 0 || l
>= cache_size
) {
3422 l
= snprintf(cache
, cache_size
, "# processors : %d\n", curcpu
+ 1);
3423 if (l
< 0 || l
>= cache_size
) {
3430 l
= snprintf(cache
, cache_size
, "%s", origcache
);
3432 if (l
< 0 || l
>= cache_size
)
3438 d
->size
= total_len
;
3439 if (total_len
> size
) total_len
= size
;
3441 /* read from off 0 */
3442 memcpy(buf
, d
->buf
, total_len
);
3453 static long int getreaperctime(pid_t pid
)
3460 qpid
= lookup_initpid_in_store(pid
);
3464 ret
= snprintf(fnam
, 100, "/proc/%d", qpid
);
3465 if (ret
< 0 || ret
>= 100)
3468 if (lstat(fnam
, &sb
) < 0)
3474 static int proc_stat_read(char *buf
, size_t size
, off_t offset
,
3475 struct fuse_file_info
*fi
)
3477 struct fuse_context
*fc
= fuse_get_context();
3478 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3480 char *cpuset
= NULL
;
3482 size_t linelen
= 0, total_len
= 0, rv
= 0;
3483 int curcpu
= -1; /* cpu numbering starts at 0 */
3484 unsigned long user
= 0, nice
= 0, system
= 0, idle
= 0, iowait
= 0, irq
= 0, softirq
= 0, steal
= 0, guest
= 0;
3485 unsigned long user_sum
= 0, nice_sum
= 0, system_sum
= 0, idle_sum
= 0, iowait_sum
= 0,
3486 irq_sum
= 0, softirq_sum
= 0, steal_sum
= 0, guest_sum
= 0;
3487 #define CPUALL_MAX_SIZE BUF_RESERVE_SIZE
3488 char cpuall
[CPUALL_MAX_SIZE
];
3489 /* reserve for cpu all */
3490 char *cache
= d
->buf
+ CPUALL_MAX_SIZE
;
3491 size_t cache_size
= d
->buflen
- CPUALL_MAX_SIZE
;
3495 if (offset
> d
->size
)
3499 int left
= d
->size
- offset
;
3500 total_len
= left
> size
? size
: left
;
3501 memcpy(buf
, d
->buf
+ offset
, total_len
);
3505 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3508 cg
= get_pid_cgroup(initpid
, "cpuset");
3510 return read_file("/proc/stat", buf
, size
, d
);
3511 prune_init_slice(cg
);
3513 cpuset
= get_cpuset(cg
);
3517 f
= fopen("/proc/stat", "r");
3522 if (getline(&line
, &linelen
, f
) < 0) {
3523 lxcfs_error("%s\n", "proc_stat_read read first line failed.");
3527 while (getline(&line
, &linelen
, f
) != -1) {
3530 char cpu_char
[10]; /* That's a lot of cores */
3533 if (strlen(line
) == 0)
3535 if (sscanf(line
, "cpu%9[^ ]", cpu_char
) != 1) {
3536 /* not a ^cpuN line containing a number N, just print it */
3537 if (strncmp(line
, "btime", 5) == 0)
3538 l
= snprintf(cache
, cache_size
, "btime %ld\n", getreaperctime(fc
->pid
));
3540 l
= snprintf(cache
, cache_size
, "%s", line
);
3542 perror("Error writing to cache");
3546 if (l
>= cache_size
) {
3547 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3557 if (sscanf(cpu_char
, "%d", &cpu
) != 1)
3559 if (!cpu_in_cpuset(cpu
, cpuset
))
3563 c
= strchr(line
, ' ');
3566 l
= snprintf(cache
, cache_size
, "cpu%d%s", curcpu
, c
);
3568 perror("Error writing to cache");
3573 if (l
>= cache_size
) {
3574 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3583 if (sscanf(line
, "%*s %lu %lu %lu %lu %lu %lu %lu %lu %lu", &user
, &nice
, &system
, &idle
, &iowait
, &irq
,
3584 &softirq
, &steal
, &guest
) != 9)
3588 system_sum
+= system
;
3590 iowait_sum
+= iowait
;
3592 softirq_sum
+= softirq
;
3599 int cpuall_len
= snprintf(cpuall
, CPUALL_MAX_SIZE
, "%s %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
3600 "cpu ", user_sum
, nice_sum
, system_sum
, idle_sum
, iowait_sum
, irq_sum
, softirq_sum
, steal_sum
, guest_sum
);
3601 if (cpuall_len
> 0 && cpuall_len
< CPUALL_MAX_SIZE
){
3602 memcpy(cache
, cpuall
, cpuall_len
);
3603 cache
+= cpuall_len
;
3605 /* shouldn't happen */
3606 lxcfs_error("proc_stat_read copy cpuall failed, cpuall_len=%d.", cpuall_len
);
3610 memmove(cache
, d
->buf
+ CPUALL_MAX_SIZE
, total_len
);
3611 total_len
+= cpuall_len
;
3613 d
->size
= total_len
;
3614 if (total_len
> size
) total_len
= size
;
3616 memcpy(buf
, d
->buf
, total_len
);
3628 static long int getreaperage(pid_t pid
)
3632 ctime
= getreaperctime(pid
);
3634 return time(NULL
) - ctime
;
3638 static unsigned long get_reaper_busy(pid_t task
)
3640 pid_t initpid
= lookup_initpid_in_store(task
);
3641 char *cgroup
= NULL
, *usage_str
= NULL
;
3642 unsigned long usage
= 0;
3647 cgroup
= get_pid_cgroup(initpid
, "cpuacct");
3650 prune_init_slice(cgroup
);
3651 if (!cgfs_get_value("cpuacct", cgroup
, "cpuacct.usage", &usage_str
))
3653 usage
= strtoul(usage_str
, NULL
, 10);
3654 usage
/= 1000000000;
3667 fd
= creat("/tmp/lxcfs-iwashere", 0644);
3674 * We read /proc/uptime and reuse its second field.
3675 * For the first field, we use the mtime for the reaper for
3676 * the calling pid as returned by getreaperage
3678 static int proc_uptime_read(char *buf
, size_t size
, off_t offset
,
3679 struct fuse_file_info
*fi
)
3681 struct fuse_context
*fc
= fuse_get_context();
3682 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3683 long int reaperage
= getreaperage(fc
->pid
);
3684 unsigned long int busytime
= get_reaper_busy(fc
->pid
), idletime
;
3685 char *cache
= d
->buf
;
3686 ssize_t total_len
= 0;
3693 if (offset
> d
->size
)
3697 int left
= d
->size
- offset
;
3698 total_len
= left
> size
? size
: left
;
3699 memcpy(buf
, cache
+ offset
, total_len
);
3703 idletime
= reaperage
- busytime
;
3704 if (idletime
> reaperage
)
3705 idletime
= reaperage
;
3707 total_len
= snprintf(d
->buf
, d
->size
, "%ld.0 %lu.0\n", reaperage
, idletime
);
3709 perror("Error writing to cache");
3713 d
->size
= (int)total_len
;
3716 if (total_len
> size
) total_len
= size
;
3718 memcpy(buf
, d
->buf
, total_len
);
3722 static int proc_diskstats_read(char *buf
, size_t size
, off_t offset
,
3723 struct fuse_file_info
*fi
)
3726 struct fuse_context
*fc
= fuse_get_context();
3727 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3729 char *io_serviced_str
= NULL
, *io_merged_str
= NULL
, *io_service_bytes_str
= NULL
,
3730 *io_wait_time_str
= NULL
, *io_service_time_str
= NULL
;
3731 unsigned long read
= 0, write
= 0;
3732 unsigned long read_merged
= 0, write_merged
= 0;
3733 unsigned long read_sectors
= 0, write_sectors
= 0;
3734 unsigned long read_ticks
= 0, write_ticks
= 0;
3735 unsigned long ios_pgr
= 0, tot_ticks
= 0, rq_ticks
= 0;
3736 unsigned long rd_svctm
= 0, wr_svctm
= 0, rd_wait
= 0, wr_wait
= 0;
3737 char *cache
= d
->buf
;
3738 size_t cache_size
= d
->buflen
;
3740 size_t linelen
= 0, total_len
= 0, rv
= 0;
3741 unsigned int major
= 0, minor
= 0;
3746 if (offset
> d
->size
)
3750 int left
= d
->size
- offset
;
3751 total_len
= left
> size
? size
: left
;
3752 memcpy(buf
, cache
+ offset
, total_len
);
3756 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3759 cg
= get_pid_cgroup(initpid
, "blkio");
3761 return read_file("/proc/diskstats", buf
, size
, d
);
3762 prune_init_slice(cg
);
3764 if (!cgfs_get_value("blkio", cg
, "blkio.io_serviced_recursive", &io_serviced_str
))
3766 if (!cgfs_get_value("blkio", cg
, "blkio.io_merged_recursive", &io_merged_str
))
3768 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_bytes_recursive", &io_service_bytes_str
))
3770 if (!cgfs_get_value("blkio", cg
, "blkio.io_wait_time_recursive", &io_wait_time_str
))
3772 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_time_recursive", &io_service_time_str
))
3776 f
= fopen("/proc/diskstats", "r");
3780 while (getline(&line
, &linelen
, f
) != -1) {
3784 i
= sscanf(line
, "%u %u %71s", &major
, &minor
, dev_name
);
3788 get_blkio_io_value(io_serviced_str
, major
, minor
, "Read", &read
);
3789 get_blkio_io_value(io_serviced_str
, major
, minor
, "Write", &write
);
3790 get_blkio_io_value(io_merged_str
, major
, minor
, "Read", &read_merged
);
3791 get_blkio_io_value(io_merged_str
, major
, minor
, "Write", &write_merged
);
3792 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Read", &read_sectors
);
3793 read_sectors
= read_sectors
/512;
3794 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Write", &write_sectors
);
3795 write_sectors
= write_sectors
/512;
3797 get_blkio_io_value(io_service_time_str
, major
, minor
, "Read", &rd_svctm
);
3798 rd_svctm
= rd_svctm
/1000000;
3799 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Read", &rd_wait
);
3800 rd_wait
= rd_wait
/1000000;
3801 read_ticks
= rd_svctm
+ rd_wait
;
3803 get_blkio_io_value(io_service_time_str
, major
, minor
, "Write", &wr_svctm
);
3804 wr_svctm
= wr_svctm
/1000000;
3805 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Write", &wr_wait
);
3806 wr_wait
= wr_wait
/1000000;
3807 write_ticks
= wr_svctm
+ wr_wait
;
3809 get_blkio_io_value(io_service_time_str
, major
, minor
, "Total", &tot_ticks
);
3810 tot_ticks
= tot_ticks
/1000000;
3812 memset(lbuf
, 0, 256);
3813 if (read
|| write
|| read_merged
|| write_merged
|| read_sectors
|| write_sectors
|| read_ticks
|| write_ticks
)
3814 snprintf(lbuf
, 256, "%u %u %s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
3815 major
, minor
, dev_name
, read
, read_merged
, read_sectors
, read_ticks
,
3816 write
, write_merged
, write_sectors
, write_ticks
, ios_pgr
, tot_ticks
, rq_ticks
);
3820 l
= snprintf(cache
, cache_size
, "%s", lbuf
);
3822 perror("Error writing to fuse buf");
3826 if (l
>= cache_size
) {
3827 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3837 d
->size
= total_len
;
3838 if (total_len
> size
) total_len
= size
;
3839 memcpy(buf
, d
->buf
, total_len
);
3847 free(io_serviced_str
);
3848 free(io_merged_str
);
3849 free(io_service_bytes_str
);
3850 free(io_wait_time_str
);
3851 free(io_service_time_str
);
3855 static int proc_swaps_read(char *buf
, size_t size
, off_t offset
,
3856 struct fuse_file_info
*fi
)
3858 struct fuse_context
*fc
= fuse_get_context();
3859 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3861 char *memswlimit_str
= NULL
, *memlimit_str
= NULL
, *memusage_str
= NULL
, *memswusage_str
= NULL
;
3862 unsigned long memswlimit
= 0, memlimit
= 0, memusage
= 0, memswusage
= 0, swap_total
= 0, swap_free
= 0;
3863 ssize_t total_len
= 0, rv
= 0;
3865 char *cache
= d
->buf
;
3868 if (offset
> d
->size
)
3872 int left
= d
->size
- offset
;
3873 total_len
= left
> size
? size
: left
;
3874 memcpy(buf
, cache
+ offset
, total_len
);
3878 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3881 cg
= get_pid_cgroup(initpid
, "memory");
3883 return read_file("/proc/swaps", buf
, size
, d
);
3884 prune_init_slice(cg
);
3886 memlimit
= get_min_memlimit(cg
, "memory.limit_in_bytes");
3888 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
3891 memusage
= strtoul(memusage_str
, NULL
, 10);
3893 if (cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
) &&
3894 cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
)) {
3896 memswlimit
= get_min_memlimit(cg
, "memory.memsw.limit_in_bytes");
3897 memswusage
= strtoul(memswusage_str
, NULL
, 10);
3899 swap_total
= (memswlimit
- memlimit
) / 1024;
3900 swap_free
= (memswusage
- memusage
) / 1024;
3903 total_len
= snprintf(d
->buf
, d
->size
, "Filename\t\t\t\tType\t\tSize\tUsed\tPriority\n");
3905 /* When no mem + swap limit is specified or swapaccount=0*/
3909 FILE *f
= fopen("/proc/meminfo", "r");
3914 while (getline(&line
, &linelen
, f
) != -1) {
3915 if (startswith(line
, "SwapTotal:")) {
3916 sscanf(line
, "SwapTotal: %8lu kB", &swap_total
);
3917 } else if (startswith(line
, "SwapFree:")) {
3918 sscanf(line
, "SwapFree: %8lu kB", &swap_free
);
3926 if (swap_total
> 0) {
3927 l
= snprintf(d
->buf
+ total_len
, d
->size
- total_len
,
3928 "none%*svirtual\t\t%lu\t%lu\t0\n", 36, " ",
3929 swap_total
, swap_free
);
3933 if (total_len
< 0 || l
< 0) {
3934 perror("Error writing to cache");
3940 d
->size
= (int)total_len
;
3942 if (total_len
> size
) total_len
= size
;
3943 memcpy(buf
, d
->buf
, total_len
);
3948 free(memswlimit_str
);
3951 free(memswusage_str
);
3955 static off_t
get_procfile_size(const char *which
)
3957 FILE *f
= fopen(which
, "r");
3960 ssize_t sz
, answer
= 0;
3964 while ((sz
= getline(&line
, &len
, f
)) != -1)
3972 int proc_getattr(const char *path
, struct stat
*sb
)
3974 struct timespec now
;
3976 memset(sb
, 0, sizeof(struct stat
));
3977 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
3979 sb
->st_uid
= sb
->st_gid
= 0;
3980 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
3981 if (strcmp(path
, "/proc") == 0) {
3982 sb
->st_mode
= S_IFDIR
| 00555;
3986 if (strcmp(path
, "/proc/meminfo") == 0 ||
3987 strcmp(path
, "/proc/cpuinfo") == 0 ||
3988 strcmp(path
, "/proc/uptime") == 0 ||
3989 strcmp(path
, "/proc/stat") == 0 ||
3990 strcmp(path
, "/proc/diskstats") == 0 ||
3991 strcmp(path
, "/proc/swaps") == 0) {
3993 sb
->st_mode
= S_IFREG
| 00444;
4001 int proc_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
4002 struct fuse_file_info
*fi
)
4004 if (filler(buf
, ".", NULL
, 0) != 0 ||
4005 filler(buf
, "..", NULL
, 0) != 0 ||
4006 filler(buf
, "cpuinfo", NULL
, 0) != 0 ||
4007 filler(buf
, "meminfo", NULL
, 0) != 0 ||
4008 filler(buf
, "stat", NULL
, 0) != 0 ||
4009 filler(buf
, "uptime", NULL
, 0) != 0 ||
4010 filler(buf
, "diskstats", NULL
, 0) != 0 ||
4011 filler(buf
, "swaps", NULL
, 0) != 0)
4016 int proc_open(const char *path
, struct fuse_file_info
*fi
)
4019 struct file_info
*info
;
4021 if (strcmp(path
, "/proc/meminfo") == 0)
4022 type
= LXC_TYPE_PROC_MEMINFO
;
4023 else if (strcmp(path
, "/proc/cpuinfo") == 0)
4024 type
= LXC_TYPE_PROC_CPUINFO
;
4025 else if (strcmp(path
, "/proc/uptime") == 0)
4026 type
= LXC_TYPE_PROC_UPTIME
;
4027 else if (strcmp(path
, "/proc/stat") == 0)
4028 type
= LXC_TYPE_PROC_STAT
;
4029 else if (strcmp(path
, "/proc/diskstats") == 0)
4030 type
= LXC_TYPE_PROC_DISKSTATS
;
4031 else if (strcmp(path
, "/proc/swaps") == 0)
4032 type
= LXC_TYPE_PROC_SWAPS
;
4036 info
= malloc(sizeof(*info
));
4040 memset(info
, 0, sizeof(*info
));
4043 info
->buflen
= get_procfile_size(path
) + BUF_RESERVE_SIZE
;
4045 info
->buf
= malloc(info
->buflen
);
4046 } while (!info
->buf
);
4047 memset(info
->buf
, 0, info
->buflen
);
4048 /* set actual size to buffer size */
4049 info
->size
= info
->buflen
;
4051 fi
->fh
= (unsigned long)info
;
4055 int proc_access(const char *path
, int mask
)
4057 if (strcmp(path
, "/proc") == 0 && access(path
, R_OK
) == 0)
4060 /* these are all read-only */
4061 if ((mask
& ~R_OK
) != 0)
4066 int proc_release(const char *path
, struct fuse_file_info
*fi
)
4068 do_release_file_info(fi
);
4072 int proc_read(const char *path
, char *buf
, size_t size
, off_t offset
,
4073 struct fuse_file_info
*fi
)
4075 struct file_info
*f
= (struct file_info
*) fi
->fh
;
4078 case LXC_TYPE_PROC_MEMINFO
:
4079 return proc_meminfo_read(buf
, size
, offset
, fi
);
4080 case LXC_TYPE_PROC_CPUINFO
:
4081 return proc_cpuinfo_read(buf
, size
, offset
, fi
);
4082 case LXC_TYPE_PROC_UPTIME
:
4083 return proc_uptime_read(buf
, size
, offset
, fi
);
4084 case LXC_TYPE_PROC_STAT
:
4085 return proc_stat_read(buf
, size
, offset
, fi
);
4086 case LXC_TYPE_PROC_DISKSTATS
:
4087 return proc_diskstats_read(buf
, size
, offset
, fi
);
4088 case LXC_TYPE_PROC_SWAPS
:
4089 return proc_swaps_read(buf
, size
, offset
, fi
);
4096 * Functions needed to setup cgroups in the __constructor__.
4099 static bool mkdir_p(const char *dir
, mode_t mode
)
4101 const char *tmp
= dir
;
4102 const char *orig
= dir
;
4106 dir
= tmp
+ strspn(tmp
, "/");
4107 tmp
= dir
+ strcspn(dir
, "/");
4108 makeme
= strndup(orig
, dir
- orig
);
4111 if (mkdir(makeme
, mode
) && errno
!= EEXIST
) {
4112 lxcfs_error("Failed to create directory '%s': %s.\n",
4113 makeme
, strerror(errno
));
4118 } while(tmp
!= dir
);
4123 static bool umount_if_mounted(void)
4125 if (umount2(BASEDIR
, MNT_DETACH
) < 0 && errno
!= EINVAL
) {
4126 lxcfs_error("Failed to unmount %s: %s.\n", BASEDIR
, strerror(errno
));
4132 /* __typeof__ should be safe to use with all compilers. */
4133 typedef __typeof__(((struct statfs
*)NULL
)->f_type
) fs_type_magic
;
4134 static bool has_fs_type(const struct statfs
*fs
, fs_type_magic magic_val
)
4136 return (fs
->f_type
== (fs_type_magic
)magic_val
);
4140 * looking at fs/proc_namespace.c, it appears we can
4141 * actually expect the rootfs entry to very specifically contain
4142 * " - rootfs rootfs "
4143 * IIUC, so long as we've chrooted so that rootfs is not our root,
4144 * the rootfs entry should always be skipped in mountinfo contents.
4146 static bool is_on_ramfs(void)
4154 f
= fopen("/proc/self/mountinfo", "r");
4158 while (getline(&line
, &len
, f
) != -1) {
4159 for (p
= line
, i
= 0; p
&& i
< 4; i
++)
4160 p
= strchr(p
+ 1, ' ');
4163 p2
= strchr(p
+ 1, ' ');
4167 if (strcmp(p
+ 1, "/") == 0) {
4168 // this is '/'. is it the ramfs?
4169 p
= strchr(p2
+ 1, '-');
4170 if (p
&& strncmp(p
, "- rootfs rootfs ", 16) == 0) {
4182 static int pivot_enter()
4184 int ret
= -1, oldroot
= -1, newroot
= -1;
4186 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
);
4188 lxcfs_error("%s\n", "Failed to open old root for fchdir.");
4192 newroot
= open(ROOTDIR
, O_DIRECTORY
| O_RDONLY
);
4194 lxcfs_error("%s\n", "Failed to open new root for fchdir.");
4198 /* change into new root fs */
4199 if (fchdir(newroot
) < 0) {
4200 lxcfs_error("Failed to change directory to new rootfs: %s.\n", ROOTDIR
);
4204 /* pivot_root into our new root fs */
4205 if (pivot_root(".", ".") < 0) {
4206 lxcfs_error("pivot_root() syscall failed: %s.\n", strerror(errno
));
4211 * At this point the old-root is mounted on top of our new-root.
4212 * To unmounted it we must not be chdir'd into it, so escape back
4215 if (fchdir(oldroot
) < 0) {
4216 lxcfs_error("%s\n", "Failed to enter old root.");
4220 if (umount2(".", MNT_DETACH
) < 0) {
4221 lxcfs_error("%s\n", "Failed to detach old root.");
4225 if (fchdir(newroot
) < 0) {
4226 lxcfs_error("%s\n", "Failed to re-enter new root.");
4241 static int chroot_enter()
4243 if (mount(ROOTDIR
, "/", NULL
, MS_REC
| MS_BIND
, NULL
)) {
4244 lxcfs_error("Failed to recursively bind-mount %s into /.", ROOTDIR
);
4248 if (chroot(".") < 0) {
4249 lxcfs_error("Call to chroot() failed: %s.\n", strerror(errno
));
4253 if (chdir("/") < 0) {
4254 lxcfs_error("Failed to change directory: %s.\n", strerror(errno
));
4261 static int permute_and_enter(void)
4265 if (statfs("/", &sb
) < 0) {
4266 lxcfs_error("%s\n", "Could not stat / mountpoint.");
4270 /* has_fs_type() is not reliable. When the ramfs is a tmpfs it will
4271 * likely report TMPFS_MAGIC. Hence, when it reports no we still check
4272 * /proc/1/mountinfo. */
4273 if (has_fs_type(&sb
, RAMFS_MAGIC
) || is_on_ramfs())
4274 return chroot_enter();
4276 if (pivot_enter() < 0) {
4277 lxcfs_error("%s\n", "Could not perform pivot root.");
4284 /* Prepare our new clean root. */
4285 static int permute_prepare(void)
4287 if (mkdir(ROOTDIR
, 0700) < 0 && errno
!= EEXIST
) {
4288 lxcfs_error("%s\n", "Failed to create directory for new root.");
4292 if (mount("/", ROOTDIR
, NULL
, MS_BIND
, 0) < 0) {
4293 lxcfs_error("Failed to bind-mount / for new root: %s.\n", strerror(errno
));
4297 if (mount(RUNTIME_PATH
, ROOTDIR RUNTIME_PATH
, NULL
, MS_BIND
, 0) < 0) {
4298 lxcfs_error("Failed to bind-mount /run into new root: %s.\n", strerror(errno
));
4302 if (mount(BASEDIR
, ROOTDIR BASEDIR
, NULL
, MS_REC
| MS_MOVE
, 0) < 0) {
4303 printf("Failed to move " BASEDIR
" into new root: %s.\n", strerror(errno
));
4310 /* Calls chroot() on ramfs, pivot_root() in all other cases. */
4311 static bool permute_root(void)
4313 /* Prepare new root. */
4314 if (permute_prepare() < 0)
4317 /* Pivot into new root. */
4318 if (permute_and_enter() < 0)
4324 static bool cgfs_prepare_mounts(void)
4326 if (!mkdir_p(BASEDIR
, 0700)) {
4327 lxcfs_error("%s\n", "Failed to create lxcfs cgroup mountpoint.");
4331 if (!umount_if_mounted()) {
4332 lxcfs_error("%s\n", "Failed to clean up old lxcfs cgroup mountpoint.");
4336 if (unshare(CLONE_NEWNS
) < 0) {
4337 lxcfs_error("Failed to unshare mount namespace: %s.\n", strerror(errno
));
4341 if (mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, 0) < 0) {
4342 lxcfs_error("Failed to remount / private: %s.\n", strerror(errno
));
4346 if (mount("tmpfs", BASEDIR
, "tmpfs", 0, "size=100000,mode=700") < 0) {
4347 lxcfs_error("%s\n", "Failed to mount tmpfs over lxcfs cgroup mountpoint.");
4354 static bool cgfs_mount_hierarchies(void)
4360 for (i
= 0; i
< num_hierarchies
; i
++) {
4361 char *controller
= hierarchies
[i
];
4362 clen
= strlen(controller
);
4363 len
= strlen(BASEDIR
) + clen
+ 2;
4364 target
= malloc(len
);
4367 ret
= snprintf(target
, len
, "%s/%s", BASEDIR
, controller
);
4368 if (ret
< 0 || ret
>= len
) {
4372 if (mkdir(target
, 0755) < 0 && errno
!= EEXIST
) {
4376 if (mount(controller
, target
, "cgroup", 0, controller
) < 0) {
4377 lxcfs_error("Failed mounting cgroup %s\n", controller
);
4382 fd_hierarchies
[i
] = open(target
, O_DIRECTORY
);
4383 if (fd_hierarchies
[i
] < 0) {
4392 static bool cgfs_setup_controllers(void)
4394 if (!cgfs_prepare_mounts())
4397 if (!cgfs_mount_hierarchies()) {
4398 lxcfs_error("%s\n", "Failed to set up private lxcfs cgroup mounts.");
4402 if (!permute_root())
4408 static int preserve_ns(int pid
)
4411 size_t len
= 5 /* /proc */ + 21 /* /int_as_str */ + 7 /* /ns/mnt */ + 1 /* \0 */;
4414 ret
= snprintf(path
, len
, "/proc/%d/ns/mnt", pid
);
4415 if (ret
< 0 || (size_t)ret
>= len
)
4418 return open(path
, O_RDONLY
| O_CLOEXEC
);
4421 static void __attribute__((constructor
)) collect_and_mount_subsystems(void)
4424 char *cret
, *line
= NULL
;
4425 char cwd
[MAXPATHLEN
];
4427 int i
, init_ns
= -1;
4429 if ((f
= fopen("/proc/self/cgroup", "r")) == NULL
) {
4430 lxcfs_error("Error opening /proc/self/cgroup: %s\n", strerror(errno
));
4434 while (getline(&line
, &len
, f
) != -1) {
4437 p
= strchr(line
, ':');
4442 p2
= strrchr(p
, ':');
4447 /* With cgroupv2 /proc/self/cgroup can contain entries of the
4448 * form: 0::/ This will cause lxcfs to fail the cgroup mounts
4449 * because it parses out the empty string "" and later on passes
4450 * it to mount(). Let's skip such entries.
4455 if (!store_hierarchy(line
, p
))
4459 /* Preserve initial namespace. */
4460 init_ns
= preserve_ns(getpid());
4462 lxcfs_error("%s\n", "Failed to preserve initial mount namespace.");
4466 fd_hierarchies
= malloc(sizeof(int *) * num_hierarchies
);
4467 if (!fd_hierarchies
) {
4468 lxcfs_error("%s\n", strerror(errno
));
4472 for (i
= 0; i
< num_hierarchies
; i
++)
4473 fd_hierarchies
[i
] = -1;
4475 cret
= getcwd(cwd
, MAXPATHLEN
);
4477 lxcfs_debug("Could not retrieve current working directory: %s.\n", strerror(errno
));
4479 /* This function calls unshare(CLONE_NEWNS) our initial mount namespace
4480 * to privately mount lxcfs cgroups. */
4481 if (!cgfs_setup_controllers()) {
4482 lxcfs_error("%s\n", "Failed to setup private cgroup mounts for lxcfs.");
4486 if (setns(init_ns
, 0) < 0) {
4487 lxcfs_error("Failed to switch back to initial mount namespace: %s.\n", strerror(errno
));
4491 if (!cret
|| chdir(cwd
) < 0)
4492 lxcfs_debug("Could not change back to original working directory: %s.\n", strerror(errno
));
4503 static void __attribute__((destructor
)) free_subsystems(void)
4507 lxcfs_debug("%s\n", "Running destructor for liblxcfs.");
4509 for (i
= 0; i
< num_hierarchies
; i
++) {
4511 free(hierarchies
[i
]);
4512 if (fd_hierarchies
&& fd_hierarchies
[i
] >= 0)
4513 close(fd_hierarchies
[i
]);
4516 free(fd_hierarchies
);