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
11 #define __STDC_FORMAT_MACROS
28 #include <linux/magic.h>
29 #include <linux/sched.h>
30 #include <sys/epoll.h>
32 #include <sys/mount.h>
33 #include <sys/param.h>
34 #include <sys/socket.h>
35 #include <sys/syscall.h>
36 #include <sys/sysinfo.h>
40 #include "config.h" // for VERSION
42 /* Maximum number for 64 bit integer is a string with 21 digits: 2^64 - 1 = 21 */
43 #define LXCFS_NUMSTRLEN64 21
45 /* Define pivot_root() if missing from the C library */
46 #ifndef HAVE_PIVOT_ROOT
47 static int pivot_root(const char * new_root
, const char * put_old
)
49 #ifdef __NR_pivot_root
50 return syscall(__NR_pivot_root
, new_root
, put_old
);
57 extern int pivot_root(const char * new_root
, const char * put_old
);
63 LXC_TYPE_PROC_MEMINFO
,
64 LXC_TYPE_PROC_CPUINFO
,
67 LXC_TYPE_PROC_DISKSTATS
,
69 LXC_TYPE_PROC_LOADAVG
,
77 char *buf
; // unused as of yet
79 int size
; //actual data size
83 /* Reserve buffer size to account for file size changes. */
84 #define BUF_RESERVE_SIZE 512
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 lxcfs_error("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
;
143 static int cgroup_mount_ns_fd
= -1;
145 static void unlock_mutex(pthread_mutex_t
*l
)
149 if ((ret
= pthread_mutex_unlock(l
)) != 0) {
150 lxcfs_error("returned:%d %s\n", ret
, strerror(ret
));
155 static void store_lock(void)
157 lock_mutex(&pidns_store_mutex
);
160 static void store_unlock(void)
162 unlock_mutex(&pidns_store_mutex
);
165 /* Must be called under store_lock */
166 static bool initpid_still_valid(struct pidns_init_store
*e
, struct stat
*nsfdsb
)
171 snprintf(fnam
, 100, "/proc/%d", e
->initpid
);
172 if (stat(fnam
, &initsb
) < 0)
175 lxcfs_debug("Comparing ctime %ld == %ld for pid %d.\n", e
->ctime
,
176 initsb
.st_ctime
, e
->initpid
);
178 if (e
->ctime
!= initsb
.st_ctime
)
183 /* Must be called under store_lock */
184 static void remove_initpid(struct pidns_init_store
*e
)
186 struct pidns_init_store
*tmp
;
189 lxcfs_debug("Remove_initpid: removing entry for %d.\n", e
->initpid
);
192 if (pidns_hash_table
[h
] == e
) {
193 pidns_hash_table
[h
] = e
->next
;
198 tmp
= pidns_hash_table
[h
];
200 if (tmp
->next
== e
) {
210 /* Must be called under store_lock */
211 static void prune_initpid_store(void)
213 static long int last_prune
= 0;
214 struct pidns_init_store
*e
, *prev
, *delme
;
215 long int now
, threshold
;
219 last_prune
= time(NULL
);
223 if (now
< last_prune
+ PURGE_SECS
)
226 lxcfs_debug("%s\n", "Pruning.");
229 threshold
= now
- 2 * PURGE_SECS
;
231 for (i
= 0; i
< PIDNS_HASH_SIZE
; i
++) {
232 for (prev
= NULL
, e
= pidns_hash_table
[i
]; e
; ) {
233 if (e
->lastcheck
< threshold
) {
235 lxcfs_debug("Removing cached entry for %d.\n", e
->initpid
);
239 prev
->next
= e
->next
;
241 pidns_hash_table
[i
] = e
->next
;
252 /* Must be called under store_lock */
253 static void save_initpid(struct stat
*sb
, pid_t pid
)
255 struct pidns_init_store
*e
;
260 lxcfs_debug("Save_initpid: adding entry for %d.\n", pid
);
262 snprintf(fpath
, 100, "/proc/%d", pid
);
263 if (stat(fpath
, &procsb
) < 0)
266 e
= malloc(sizeof(*e
));
270 e
->ctime
= procsb
.st_ctime
;
272 e
->next
= pidns_hash_table
[h
];
273 e
->lastcheck
= time(NULL
);
274 pidns_hash_table
[h
] = e
;
278 * Given the stat(2) info for a nsfd pid inode, lookup the init_pid_store
279 * entry for the inode number and creation time. Verify that the init pid
280 * is still valid. If not, remove it. Return the entry if valid, NULL
282 * Must be called under store_lock
284 static struct pidns_init_store
*lookup_verify_initpid(struct stat
*sb
)
286 int h
= HASH(sb
->st_ino
);
287 struct pidns_init_store
*e
= pidns_hash_table
[h
];
290 if (e
->ino
== sb
->st_ino
) {
291 if (initpid_still_valid(e
, sb
)) {
292 e
->lastcheck
= time(NULL
);
304 static int is_dir(const char *path
, int fd
)
307 int ret
= fstatat(fd
, path
, &statbuf
, fd
);
308 if (ret
== 0 && S_ISDIR(statbuf
.st_mode
))
313 static char *must_copy_string(const char *str
)
325 static inline void drop_trailing_newlines(char *s
)
329 for (l
=strlen(s
); l
>0 && s
[l
-1] == '\n'; l
--)
333 #define BATCH_SIZE 50
334 static void dorealloc(char **mem
, size_t oldlen
, size_t newlen
)
336 int newbatches
= (newlen
/ BATCH_SIZE
) + 1;
337 int oldbatches
= (oldlen
/ BATCH_SIZE
) + 1;
339 if (!*mem
|| newbatches
> oldbatches
) {
342 tmp
= realloc(*mem
, newbatches
* BATCH_SIZE
);
347 static void append_line(char **contents
, size_t *len
, char *line
, ssize_t linelen
)
349 size_t newlen
= *len
+ linelen
;
350 dorealloc(contents
, *len
, newlen
+ 1);
351 memcpy(*contents
+ *len
, line
, linelen
+1);
355 static char *slurp_file(const char *from
, int fd
)
358 char *contents
= NULL
;
359 FILE *f
= fdopen(fd
, "r");
360 size_t len
= 0, fulllen
= 0;
366 while ((linelen
= getline(&line
, &len
, f
)) != -1) {
367 append_line(&contents
, &fulllen
, line
, linelen
);
372 drop_trailing_newlines(contents
);
377 static bool write_string(const char *fnam
, const char *string
, int fd
)
382 if (!(f
= fdopen(fd
, "w")))
384 len
= strlen(string
);
385 ret
= fwrite(string
, 1, len
, f
);
387 lxcfs_error("Error writing to file: %s\n", strerror(errno
));
392 lxcfs_error("Error writing to file: %s\n", strerror(errno
));
405 static bool store_hierarchy(char *stridx
, char *h
)
407 if (num_hierarchies
% ALLOC_NUM
== 0) {
408 size_t n
= (num_hierarchies
/ ALLOC_NUM
) + 1;
410 char **tmp
= realloc(hierarchies
, n
* sizeof(char *));
412 lxcfs_error("%s\n", strerror(errno
));
418 hierarchies
[num_hierarchies
++] = must_copy_string(h
);
422 static void print_subsystems(void)
426 fprintf(stderr
, "mount namespace: %d\n", cgroup_mount_ns_fd
);
427 fprintf(stderr
, "hierarchies:\n");
428 for (i
= 0; i
< num_hierarchies
; i
++) {
430 fprintf(stderr
, " %2d: fd: %3d: %s\n", i
,
431 fd_hierarchies
[i
], hierarchies
[i
]);
435 static bool in_comma_list(const char *needle
, const char *haystack
)
437 const char *s
= haystack
, *e
;
438 size_t nlen
= strlen(needle
);
440 while (*s
&& (e
= strchr(s
, ','))) {
445 if (strncmp(needle
, s
, nlen
) == 0)
449 if (strcmp(needle
, s
) == 0)
454 /* do we need to do any massaging here? I'm not sure... */
455 /* Return the mounted controller and store the corresponding open file descriptor
456 * referring to the controller mountpoint in the private lxcfs namespace in
459 static char *find_mounted_controller(const char *controller
, int *cfd
)
463 for (i
= 0; i
< num_hierarchies
; i
++) {
466 if (strcmp(hierarchies
[i
], controller
) == 0) {
467 *cfd
= fd_hierarchies
[i
];
468 return hierarchies
[i
];
470 if (in_comma_list(controller
, hierarchies
[i
])) {
471 *cfd
= fd_hierarchies
[i
];
472 return hierarchies
[i
];
479 bool cgfs_set_value(const char *controller
, const char *cgroup
, const char *file
,
486 tmpc
= find_mounted_controller(controller
, &cfd
);
490 /* Make sure we pass a relative path to *at() family of functions.
491 * . + /cgroup + / + file + \0
493 len
= strlen(cgroup
) + strlen(file
) + 3;
495 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, file
);
496 if (ret
< 0 || (size_t)ret
>= len
)
499 fd
= openat(cfd
, fnam
, O_WRONLY
);
503 return write_string(fnam
, value
, fd
);
506 // Chown all the files in the cgroup directory. We do this when we create
507 // a cgroup on behalf of a user.
508 static void chown_all_cgroup_files(const char *dirname
, uid_t uid
, gid_t gid
, int fd
)
510 struct dirent
*direntp
;
511 char path
[MAXPATHLEN
];
516 len
= strlen(dirname
);
517 if (len
>= MAXPATHLEN
) {
518 lxcfs_error("Pathname too long: %s\n", dirname
);
522 fd1
= openat(fd
, dirname
, O_DIRECTORY
);
528 lxcfs_error("Failed to open %s\n", dirname
);
532 while ((direntp
= readdir(d
))) {
533 if (!strcmp(direntp
->d_name
, ".") || !strcmp(direntp
->d_name
, ".."))
535 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
536 if (ret
< 0 || ret
>= MAXPATHLEN
) {
537 lxcfs_error("Pathname too long under %s\n", dirname
);
540 if (fchownat(fd
, path
, uid
, gid
, 0) < 0)
541 lxcfs_error("Failed to chown file %s to %u:%u", path
, uid
, gid
);
546 int cgfs_create(const char *controller
, const char *cg
, uid_t uid
, gid_t gid
)
552 tmpc
= find_mounted_controller(controller
, &cfd
);
556 /* Make sure we pass a relative path to *at() family of functions.
559 len
= strlen(cg
) + 2;
560 dirnam
= alloca(len
);
561 snprintf(dirnam
, len
, "%s%s", *cg
== '/' ? "." : "", cg
);
563 if (mkdirat(cfd
, dirnam
, 0755) < 0)
566 if (uid
== 0 && gid
== 0)
569 if (fchownat(cfd
, dirnam
, uid
, gid
, 0) < 0)
572 chown_all_cgroup_files(dirnam
, uid
, gid
, cfd
);
577 static bool recursive_rmdir(const char *dirname
, int fd
, const int cfd
)
579 struct dirent
*direntp
;
582 char pathname
[MAXPATHLEN
];
585 dupfd
= dup(fd
); // fdopendir() does bad things once it uses an fd.
589 dir
= fdopendir(dupfd
);
591 lxcfs_debug("Failed to open %s: %s.\n", dirname
, strerror(errno
));
596 while ((direntp
= readdir(dir
))) {
600 if (!strcmp(direntp
->d_name
, ".") ||
601 !strcmp(direntp
->d_name
, ".."))
604 rc
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
605 if (rc
< 0 || rc
>= MAXPATHLEN
) {
606 lxcfs_error("%s\n", "Pathname too long.");
610 rc
= fstatat(cfd
, pathname
, &mystat
, AT_SYMLINK_NOFOLLOW
);
612 lxcfs_debug("Failed to stat %s: %s.\n", pathname
, strerror(errno
));
615 if (S_ISDIR(mystat
.st_mode
))
616 if (!recursive_rmdir(pathname
, fd
, cfd
))
617 lxcfs_debug("Error removing %s.\n", pathname
);
621 if (closedir(dir
) < 0) {
622 lxcfs_error("Failed to close directory %s: %s\n", dirname
, strerror(errno
));
626 if (unlinkat(cfd
, dirname
, AT_REMOVEDIR
) < 0) {
627 lxcfs_debug("Failed to delete %s: %s.\n", dirname
, strerror(errno
));
636 bool cgfs_remove(const char *controller
, const char *cg
)
643 tmpc
= find_mounted_controller(controller
, &cfd
);
647 /* Make sure we pass a relative path to *at() family of functions.
650 len
= strlen(cg
) + 2;
651 dirnam
= alloca(len
);
652 snprintf(dirnam
, len
, "%s%s", *cg
== '/' ? "." : "", cg
);
654 fd
= openat(cfd
, dirnam
, O_DIRECTORY
);
658 bret
= recursive_rmdir(dirnam
, fd
, cfd
);
663 bool cgfs_chmod_file(const char *controller
, const char *file
, mode_t mode
)
667 char *pathname
, *tmpc
;
669 tmpc
= find_mounted_controller(controller
, &cfd
);
673 /* Make sure we pass a relative path to *at() family of functions.
676 len
= strlen(file
) + 2;
677 pathname
= alloca(len
);
678 snprintf(pathname
, len
, "%s%s", *file
== '/' ? "." : "", file
);
679 if (fchmodat(cfd
, pathname
, mode
, 0) < 0)
684 static int chown_tasks_files(const char *dirname
, uid_t uid
, gid_t gid
, int fd
)
689 len
= strlen(dirname
) + strlen("/cgroup.procs") + 1;
691 snprintf(fname
, len
, "%s/tasks", dirname
);
692 if (fchownat(fd
, fname
, uid
, gid
, 0) != 0)
694 snprintf(fname
, len
, "%s/cgroup.procs", dirname
);
695 if (fchownat(fd
, fname
, uid
, gid
, 0) != 0)
700 int cgfs_chown_file(const char *controller
, const char *file
, uid_t uid
, gid_t gid
)
704 char *pathname
, *tmpc
;
706 tmpc
= find_mounted_controller(controller
, &cfd
);
710 /* Make sure we pass a relative path to *at() family of functions.
713 len
= strlen(file
) + 2;
714 pathname
= alloca(len
);
715 snprintf(pathname
, len
, "%s%s", *file
== '/' ? "." : "", file
);
716 if (fchownat(cfd
, pathname
, uid
, gid
, 0) < 0)
719 if (is_dir(pathname
, cfd
))
720 // like cgmanager did, we want to chown the tasks file as well
721 return chown_tasks_files(pathname
, uid
, gid
, cfd
);
726 FILE *open_pids_file(const char *controller
, const char *cgroup
)
730 char *pathname
, *tmpc
;
732 tmpc
= find_mounted_controller(controller
, &cfd
);
736 /* Make sure we pass a relative path to *at() family of functions.
737 * . + /cgroup + / "cgroup.procs" + \0
739 len
= strlen(cgroup
) + strlen("cgroup.procs") + 3;
740 pathname
= alloca(len
);
741 snprintf(pathname
, len
, "%s%s/cgroup.procs", *cgroup
== '/' ? "." : "", cgroup
);
743 fd
= openat(cfd
, pathname
, O_WRONLY
);
747 return fdopen(fd
, "w");
750 static bool cgfs_iterate_cgroup(const char *controller
, const char *cgroup
, bool directories
,
751 void ***list
, size_t typesize
,
752 void* (*iterator
)(const char*, const char*, const char*))
757 char pathname
[MAXPATHLEN
];
758 size_t sz
= 0, asz
= 0;
759 struct dirent
*dirent
;
762 tmpc
= find_mounted_controller(controller
, &cfd
);
767 /* Make sure we pass a relative path to *at() family of functions. */
768 len
= strlen(cgroup
) + 1 /* . */ + 1 /* \0 */;
770 ret
= snprintf(cg
, len
, "%s%s", *cgroup
== '/' ? "." : "", cgroup
);
771 if (ret
< 0 || (size_t)ret
>= len
) {
772 lxcfs_error("Pathname too long under %s\n", cgroup
);
776 fd
= openat(cfd
, cg
, O_DIRECTORY
);
784 while ((dirent
= readdir(dir
))) {
787 if (!strcmp(dirent
->d_name
, ".") ||
788 !strcmp(dirent
->d_name
, ".."))
791 ret
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", cg
, dirent
->d_name
);
792 if (ret
< 0 || ret
>= MAXPATHLEN
) {
793 lxcfs_error("Pathname too long under %s\n", cg
);
797 ret
= fstatat(cfd
, pathname
, &mystat
, AT_SYMLINK_NOFOLLOW
);
799 lxcfs_error("Failed to stat %s: %s\n", pathname
, strerror(errno
));
802 if ((!directories
&& !S_ISREG(mystat
.st_mode
)) ||
803 (directories
&& !S_ISDIR(mystat
.st_mode
)))
810 tmp
= realloc(*list
, asz
* typesize
);
814 (*list
)[sz
] = (*iterator
)(controller
, cg
, dirent
->d_name
);
815 (*list
)[sz
+1] = NULL
;
818 if (closedir(dir
) < 0) {
819 lxcfs_error("Failed closedir for %s: %s\n", cgroup
, strerror(errno
));
825 static void *make_children_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
829 dup
= strdup(dir_entry
);
834 bool cgfs_list_children(const char *controller
, const char *cgroup
, char ***list
)
836 return cgfs_iterate_cgroup(controller
, cgroup
, true, (void***)list
, sizeof(*list
), &make_children_list_entry
);
839 void free_key(struct cgfs_files
*k
)
847 void free_keys(struct cgfs_files
**keys
)
853 for (i
= 0; keys
[i
]; i
++) {
859 bool cgfs_get_value(const char *controller
, const char *cgroup
, const char *file
, char **value
)
865 tmpc
= find_mounted_controller(controller
, &cfd
);
869 /* Make sure we pass a relative path to *at() family of functions.
870 * . + /cgroup + / + file + \0
872 len
= strlen(cgroup
) + strlen(file
) + 3;
874 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, file
);
875 if (ret
< 0 || (size_t)ret
>= len
)
878 fd
= openat(cfd
, fnam
, O_RDONLY
);
882 *value
= slurp_file(fnam
, fd
);
883 return *value
!= NULL
;
886 struct cgfs_files
*cgfs_get_key(const char *controller
, const char *cgroup
, const char *file
)
892 struct cgfs_files
*newkey
;
894 tmpc
= find_mounted_controller(controller
, &cfd
);
898 if (file
&& *file
== '/')
901 if (file
&& strchr(file
, '/'))
904 /* Make sure we pass a relative path to *at() family of functions.
905 * . + /cgroup + / + file + \0
907 len
= strlen(cgroup
) + 3;
909 len
+= strlen(file
) + 1;
911 snprintf(fnam
, len
, "%s%s%s%s", *cgroup
== '/' ? "." : "", cgroup
,
912 file
? "/" : "", file
? file
: "");
914 ret
= fstatat(cfd
, fnam
, &sb
, 0);
919 newkey
= malloc(sizeof(struct cgfs_files
));
922 newkey
->name
= must_copy_string(file
);
923 else if (strrchr(cgroup
, '/'))
924 newkey
->name
= must_copy_string(strrchr(cgroup
, '/'));
926 newkey
->name
= must_copy_string(cgroup
);
927 newkey
->uid
= sb
.st_uid
;
928 newkey
->gid
= sb
.st_gid
;
929 newkey
->mode
= sb
.st_mode
;
934 static void *make_key_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
936 struct cgfs_files
*entry
= cgfs_get_key(controller
, cgroup
, dir_entry
);
938 lxcfs_error("Error getting files under %s:%s\n", controller
,
944 bool cgfs_list_keys(const char *controller
, const char *cgroup
, struct cgfs_files
***keys
)
946 return cgfs_iterate_cgroup(controller
, cgroup
, false, (void***)keys
, sizeof(*keys
), &make_key_list_entry
);
949 bool is_child_cgroup(const char *controller
, const char *cgroup
, const char *f
)
957 tmpc
= find_mounted_controller(controller
, &cfd
);
961 /* Make sure we pass a relative path to *at() family of functions.
962 * . + /cgroup + / + f + \0
964 len
= strlen(cgroup
) + strlen(f
) + 3;
966 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, f
);
967 if (ret
< 0 || (size_t)ret
>= len
)
970 ret
= fstatat(cfd
, fnam
, &sb
, 0);
971 if (ret
< 0 || !S_ISDIR(sb
.st_mode
))
977 #define SEND_CREDS_OK 0
978 #define SEND_CREDS_NOTSK 1
979 #define SEND_CREDS_FAIL 2
980 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
);
981 static int wait_for_pid(pid_t pid
);
982 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
);
983 static int send_creds_clone_wrapper(void *arg
);
986 * clone a task which switches to @task's namespace and writes '1'.
987 * over a unix sock so we can read the task's reaper's pid in our
990 * Note: glibc's fork() does not respect pidns, which can lead to failed
991 * assertions inside glibc (and thus failed forks) if the child's pid in
992 * the pidns and the parent pid outside are identical. Using clone prevents
995 static void write_task_init_pid_exit(int sock
, pid_t target
)
1000 size_t stack_size
= sysconf(_SC_PAGESIZE
);
1001 void *stack
= alloca(stack_size
);
1003 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", (int)target
);
1004 if (ret
< 0 || ret
>= sizeof(fnam
))
1007 fd
= open(fnam
, O_RDONLY
);
1009 perror("write_task_init_pid_exit open of ns/pid");
1013 perror("write_task_init_pid_exit setns 1");
1017 pid
= clone(send_creds_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &sock
);
1021 if (!wait_for_pid(pid
))
1027 static int send_creds_clone_wrapper(void *arg
) {
1030 int sock
= *(int *)arg
;
1032 /* we are the child */
1037 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
)
1042 static pid_t
get_init_pid_for_task(pid_t task
)
1050 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
1051 perror("socketpair");
1060 write_task_init_pid_exit(sock
[0], task
);
1064 if (!recv_creds(sock
[1], &cred
, &v
))
1076 static pid_t
lookup_initpid_in_store(pid_t qpid
)
1080 struct pidns_init_store
*e
;
1083 snprintf(fnam
, 100, "/proc/%d/ns/pid", qpid
);
1085 if (stat(fnam
, &sb
) < 0)
1087 e
= lookup_verify_initpid(&sb
);
1089 answer
= e
->initpid
;
1092 answer
= get_init_pid_for_task(qpid
);
1094 save_initpid(&sb
, answer
);
1097 /* we prune at end in case we are returning
1098 * the value we were about to return */
1099 prune_initpid_store();
1104 static int wait_for_pid(pid_t pid
)
1112 ret
= waitpid(pid
, &status
, 0);
1120 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
1127 * append pid to *src.
1128 * src: a pointer to a char* in which ot append the pid.
1129 * sz: the number of characters printed so far, minus trailing \0.
1130 * asz: the allocated size so far
1131 * pid: the pid to append
1133 static void must_strcat_pid(char **src
, size_t *sz
, size_t *asz
, pid_t pid
)
1137 int tmplen
= sprintf(tmp
, "%d\n", (int)pid
);
1139 if (!*src
|| tmplen
+ *sz
+ 1 >= *asz
) {
1142 tmp
= realloc(*src
, *asz
+ BUF_RESERVE_SIZE
);
1145 *asz
+= BUF_RESERVE_SIZE
;
1147 memcpy((*src
) +*sz
, tmp
, tmplen
+1); /* include the \0 */
1152 * Given a open file * to /proc/pid/{u,g}id_map, and an id
1153 * valid in the caller's namespace, return the id mapped into
1155 * Returns the mapped id, or -1 on error.
1158 convert_id_to_ns(FILE *idfile
, unsigned int in_id
)
1160 unsigned int nsuid
, // base id for a range in the idfile's namespace
1161 hostuid
, // base id for a range in the caller's namespace
1162 count
; // number of ids in this range
1166 fseek(idfile
, 0L, SEEK_SET
);
1167 while (fgets(line
, 400, idfile
)) {
1168 ret
= sscanf(line
, "%u %u %u\n", &nsuid
, &hostuid
, &count
);
1171 if (hostuid
+ count
< hostuid
|| nsuid
+ count
< nsuid
) {
1173 * uids wrapped around - unexpected as this is a procfile,
1176 lxcfs_error("pid wrapparound at entry %u %u %u in %s\n",
1177 nsuid
, hostuid
, count
, line
);
1180 if (hostuid
<= in_id
&& hostuid
+count
> in_id
) {
1182 * now since hostuid <= in_id < hostuid+count, and
1183 * hostuid+count and nsuid+count do not wrap around,
1184 * we know that nsuid+(in_id-hostuid) which must be
1185 * less that nsuid+(count) must not wrap around
1187 return (in_id
- hostuid
) + nsuid
;
1196 * for is_privileged_over,
1197 * specify whether we require the calling uid to be root in his
1200 #define NS_ROOT_REQD true
1201 #define NS_ROOT_OPT false
1205 static bool is_privileged_over(pid_t pid
, uid_t uid
, uid_t victim
, bool req_ns_root
)
1207 char fpath
[PROCLEN
];
1209 bool answer
= false;
1212 if (victim
== -1 || uid
== -1)
1216 * If the request is one not requiring root in the namespace,
1217 * then having the same uid suffices. (i.e. uid 1000 has write
1218 * access to files owned by uid 1000
1220 if (!req_ns_root
&& uid
== victim
)
1223 ret
= snprintf(fpath
, PROCLEN
, "/proc/%d/uid_map", pid
);
1224 if (ret
< 0 || ret
>= PROCLEN
)
1226 FILE *f
= fopen(fpath
, "r");
1230 /* if caller's not root in his namespace, reject */
1231 nsuid
= convert_id_to_ns(f
, uid
);
1236 * If victim is not mapped into caller's ns, reject.
1237 * XXX I'm not sure this check is needed given that fuse
1238 * will be sending requests where the vfs has converted
1240 nsuid
= convert_id_to_ns(f
, victim
);
1251 static bool perms_include(int fmode
, mode_t req_mode
)
1255 switch (req_mode
& O_ACCMODE
) {
1263 r
= S_IROTH
| S_IWOTH
;
1268 return ((fmode
& r
) == r
);
1274 * querycg is /a/b/c/d/e
1277 static char *get_next_cgroup_dir(const char *taskcg
, const char *querycg
)
1281 if (strlen(taskcg
) <= strlen(querycg
)) {
1282 lxcfs_error("%s\n", "I was fed bad input.");
1286 if ((strcmp(querycg
, "/") == 0) || (strcmp(querycg
, "./") == 0))
1287 start
= strdup(taskcg
+ 1);
1289 start
= strdup(taskcg
+ strlen(querycg
) + 1);
1292 end
= strchr(start
, '/');
1298 static void stripnewline(char *x
)
1300 size_t l
= strlen(x
);
1301 if (l
&& x
[l
-1] == '\n')
1305 static char *get_pid_cgroup(pid_t pid
, const char *contrl
)
1310 char *answer
= NULL
;
1314 const char *h
= find_mounted_controller(contrl
, &cfd
);
1318 ret
= snprintf(fnam
, PROCLEN
, "/proc/%d/cgroup", pid
);
1319 if (ret
< 0 || ret
>= PROCLEN
)
1321 if (!(f
= fopen(fnam
, "r")))
1324 while (getline(&line
, &len
, f
) != -1) {
1328 c1
= strchr(line
, ':');
1332 c2
= strchr(c1
, ':');
1336 if (strcmp(c1
, h
) != 0)
1341 answer
= strdup(c2
);
1353 * check whether a fuse context may access a cgroup dir or file
1355 * If file is not null, it is a cgroup file to check under cg.
1356 * If file is null, then we are checking perms on cg itself.
1358 * For files we can check the mode of the list_keys result.
1359 * For cgroups, we must make assumptions based on the files under the
1360 * cgroup, because cgmanager doesn't tell us ownership/perms of cgroups
1363 static bool fc_may_access(struct fuse_context
*fc
, const char *contrl
, const char *cg
, const char *file
, mode_t mode
)
1365 struct cgfs_files
*k
= NULL
;
1368 k
= cgfs_get_key(contrl
, cg
, file
);
1372 if (is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
1373 if (perms_include(k
->mode
>> 6, mode
)) {
1378 if (fc
->gid
== k
->gid
) {
1379 if (perms_include(k
->mode
>> 3, mode
)) {
1384 ret
= perms_include(k
->mode
, mode
);
1391 #define INITSCOPE "/init.scope"
1392 static void prune_init_slice(char *cg
)
1395 size_t cg_len
= strlen(cg
), initscope_len
= strlen(INITSCOPE
);
1397 if (cg_len
< initscope_len
)
1400 point
= cg
+ cg_len
- initscope_len
;
1401 if (strcmp(point
, INITSCOPE
) == 0) {
1410 * If pid is in /a/b/c/d, he may only act on things under cg=/a/b/c/d.
1411 * If pid is in /a, he may act on /a/b, but not on /b.
1412 * if the answer is false and nextcg is not NULL, then *nextcg will point
1413 * to a string containing the next cgroup directory under cg, which must be
1414 * freed by the caller.
1416 static bool caller_is_in_ancestor(pid_t pid
, const char *contrl
, const char *cg
, char **nextcg
)
1418 bool answer
= false;
1419 char *c2
= get_pid_cgroup(pid
, contrl
);
1424 prune_init_slice(c2
);
1427 * callers pass in '/' or './' (openat()) for root cgroup, otherwise
1428 * they pass in a cgroup without leading '/'
1430 * The original line here was:
1431 * linecmp = *cg == '/' ? c2 : c2+1;
1432 * TODO: I'm not sure why you'd want to increment when *cg != '/'?
1433 * Serge, do you know?
1435 if (*cg
== '/' || !strncmp(cg
, "./", 2))
1439 if (strncmp(linecmp
, cg
, strlen(linecmp
)) != 0) {
1441 *nextcg
= get_next_cgroup_dir(linecmp
, cg
);
1453 * If pid is in /a/b/c, he may see that /a exists, but not /b or /a/c.
1455 static bool caller_may_see_dir(pid_t pid
, const char *contrl
, const char *cg
)
1457 bool answer
= false;
1459 size_t target_len
, task_len
;
1461 if (strcmp(cg
, "/") == 0 || strcmp(cg
, "./") == 0)
1464 c2
= get_pid_cgroup(pid
, contrl
);
1467 prune_init_slice(c2
);
1470 target_len
= strlen(cg
);
1471 task_len
= strlen(task_cg
);
1472 if (task_len
== 0) {
1473 /* Task is in the root cg, it can see everything. This case is
1474 * not handled by the strmcps below, since they test for the
1475 * last /, but that is the first / that we've chopped off
1481 if (strcmp(cg
, task_cg
) == 0) {
1485 if (target_len
< task_len
) {
1486 /* looking up a parent dir */
1487 if (strncmp(task_cg
, cg
, target_len
) == 0 && task_cg
[target_len
] == '/')
1491 if (target_len
> task_len
) {
1492 /* looking up a child dir */
1493 if (strncmp(task_cg
, cg
, task_len
) == 0 && cg
[task_len
] == '/')
1504 * given /cgroup/freezer/a/b, return "freezer".
1505 * the returned char* should NOT be freed.
1507 static char *pick_controller_from_path(struct fuse_context
*fc
, const char *path
)
1510 char *contr
, *slash
;
1512 if (strlen(path
) < 9) {
1516 if (*(path
+ 7) != '/') {
1521 contr
= strdupa(p1
);
1526 slash
= strstr(contr
, "/");
1531 for (i
= 0; i
< num_hierarchies
; i
++) {
1532 if (hierarchies
[i
] && strcmp(hierarchies
[i
], contr
) == 0)
1533 return hierarchies
[i
];
1540 * Find the start of cgroup in /cgroup/controller/the/cgroup/path
1541 * Note that the returned value may include files (keynames) etc
1543 static const char *find_cgroup_in_path(const char *path
)
1547 if (strlen(path
) < 9) {
1551 p1
= strstr(path
+ 8, "/");
1561 * split the last path element from the path in @cg.
1562 * @dir is newly allocated and should be freed, @last not
1564 static void get_cgdir_and_path(const char *cg
, char **dir
, char **last
)
1571 *last
= strrchr(cg
, '/');
1576 p
= strrchr(*dir
, '/');
1581 * FUSE ops for /cgroup
1584 int cg_getattr(const char *path
, struct stat
*sb
)
1586 struct timespec now
;
1587 struct fuse_context
*fc
= fuse_get_context();
1588 char * cgdir
= NULL
;
1589 char *last
= NULL
, *path1
, *path2
;
1590 struct cgfs_files
*k
= NULL
;
1592 const char *controller
= NULL
;
1599 memset(sb
, 0, sizeof(struct stat
));
1601 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
1604 sb
->st_uid
= sb
->st_gid
= 0;
1605 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
1608 if (strcmp(path
, "/cgroup") == 0) {
1609 sb
->st_mode
= S_IFDIR
| 00755;
1614 controller
= pick_controller_from_path(fc
, path
);
1617 cgroup
= find_cgroup_in_path(path
);
1619 /* this is just /cgroup/controller, return it as a dir */
1620 sb
->st_mode
= S_IFDIR
| 00755;
1625 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
1635 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1638 /* check that cgcopy is either a child cgroup of cgdir, or listed in its keys.
1639 * Then check that caller's cgroup is under path if last is a child
1640 * cgroup, or cgdir if last is a file */
1642 if (is_child_cgroup(controller
, path1
, path2
)) {
1643 if (!caller_may_see_dir(initpid
, controller
, cgroup
)) {
1647 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
1648 /* this is just /cgroup/controller, return it as a dir */
1649 sb
->st_mode
= S_IFDIR
| 00555;
1654 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
)) {
1659 // get uid, gid, from '/tasks' file and make up a mode
1660 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
1661 sb
->st_mode
= S_IFDIR
| 00755;
1662 k
= cgfs_get_key(controller
, cgroup
, NULL
);
1664 sb
->st_uid
= sb
->st_gid
= 0;
1666 sb
->st_uid
= k
->uid
;
1667 sb
->st_gid
= k
->gid
;
1675 if ((k
= cgfs_get_key(controller
, path1
, path2
)) != NULL
) {
1676 sb
->st_mode
= S_IFREG
| k
->mode
;
1678 sb
->st_uid
= k
->uid
;
1679 sb
->st_gid
= k
->gid
;
1682 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
1694 int cg_opendir(const char *path
, struct fuse_file_info
*fi
)
1696 struct fuse_context
*fc
= fuse_get_context();
1698 struct file_info
*dir_info
;
1699 char *controller
= NULL
;
1704 if (strcmp(path
, "/cgroup") == 0) {
1708 // return list of keys for the controller, and list of child cgroups
1709 controller
= pick_controller_from_path(fc
, path
);
1713 cgroup
= find_cgroup_in_path(path
);
1715 /* this is just /cgroup/controller, return its contents */
1720 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1724 if (!caller_may_see_dir(initpid
, controller
, cgroup
))
1726 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
))
1730 /* we'll free this at cg_releasedir */
1731 dir_info
= malloc(sizeof(*dir_info
));
1734 dir_info
->controller
= must_copy_string(controller
);
1735 dir_info
->cgroup
= must_copy_string(cgroup
);
1736 dir_info
->type
= LXC_TYPE_CGDIR
;
1737 dir_info
->buf
= NULL
;
1738 dir_info
->file
= NULL
;
1739 dir_info
->buflen
= 0;
1741 fi
->fh
= (unsigned long)dir_info
;
1745 int cg_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
1746 struct fuse_file_info
*fi
)
1748 struct file_info
*d
= (struct file_info
*)fi
->fh
;
1749 struct cgfs_files
**list
= NULL
;
1751 char *nextcg
= NULL
;
1752 struct fuse_context
*fc
= fuse_get_context();
1753 char **clist
= NULL
;
1755 if (filler(buf
, ".", NULL
, 0) != 0 || filler(buf
, "..", NULL
, 0) != 0)
1758 if (d
->type
!= LXC_TYPE_CGDIR
) {
1759 lxcfs_error("%s\n", "Internal error: file cache info used in readdir.");
1762 if (!d
->cgroup
&& !d
->controller
) {
1763 // ls /var/lib/lxcfs/cgroup - just show list of controllers
1766 for (i
= 0; i
< num_hierarchies
; i
++) {
1767 if (hierarchies
[i
] && filler(buf
, hierarchies
[i
], NULL
, 0) != 0) {
1774 if (!cgfs_list_keys(d
->controller
, d
->cgroup
, &list
)) {
1775 // not a valid cgroup
1780 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1783 if (!caller_is_in_ancestor(initpid
, d
->controller
, d
->cgroup
, &nextcg
)) {
1785 ret
= filler(buf
, nextcg
, NULL
, 0);
1796 for (i
= 0; list
[i
]; i
++) {
1797 if (filler(buf
, list
[i
]->name
, NULL
, 0) != 0) {
1803 // now get the list of child cgroups
1805 if (!cgfs_list_children(d
->controller
, d
->cgroup
, &clist
)) {
1810 for (i
= 0; clist
[i
]; i
++) {
1811 if (filler(buf
, clist
[i
], NULL
, 0) != 0) {
1822 for (i
= 0; clist
[i
]; i
++)
1829 static void do_release_file_info(struct fuse_file_info
*fi
)
1831 struct file_info
*f
= (struct file_info
*)fi
->fh
;
1838 free(f
->controller
);
1839 f
->controller
= NULL
;
1849 int cg_releasedir(const char *path
, struct fuse_file_info
*fi
)
1851 do_release_file_info(fi
);
1855 int cg_open(const char *path
, struct fuse_file_info
*fi
)
1858 char *last
= NULL
, *path1
, *path2
, * cgdir
= NULL
, *controller
;
1859 struct cgfs_files
*k
= NULL
;
1860 struct file_info
*file_info
;
1861 struct fuse_context
*fc
= fuse_get_context();
1867 controller
= pick_controller_from_path(fc
, path
);
1870 cgroup
= find_cgroup_in_path(path
);
1874 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
1883 k
= cgfs_get_key(controller
, path1
, path2
);
1890 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1893 if (!caller_may_see_dir(initpid
, controller
, path1
)) {
1897 if (!fc_may_access(fc
, controller
, path1
, path2
, fi
->flags
)) {
1902 /* we'll free this at cg_release */
1903 file_info
= malloc(sizeof(*file_info
));
1908 file_info
->controller
= must_copy_string(controller
);
1909 file_info
->cgroup
= must_copy_string(path1
);
1910 file_info
->file
= must_copy_string(path2
);
1911 file_info
->type
= LXC_TYPE_CGFILE
;
1912 file_info
->buf
= NULL
;
1913 file_info
->buflen
= 0;
1915 fi
->fh
= (unsigned long)file_info
;
1923 int cg_access(const char *path
, int mode
)
1927 char *path1
, *path2
, *controller
;
1928 char *last
= NULL
, *cgdir
= NULL
;
1929 struct cgfs_files
*k
= NULL
;
1930 struct fuse_context
*fc
= fuse_get_context();
1932 if (strcmp(path
, "/cgroup") == 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 lxcfs_error("%s\n", "Failed to create epoll socket: %m.");
2008 ev
.events
= POLLIN_SET
;
2010 if (epoll_ctl(epfd
, EPOLL_CTL_ADD
, sock
, &ev
) < 0) {
2011 lxcfs_error("%s\n", "Failed adding socket to epoll: %m.");
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 lxcfs_error("%s\n", "Error getting reply from server over socketpair.");
2060 return SEND_CREDS_FAIL
;
2064 msg
.msg_control
= cmsgbuf
;
2065 msg
.msg_controllen
= sizeof(cmsgbuf
);
2067 cmsg
= CMSG_FIRSTHDR(&msg
);
2068 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct ucred
));
2069 cmsg
->cmsg_level
= SOL_SOCKET
;
2070 cmsg
->cmsg_type
= SCM_CREDENTIALS
;
2071 memcpy(CMSG_DATA(cmsg
), cred
, sizeof(*cred
));
2073 msg
.msg_name
= NULL
;
2074 msg
.msg_namelen
= 0;
2078 iov
.iov_len
= sizeof(buf
);
2082 if (sendmsg(sock
, &msg
, 0) < 0) {
2083 lxcfs_error("Failed at sendmsg: %s.\n",strerror(errno
));
2085 return SEND_CREDS_NOTSK
;
2086 return SEND_CREDS_FAIL
;
2089 return SEND_CREDS_OK
;
2092 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
)
2094 struct msghdr msg
= { 0 };
2096 struct cmsghdr
*cmsg
;
2097 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
2108 if (setsockopt(sock
, SOL_SOCKET
, SO_PASSCRED
, &optval
, sizeof(optval
)) == -1) {
2109 lxcfs_error("Failed to set passcred: %s\n", strerror(errno
));
2113 if (write(sock
, buf
, 1) != 1) {
2114 lxcfs_error("Failed to start write on scm fd: %s\n", strerror(errno
));
2118 msg
.msg_name
= NULL
;
2119 msg
.msg_namelen
= 0;
2120 msg
.msg_control
= cmsgbuf
;
2121 msg
.msg_controllen
= sizeof(cmsgbuf
);
2124 iov
.iov_len
= sizeof(buf
);
2128 if (!wait_for_sock(sock
, 2)) {
2129 lxcfs_error("Timed out waiting for scm_cred: %s\n", strerror(errno
));
2132 ret
= recvmsg(sock
, &msg
, MSG_DONTWAIT
);
2134 lxcfs_error("Failed to receive scm_cred: %s\n", strerror(errno
));
2138 cmsg
= CMSG_FIRSTHDR(&msg
);
2140 if (cmsg
&& cmsg
->cmsg_len
== CMSG_LEN(sizeof(struct ucred
)) &&
2141 cmsg
->cmsg_level
== SOL_SOCKET
&&
2142 cmsg
->cmsg_type
== SCM_CREDENTIALS
) {
2143 memcpy(cred
, CMSG_DATA(cmsg
), sizeof(*cred
));
2150 struct pid_ns_clone_args
{
2154 int (*wrapped
) (int, pid_t
); // pid_from_ns or pid_to_ns
2158 * pid_ns_clone_wrapper - wraps pid_to_ns or pid_from_ns for usage
2159 * with clone(). This simply writes '1' as ACK back to the parent
2160 * before calling the actual wrapped function.
2162 static int pid_ns_clone_wrapper(void *arg
) {
2163 struct pid_ns_clone_args
* args
= (struct pid_ns_clone_args
*) arg
;
2166 close(args
->cpipe
[0]);
2167 if (write(args
->cpipe
[1], &b
, sizeof(char)) < 0)
2168 lxcfs_error("(child): error on write: %s.\n", strerror(errno
));
2169 close(args
->cpipe
[1]);
2170 return args
->wrapped(args
->sock
, args
->tpid
);
2174 * pid_to_ns - reads pids from a ucred over a socket, then writes the
2175 * int value back over the socket. This shifts the pid from the
2176 * sender's pidns into tpid's pidns.
2178 static int pid_to_ns(int sock
, pid_t tpid
)
2183 while (recv_creds(sock
, &cred
, &v
)) {
2186 if (write(sock
, &cred
.pid
, sizeof(pid_t
)) != sizeof(pid_t
))
2194 * pid_to_ns_wrapper: when you setns into a pidns, you yourself remain
2195 * in your old pidns. Only children which you clone will be in the target
2196 * pidns. So the pid_to_ns_wrapper does the setns, then clones a child to
2197 * actually convert pids.
2199 * Note: glibc's fork() does not respect pidns, which can lead to failed
2200 * assertions inside glibc (and thus failed forks) if the child's pid in
2201 * the pidns and the parent pid outside are identical. Using clone prevents
2204 static void pid_to_ns_wrapper(int sock
, pid_t tpid
)
2206 int newnsfd
= -1, ret
, cpipe
[2];
2211 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
2212 if (ret
< 0 || ret
>= sizeof(fnam
))
2214 newnsfd
= open(fnam
, O_RDONLY
);
2217 if (setns(newnsfd
, 0) < 0)
2221 if (pipe(cpipe
) < 0)
2224 struct pid_ns_clone_args args
= {
2228 .wrapped
= &pid_to_ns
2230 size_t stack_size
= sysconf(_SC_PAGESIZE
);
2231 void *stack
= alloca(stack_size
);
2233 cpid
= clone(pid_ns_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &args
);
2237 // give the child 1 second to be done forking and
2239 if (!wait_for_sock(cpipe
[0], 1))
2241 ret
= read(cpipe
[0], &v
, 1);
2242 if (ret
!= sizeof(char) || v
!= '1')
2245 if (!wait_for_pid(cpid
))
2251 * To read cgroup files with a particular pid, we will setns into the child
2252 * pidns, open a pipe, fork a child - which will be the first to really be in
2253 * the child ns - which does the cgfs_get_value and writes the data to the pipe.
2255 bool do_read_pids(pid_t tpid
, const char *contrl
, const char *cg
, const char *file
, char **d
)
2257 int sock
[2] = {-1, -1};
2258 char *tmpdata
= NULL
;
2260 pid_t qpid
, cpid
= -1;
2261 bool answer
= false;
2264 size_t sz
= 0, asz
= 0;
2266 if (!cgfs_get_value(contrl
, cg
, file
, &tmpdata
))
2270 * Now we read the pids from returned data one by one, pass
2271 * them into a child in the target namespace, read back the
2272 * translated pids, and put them into our to-return data
2275 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2276 perror("socketpair");
2285 if (!cpid
) // child - exits when done
2286 pid_to_ns_wrapper(sock
[1], tpid
);
2288 char *ptr
= tmpdata
;
2291 while (sscanf(ptr
, "%d\n", &qpid
) == 1) {
2293 ret
= send_creds(sock
[0], &cred
, v
, true);
2295 if (ret
== SEND_CREDS_NOTSK
)
2297 if (ret
== SEND_CREDS_FAIL
)
2300 // read converted results
2301 if (!wait_for_sock(sock
[0], 2)) {
2302 lxcfs_error("Timed out waiting for pid from child: %s.\n", strerror(errno
));
2305 if (read(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2306 lxcfs_error("Error reading pid from child: %s.\n", strerror(errno
));
2309 must_strcat_pid(d
, &sz
, &asz
, qpid
);
2311 ptr
= strchr(ptr
, '\n');
2317 cred
.pid
= getpid();
2319 if (send_creds(sock
[0], &cred
, v
, true) != SEND_CREDS_OK
) {
2320 // failed to ask child to exit
2321 lxcfs_error("Failed to ask child to exit: %s.\n", strerror(errno
));
2331 if (sock
[0] != -1) {
2338 int cg_read(const char *path
, char *buf
, size_t size
, off_t offset
,
2339 struct fuse_file_info
*fi
)
2341 struct fuse_context
*fc
= fuse_get_context();
2342 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2343 struct cgfs_files
*k
= NULL
;
2348 if (f
->type
!= LXC_TYPE_CGFILE
) {
2349 lxcfs_error("%s\n", "Internal error: directory cache info used in cg_read.");
2362 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
2368 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_RDONLY
)) {
2373 if (strcmp(f
->file
, "tasks") == 0 ||
2374 strcmp(f
->file
, "/tasks") == 0 ||
2375 strcmp(f
->file
, "/cgroup.procs") == 0 ||
2376 strcmp(f
->file
, "cgroup.procs") == 0)
2377 // special case - we have to translate the pids
2378 r
= do_read_pids(fc
->pid
, f
->controller
, f
->cgroup
, f
->file
, &data
);
2380 r
= cgfs_get_value(f
->controller
, f
->cgroup
, f
->file
, &data
);
2394 memcpy(buf
, data
, s
);
2395 if (s
> 0 && s
< size
&& data
[s
-1] != '\n')
2405 static int pid_from_ns(int sock
, pid_t tpid
)
2415 if (!wait_for_sock(sock
, 2)) {
2416 lxcfs_error("%s\n", "Timeout reading from parent.");
2419 if ((ret
= read(sock
, &vpid
, sizeof(pid_t
))) != sizeof(pid_t
)) {
2420 lxcfs_error("Bad read from parent: %s.\n", strerror(errno
));
2423 if (vpid
== -1) // done
2427 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
) {
2429 cred
.pid
= getpid();
2430 if (send_creds(sock
, &cred
, v
, false) != SEND_CREDS_OK
)
2437 static void pid_from_ns_wrapper(int sock
, pid_t tpid
)
2439 int newnsfd
= -1, ret
, cpipe
[2];
2444 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
2445 if (ret
< 0 || ret
>= sizeof(fnam
))
2447 newnsfd
= open(fnam
, O_RDONLY
);
2450 if (setns(newnsfd
, 0) < 0)
2454 if (pipe(cpipe
) < 0)
2457 struct pid_ns_clone_args args
= {
2461 .wrapped
= &pid_from_ns
2463 size_t stack_size
= sysconf(_SC_PAGESIZE
);
2464 void *stack
= alloca(stack_size
);
2466 cpid
= clone(pid_ns_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &args
);
2470 // give the child 1 second to be done forking and
2472 if (!wait_for_sock(cpipe
[0], 1))
2474 ret
= read(cpipe
[0], &v
, 1);
2475 if (ret
!= sizeof(char) || v
!= '1')
2478 if (!wait_for_pid(cpid
))
2484 * Given host @uid, return the uid to which it maps in
2485 * @pid's user namespace, or -1 if none.
2487 bool hostuid_to_ns(uid_t uid
, pid_t pid
, uid_t
*answer
)
2492 sprintf(line
, "/proc/%d/uid_map", pid
);
2493 if ((f
= fopen(line
, "r")) == NULL
) {
2497 *answer
= convert_id_to_ns(f
, uid
);
2506 * get_pid_creds: get the real uid and gid of @pid from
2508 * (XXX should we use euid here?)
2510 void get_pid_creds(pid_t pid
, uid_t
*uid
, gid_t
*gid
)
2519 sprintf(line
, "/proc/%d/status", pid
);
2520 if ((f
= fopen(line
, "r")) == NULL
) {
2521 lxcfs_error("Error opening %s: %s\n", line
, strerror(errno
));
2524 while (fgets(line
, 400, f
)) {
2525 if (strncmp(line
, "Uid:", 4) == 0) {
2526 if (sscanf(line
+4, "%u", &u
) != 1) {
2527 lxcfs_error("bad uid line for pid %u\n", pid
);
2532 } else if (strncmp(line
, "Gid:", 4) == 0) {
2533 if (sscanf(line
+4, "%u", &g
) != 1) {
2534 lxcfs_error("bad gid line for pid %u\n", pid
);
2545 * May the requestor @r move victim @v to a new cgroup?
2546 * This is allowed if
2547 * . they are the same task
2548 * . they are ownedy by the same uid
2549 * . @r is root on the host, or
2550 * . @v's uid is mapped into @r's where @r is root.
2552 bool may_move_pid(pid_t r
, uid_t r_uid
, pid_t v
)
2554 uid_t v_uid
, tmpuid
;
2561 get_pid_creds(v
, &v_uid
, &v_gid
);
2564 if (hostuid_to_ns(r_uid
, r
, &tmpuid
) && tmpuid
== 0
2565 && hostuid_to_ns(v_uid
, r
, &tmpuid
))
2570 static bool do_write_pids(pid_t tpid
, uid_t tuid
, const char *contrl
, const char *cg
,
2571 const char *file
, const char *buf
)
2573 int sock
[2] = {-1, -1};
2574 pid_t qpid
, cpid
= -1;
2575 FILE *pids_file
= NULL
;
2576 bool answer
= false, fail
= false;
2578 pids_file
= open_pids_file(contrl
, cg
);
2583 * write the pids to a socket, have helper in writer's pidns
2584 * call movepid for us
2586 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2587 perror("socketpair");
2595 if (!cpid
) { // child
2597 pid_from_ns_wrapper(sock
[1], tpid
);
2600 const char *ptr
= buf
;
2601 while (sscanf(ptr
, "%d", &qpid
) == 1) {
2605 if (write(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2606 lxcfs_error("Error writing pid to child: %s.\n", strerror(errno
));
2610 if (recv_creds(sock
[0], &cred
, &v
)) {
2612 if (!may_move_pid(tpid
, tuid
, cred
.pid
)) {
2616 if (fprintf(pids_file
, "%d", (int) cred
.pid
) < 0)
2621 ptr
= strchr(ptr
, '\n');
2627 /* All good, write the value */
2629 if (write(sock
[0], &qpid
,sizeof(qpid
)) != sizeof(qpid
))
2630 lxcfs_error("%s\n", "Warning: failed to ask child to exit.");
2638 if (sock
[0] != -1) {
2643 if (fclose(pids_file
) != 0)
2649 int cg_write(const char *path
, const char *buf
, size_t size
, off_t offset
,
2650 struct fuse_file_info
*fi
)
2652 struct fuse_context
*fc
= fuse_get_context();
2653 char *localbuf
= NULL
;
2654 struct cgfs_files
*k
= NULL
;
2655 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2658 if (f
->type
!= LXC_TYPE_CGFILE
) {
2659 lxcfs_error("%s\n", "Internal error: directory cache info used in cg_write.");
2669 localbuf
= alloca(size
+1);
2670 localbuf
[size
] = '\0';
2671 memcpy(localbuf
, buf
, size
);
2673 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
2678 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_WRONLY
)) {
2683 if (strcmp(f
->file
, "tasks") == 0 ||
2684 strcmp(f
->file
, "/tasks") == 0 ||
2685 strcmp(f
->file
, "/cgroup.procs") == 0 ||
2686 strcmp(f
->file
, "cgroup.procs") == 0)
2687 // special case - we have to translate the pids
2688 r
= do_write_pids(fc
->pid
, fc
->uid
, f
->controller
, f
->cgroup
, f
->file
, localbuf
);
2690 r
= cgfs_set_value(f
->controller
, f
->cgroup
, f
->file
, localbuf
);
2700 int cg_chown(const char *path
, uid_t uid
, gid_t gid
)
2702 struct fuse_context
*fc
= fuse_get_context();
2703 char *cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
2704 struct cgfs_files
*k
= NULL
;
2711 if (strcmp(path
, "/cgroup") == 0)
2714 controller
= pick_controller_from_path(fc
, path
);
2716 return errno
== ENOENT
? -EPERM
: -errno
;
2718 cgroup
= find_cgroup_in_path(path
);
2720 /* this is just /cgroup/controller */
2723 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2733 if (is_child_cgroup(controller
, path1
, path2
)) {
2734 // get uid, gid, from '/tasks' file and make up a mode
2735 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
2736 k
= cgfs_get_key(controller
, cgroup
, "tasks");
2739 k
= cgfs_get_key(controller
, path1
, path2
);
2747 * This being a fuse request, the uid and gid must be valid
2748 * in the caller's namespace. So we can just check to make
2749 * sure that the caller is root in his uid, and privileged
2750 * over the file's current owner.
2752 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_REQD
)) {
2757 ret
= cgfs_chown_file(controller
, cgroup
, uid
, gid
);
2766 int cg_chmod(const char *path
, mode_t mode
)
2768 struct fuse_context
*fc
= fuse_get_context();
2769 char * cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
2770 struct cgfs_files
*k
= NULL
;
2777 if (strcmp(path
, "/cgroup") == 0)
2780 controller
= pick_controller_from_path(fc
, path
);
2782 return errno
== ENOENT
? -EPERM
: -errno
;
2784 cgroup
= find_cgroup_in_path(path
);
2786 /* this is just /cgroup/controller */
2789 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2799 if (is_child_cgroup(controller
, path1
, path2
)) {
2800 // get uid, gid, from '/tasks' file and make up a mode
2801 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
2802 k
= cgfs_get_key(controller
, cgroup
, "tasks");
2805 k
= cgfs_get_key(controller
, path1
, path2
);
2813 * This being a fuse request, the uid and gid must be valid
2814 * in the caller's namespace. So we can just check to make
2815 * sure that the caller is root in his uid, and privileged
2816 * over the file's current owner.
2818 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
2823 if (!cgfs_chmod_file(controller
, cgroup
, mode
)) {
2835 int cg_mkdir(const char *path
, mode_t mode
)
2837 struct fuse_context
*fc
= fuse_get_context();
2838 char *last
= NULL
, *path1
, *cgdir
= NULL
, *controller
, *next
= NULL
;
2845 controller
= pick_controller_from_path(fc
, path
);
2847 return errno
== ENOENT
? -EPERM
: -errno
;
2849 cgroup
= find_cgroup_in_path(path
);
2853 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2859 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2862 if (!caller_is_in_ancestor(initpid
, controller
, path1
, &next
)) {
2865 else if (last
&& strcmp(next
, last
) == 0)
2872 if (!fc_may_access(fc
, controller
, path1
, NULL
, O_RDWR
)) {
2876 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
2881 ret
= cgfs_create(controller
, cgroup
, fc
->uid
, fc
->gid
);
2889 int cg_rmdir(const char *path
)
2891 struct fuse_context
*fc
= fuse_get_context();
2892 char *last
= NULL
, *cgdir
= NULL
, *controller
, *next
= NULL
;
2899 controller
= pick_controller_from_path(fc
, path
);
2900 if (!controller
) /* Someone's trying to delete "/cgroup". */
2903 cgroup
= find_cgroup_in_path(path
);
2904 if (!cgroup
) /* Someone's trying to delete a controller e.g. "/blkio". */
2907 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2909 /* Someone's trying to delete a cgroup on the same level as the
2910 * "/lxc" cgroup e.g. rmdir "/cgroup/blkio/lxc" or
2911 * rmdir "/cgroup/blkio/init.slice".
2917 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2920 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, &next
)) {
2921 if (!last
|| (next
&& (strcmp(next
, last
) == 0)))
2928 if (!fc_may_access(fc
, controller
, cgdir
, NULL
, O_WRONLY
)) {
2932 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
2937 if (!cgfs_remove(controller
, cgroup
)) {
2950 static bool startswith(const char *line
, const char *pref
)
2952 if (strncmp(line
, pref
, strlen(pref
)) == 0)
2957 static void parse_memstat(char *memstat
, unsigned long *cached
,
2958 unsigned long *active_anon
, unsigned long *inactive_anon
,
2959 unsigned long *active_file
, unsigned long *inactive_file
,
2960 unsigned long *unevictable
)
2965 if (startswith(memstat
, "total_cache")) {
2966 sscanf(memstat
+ 11, "%lu", cached
);
2968 } else if (startswith(memstat
, "total_active_anon")) {
2969 sscanf(memstat
+ 17, "%lu", active_anon
);
2970 *active_anon
/= 1024;
2971 } else if (startswith(memstat
, "total_inactive_anon")) {
2972 sscanf(memstat
+ 19, "%lu", inactive_anon
);
2973 *inactive_anon
/= 1024;
2974 } else if (startswith(memstat
, "total_active_file")) {
2975 sscanf(memstat
+ 17, "%lu", active_file
);
2976 *active_file
/= 1024;
2977 } else if (startswith(memstat
, "total_inactive_file")) {
2978 sscanf(memstat
+ 19, "%lu", inactive_file
);
2979 *inactive_file
/= 1024;
2980 } else if (startswith(memstat
, "total_unevictable")) {
2981 sscanf(memstat
+ 17, "%lu", unevictable
);
2982 *unevictable
/= 1024;
2984 eol
= strchr(memstat
, '\n');
2991 static void get_blkio_io_value(char *str
, unsigned major
, unsigned minor
, char *iotype
, unsigned long *v
)
2997 snprintf(key
, 32, "%u:%u %s", major
, minor
, iotype
);
2999 size_t len
= strlen(key
);
3003 if (startswith(str
, key
)) {
3004 sscanf(str
+ len
, "%lu", v
);
3007 eol
= strchr(str
, '\n');
3014 static int read_file(const char *path
, char *buf
, size_t size
,
3015 struct file_info
*d
)
3017 size_t linelen
= 0, total_len
= 0, rv
= 0;
3019 char *cache
= d
->buf
;
3020 size_t cache_size
= d
->buflen
;
3021 FILE *f
= fopen(path
, "r");
3025 while (getline(&line
, &linelen
, f
) != -1) {
3026 ssize_t l
= snprintf(cache
, cache_size
, "%s", line
);
3028 perror("Error writing to cache");
3032 if (l
>= cache_size
) {
3033 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3042 d
->size
= total_len
;
3043 if (total_len
> size
)
3046 /* read from off 0 */
3047 memcpy(buf
, d
->buf
, total_len
);
3056 * FUSE ops for /proc
3059 static unsigned long get_memlimit(const char *cgroup
, const char *file
)
3061 char *memlimit_str
= NULL
;
3062 unsigned long memlimit
= -1;
3064 if (cgfs_get_value("memory", cgroup
, file
, &memlimit_str
))
3065 memlimit
= strtoul(memlimit_str
, NULL
, 10);
3072 static unsigned long get_min_memlimit(const char *cgroup
, const char *file
)
3074 char *copy
= strdupa(cgroup
);
3075 unsigned long memlimit
= 0, retlimit
;
3077 retlimit
= get_memlimit(copy
, file
);
3079 while (strcmp(copy
, "/") != 0) {
3080 copy
= dirname(copy
);
3081 memlimit
= get_memlimit(copy
, file
);
3082 if (memlimit
!= -1 && memlimit
< retlimit
)
3083 retlimit
= memlimit
;
3089 static int proc_meminfo_read(char *buf
, size_t size
, off_t offset
,
3090 struct fuse_file_info
*fi
)
3092 struct fuse_context
*fc
= fuse_get_context();
3093 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3095 char *memusage_str
= NULL
, *memstat_str
= NULL
,
3096 *memswlimit_str
= NULL
, *memswusage_str
= NULL
;
3097 unsigned long memlimit
= 0, memusage
= 0, memswlimit
= 0, memswusage
= 0,
3098 cached
= 0, hosttotal
= 0, active_anon
= 0, inactive_anon
= 0,
3099 active_file
= 0, inactive_file
= 0, unevictable
= 0,
3102 size_t linelen
= 0, total_len
= 0, rv
= 0;
3103 char *cache
= d
->buf
;
3104 size_t cache_size
= d
->buflen
;
3108 if (offset
> d
->size
)
3112 int left
= d
->size
- offset
;
3113 total_len
= left
> size
? size
: left
;
3114 memcpy(buf
, cache
+ offset
, total_len
);
3118 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3121 cg
= get_pid_cgroup(initpid
, "memory");
3123 return read_file("/proc/meminfo", buf
, size
, d
);
3124 prune_init_slice(cg
);
3126 memlimit
= get_min_memlimit(cg
, "memory.limit_in_bytes");
3127 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
3129 if (!cgfs_get_value("memory", cg
, "memory.stat", &memstat_str
))
3132 // Following values are allowed to fail, because swapaccount might be turned
3133 // off for current kernel
3134 if(cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
) &&
3135 cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
))
3137 memswlimit
= get_min_memlimit(cg
, "memory.memsw.limit_in_bytes");
3138 memswusage
= strtoul(memswusage_str
, NULL
, 10);
3140 memswlimit
= memswlimit
/ 1024;
3141 memswusage
= memswusage
/ 1024;
3144 memusage
= strtoul(memusage_str
, NULL
, 10);
3148 parse_memstat(memstat_str
, &cached
, &active_anon
,
3149 &inactive_anon
, &active_file
, &inactive_file
,
3152 f
= fopen("/proc/meminfo", "r");
3156 while (getline(&line
, &linelen
, f
) != -1) {
3158 char *printme
, lbuf
[100];
3160 memset(lbuf
, 0, 100);
3161 if (startswith(line
, "MemTotal:")) {
3162 sscanf(line
+sizeof("MemTotal:")-1, "%lu", &hosttotal
);
3163 if (hosttotal
< memlimit
)
3164 memlimit
= hosttotal
;
3165 snprintf(lbuf
, 100, "MemTotal: %8lu kB\n", memlimit
);
3167 } else if (startswith(line
, "MemFree:")) {
3168 snprintf(lbuf
, 100, "MemFree: %8lu kB\n", memlimit
- memusage
);
3170 } else if (startswith(line
, "MemAvailable:")) {
3171 snprintf(lbuf
, 100, "MemAvailable: %8lu kB\n", memlimit
- memusage
+ cached
);
3173 } else if (startswith(line
, "SwapTotal:") && memswlimit
> 0) {
3174 sscanf(line
+sizeof("SwapTotal:")-1, "%lu", &hostswtotal
);
3175 if (hostswtotal
< memswlimit
)
3176 memswlimit
= hostswtotal
;
3177 snprintf(lbuf
, 100, "SwapTotal: %8lu kB\n", memswlimit
);
3179 } else if (startswith(line
, "SwapFree:") && memswlimit
> 0 && memswusage
> 0) {
3180 unsigned long swaptotal
= memswlimit
,
3181 swapusage
= memswusage
- memusage
,
3182 swapfree
= swapusage
< swaptotal
? swaptotal
- swapusage
: 0;
3183 snprintf(lbuf
, 100, "SwapFree: %8lu kB\n", swapfree
);
3185 } else if (startswith(line
, "Slab:")) {
3186 snprintf(lbuf
, 100, "Slab: %8lu kB\n", 0UL);
3188 } else if (startswith(line
, "Buffers:")) {
3189 snprintf(lbuf
, 100, "Buffers: %8lu kB\n", 0UL);
3191 } else if (startswith(line
, "Cached:")) {
3192 snprintf(lbuf
, 100, "Cached: %8lu kB\n", cached
);
3194 } else if (startswith(line
, "SwapCached:")) {
3195 snprintf(lbuf
, 100, "SwapCached: %8lu kB\n", 0UL);
3197 } else if (startswith(line
, "Active:")) {
3198 snprintf(lbuf
, 100, "Active: %8lu kB\n",
3199 active_anon
+ active_file
);
3201 } else if (startswith(line
, "Inactive:")) {
3202 snprintf(lbuf
, 100, "Inactive: %8lu kB\n",
3203 inactive_anon
+ inactive_file
);
3205 } else if (startswith(line
, "Active(anon)")) {
3206 snprintf(lbuf
, 100, "Active(anon): %8lu kB\n", active_anon
);
3208 } else if (startswith(line
, "Inactive(anon)")) {
3209 snprintf(lbuf
, 100, "Inactive(anon): %8lu kB\n", inactive_anon
);
3211 } else if (startswith(line
, "Active(file)")) {
3212 snprintf(lbuf
, 100, "Active(file): %8lu kB\n", active_file
);
3214 } else if (startswith(line
, "Inactive(file)")) {
3215 snprintf(lbuf
, 100, "Inactive(file): %8lu kB\n", inactive_file
);
3217 } else if (startswith(line
, "Unevictable")) {
3218 snprintf(lbuf
, 100, "Unevictable: %8lu kB\n", unevictable
);
3220 } else if (startswith(line
, "SReclaimable")) {
3221 snprintf(lbuf
, 100, "SReclaimable: %8lu kB\n", 0UL);
3223 } else if (startswith(line
, "SUnreclaim")) {
3224 snprintf(lbuf
, 100, "SUnreclaim: %8lu kB\n", 0UL);
3229 l
= snprintf(cache
, cache_size
, "%s", printme
);
3231 perror("Error writing to cache");
3236 if (l
>= cache_size
) {
3237 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3248 d
->size
= total_len
;
3249 if (total_len
> size
) total_len
= size
;
3250 memcpy(buf
, d
->buf
, total_len
);
3259 free(memswlimit_str
);
3260 free(memswusage_str
);
3266 * Read the cpuset.cpus for cg
3267 * Return the answer in a newly allocated string which must be freed
3269 static char *get_cpuset(const char *cg
)
3273 if (!cgfs_get_value("cpuset", cg
, "cpuset.cpus", &answer
))
3278 bool cpu_in_cpuset(int cpu
, const char *cpuset
);
3280 static bool cpuline_in_cpuset(const char *line
, const char *cpuset
)
3284 if (sscanf(line
, "processor : %d", &cpu
) != 1)
3286 return cpu_in_cpuset(cpu
, cpuset
);
3290 * check whether this is a '^processor" line in /proc/cpuinfo
3292 static bool is_processor_line(const char *line
)
3296 if (sscanf(line
, "processor : %d", &cpu
) == 1)
3301 static int proc_cpuinfo_read(char *buf
, size_t size
, off_t offset
,
3302 struct fuse_file_info
*fi
)
3304 struct fuse_context
*fc
= fuse_get_context();
3305 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3307 char *cpuset
= NULL
;
3309 size_t linelen
= 0, total_len
= 0, rv
= 0;
3310 bool am_printing
= false, firstline
= true, is_s390x
= false;
3311 int curcpu
= -1, cpu
;
3312 char *cache
= d
->buf
;
3313 size_t cache_size
= d
->buflen
;
3317 if (offset
> d
->size
)
3321 int left
= d
->size
- offset
;
3322 total_len
= left
> size
? size
: left
;
3323 memcpy(buf
, cache
+ offset
, total_len
);
3327 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3330 cg
= get_pid_cgroup(initpid
, "cpuset");
3332 return read_file("proc/cpuinfo", buf
, size
, d
);
3333 prune_init_slice(cg
);
3335 cpuset
= get_cpuset(cg
);
3339 f
= fopen("/proc/cpuinfo", "r");
3343 while (getline(&line
, &linelen
, f
) != -1) {
3347 if (strstr(line
, "IBM/S390") != NULL
) {
3353 if (strncmp(line
, "# processors:", 12) == 0)
3355 if (is_processor_line(line
)) {
3356 am_printing
= cpuline_in_cpuset(line
, cpuset
);
3359 l
= snprintf(cache
, cache_size
, "processor : %d\n", curcpu
);
3361 perror("Error writing to cache");
3365 if (l
>= cache_size
) {
3366 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3375 } else if (is_s390x
&& sscanf(line
, "processor %d:", &cpu
) == 1) {
3377 if (!cpu_in_cpuset(cpu
, cpuset
))
3380 p
= strchr(line
, ':');
3384 l
= snprintf(cache
, cache_size
, "processor %d:%s", curcpu
, p
);
3386 perror("Error writing to cache");
3390 if (l
>= cache_size
) {
3391 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3402 l
= snprintf(cache
, cache_size
, "%s", line
);
3404 perror("Error writing to cache");
3408 if (l
>= cache_size
) {
3409 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3420 char *origcache
= d
->buf
;
3423 d
->buf
= malloc(d
->buflen
);
3426 cache_size
= d
->buflen
;
3428 l
= snprintf(cache
, cache_size
, "vendor_id : IBM/S390\n");
3429 if (l
< 0 || l
>= cache_size
) {
3436 l
= snprintf(cache
, cache_size
, "# processors : %d\n", curcpu
+ 1);
3437 if (l
< 0 || l
>= cache_size
) {
3444 l
= snprintf(cache
, cache_size
, "%s", origcache
);
3446 if (l
< 0 || l
>= cache_size
)
3452 d
->size
= total_len
;
3453 if (total_len
> size
) total_len
= size
;
3455 /* read from off 0 */
3456 memcpy(buf
, d
->buf
, total_len
);
3467 static uint64_t get_reaper_start_time(pid_t pid
)
3472 /* strlen("/proc/") = 6
3476 * strlen("/stat") = 5
3480 #define __PROC_PID_STAT_LEN (6 + LXCFS_NUMSTRLEN64 + 5 + 1)
3481 char path
[__PROC_PID_STAT_LEN
];
3484 qpid
= lookup_initpid_in_store(pid
);
3486 /* Caller can check for EINVAL on 0. */
3491 ret
= snprintf(path
, __PROC_PID_STAT_LEN
, "/proc/%d/stat", qpid
);
3492 if (ret
< 0 || ret
>= __PROC_PID_STAT_LEN
) {
3493 /* Caller can check for EINVAL on 0. */
3498 f
= fopen(path
, "r");
3500 /* Caller can check for EINVAL on 0. */
3505 /* Note that the *scanf() argument supression requires that length
3506 * modifiers such as "l" are omitted. Otherwise some compilers will yell
3507 * at us. It's like telling someone you're not married and then asking
3508 * if you can bring your wife to the party.
3510 ret
= fscanf(f
, "%*d " /* (1) pid %d */
3511 "%*s " /* (2) comm %s */
3512 "%*c " /* (3) state %c */
3513 "%*d " /* (4) ppid %d */
3514 "%*d " /* (5) pgrp %d */
3515 "%*d " /* (6) session %d */
3516 "%*d " /* (7) tty_nr %d */
3517 "%*d " /* (8) tpgid %d */
3518 "%*u " /* (9) flags %u */
3519 "%*u " /* (10) minflt %lu */
3520 "%*u " /* (11) cminflt %lu */
3521 "%*u " /* (12) majflt %lu */
3522 "%*u " /* (13) cmajflt %lu */
3523 "%*u " /* (14) utime %lu */
3524 "%*u " /* (15) stime %lu */
3525 "%*d " /* (16) cutime %ld */
3526 "%*d " /* (17) cstime %ld */
3527 "%*d " /* (18) priority %ld */
3528 "%*d " /* (19) nice %ld */
3529 "%*d " /* (20) num_threads %ld */
3530 "%*d " /* (21) itrealvalue %ld */
3531 "%" PRIu64
, /* (22) starttime %llu */
3535 /* Caller can check for EINVAL on 0. */
3546 static uint64_t get_reaper_start_time_in_sec(pid_t pid
)
3548 uint64_t clockticks
;
3549 int64_t ticks_per_sec
;
3551 clockticks
= get_reaper_start_time(pid
);
3552 if (clockticks
== 0 && errno
== EINVAL
) {
3553 lxcfs_debug("failed to retrieve start time of pid %d\n", pid
);
3557 ticks_per_sec
= sysconf(_SC_CLK_TCK
);
3558 if (ticks_per_sec
< 0 && errno
== EINVAL
) {
3561 "failed to determine number of clock ticks in a second");
3565 return (clockticks
/= ticks_per_sec
);
3568 static uint64_t get_reaper_age(pid_t pid
)
3570 uint64_t procstart
, uptime
, procage
;
3572 /* We need to substract the time the process has started since system
3573 * boot minus the time when the system has started to get the actual
3576 procstart
= get_reaper_start_time_in_sec(pid
);
3577 procage
= procstart
;
3578 if (procstart
> 0) {
3580 struct timespec spec
;
3582 ret
= clock_gettime(CLOCK_BOOTTIME
, &spec
);
3585 /* We could make this more precise here by using the tv_nsec
3586 * field in the timespec struct and convert it to milliseconds
3587 * and then create a double for the seconds and milliseconds but
3588 * that seems more work than it is worth.
3590 uptime
= spec
.tv_sec
;
3591 procage
= uptime
- procstart
;
3597 #define CPUALL_MAX_SIZE (BUF_RESERVE_SIZE / 2)
3598 static int proc_stat_read(char *buf
, size_t size
, off_t offset
,
3599 struct fuse_file_info
*fi
)
3601 struct fuse_context
*fc
= fuse_get_context();
3602 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3604 char *cpuset
= NULL
;
3606 size_t linelen
= 0, total_len
= 0, rv
= 0;
3607 int curcpu
= -1; /* cpu numbering starts at 0 */
3608 unsigned long user
= 0, nice
= 0, system
= 0, idle
= 0, iowait
= 0, irq
= 0, softirq
= 0, steal
= 0, guest
= 0, guest_nice
= 0;
3609 unsigned long user_sum
= 0, nice_sum
= 0, system_sum
= 0, idle_sum
= 0, iowait_sum
= 0,
3610 irq_sum
= 0, softirq_sum
= 0, steal_sum
= 0, guest_sum
= 0, guest_nice_sum
= 0;
3611 char cpuall
[CPUALL_MAX_SIZE
];
3612 /* reserve for cpu all */
3613 char *cache
= d
->buf
+ CPUALL_MAX_SIZE
;
3614 size_t cache_size
= d
->buflen
- CPUALL_MAX_SIZE
;
3618 if (offset
> d
->size
)
3622 int left
= d
->size
- offset
;
3623 total_len
= left
> size
? size
: left
;
3624 memcpy(buf
, d
->buf
+ offset
, total_len
);
3628 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3631 cg
= get_pid_cgroup(initpid
, "cpuset");
3633 return read_file("/proc/stat", buf
, size
, d
);
3634 prune_init_slice(cg
);
3636 cpuset
= get_cpuset(cg
);
3640 f
= fopen("/proc/stat", "r");
3645 if (getline(&line
, &linelen
, f
) < 0) {
3646 lxcfs_error("%s\n", "proc_stat_read read first line failed.");
3650 while (getline(&line
, &linelen
, f
) != -1) {
3653 char cpu_char
[10]; /* That's a lot of cores */
3656 if (strlen(line
) == 0)
3658 if (sscanf(line
, "cpu%9[^ ]", cpu_char
) != 1) {
3659 /* not a ^cpuN line containing a number N, just print it */
3660 l
= snprintf(cache
, cache_size
, "%s", line
);
3662 perror("Error writing to cache");
3666 if (l
>= cache_size
) {
3667 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3677 if (sscanf(cpu_char
, "%d", &cpu
) != 1)
3679 if (!cpu_in_cpuset(cpu
, cpuset
))
3683 c
= strchr(line
, ' ');
3686 l
= snprintf(cache
, cache_size
, "cpu%d%s", curcpu
, c
);
3688 perror("Error writing to cache");
3693 if (l
>= cache_size
) {
3694 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3703 if (sscanf(line
, "%*s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
3717 system_sum
+= system
;
3719 iowait_sum
+= iowait
;
3721 softirq_sum
+= softirq
;
3724 guest_nice_sum
+= guest_nice
;
3729 int cpuall_len
= snprintf(cpuall
, CPUALL_MAX_SIZE
, "cpu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
3740 if (cpuall_len
> 0 && cpuall_len
< CPUALL_MAX_SIZE
) {
3741 memcpy(cache
, cpuall
, cpuall_len
);
3742 cache
+= cpuall_len
;
3744 /* shouldn't happen */
3745 lxcfs_error("proc_stat_read copy cpuall failed, cpuall_len=%d.", cpuall_len
);
3749 memmove(cache
, d
->buf
+ CPUALL_MAX_SIZE
, total_len
);
3750 total_len
+= cpuall_len
;
3752 d
->size
= total_len
;
3753 if (total_len
> size
)
3756 memcpy(buf
, d
->buf
, total_len
);
3768 /* This function retrieves the busy time of a group of tasks by looking at
3769 * cpuacct.usage. Unfortunately, this only makes sense when the container has
3770 * been given it's own cpuacct cgroup. If not, this function will take the busy
3771 * time of all other taks that do not actually belong to the container into
3772 * account as well. If someone has a clever solution for this please send a
3775 static unsigned long get_reaper_busy(pid_t task
)
3777 pid_t initpid
= lookup_initpid_in_store(task
);
3778 char *cgroup
= NULL
, *usage_str
= NULL
;
3779 unsigned long usage
= 0;
3784 cgroup
= get_pid_cgroup(initpid
, "cpuacct");
3787 prune_init_slice(cgroup
);
3788 if (!cgfs_get_value("cpuacct", cgroup
, "cpuacct.usage", &usage_str
))
3790 usage
= strtoul(usage_str
, NULL
, 10);
3791 usage
/= 1000000000;
3804 fd
= creat("/tmp/lxcfs-iwashere", 0644);
3811 * We read /proc/uptime and reuse its second field.
3812 * For the first field, we use the mtime for the reaper for
3813 * the calling pid as returned by getreaperage
3815 static int proc_uptime_read(char *buf
, size_t size
, off_t offset
,
3816 struct fuse_file_info
*fi
)
3818 struct fuse_context
*fc
= fuse_get_context();
3819 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3820 unsigned long int busytime
= get_reaper_busy(fc
->pid
);
3821 char *cache
= d
->buf
;
3822 ssize_t total_len
= 0;
3823 uint64_t idletime
, reaperage
;
3832 if (offset
> d
->size
)
3834 int left
= d
->size
- offset
;
3835 total_len
= left
> size
? size
: left
;
3836 memcpy(buf
, cache
+ offset
, total_len
);
3840 reaperage
= get_reaper_age(fc
->pid
);
3841 /* To understand why this is done, please read the comment to the
3842 * get_reaper_busy() function.
3844 idletime
= reaperage
;
3845 if (reaperage
>= busytime
)
3846 idletime
= reaperage
- busytime
;
3848 total_len
= snprintf(d
->buf
, d
->buflen
, "%"PRIu64
".00 %"PRIu64
".00\n", reaperage
, idletime
);
3849 if (total_len
< 0 || total_len
>= d
->buflen
){
3850 lxcfs_error("%s\n", "failed to write to cache");
3854 d
->size
= (int)total_len
;
3857 if (total_len
> size
) total_len
= size
;
3859 memcpy(buf
, d
->buf
, total_len
);
3863 static int proc_diskstats_read(char *buf
, size_t size
, off_t offset
,
3864 struct fuse_file_info
*fi
)
3867 struct fuse_context
*fc
= fuse_get_context();
3868 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3870 char *io_serviced_str
= NULL
, *io_merged_str
= NULL
, *io_service_bytes_str
= NULL
,
3871 *io_wait_time_str
= NULL
, *io_service_time_str
= NULL
;
3872 unsigned long read
= 0, write
= 0;
3873 unsigned long read_merged
= 0, write_merged
= 0;
3874 unsigned long read_sectors
= 0, write_sectors
= 0;
3875 unsigned long read_ticks
= 0, write_ticks
= 0;
3876 unsigned long ios_pgr
= 0, tot_ticks
= 0, rq_ticks
= 0;
3877 unsigned long rd_svctm
= 0, wr_svctm
= 0, rd_wait
= 0, wr_wait
= 0;
3878 char *cache
= d
->buf
;
3879 size_t cache_size
= d
->buflen
;
3881 size_t linelen
= 0, total_len
= 0, rv
= 0;
3882 unsigned int major
= 0, minor
= 0;
3887 if (offset
> d
->size
)
3891 int left
= d
->size
- offset
;
3892 total_len
= left
> size
? size
: left
;
3893 memcpy(buf
, cache
+ offset
, total_len
);
3897 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3900 cg
= get_pid_cgroup(initpid
, "blkio");
3902 return read_file("/proc/diskstats", buf
, size
, d
);
3903 prune_init_slice(cg
);
3905 if (!cgfs_get_value("blkio", cg
, "blkio.io_serviced_recursive", &io_serviced_str
))
3907 if (!cgfs_get_value("blkio", cg
, "blkio.io_merged_recursive", &io_merged_str
))
3909 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_bytes_recursive", &io_service_bytes_str
))
3911 if (!cgfs_get_value("blkio", cg
, "blkio.io_wait_time_recursive", &io_wait_time_str
))
3913 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_time_recursive", &io_service_time_str
))
3917 f
= fopen("/proc/diskstats", "r");
3921 while (getline(&line
, &linelen
, f
) != -1) {
3925 i
= sscanf(line
, "%u %u %71s", &major
, &minor
, dev_name
);
3929 get_blkio_io_value(io_serviced_str
, major
, minor
, "Read", &read
);
3930 get_blkio_io_value(io_serviced_str
, major
, minor
, "Write", &write
);
3931 get_blkio_io_value(io_merged_str
, major
, minor
, "Read", &read_merged
);
3932 get_blkio_io_value(io_merged_str
, major
, minor
, "Write", &write_merged
);
3933 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Read", &read_sectors
);
3934 read_sectors
= read_sectors
/512;
3935 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Write", &write_sectors
);
3936 write_sectors
= write_sectors
/512;
3938 get_blkio_io_value(io_service_time_str
, major
, minor
, "Read", &rd_svctm
);
3939 rd_svctm
= rd_svctm
/1000000;
3940 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Read", &rd_wait
);
3941 rd_wait
= rd_wait
/1000000;
3942 read_ticks
= rd_svctm
+ rd_wait
;
3944 get_blkio_io_value(io_service_time_str
, major
, minor
, "Write", &wr_svctm
);
3945 wr_svctm
= wr_svctm
/1000000;
3946 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Write", &wr_wait
);
3947 wr_wait
= wr_wait
/1000000;
3948 write_ticks
= wr_svctm
+ wr_wait
;
3950 get_blkio_io_value(io_service_time_str
, major
, minor
, "Total", &tot_ticks
);
3951 tot_ticks
= tot_ticks
/1000000;
3953 memset(lbuf
, 0, 256);
3954 if (read
|| write
|| read_merged
|| write_merged
|| read_sectors
|| write_sectors
|| read_ticks
|| write_ticks
)
3955 snprintf(lbuf
, 256, "%u %u %s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
3956 major
, minor
, dev_name
, read
, read_merged
, read_sectors
, read_ticks
,
3957 write
, write_merged
, write_sectors
, write_ticks
, ios_pgr
, tot_ticks
, rq_ticks
);
3961 l
= snprintf(cache
, cache_size
, "%s", lbuf
);
3963 perror("Error writing to fuse buf");
3967 if (l
>= cache_size
) {
3968 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3978 d
->size
= total_len
;
3979 if (total_len
> size
) total_len
= size
;
3980 memcpy(buf
, d
->buf
, total_len
);
3988 free(io_serviced_str
);
3989 free(io_merged_str
);
3990 free(io_service_bytes_str
);
3991 free(io_wait_time_str
);
3992 free(io_service_time_str
);
3996 static int proc_swaps_read(char *buf
, size_t size
, off_t offset
,
3997 struct fuse_file_info
*fi
)
3999 struct fuse_context
*fc
= fuse_get_context();
4000 struct file_info
*d
= (struct file_info
*)fi
->fh
;
4002 char *memswlimit_str
= NULL
, *memlimit_str
= NULL
, *memusage_str
= NULL
, *memswusage_str
= NULL
;
4003 unsigned long memswlimit
= 0, memlimit
= 0, memusage
= 0, memswusage
= 0, swap_total
= 0, swap_free
= 0;
4004 ssize_t total_len
= 0, rv
= 0;
4006 char *cache
= d
->buf
;
4009 if (offset
> d
->size
)
4013 int left
= d
->size
- offset
;
4014 total_len
= left
> size
? size
: left
;
4015 memcpy(buf
, cache
+ offset
, total_len
);
4019 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
4022 cg
= get_pid_cgroup(initpid
, "memory");
4024 return read_file("/proc/swaps", buf
, size
, d
);
4025 prune_init_slice(cg
);
4027 memlimit
= get_min_memlimit(cg
, "memory.limit_in_bytes");
4029 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
4032 memusage
= strtoul(memusage_str
, NULL
, 10);
4034 if (cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
) &&
4035 cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
)) {
4037 memswlimit
= get_min_memlimit(cg
, "memory.memsw.limit_in_bytes");
4038 memswusage
= strtoul(memswusage_str
, NULL
, 10);
4040 swap_total
= (memswlimit
- memlimit
) / 1024;
4041 swap_free
= (memswusage
- memusage
) / 1024;
4044 total_len
= snprintf(d
->buf
, d
->size
, "Filename\t\t\t\tType\t\tSize\tUsed\tPriority\n");
4046 /* When no mem + swap limit is specified or swapaccount=0*/
4050 FILE *f
= fopen("/proc/meminfo", "r");
4055 while (getline(&line
, &linelen
, f
) != -1) {
4056 if (startswith(line
, "SwapTotal:")) {
4057 sscanf(line
, "SwapTotal: %8lu kB", &swap_total
);
4058 } else if (startswith(line
, "SwapFree:")) {
4059 sscanf(line
, "SwapFree: %8lu kB", &swap_free
);
4067 if (swap_total
> 0) {
4068 l
= snprintf(d
->buf
+ total_len
, d
->size
- total_len
,
4069 "none%*svirtual\t\t%lu\t%lu\t0\n", 36, " ",
4070 swap_total
, swap_free
);
4074 if (total_len
< 0 || l
< 0) {
4075 perror("Error writing to cache");
4081 d
->size
= (int)total_len
;
4083 if (total_len
> size
) total_len
= size
;
4084 memcpy(buf
, d
->buf
, total_len
);
4089 free(memswlimit_str
);
4092 free(memswusage_str
);
4096 static off_t
get_procfile_size(const char *which
)
4098 FILE *f
= fopen(which
, "r");
4101 ssize_t sz
, answer
= 0;
4105 while ((sz
= getline(&line
, &len
, f
)) != -1)
4113 int proc_getattr(const char *path
, struct stat
*sb
)
4115 struct timespec now
;
4117 memset(sb
, 0, sizeof(struct stat
));
4118 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
4120 sb
->st_uid
= sb
->st_gid
= 0;
4121 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
4122 if (strcmp(path
, "/proc") == 0) {
4123 sb
->st_mode
= S_IFDIR
| 00555;
4127 if (strcmp(path
, "/proc/meminfo") == 0 ||
4128 strcmp(path
, "/proc/cpuinfo") == 0 ||
4129 strcmp(path
, "/proc/uptime") == 0 ||
4130 strcmp(path
, "/proc/stat") == 0 ||
4131 strcmp(path
, "/proc/diskstats") == 0 ||
4132 strcmp(path
, "/proc/swaps") == 0 ||
4133 strcmp(path
, "/proc/loadavg") == 0) {
4135 sb
->st_mode
= S_IFREG
| 00444;
4143 int proc_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
4144 struct fuse_file_info
*fi
)
4146 if (filler(buf
, ".", NULL
, 0) != 0 ||
4147 filler(buf
, "..", NULL
, 0) != 0 ||
4148 filler(buf
, "cpuinfo", NULL
, 0) != 0 ||
4149 filler(buf
, "meminfo", NULL
, 0) != 0 ||
4150 filler(buf
, "stat", NULL
, 0) != 0 ||
4151 filler(buf
, "uptime", NULL
, 0) != 0 ||
4152 filler(buf
, "diskstats", NULL
, 0) != 0 ||
4153 filler(buf
, "swaps", NULL
, 0) != 0 ||
4154 filler(buf
, "loadavg", NULL
, 0) != 0)
4159 int proc_open(const char *path
, struct fuse_file_info
*fi
)
4162 struct file_info
*info
;
4164 if (strcmp(path
, "/proc/meminfo") == 0)
4165 type
= LXC_TYPE_PROC_MEMINFO
;
4166 else if (strcmp(path
, "/proc/cpuinfo") == 0)
4167 type
= LXC_TYPE_PROC_CPUINFO
;
4168 else if (strcmp(path
, "/proc/uptime") == 0)
4169 type
= LXC_TYPE_PROC_UPTIME
;
4170 else if (strcmp(path
, "/proc/stat") == 0)
4171 type
= LXC_TYPE_PROC_STAT
;
4172 else if (strcmp(path
, "/proc/diskstats") == 0)
4173 type
= LXC_TYPE_PROC_DISKSTATS
;
4174 else if (strcmp(path
, "/proc/swaps") == 0)
4175 type
= LXC_TYPE_PROC_SWAPS
;
4176 else if (strcmp(path
, "/proc/loadavg") == 0)
4177 type
= LXC_TYPE_PROC_LOADAVG
;
4181 info
= malloc(sizeof(*info
));
4185 memset(info
, 0, sizeof(*info
));
4188 info
->buflen
= get_procfile_size(path
) + BUF_RESERVE_SIZE
;
4190 info
->buf
= malloc(info
->buflen
);
4191 } while (!info
->buf
);
4192 memset(info
->buf
, 0, info
->buflen
);
4193 /* set actual size to buffer size */
4194 info
->size
= info
->buflen
;
4196 fi
->fh
= (unsigned long)info
;
4200 int proc_access(const char *path
, int mask
)
4202 if (strcmp(path
, "/proc") == 0 && access(path
, R_OK
) == 0)
4205 /* these are all read-only */
4206 if ((mask
& ~R_OK
) != 0)
4211 int proc_release(const char *path
, struct fuse_file_info
*fi
)
4213 do_release_file_info(fi
);
4217 int proc_read(const char *path
, char *buf
, size_t size
, off_t offset
,
4218 struct fuse_file_info
*fi
)
4220 struct file_info
*f
= (struct file_info
*) fi
->fh
;
4223 case LXC_TYPE_PROC_MEMINFO
:
4224 return proc_meminfo_read(buf
, size
, offset
, fi
);
4225 case LXC_TYPE_PROC_CPUINFO
:
4226 return proc_cpuinfo_read(buf
, size
, offset
, fi
);
4227 case LXC_TYPE_PROC_UPTIME
:
4228 return proc_uptime_read(buf
, size
, offset
, fi
);
4229 case LXC_TYPE_PROC_STAT
:
4230 return proc_stat_read(buf
, size
, offset
, fi
);
4231 case LXC_TYPE_PROC_DISKSTATS
:
4232 return proc_diskstats_read(buf
, size
, offset
, fi
);
4233 case LXC_TYPE_PROC_SWAPS
:
4234 return proc_swaps_read(buf
, size
, offset
, fi
);
4235 case LXC_TYPE_PROC_LOADAVG
:
4236 return proc_loadavg_read(buf
, size
, offset
, fi
);
4243 * Functions needed to setup cgroups in the __constructor__.
4246 static bool mkdir_p(const char *dir
, mode_t mode
)
4248 const char *tmp
= dir
;
4249 const char *orig
= dir
;
4253 dir
= tmp
+ strspn(tmp
, "/");
4254 tmp
= dir
+ strcspn(dir
, "/");
4255 makeme
= strndup(orig
, dir
- orig
);
4258 if (mkdir(makeme
, mode
) && errno
!= EEXIST
) {
4259 lxcfs_error("Failed to create directory '%s': %s.\n",
4260 makeme
, strerror(errno
));
4265 } while(tmp
!= dir
);
4270 static bool umount_if_mounted(void)
4272 if (umount2(BASEDIR
, MNT_DETACH
) < 0 && errno
!= EINVAL
) {
4273 lxcfs_error("Failed to unmount %s: %s.\n", BASEDIR
, strerror(errno
));
4279 /* __typeof__ should be safe to use with all compilers. */
4280 typedef __typeof__(((struct statfs
*)NULL
)->f_type
) fs_type_magic
;
4281 static bool has_fs_type(const struct statfs
*fs
, fs_type_magic magic_val
)
4283 return (fs
->f_type
== (fs_type_magic
)magic_val
);
4287 * looking at fs/proc_namespace.c, it appears we can
4288 * actually expect the rootfs entry to very specifically contain
4289 * " - rootfs rootfs "
4290 * IIUC, so long as we've chrooted so that rootfs is not our root,
4291 * the rootfs entry should always be skipped in mountinfo contents.
4293 static bool is_on_ramfs(void)
4301 f
= fopen("/proc/self/mountinfo", "r");
4305 while (getline(&line
, &len
, f
) != -1) {
4306 for (p
= line
, i
= 0; p
&& i
< 4; i
++)
4307 p
= strchr(p
+ 1, ' ');
4310 p2
= strchr(p
+ 1, ' ');
4314 if (strcmp(p
+ 1, "/") == 0) {
4315 // this is '/'. is it the ramfs?
4316 p
= strchr(p2
+ 1, '-');
4317 if (p
&& strncmp(p
, "- rootfs rootfs ", 16) == 0) {
4329 static int pivot_enter()
4331 int ret
= -1, oldroot
= -1, newroot
= -1;
4333 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
);
4335 lxcfs_error("%s\n", "Failed to open old root for fchdir.");
4339 newroot
= open(ROOTDIR
, O_DIRECTORY
| O_RDONLY
);
4341 lxcfs_error("%s\n", "Failed to open new root for fchdir.");
4345 /* change into new root fs */
4346 if (fchdir(newroot
) < 0) {
4347 lxcfs_error("Failed to change directory to new rootfs: %s.\n", ROOTDIR
);
4351 /* pivot_root into our new root fs */
4352 if (pivot_root(".", ".") < 0) {
4353 lxcfs_error("pivot_root() syscall failed: %s.\n", strerror(errno
));
4358 * At this point the old-root is mounted on top of our new-root.
4359 * To unmounted it we must not be chdir'd into it, so escape back
4362 if (fchdir(oldroot
) < 0) {
4363 lxcfs_error("%s\n", "Failed to enter old root.");
4367 if (umount2(".", MNT_DETACH
) < 0) {
4368 lxcfs_error("%s\n", "Failed to detach old root.");
4372 if (fchdir(newroot
) < 0) {
4373 lxcfs_error("%s\n", "Failed to re-enter new root.");
4388 static int chroot_enter()
4390 if (mount(ROOTDIR
, "/", NULL
, MS_REC
| MS_BIND
, NULL
)) {
4391 lxcfs_error("Failed to recursively bind-mount %s into /.", ROOTDIR
);
4395 if (chroot(".") < 0) {
4396 lxcfs_error("Call to chroot() failed: %s.\n", strerror(errno
));
4400 if (chdir("/") < 0) {
4401 lxcfs_error("Failed to change directory: %s.\n", strerror(errno
));
4408 static int permute_and_enter(void)
4412 if (statfs("/", &sb
) < 0) {
4413 lxcfs_error("%s\n", "Could not stat / mountpoint.");
4417 /* has_fs_type() is not reliable. When the ramfs is a tmpfs it will
4418 * likely report TMPFS_MAGIC. Hence, when it reports no we still check
4419 * /proc/1/mountinfo. */
4420 if (has_fs_type(&sb
, RAMFS_MAGIC
) || is_on_ramfs())
4421 return chroot_enter();
4423 if (pivot_enter() < 0) {
4424 lxcfs_error("%s\n", "Could not perform pivot root.");
4431 /* Prepare our new clean root. */
4432 static int permute_prepare(void)
4434 if (mkdir(ROOTDIR
, 0700) < 0 && errno
!= EEXIST
) {
4435 lxcfs_error("%s\n", "Failed to create directory for new root.");
4439 if (mount("/", ROOTDIR
, NULL
, MS_BIND
, 0) < 0) {
4440 lxcfs_error("Failed to bind-mount / for new root: %s.\n", strerror(errno
));
4444 if (mount(RUNTIME_PATH
, ROOTDIR RUNTIME_PATH
, NULL
, MS_BIND
, 0) < 0) {
4445 lxcfs_error("Failed to bind-mount /run into new root: %s.\n", strerror(errno
));
4449 if (mount(BASEDIR
, ROOTDIR BASEDIR
, NULL
, MS_REC
| MS_MOVE
, 0) < 0) {
4450 printf("Failed to move " BASEDIR
" into new root: %s.\n", strerror(errno
));
4457 /* Calls chroot() on ramfs, pivot_root() in all other cases. */
4458 static bool permute_root(void)
4460 /* Prepare new root. */
4461 if (permute_prepare() < 0)
4464 /* Pivot into new root. */
4465 if (permute_and_enter() < 0)
4471 static int preserve_mnt_ns(int pid
)
4474 size_t len
= sizeof("/proc/") + 21 + sizeof("/ns/mnt");
4477 ret
= snprintf(path
, len
, "/proc/%d/ns/mnt", pid
);
4478 if (ret
< 0 || (size_t)ret
>= len
)
4481 return open(path
, O_RDONLY
| O_CLOEXEC
);
4484 static bool cgfs_prepare_mounts(void)
4486 if (!mkdir_p(BASEDIR
, 0700)) {
4487 lxcfs_error("%s\n", "Failed to create lxcfs cgroup mountpoint.");
4491 if (!umount_if_mounted()) {
4492 lxcfs_error("%s\n", "Failed to clean up old lxcfs cgroup mountpoint.");
4496 if (unshare(CLONE_NEWNS
) < 0) {
4497 lxcfs_error("Failed to unshare mount namespace: %s.\n", strerror(errno
));
4501 cgroup_mount_ns_fd
= preserve_mnt_ns(getpid());
4502 if (cgroup_mount_ns_fd
< 0) {
4503 lxcfs_error("Failed to preserve mount namespace: %s.\n", strerror(errno
));
4507 if (mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, 0) < 0) {
4508 lxcfs_error("Failed to remount / private: %s.\n", strerror(errno
));
4512 if (mount("tmpfs", BASEDIR
, "tmpfs", 0, "size=100000,mode=700") < 0) {
4513 lxcfs_error("%s\n", "Failed to mount tmpfs over lxcfs cgroup mountpoint.");
4520 static bool cgfs_mount_hierarchies(void)
4526 for (i
= 0; i
< num_hierarchies
; i
++) {
4527 char *controller
= hierarchies
[i
];
4529 clen
= strlen(controller
);
4530 len
= strlen(BASEDIR
) + clen
+ 2;
4531 target
= malloc(len
);
4535 ret
= snprintf(target
, len
, "%s/%s", BASEDIR
, controller
);
4536 if (ret
< 0 || ret
>= len
) {
4540 if (mkdir(target
, 0755) < 0 && errno
!= EEXIST
) {
4544 if (!strcmp(controller
, "unified"))
4545 ret
= mount("none", target
, "cgroup2", 0, NULL
);
4547 ret
= mount(controller
, target
, "cgroup", 0, controller
);
4549 lxcfs_error("Failed mounting cgroup %s: %s\n", controller
, strerror(errno
));
4554 fd_hierarchies
[i
] = open(target
, O_DIRECTORY
);
4555 if (fd_hierarchies
[i
] < 0) {
4564 static bool cgfs_setup_controllers(void)
4566 if (!cgfs_prepare_mounts())
4569 if (!cgfs_mount_hierarchies()) {
4570 lxcfs_error("%s\n", "Failed to set up private lxcfs cgroup mounts.");
4574 if (!permute_root())
4580 static void __attribute__((constructor
)) collect_and_mount_subsystems(void)
4583 char *cret
, *line
= NULL
;
4584 char cwd
[MAXPATHLEN
];
4586 int i
, init_ns
= -1;
4587 bool found_unified
= false;
4589 if ((f
= fopen("/proc/self/cgroup", "r")) == NULL
) {
4590 lxcfs_error("Error opening /proc/self/cgroup: %s\n", strerror(errno
));
4594 while (getline(&line
, &len
, f
) != -1) {
4597 p
= strchr(line
, ':');
4603 p2
= strrchr(p
, ':');
4608 /* With cgroupv2 /proc/self/cgroup can contain entries of the
4609 * form: 0::/ This will cause lxcfs to fail the cgroup mounts
4610 * because it parses out the empty string "" and later on passes
4611 * it to mount(). Let's skip such entries.
4613 if (!strcmp(p
, "") && !strcmp(idx
, "0") && !found_unified
) {
4614 found_unified
= true;
4618 if (!store_hierarchy(line
, p
))
4622 /* Preserve initial namespace. */
4623 init_ns
= preserve_mnt_ns(getpid());
4625 lxcfs_error("%s\n", "Failed to preserve initial mount namespace.");
4629 fd_hierarchies
= malloc(sizeof(int) * num_hierarchies
);
4630 if (!fd_hierarchies
) {
4631 lxcfs_error("%s\n", strerror(errno
));
4635 for (i
= 0; i
< num_hierarchies
; i
++)
4636 fd_hierarchies
[i
] = -1;
4638 cret
= getcwd(cwd
, MAXPATHLEN
);
4640 lxcfs_debug("Could not retrieve current working directory: %s.\n", strerror(errno
));
4642 /* This function calls unshare(CLONE_NEWNS) our initial mount namespace
4643 * to privately mount lxcfs cgroups. */
4644 if (!cgfs_setup_controllers()) {
4645 lxcfs_error("%s\n", "Failed to setup private cgroup mounts for lxcfs.");
4649 if (setns(init_ns
, 0) < 0) {
4650 lxcfs_error("Failed to switch back to initial mount namespace: %s.\n", strerror(errno
));
4654 if (!cret
|| chdir(cwd
) < 0)
4655 lxcfs_debug("Could not change back to original working directory: %s.\n", strerror(errno
));
4666 static void __attribute__((destructor
)) free_subsystems(void)
4670 lxcfs_debug("%s\n", "Running destructor for liblxcfs.");
4672 for (i
= 0; i
< num_hierarchies
; i
++) {
4674 free(hierarchies
[i
]);
4675 if (fd_hierarchies
&& fd_hierarchies
[i
] >= 0)
4676 close(fd_hierarchies
[i
]);
4679 free(fd_hierarchies
);
4681 if (cgroup_mount_ns_fd
>= 0)
4682 close(cgroup_mount_ns_fd
);