3 * Copyright © 2014-2016 Canonical, Inc
4 * Author: Serge Hallyn <serge.hallyn@ubuntu.com>
6 * See COPYING file for details.
9 #define FUSE_USE_VERSION 26
25 #include <linux/sched.h>
26 #include <sys/epoll.h>
28 #include <sys/mount.h>
29 #include <sys/param.h>
30 #include <sys/socket.h>
31 #include <sys/syscall.h>
34 #include "config.h" // for VERSION
36 /* Define pivot_root() if missing from the C library */
37 #ifndef HAVE_PIVOT_ROOT
38 static int pivot_root(const char * new_root
, const char * put_old
)
40 #ifdef __NR_pivot_root
41 return syscall(__NR_pivot_root
, new_root
, put_old
);
48 extern int pivot_root(const char * new_root
, const char * put_old
);
54 LXC_TYPE_PROC_MEMINFO
,
55 LXC_TYPE_PROC_CPUINFO
,
58 LXC_TYPE_PROC_DISKSTATS
,
67 char *buf
; // unused as of yet
69 int size
; //actual data size
73 /* reserve buffer size, for cpuall in /proc/stat */
74 #define BUF_RESERVE_SIZE 256
77 * A table caching which pid is init for a pid namespace.
78 * When looking up which pid is init for $qpid, we first
79 * 1. Stat /proc/$qpid/ns/pid.
80 * 2. Check whether the ino_t is in our store.
81 * a. if not, fork a child in qpid's ns to send us
82 * ucred.pid = 1, and read the initpid. Cache
83 * initpid and creation time for /proc/initpid
84 * in a new store entry.
85 * b. if so, verify that /proc/initpid still matches
86 * what we have saved. If not, clear the store
87 * entry and go back to a. If so, return the
90 struct pidns_init_store
{
91 ino_t ino
; // inode number for /proc/$pid/ns/pid
92 pid_t initpid
; // the pid of nit in that ns
93 long int ctime
; // the time at which /proc/$initpid was created
94 struct pidns_init_store
*next
;
98 /* lol - look at how they are allocated in the kernel */
99 #define PIDNS_HASH_SIZE 4096
100 #define HASH(x) ((x) % PIDNS_HASH_SIZE)
102 static struct pidns_init_store
*pidns_hash_table
[PIDNS_HASH_SIZE
];
103 static pthread_mutex_t pidns_store_mutex
= PTHREAD_MUTEX_INITIALIZER
;
104 static void lock_mutex(pthread_mutex_t
*l
)
108 if ((ret
= pthread_mutex_lock(l
)) != 0) {
109 lxcfs_error("returned:%d %s\n", ret
, strerror(ret
));
114 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
115 * Number of hierarchies mounted. */
116 static int num_hierarchies
;
118 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
119 * Hierachies mounted {cpuset, blkio, ...}:
120 * Initialized via __constructor__ collect_and_mount_subsystems(). */
121 static char **hierarchies
;
123 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
124 * Open file descriptors:
125 * @fd_hierarchies[i] refers to cgroup @hierarchies[i]. They are mounted in a
126 * private mount namespace.
127 * Initialized via __constructor__ collect_and_mount_subsystems().
128 * @fd_hierarchies[i] can be used to perform file operations on the cgroup
129 * mounts and respective files in the private namespace even when located in
130 * another namespace using the *at() family of functions
131 * {openat(), fchownat(), ...}. */
132 static int *fd_hierarchies
;
134 static void unlock_mutex(pthread_mutex_t
*l
)
138 if ((ret
= pthread_mutex_unlock(l
)) != 0) {
139 lxcfs_error("returned:%d %s\n", ret
, strerror(ret
));
144 static void store_lock(void)
146 lock_mutex(&pidns_store_mutex
);
149 static void store_unlock(void)
151 unlock_mutex(&pidns_store_mutex
);
154 /* Must be called under store_lock */
155 static bool initpid_still_valid(struct pidns_init_store
*e
, struct stat
*nsfdsb
)
160 snprintf(fnam
, 100, "/proc/%d", e
->initpid
);
161 if (stat(fnam
, &initsb
) < 0)
164 lxcfs_debug("Comparing ctime %ld == %ld for pid %d.\n", e
->ctime
,
165 initsb
.st_ctime
, e
->initpid
);
167 if (e
->ctime
!= initsb
.st_ctime
)
172 /* Must be called under store_lock */
173 static void remove_initpid(struct pidns_init_store
*e
)
175 struct pidns_init_store
*tmp
;
178 lxcfs_debug("Remove_initpid: removing entry for %d.\n", e
->initpid
);
181 if (pidns_hash_table
[h
] == e
) {
182 pidns_hash_table
[h
] = e
->next
;
187 tmp
= pidns_hash_table
[h
];
189 if (tmp
->next
== e
) {
199 /* Must be called under store_lock */
200 static void prune_initpid_store(void)
202 static long int last_prune
= 0;
203 struct pidns_init_store
*e
, *prev
, *delme
;
204 long int now
, threshold
;
208 last_prune
= time(NULL
);
212 if (now
< last_prune
+ PURGE_SECS
)
215 lxcfs_debug("%s\n", "Pruning.");
218 threshold
= now
- 2 * PURGE_SECS
;
220 for (i
= 0; i
< PIDNS_HASH_SIZE
; i
++) {
221 for (prev
= NULL
, e
= pidns_hash_table
[i
]; e
; ) {
222 if (e
->lastcheck
< threshold
) {
224 lxcfs_debug("Removing cached entry for %d.\n", e
->initpid
);
228 prev
->next
= e
->next
;
230 pidns_hash_table
[i
] = e
->next
;
241 /* Must be called under store_lock */
242 static void save_initpid(struct stat
*sb
, pid_t pid
)
244 struct pidns_init_store
*e
;
249 lxcfs_debug("Save_initpid: adding entry for %d.\n", pid
);
251 snprintf(fpath
, 100, "/proc/%d", pid
);
252 if (stat(fpath
, &procsb
) < 0)
255 e
= malloc(sizeof(*e
));
259 e
->ctime
= procsb
.st_ctime
;
261 e
->next
= pidns_hash_table
[h
];
262 e
->lastcheck
= time(NULL
);
263 pidns_hash_table
[h
] = e
;
267 * Given the stat(2) info for a nsfd pid inode, lookup the init_pid_store
268 * entry for the inode number and creation time. Verify that the init pid
269 * is still valid. If not, remove it. Return the entry if valid, NULL
271 * Must be called under store_lock
273 static struct pidns_init_store
*lookup_verify_initpid(struct stat
*sb
)
275 int h
= HASH(sb
->st_ino
);
276 struct pidns_init_store
*e
= pidns_hash_table
[h
];
279 if (e
->ino
== sb
->st_ino
) {
280 if (initpid_still_valid(e
, sb
)) {
281 e
->lastcheck
= time(NULL
);
293 static int is_dir(const char *path
, int fd
)
296 int ret
= fstatat(fd
, path
, &statbuf
, fd
);
297 if (ret
== 0 && S_ISDIR(statbuf
.st_mode
))
302 static char *must_copy_string(const char *str
)
314 static inline void drop_trailing_newlines(char *s
)
318 for (l
=strlen(s
); l
>0 && s
[l
-1] == '\n'; l
--)
322 #define BATCH_SIZE 50
323 static void dorealloc(char **mem
, size_t oldlen
, size_t newlen
)
325 int newbatches
= (newlen
/ BATCH_SIZE
) + 1;
326 int oldbatches
= (oldlen
/ BATCH_SIZE
) + 1;
328 if (!*mem
|| newbatches
> oldbatches
) {
331 tmp
= realloc(*mem
, newbatches
* BATCH_SIZE
);
336 static void append_line(char **contents
, size_t *len
, char *line
, ssize_t linelen
)
338 size_t newlen
= *len
+ linelen
;
339 dorealloc(contents
, *len
, newlen
+ 1);
340 memcpy(*contents
+ *len
, line
, linelen
+1);
344 static char *slurp_file(const char *from
, int fd
)
347 char *contents
= NULL
;
348 FILE *f
= fdopen(fd
, "r");
349 size_t len
= 0, fulllen
= 0;
355 while ((linelen
= getline(&line
, &len
, f
)) != -1) {
356 append_line(&contents
, &fulllen
, line
, linelen
);
361 drop_trailing_newlines(contents
);
366 static bool write_string(const char *fnam
, const char *string
, int fd
)
371 if (!(f
= fdopen(fd
, "w")))
373 len
= strlen(string
);
374 ret
= fwrite(string
, 1, len
, f
);
376 lxcfs_error("Error writing to file: %s\n", strerror(errno
));
381 lxcfs_error("Error writing to file: %s\n", strerror(errno
));
394 static bool store_hierarchy(char *stridx
, char *h
)
396 if (num_hierarchies
% ALLOC_NUM
== 0) {
397 size_t n
= (num_hierarchies
/ ALLOC_NUM
) + 1;
399 char **tmp
= realloc(hierarchies
, n
* sizeof(char *));
401 lxcfs_error("%s\n", strerror(errno
));
407 hierarchies
[num_hierarchies
++] = must_copy_string(h
);
411 static void print_subsystems(void)
415 fprintf(stderr
, "hierarchies:\n");
416 for (i
= 0; i
< num_hierarchies
; i
++) {
418 fprintf(stderr
, " %2d: fd: %3d: %s\n", i
,
419 fd_hierarchies
[i
], hierarchies
[i
]);
423 static bool in_comma_list(const char *needle
, const char *haystack
)
425 const char *s
= haystack
, *e
;
426 size_t nlen
= strlen(needle
);
428 while (*s
&& (e
= strchr(s
, ','))) {
433 if (strncmp(needle
, s
, nlen
) == 0)
437 if (strcmp(needle
, s
) == 0)
442 /* do we need to do any massaging here? I'm not sure... */
443 /* Return the mounted controller and store the corresponding open file descriptor
444 * referring to the controller mountpoint in the private lxcfs namespace in
447 static char *find_mounted_controller(const char *controller
, int *cfd
)
451 for (i
= 0; i
< num_hierarchies
; i
++) {
454 if (strcmp(hierarchies
[i
], controller
) == 0) {
455 *cfd
= fd_hierarchies
[i
];
456 return hierarchies
[i
];
458 if (in_comma_list(controller
, hierarchies
[i
])) {
459 *cfd
= fd_hierarchies
[i
];
460 return hierarchies
[i
];
467 bool cgfs_set_value(const char *controller
, const char *cgroup
, const char *file
,
474 tmpc
= find_mounted_controller(controller
, &cfd
);
478 /* Make sure we pass a relative path to *at() family of functions.
479 * . + /cgroup + / + file + \0
481 len
= strlen(cgroup
) + strlen(file
) + 3;
483 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, file
);
484 if (ret
< 0 || (size_t)ret
>= len
)
487 fd
= openat(cfd
, fnam
, O_WRONLY
);
491 return write_string(fnam
, value
, fd
);
494 // Chown all the files in the cgroup directory. We do this when we create
495 // a cgroup on behalf of a user.
496 static void chown_all_cgroup_files(const char *dirname
, uid_t uid
, gid_t gid
, int fd
)
498 struct dirent
*direntp
;
499 char path
[MAXPATHLEN
];
504 len
= strlen(dirname
);
505 if (len
>= MAXPATHLEN
) {
506 lxcfs_error("Pathname too long: %s\n", dirname
);
510 fd1
= openat(fd
, dirname
, O_DIRECTORY
);
516 lxcfs_error("Failed to open %s\n", dirname
);
520 while ((direntp
= readdir(d
))) {
521 if (!strcmp(direntp
->d_name
, ".") || !strcmp(direntp
->d_name
, ".."))
523 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
524 if (ret
< 0 || ret
>= MAXPATHLEN
) {
525 lxcfs_error("Pathname too long under %s\n", dirname
);
528 if (fchownat(fd
, path
, uid
, gid
, 0) < 0)
529 lxcfs_error("Failed to chown file %s to %u:%u", path
, uid
, gid
);
534 int cgfs_create(const char *controller
, const char *cg
, uid_t uid
, gid_t gid
)
540 tmpc
= find_mounted_controller(controller
, &cfd
);
544 /* Make sure we pass a relative path to *at() family of functions.
547 len
= strlen(cg
) + 2;
548 dirnam
= alloca(len
);
549 snprintf(dirnam
, len
, "%s%s", *cg
== '/' ? "." : "", cg
);
551 if (mkdirat(cfd
, dirnam
, 0755) < 0)
554 if (uid
== 0 && gid
== 0)
557 if (fchownat(cfd
, dirnam
, uid
, gid
, 0) < 0)
560 chown_all_cgroup_files(dirnam
, uid
, gid
, cfd
);
565 static bool recursive_rmdir(const char *dirname
, int fd
, const int cfd
)
567 struct dirent
*direntp
;
570 char pathname
[MAXPATHLEN
];
573 dupfd
= dup(fd
); // fdopendir() does bad things once it uses an fd.
577 dir
= fdopendir(dupfd
);
579 lxcfs_debug("Failed to open %s: %s.\n", dirname
, strerror(errno
));
584 while ((direntp
= readdir(dir
))) {
588 if (!strcmp(direntp
->d_name
, ".") ||
589 !strcmp(direntp
->d_name
, ".."))
592 rc
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
593 if (rc
< 0 || rc
>= MAXPATHLEN
) {
594 lxcfs_error("%s\n", "Pathname too long.");
598 rc
= fstatat(cfd
, pathname
, &mystat
, AT_SYMLINK_NOFOLLOW
);
600 lxcfs_debug("Failed to stat %s: %s.\n", pathname
, strerror(errno
));
603 if (S_ISDIR(mystat
.st_mode
))
604 if (!recursive_rmdir(pathname
, fd
, cfd
))
605 lxcfs_debug("Error removing %s.\n", pathname
);
609 if (closedir(dir
) < 0) {
610 lxcfs_error("Failed to close directory %s: %s\n", dirname
, strerror(errno
));
614 if (unlinkat(cfd
, dirname
, AT_REMOVEDIR
) < 0) {
615 lxcfs_debug("Failed to delete %s: %s.\n", dirname
, strerror(errno
));
624 bool cgfs_remove(const char *controller
, const char *cg
)
631 tmpc
= find_mounted_controller(controller
, &cfd
);
635 /* Make sure we pass a relative path to *at() family of functions.
638 len
= strlen(cg
) + 2;
639 dirnam
= alloca(len
);
640 snprintf(dirnam
, len
, "%s%s", *cg
== '/' ? "." : "", cg
);
642 fd
= openat(cfd
, dirnam
, O_DIRECTORY
);
646 bret
= recursive_rmdir(dirnam
, fd
, cfd
);
651 bool cgfs_chmod_file(const char *controller
, const char *file
, mode_t mode
)
655 char *pathname
, *tmpc
;
657 tmpc
= find_mounted_controller(controller
, &cfd
);
661 /* Make sure we pass a relative path to *at() family of functions.
664 len
= strlen(file
) + 2;
665 pathname
= alloca(len
);
666 snprintf(pathname
, len
, "%s%s", *file
== '/' ? "." : "", file
);
667 if (fchmodat(cfd
, pathname
, mode
, 0) < 0)
672 static int chown_tasks_files(const char *dirname
, uid_t uid
, gid_t gid
, int fd
)
677 len
= strlen(dirname
) + strlen("/cgroup.procs") + 1;
679 snprintf(fname
, len
, "%s/tasks", dirname
);
680 if (fchownat(fd
, fname
, uid
, gid
, 0) != 0)
682 snprintf(fname
, len
, "%s/cgroup.procs", dirname
);
683 if (fchownat(fd
, fname
, uid
, gid
, 0) != 0)
688 int cgfs_chown_file(const char *controller
, const char *file
, uid_t uid
, gid_t gid
)
692 char *pathname
, *tmpc
;
694 tmpc
= find_mounted_controller(controller
, &cfd
);
698 /* Make sure we pass a relative path to *at() family of functions.
701 len
= strlen(file
) + 2;
702 pathname
= alloca(len
);
703 snprintf(pathname
, len
, "%s%s", *file
== '/' ? "." : "", file
);
704 if (fchownat(cfd
, pathname
, uid
, gid
, 0) < 0)
707 if (is_dir(pathname
, cfd
))
708 // like cgmanager did, we want to chown the tasks file as well
709 return chown_tasks_files(pathname
, uid
, gid
, cfd
);
714 FILE *open_pids_file(const char *controller
, const char *cgroup
)
718 char *pathname
, *tmpc
;
720 tmpc
= find_mounted_controller(controller
, &cfd
);
724 /* Make sure we pass a relative path to *at() family of functions.
725 * . + /cgroup + / "cgroup.procs" + \0
727 len
= strlen(cgroup
) + strlen("cgroup.procs") + 3;
728 pathname
= alloca(len
);
729 snprintf(pathname
, len
, "%s%s/cgroup.procs", *cgroup
== '/' ? "." : "", cgroup
);
731 fd
= openat(cfd
, pathname
, O_WRONLY
);
735 return fdopen(fd
, "w");
738 static bool cgfs_iterate_cgroup(const char *controller
, const char *cgroup
, bool directories
,
739 void ***list
, size_t typesize
,
740 void* (*iterator
)(const char*, const char*, const char*))
745 char pathname
[MAXPATHLEN
];
746 size_t sz
= 0, asz
= 0;
747 struct dirent
*dirent
;
750 tmpc
= find_mounted_controller(controller
, &cfd
);
755 /* Make sure we pass a relative path to *at() family of functions. */
756 len
= strlen(cgroup
) + 1 /* . */ + 1 /* \0 */;
758 ret
= snprintf(cg
, len
, "%s%s", *cgroup
== '/' ? "." : "", cgroup
);
759 if (ret
< 0 || (size_t)ret
>= len
) {
760 lxcfs_error("Pathname too long under %s\n", cgroup
);
764 fd
= openat(cfd
, cg
, O_DIRECTORY
);
772 while ((dirent
= readdir(dir
))) {
775 if (!strcmp(dirent
->d_name
, ".") ||
776 !strcmp(dirent
->d_name
, ".."))
779 ret
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", cg
, dirent
->d_name
);
780 if (ret
< 0 || ret
>= MAXPATHLEN
) {
781 lxcfs_error("Pathname too long under %s\n", cg
);
785 ret
= fstatat(cfd
, pathname
, &mystat
, AT_SYMLINK_NOFOLLOW
);
787 lxcfs_error("Failed to stat %s: %s\n", pathname
, strerror(errno
));
790 if ((!directories
&& !S_ISREG(mystat
.st_mode
)) ||
791 (directories
&& !S_ISDIR(mystat
.st_mode
)))
798 tmp
= realloc(*list
, asz
* typesize
);
802 (*list
)[sz
] = (*iterator
)(controller
, cg
, dirent
->d_name
);
803 (*list
)[sz
+1] = NULL
;
806 if (closedir(dir
) < 0) {
807 lxcfs_error("Failed closedir for %s: %s\n", cgroup
, strerror(errno
));
813 static void *make_children_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
817 dup
= strdup(dir_entry
);
822 bool cgfs_list_children(const char *controller
, const char *cgroup
, char ***list
)
824 return cgfs_iterate_cgroup(controller
, cgroup
, true, (void***)list
, sizeof(*list
), &make_children_list_entry
);
827 void free_key(struct cgfs_files
*k
)
835 void free_keys(struct cgfs_files
**keys
)
841 for (i
= 0; keys
[i
]; i
++) {
847 bool cgfs_get_value(const char *controller
, const char *cgroup
, const char *file
, char **value
)
853 tmpc
= find_mounted_controller(controller
, &cfd
);
857 /* Make sure we pass a relative path to *at() family of functions.
858 * . + /cgroup + / + file + \0
860 len
= strlen(cgroup
) + strlen(file
) + 3;
862 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, file
);
863 if (ret
< 0 || (size_t)ret
>= len
)
866 fd
= openat(cfd
, fnam
, O_RDONLY
);
870 *value
= slurp_file(fnam
, fd
);
871 return *value
!= NULL
;
874 struct cgfs_files
*cgfs_get_key(const char *controller
, const char *cgroup
, const char *file
)
880 struct cgfs_files
*newkey
;
882 tmpc
= find_mounted_controller(controller
, &cfd
);
886 if (file
&& *file
== '/')
889 if (file
&& strchr(file
, '/'))
892 /* Make sure we pass a relative path to *at() family of functions.
893 * . + /cgroup + / + file + \0
895 len
= strlen(cgroup
) + 3;
897 len
+= strlen(file
) + 1;
899 snprintf(fnam
, len
, "%s%s%s%s", *cgroup
== '/' ? "." : "", cgroup
,
900 file
? "/" : "", file
? file
: "");
902 ret
= fstatat(cfd
, fnam
, &sb
, 0);
907 newkey
= malloc(sizeof(struct cgfs_files
));
910 newkey
->name
= must_copy_string(file
);
911 else if (strrchr(cgroup
, '/'))
912 newkey
->name
= must_copy_string(strrchr(cgroup
, '/'));
914 newkey
->name
= must_copy_string(cgroup
);
915 newkey
->uid
= sb
.st_uid
;
916 newkey
->gid
= sb
.st_gid
;
917 newkey
->mode
= sb
.st_mode
;
922 static void *make_key_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
924 struct cgfs_files
*entry
= cgfs_get_key(controller
, cgroup
, dir_entry
);
926 lxcfs_error("Error getting files under %s:%s\n", controller
,
932 bool cgfs_list_keys(const char *controller
, const char *cgroup
, struct cgfs_files
***keys
)
934 return cgfs_iterate_cgroup(controller
, cgroup
, false, (void***)keys
, sizeof(*keys
), &make_key_list_entry
);
937 bool is_child_cgroup(const char *controller
, const char *cgroup
, const char *f
)
945 tmpc
= find_mounted_controller(controller
, &cfd
);
949 /* Make sure we pass a relative path to *at() family of functions.
950 * . + /cgroup + / + f + \0
952 len
= strlen(cgroup
) + strlen(f
) + 3;
954 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, f
);
955 if (ret
< 0 || (size_t)ret
>= len
)
958 ret
= fstatat(cfd
, fnam
, &sb
, 0);
959 if (ret
< 0 || !S_ISDIR(sb
.st_mode
))
965 #define SEND_CREDS_OK 0
966 #define SEND_CREDS_NOTSK 1
967 #define SEND_CREDS_FAIL 2
968 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
);
969 static int wait_for_pid(pid_t pid
);
970 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
);
971 static int send_creds_clone_wrapper(void *arg
);
974 * clone a task which switches to @task's namespace and writes '1'.
975 * over a unix sock so we can read the task's reaper's pid in our
978 * Note: glibc's fork() does not respect pidns, which can lead to failed
979 * assertions inside glibc (and thus failed forks) if the child's pid in
980 * the pidns and the parent pid outside are identical. Using clone prevents
983 static void write_task_init_pid_exit(int sock
, pid_t target
)
988 size_t stack_size
= sysconf(_SC_PAGESIZE
);
989 void *stack
= alloca(stack_size
);
991 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", (int)target
);
992 if (ret
< 0 || ret
>= sizeof(fnam
))
995 fd
= open(fnam
, O_RDONLY
);
997 perror("write_task_init_pid_exit open of ns/pid");
1001 perror("write_task_init_pid_exit setns 1");
1005 pid
= clone(send_creds_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &sock
);
1009 if (!wait_for_pid(pid
))
1015 static int send_creds_clone_wrapper(void *arg
) {
1018 int sock
= *(int *)arg
;
1020 /* we are the child */
1025 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
)
1030 static pid_t
get_init_pid_for_task(pid_t task
)
1038 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
1039 perror("socketpair");
1048 write_task_init_pid_exit(sock
[0], task
);
1052 if (!recv_creds(sock
[1], &cred
, &v
))
1064 static pid_t
lookup_initpid_in_store(pid_t qpid
)
1068 struct pidns_init_store
*e
;
1071 snprintf(fnam
, 100, "/proc/%d/ns/pid", qpid
);
1073 if (stat(fnam
, &sb
) < 0)
1075 e
= lookup_verify_initpid(&sb
);
1077 answer
= e
->initpid
;
1080 answer
= get_init_pid_for_task(qpid
);
1082 save_initpid(&sb
, answer
);
1085 /* we prune at end in case we are returning
1086 * the value we were about to return */
1087 prune_initpid_store();
1092 static int wait_for_pid(pid_t pid
)
1100 ret
= waitpid(pid
, &status
, 0);
1108 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
1115 * append pid to *src.
1116 * src: a pointer to a char* in which ot append the pid.
1117 * sz: the number of characters printed so far, minus trailing \0.
1118 * asz: the allocated size so far
1119 * pid: the pid to append
1121 static void must_strcat_pid(char **src
, size_t *sz
, size_t *asz
, pid_t pid
)
1125 int tmplen
= sprintf(tmp
, "%d\n", (int)pid
);
1127 if (!*src
|| tmplen
+ *sz
+ 1 >= *asz
) {
1130 tmp
= realloc(*src
, *asz
+ BUF_RESERVE_SIZE
);
1133 *asz
+= BUF_RESERVE_SIZE
;
1135 memcpy((*src
) +*sz
, tmp
, tmplen
+1); /* include the \0 */
1140 * Given a open file * to /proc/pid/{u,g}id_map, and an id
1141 * valid in the caller's namespace, return the id mapped into
1143 * Returns the mapped id, or -1 on error.
1146 convert_id_to_ns(FILE *idfile
, unsigned int in_id
)
1148 unsigned int nsuid
, // base id for a range in the idfile's namespace
1149 hostuid
, // base id for a range in the caller's namespace
1150 count
; // number of ids in this range
1154 fseek(idfile
, 0L, SEEK_SET
);
1155 while (fgets(line
, 400, idfile
)) {
1156 ret
= sscanf(line
, "%u %u %u\n", &nsuid
, &hostuid
, &count
);
1159 if (hostuid
+ count
< hostuid
|| nsuid
+ count
< nsuid
) {
1161 * uids wrapped around - unexpected as this is a procfile,
1164 lxcfs_error("pid wrapparound at entry %u %u %u in %s\n",
1165 nsuid
, hostuid
, count
, line
);
1168 if (hostuid
<= in_id
&& hostuid
+count
> in_id
) {
1170 * now since hostuid <= in_id < hostuid+count, and
1171 * hostuid+count and nsuid+count do not wrap around,
1172 * we know that nsuid+(in_id-hostuid) which must be
1173 * less that nsuid+(count) must not wrap around
1175 return (in_id
- hostuid
) + nsuid
;
1184 * for is_privileged_over,
1185 * specify whether we require the calling uid to be root in his
1188 #define NS_ROOT_REQD true
1189 #define NS_ROOT_OPT false
1193 static bool is_privileged_over(pid_t pid
, uid_t uid
, uid_t victim
, bool req_ns_root
)
1195 char fpath
[PROCLEN
];
1197 bool answer
= false;
1200 if (victim
== -1 || uid
== -1)
1204 * If the request is one not requiring root in the namespace,
1205 * then having the same uid suffices. (i.e. uid 1000 has write
1206 * access to files owned by uid 1000
1208 if (!req_ns_root
&& uid
== victim
)
1211 ret
= snprintf(fpath
, PROCLEN
, "/proc/%d/uid_map", pid
);
1212 if (ret
< 0 || ret
>= PROCLEN
)
1214 FILE *f
= fopen(fpath
, "r");
1218 /* if caller's not root in his namespace, reject */
1219 nsuid
= convert_id_to_ns(f
, uid
);
1224 * If victim is not mapped into caller's ns, reject.
1225 * XXX I'm not sure this check is needed given that fuse
1226 * will be sending requests where the vfs has converted
1228 nsuid
= convert_id_to_ns(f
, victim
);
1239 static bool perms_include(int fmode
, mode_t req_mode
)
1243 switch (req_mode
& O_ACCMODE
) {
1251 r
= S_IROTH
| S_IWOTH
;
1256 return ((fmode
& r
) == r
);
1262 * querycg is /a/b/c/d/e
1265 static char *get_next_cgroup_dir(const char *taskcg
, const char *querycg
)
1269 if (strlen(taskcg
) <= strlen(querycg
)) {
1270 lxcfs_error("%s\n", "I was fed bad input.");
1274 if ((strcmp(querycg
, "/") == 0) || (strcmp(querycg
, "./") == 0))
1275 start
= strdup(taskcg
+ 1);
1277 start
= strdup(taskcg
+ strlen(querycg
) + 1);
1280 end
= strchr(start
, '/');
1286 static void stripnewline(char *x
)
1288 size_t l
= strlen(x
);
1289 if (l
&& x
[l
-1] == '\n')
1293 static char *get_pid_cgroup(pid_t pid
, const char *contrl
)
1298 char *answer
= NULL
;
1302 const char *h
= find_mounted_controller(contrl
, &cfd
);
1306 ret
= snprintf(fnam
, PROCLEN
, "/proc/%d/cgroup", pid
);
1307 if (ret
< 0 || ret
>= PROCLEN
)
1309 if (!(f
= fopen(fnam
, "r")))
1312 while (getline(&line
, &len
, f
) != -1) {
1316 c1
= strchr(line
, ':');
1320 c2
= strchr(c1
, ':');
1324 if (strcmp(c1
, h
) != 0)
1329 answer
= strdup(c2
);
1341 * check whether a fuse context may access a cgroup dir or file
1343 * If file is not null, it is a cgroup file to check under cg.
1344 * If file is null, then we are checking perms on cg itself.
1346 * For files we can check the mode of the list_keys result.
1347 * For cgroups, we must make assumptions based on the files under the
1348 * cgroup, because cgmanager doesn't tell us ownership/perms of cgroups
1351 static bool fc_may_access(struct fuse_context
*fc
, const char *contrl
, const char *cg
, const char *file
, mode_t mode
)
1353 struct cgfs_files
*k
= NULL
;
1356 k
= cgfs_get_key(contrl
, cg
, file
);
1360 if (is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
1361 if (perms_include(k
->mode
>> 6, mode
)) {
1366 if (fc
->gid
== k
->gid
) {
1367 if (perms_include(k
->mode
>> 3, mode
)) {
1372 ret
= perms_include(k
->mode
, mode
);
1379 #define INITSCOPE "/init.scope"
1380 static void prune_init_slice(char *cg
)
1383 size_t cg_len
= strlen(cg
), initscope_len
= strlen(INITSCOPE
);
1385 if (cg_len
< initscope_len
)
1388 point
= cg
+ cg_len
- initscope_len
;
1389 if (strcmp(point
, INITSCOPE
) == 0) {
1398 * If pid is in /a/b/c/d, he may only act on things under cg=/a/b/c/d.
1399 * If pid is in /a, he may act on /a/b, but not on /b.
1400 * if the answer is false and nextcg is not NULL, then *nextcg will point
1401 * to a string containing the next cgroup directory under cg, which must be
1402 * freed by the caller.
1404 static bool caller_is_in_ancestor(pid_t pid
, const char *contrl
, const char *cg
, char **nextcg
)
1406 bool answer
= false;
1407 char *c2
= get_pid_cgroup(pid
, contrl
);
1412 prune_init_slice(c2
);
1415 * callers pass in '/' or './' (openat()) for root cgroup, otherwise
1416 * they pass in a cgroup without leading '/'
1418 * The original line here was:
1419 * linecmp = *cg == '/' ? c2 : c2+1;
1420 * TODO: I'm not sure why you'd want to increment when *cg != '/'?
1421 * Serge, do you know?
1423 if (*cg
== '/' || !strncmp(cg
, "./", 2))
1427 if (strncmp(linecmp
, cg
, strlen(linecmp
)) != 0) {
1429 *nextcg
= get_next_cgroup_dir(linecmp
, cg
);
1441 * If pid is in /a/b/c, he may see that /a exists, but not /b or /a/c.
1443 static bool caller_may_see_dir(pid_t pid
, const char *contrl
, const char *cg
)
1445 bool answer
= false;
1447 size_t target_len
, task_len
;
1449 if (strcmp(cg
, "/") == 0 || strcmp(cg
, "./") == 0)
1452 c2
= get_pid_cgroup(pid
, contrl
);
1455 prune_init_slice(c2
);
1458 target_len
= strlen(cg
);
1459 task_len
= strlen(task_cg
);
1460 if (task_len
== 0) {
1461 /* Task is in the root cg, it can see everything. This case is
1462 * not handled by the strmcps below, since they test for the
1463 * last /, but that is the first / that we've chopped off
1469 if (strcmp(cg
, task_cg
) == 0) {
1473 if (target_len
< task_len
) {
1474 /* looking up a parent dir */
1475 if (strncmp(task_cg
, cg
, target_len
) == 0 && task_cg
[target_len
] == '/')
1479 if (target_len
> task_len
) {
1480 /* looking up a child dir */
1481 if (strncmp(task_cg
, cg
, task_len
) == 0 && cg
[task_len
] == '/')
1492 * given /cgroup/freezer/a/b, return "freezer".
1493 * the returned char* should NOT be freed.
1495 static char *pick_controller_from_path(struct fuse_context
*fc
, const char *path
)
1498 char *contr
, *slash
;
1500 if (strlen(path
) < 9) {
1504 if (*(path
+ 7) != '/') {
1509 contr
= strdupa(p1
);
1514 slash
= strstr(contr
, "/");
1519 for (i
= 0; i
< num_hierarchies
; i
++) {
1520 if (hierarchies
[i
] && strcmp(hierarchies
[i
], contr
) == 0)
1521 return hierarchies
[i
];
1528 * Find the start of cgroup in /cgroup/controller/the/cgroup/path
1529 * Note that the returned value may include files (keynames) etc
1531 static const char *find_cgroup_in_path(const char *path
)
1535 if (strlen(path
) < 9) {
1539 p1
= strstr(path
+ 8, "/");
1549 * split the last path element from the path in @cg.
1550 * @dir is newly allocated and should be freed, @last not
1552 static void get_cgdir_and_path(const char *cg
, char **dir
, char **last
)
1559 *last
= strrchr(cg
, '/');
1564 p
= strrchr(*dir
, '/');
1569 * FUSE ops for /cgroup
1572 int cg_getattr(const char *path
, struct stat
*sb
)
1574 struct timespec now
;
1575 struct fuse_context
*fc
= fuse_get_context();
1576 char * cgdir
= NULL
;
1577 char *last
= NULL
, *path1
, *path2
;
1578 struct cgfs_files
*k
= NULL
;
1580 const char *controller
= NULL
;
1587 memset(sb
, 0, sizeof(struct stat
));
1589 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
1592 sb
->st_uid
= sb
->st_gid
= 0;
1593 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
1596 if (strcmp(path
, "/cgroup") == 0) {
1597 sb
->st_mode
= S_IFDIR
| 00755;
1602 controller
= pick_controller_from_path(fc
, path
);
1605 cgroup
= find_cgroup_in_path(path
);
1607 /* this is just /cgroup/controller, return it as a dir */
1608 sb
->st_mode
= S_IFDIR
| 00755;
1613 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
1623 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1626 /* check that cgcopy is either a child cgroup of cgdir, or listed in its keys.
1627 * Then check that caller's cgroup is under path if last is a child
1628 * cgroup, or cgdir if last is a file */
1630 if (is_child_cgroup(controller
, path1
, path2
)) {
1631 if (!caller_may_see_dir(initpid
, controller
, cgroup
)) {
1635 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
1636 /* this is just /cgroup/controller, return it as a dir */
1637 sb
->st_mode
= S_IFDIR
| 00555;
1642 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
)) {
1647 // get uid, gid, from '/tasks' file and make up a mode
1648 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
1649 sb
->st_mode
= S_IFDIR
| 00755;
1650 k
= cgfs_get_key(controller
, cgroup
, NULL
);
1652 sb
->st_uid
= sb
->st_gid
= 0;
1654 sb
->st_uid
= k
->uid
;
1655 sb
->st_gid
= k
->gid
;
1663 if ((k
= cgfs_get_key(controller
, path1
, path2
)) != NULL
) {
1664 sb
->st_mode
= S_IFREG
| k
->mode
;
1666 sb
->st_uid
= k
->uid
;
1667 sb
->st_gid
= k
->gid
;
1670 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
1674 if (!fc_may_access(fc
, controller
, path1
, path2
, O_RDONLY
)) {
1687 int cg_opendir(const char *path
, struct fuse_file_info
*fi
)
1689 struct fuse_context
*fc
= fuse_get_context();
1691 struct file_info
*dir_info
;
1692 char *controller
= NULL
;
1697 if (strcmp(path
, "/cgroup") == 0) {
1701 // return list of keys for the controller, and list of child cgroups
1702 controller
= pick_controller_from_path(fc
, path
);
1706 cgroup
= find_cgroup_in_path(path
);
1708 /* this is just /cgroup/controller, return its contents */
1713 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1717 if (!caller_may_see_dir(initpid
, controller
, cgroup
))
1719 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
))
1723 /* we'll free this at cg_releasedir */
1724 dir_info
= malloc(sizeof(*dir_info
));
1727 dir_info
->controller
= must_copy_string(controller
);
1728 dir_info
->cgroup
= must_copy_string(cgroup
);
1729 dir_info
->type
= LXC_TYPE_CGDIR
;
1730 dir_info
->buf
= NULL
;
1731 dir_info
->file
= NULL
;
1732 dir_info
->buflen
= 0;
1734 fi
->fh
= (unsigned long)dir_info
;
1738 int cg_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
1739 struct fuse_file_info
*fi
)
1741 struct file_info
*d
= (struct file_info
*)fi
->fh
;
1742 struct cgfs_files
**list
= NULL
;
1744 char *nextcg
= NULL
;
1745 struct fuse_context
*fc
= fuse_get_context();
1746 char **clist
= NULL
;
1748 if (filler(buf
, ".", NULL
, 0) != 0 || filler(buf
, "..", NULL
, 0) != 0)
1751 if (d
->type
!= LXC_TYPE_CGDIR
) {
1752 lxcfs_error("%s\n", "Internal error: file cache info used in readdir.");
1755 if (!d
->cgroup
&& !d
->controller
) {
1756 // ls /var/lib/lxcfs/cgroup - just show list of controllers
1759 for (i
= 0; i
< num_hierarchies
; i
++) {
1760 if (hierarchies
[i
] && filler(buf
, hierarchies
[i
], NULL
, 0) != 0) {
1767 if (!cgfs_list_keys(d
->controller
, d
->cgroup
, &list
)) {
1768 // not a valid cgroup
1773 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1776 if (!caller_is_in_ancestor(initpid
, d
->controller
, d
->cgroup
, &nextcg
)) {
1778 ret
= filler(buf
, nextcg
, NULL
, 0);
1789 for (i
= 0; list
[i
]; i
++) {
1790 if (filler(buf
, list
[i
]->name
, NULL
, 0) != 0) {
1796 // now get the list of child cgroups
1798 if (!cgfs_list_children(d
->controller
, d
->cgroup
, &clist
)) {
1803 for (i
= 0; clist
[i
]; i
++) {
1804 if (filler(buf
, clist
[i
], NULL
, 0) != 0) {
1815 for (i
= 0; clist
[i
]; i
++)
1822 static void do_release_file_info(struct fuse_file_info
*fi
)
1824 struct file_info
*f
= (struct file_info
*)fi
->fh
;
1831 free(f
->controller
);
1832 f
->controller
= NULL
;
1842 int cg_releasedir(const char *path
, struct fuse_file_info
*fi
)
1844 do_release_file_info(fi
);
1848 int cg_open(const char *path
, struct fuse_file_info
*fi
)
1851 char *last
= NULL
, *path1
, *path2
, * cgdir
= NULL
, *controller
;
1852 struct cgfs_files
*k
= NULL
;
1853 struct file_info
*file_info
;
1854 struct fuse_context
*fc
= fuse_get_context();
1860 controller
= pick_controller_from_path(fc
, path
);
1863 cgroup
= find_cgroup_in_path(path
);
1867 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
1876 k
= cgfs_get_key(controller
, path1
, path2
);
1883 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1886 if (!caller_may_see_dir(initpid
, controller
, path1
)) {
1890 if (!fc_may_access(fc
, controller
, path1
, path2
, fi
->flags
)) {
1895 /* we'll free this at cg_release */
1896 file_info
= malloc(sizeof(*file_info
));
1901 file_info
->controller
= must_copy_string(controller
);
1902 file_info
->cgroup
= must_copy_string(path1
);
1903 file_info
->file
= must_copy_string(path2
);
1904 file_info
->type
= LXC_TYPE_CGFILE
;
1905 file_info
->buf
= NULL
;
1906 file_info
->buflen
= 0;
1908 fi
->fh
= (unsigned long)file_info
;
1916 int cg_access(const char *path
, int mode
)
1920 char *path1
, *path2
, *controller
;
1921 char *last
= NULL
, *cgdir
= NULL
;
1922 struct cgfs_files
*k
= NULL
;
1923 struct fuse_context
*fc
= fuse_get_context();
1925 if (strcmp(path
, "/cgroup") == 0)
1931 controller
= pick_controller_from_path(fc
, path
);
1934 cgroup
= find_cgroup_in_path(path
);
1936 // access("/sys/fs/cgroup/systemd", mode) - rx allowed, w not
1937 if ((mode
& W_OK
) == 0)
1942 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
1951 k
= cgfs_get_key(controller
, path1
, path2
);
1953 if ((mode
& W_OK
) == 0)
1961 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1964 if (!caller_may_see_dir(initpid
, controller
, path1
)) {
1968 if (!fc_may_access(fc
, controller
, path1
, path2
, mode
)) {
1980 int cg_release(const char *path
, struct fuse_file_info
*fi
)
1982 do_release_file_info(fi
);
1986 #define POLLIN_SET ( EPOLLIN | EPOLLHUP | EPOLLRDHUP )
1988 static bool wait_for_sock(int sock
, int timeout
)
1990 struct epoll_event ev
;
1991 int epfd
, ret
, now
, starttime
, deltatime
, saved_errno
;
1993 if ((starttime
= time(NULL
)) < 0)
1996 if ((epfd
= epoll_create(1)) < 0) {
1997 lxcfs_error("%s\n", "Failed to create epoll socket: %m.");
2001 ev
.events
= POLLIN_SET
;
2003 if (epoll_ctl(epfd
, EPOLL_CTL_ADD
, sock
, &ev
) < 0) {
2004 lxcfs_error("%s\n", "Failed adding socket to epoll: %m.");
2010 if ((now
= time(NULL
)) < 0) {
2015 deltatime
= (starttime
+ timeout
) - now
;
2016 if (deltatime
< 0) { // timeout
2021 ret
= epoll_wait(epfd
, &ev
, 1, 1000*deltatime
+ 1);
2022 if (ret
< 0 && errno
== EINTR
)
2024 saved_errno
= errno
;
2028 errno
= saved_errno
;
2034 static int msgrecv(int sockfd
, void *buf
, size_t len
)
2036 if (!wait_for_sock(sockfd
, 2))
2038 return recv(sockfd
, buf
, len
, MSG_DONTWAIT
);
2041 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
)
2043 struct msghdr msg
= { 0 };
2045 struct cmsghdr
*cmsg
;
2046 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
2051 if (msgrecv(sock
, buf
, 1) != 1) {
2052 lxcfs_error("%s\n", "Error getting reply from server over socketpair.");
2053 return SEND_CREDS_FAIL
;
2057 msg
.msg_control
= cmsgbuf
;
2058 msg
.msg_controllen
= sizeof(cmsgbuf
);
2060 cmsg
= CMSG_FIRSTHDR(&msg
);
2061 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct ucred
));
2062 cmsg
->cmsg_level
= SOL_SOCKET
;
2063 cmsg
->cmsg_type
= SCM_CREDENTIALS
;
2064 memcpy(CMSG_DATA(cmsg
), cred
, sizeof(*cred
));
2066 msg
.msg_name
= NULL
;
2067 msg
.msg_namelen
= 0;
2071 iov
.iov_len
= sizeof(buf
);
2075 if (sendmsg(sock
, &msg
, 0) < 0) {
2076 lxcfs_error("Failed at sendmsg: %s.\n",strerror(errno
));
2078 return SEND_CREDS_NOTSK
;
2079 return SEND_CREDS_FAIL
;
2082 return SEND_CREDS_OK
;
2085 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
)
2087 struct msghdr msg
= { 0 };
2089 struct cmsghdr
*cmsg
;
2090 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
2101 if (setsockopt(sock
, SOL_SOCKET
, SO_PASSCRED
, &optval
, sizeof(optval
)) == -1) {
2102 lxcfs_error("Failed to set passcred: %s\n", strerror(errno
));
2106 if (write(sock
, buf
, 1) != 1) {
2107 lxcfs_error("Failed to start write on scm fd: %s\n", strerror(errno
));
2111 msg
.msg_name
= NULL
;
2112 msg
.msg_namelen
= 0;
2113 msg
.msg_control
= cmsgbuf
;
2114 msg
.msg_controllen
= sizeof(cmsgbuf
);
2117 iov
.iov_len
= sizeof(buf
);
2121 if (!wait_for_sock(sock
, 2)) {
2122 lxcfs_error("Timed out waiting for scm_cred: %s\n", strerror(errno
));
2125 ret
= recvmsg(sock
, &msg
, MSG_DONTWAIT
);
2127 lxcfs_error("Failed to receive scm_cred: %s\n", strerror(errno
));
2131 cmsg
= CMSG_FIRSTHDR(&msg
);
2133 if (cmsg
&& cmsg
->cmsg_len
== CMSG_LEN(sizeof(struct ucred
)) &&
2134 cmsg
->cmsg_level
== SOL_SOCKET
&&
2135 cmsg
->cmsg_type
== SCM_CREDENTIALS
) {
2136 memcpy(cred
, CMSG_DATA(cmsg
), sizeof(*cred
));
2143 struct pid_ns_clone_args
{
2147 int (*wrapped
) (int, pid_t
); // pid_from_ns or pid_to_ns
2151 * pid_ns_clone_wrapper - wraps pid_to_ns or pid_from_ns for usage
2152 * with clone(). This simply writes '1' as ACK back to the parent
2153 * before calling the actual wrapped function.
2155 static int pid_ns_clone_wrapper(void *arg
) {
2156 struct pid_ns_clone_args
* args
= (struct pid_ns_clone_args
*) arg
;
2159 close(args
->cpipe
[0]);
2160 if (write(args
->cpipe
[1], &b
, sizeof(char)) < 0)
2161 lxcfs_error("(child): error on write: %s.\n", strerror(errno
));
2162 close(args
->cpipe
[1]);
2163 return args
->wrapped(args
->sock
, args
->tpid
);
2167 * pid_to_ns - reads pids from a ucred over a socket, then writes the
2168 * int value back over the socket. This shifts the pid from the
2169 * sender's pidns into tpid's pidns.
2171 static int pid_to_ns(int sock
, pid_t tpid
)
2176 while (recv_creds(sock
, &cred
, &v
)) {
2179 if (write(sock
, &cred
.pid
, sizeof(pid_t
)) != sizeof(pid_t
))
2187 * pid_to_ns_wrapper: when you setns into a pidns, you yourself remain
2188 * in your old pidns. Only children which you clone will be in the target
2189 * pidns. So the pid_to_ns_wrapper does the setns, then clones a child to
2190 * actually convert pids.
2192 * Note: glibc's fork() does not respect pidns, which can lead to failed
2193 * assertions inside glibc (and thus failed forks) if the child's pid in
2194 * the pidns and the parent pid outside are identical. Using clone prevents
2197 static void pid_to_ns_wrapper(int sock
, pid_t tpid
)
2199 int newnsfd
= -1, ret
, cpipe
[2];
2204 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
2205 if (ret
< 0 || ret
>= sizeof(fnam
))
2207 newnsfd
= open(fnam
, O_RDONLY
);
2210 if (setns(newnsfd
, 0) < 0)
2214 if (pipe(cpipe
) < 0)
2217 struct pid_ns_clone_args args
= {
2221 .wrapped
= &pid_to_ns
2223 size_t stack_size
= sysconf(_SC_PAGESIZE
);
2224 void *stack
= alloca(stack_size
);
2226 cpid
= clone(pid_ns_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &args
);
2230 // give the child 1 second to be done forking and
2232 if (!wait_for_sock(cpipe
[0], 1))
2234 ret
= read(cpipe
[0], &v
, 1);
2235 if (ret
!= sizeof(char) || v
!= '1')
2238 if (!wait_for_pid(cpid
))
2244 * To read cgroup files with a particular pid, we will setns into the child
2245 * pidns, open a pipe, fork a child - which will be the first to really be in
2246 * the child ns - which does the cgfs_get_value and writes the data to the pipe.
2248 bool do_read_pids(pid_t tpid
, const char *contrl
, const char *cg
, const char *file
, char **d
)
2250 int sock
[2] = {-1, -1};
2251 char *tmpdata
= NULL
;
2253 pid_t qpid
, cpid
= -1;
2254 bool answer
= false;
2257 size_t sz
= 0, asz
= 0;
2259 if (!cgfs_get_value(contrl
, cg
, file
, &tmpdata
))
2263 * Now we read the pids from returned data one by one, pass
2264 * them into a child in the target namespace, read back the
2265 * translated pids, and put them into our to-return data
2268 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2269 perror("socketpair");
2278 if (!cpid
) // child - exits when done
2279 pid_to_ns_wrapper(sock
[1], tpid
);
2281 char *ptr
= tmpdata
;
2284 while (sscanf(ptr
, "%d\n", &qpid
) == 1) {
2286 ret
= send_creds(sock
[0], &cred
, v
, true);
2288 if (ret
== SEND_CREDS_NOTSK
)
2290 if (ret
== SEND_CREDS_FAIL
)
2293 // read converted results
2294 if (!wait_for_sock(sock
[0], 2)) {
2295 lxcfs_error("Timed out waiting for pid from child: %s.\n", strerror(errno
));
2298 if (read(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2299 lxcfs_error("Error reading pid from child: %s.\n", strerror(errno
));
2302 must_strcat_pid(d
, &sz
, &asz
, qpid
);
2304 ptr
= strchr(ptr
, '\n');
2310 cred
.pid
= getpid();
2312 if (send_creds(sock
[0], &cred
, v
, true) != SEND_CREDS_OK
) {
2313 // failed to ask child to exit
2314 lxcfs_error("Failed to ask child to exit: %s.\n", strerror(errno
));
2324 if (sock
[0] != -1) {
2331 int cg_read(const char *path
, char *buf
, size_t size
, off_t offset
,
2332 struct fuse_file_info
*fi
)
2334 struct fuse_context
*fc
= fuse_get_context();
2335 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2336 struct cgfs_files
*k
= NULL
;
2341 if (f
->type
!= LXC_TYPE_CGFILE
) {
2342 lxcfs_error("%s\n", "Internal error: directory cache info used in cg_read.");
2355 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
2361 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_RDONLY
)) {
2366 if (strcmp(f
->file
, "tasks") == 0 ||
2367 strcmp(f
->file
, "/tasks") == 0 ||
2368 strcmp(f
->file
, "/cgroup.procs") == 0 ||
2369 strcmp(f
->file
, "cgroup.procs") == 0)
2370 // special case - we have to translate the pids
2371 r
= do_read_pids(fc
->pid
, f
->controller
, f
->cgroup
, f
->file
, &data
);
2373 r
= cgfs_get_value(f
->controller
, f
->cgroup
, f
->file
, &data
);
2387 memcpy(buf
, data
, s
);
2388 if (s
> 0 && s
< size
&& data
[s
-1] != '\n')
2398 static int pid_from_ns(int sock
, pid_t tpid
)
2408 if (!wait_for_sock(sock
, 2)) {
2409 lxcfs_error("%s\n", "Timeout reading from parent.");
2412 if ((ret
= read(sock
, &vpid
, sizeof(pid_t
))) != sizeof(pid_t
)) {
2413 lxcfs_error("Bad read from parent: %s.\n", strerror(errno
));
2416 if (vpid
== -1) // done
2420 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
) {
2422 cred
.pid
= getpid();
2423 if (send_creds(sock
, &cred
, v
, false) != SEND_CREDS_OK
)
2430 static void pid_from_ns_wrapper(int sock
, pid_t tpid
)
2432 int newnsfd
= -1, ret
, cpipe
[2];
2437 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
2438 if (ret
< 0 || ret
>= sizeof(fnam
))
2440 newnsfd
= open(fnam
, O_RDONLY
);
2443 if (setns(newnsfd
, 0) < 0)
2447 if (pipe(cpipe
) < 0)
2450 struct pid_ns_clone_args args
= {
2454 .wrapped
= &pid_from_ns
2456 size_t stack_size
= sysconf(_SC_PAGESIZE
);
2457 void *stack
= alloca(stack_size
);
2459 cpid
= clone(pid_ns_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &args
);
2463 // give the child 1 second to be done forking and
2465 if (!wait_for_sock(cpipe
[0], 1))
2467 ret
= read(cpipe
[0], &v
, 1);
2468 if (ret
!= sizeof(char) || v
!= '1')
2471 if (!wait_for_pid(cpid
))
2477 * Given host @uid, return the uid to which it maps in
2478 * @pid's user namespace, or -1 if none.
2480 bool hostuid_to_ns(uid_t uid
, pid_t pid
, uid_t
*answer
)
2485 sprintf(line
, "/proc/%d/uid_map", pid
);
2486 if ((f
= fopen(line
, "r")) == NULL
) {
2490 *answer
= convert_id_to_ns(f
, uid
);
2499 * get_pid_creds: get the real uid and gid of @pid from
2501 * (XXX should we use euid here?)
2503 void get_pid_creds(pid_t pid
, uid_t
*uid
, gid_t
*gid
)
2512 sprintf(line
, "/proc/%d/status", pid
);
2513 if ((f
= fopen(line
, "r")) == NULL
) {
2514 lxcfs_error("Error opening %s: %s\n", line
, strerror(errno
));
2517 while (fgets(line
, 400, f
)) {
2518 if (strncmp(line
, "Uid:", 4) == 0) {
2519 if (sscanf(line
+4, "%u", &u
) != 1) {
2520 lxcfs_error("bad uid line for pid %u\n", pid
);
2525 } else if (strncmp(line
, "Gid:", 4) == 0) {
2526 if (sscanf(line
+4, "%u", &g
) != 1) {
2527 lxcfs_error("bad gid line for pid %u\n", pid
);
2538 * May the requestor @r move victim @v to a new cgroup?
2539 * This is allowed if
2540 * . they are the same task
2541 * . they are ownedy by the same uid
2542 * . @r is root on the host, or
2543 * . @v's uid is mapped into @r's where @r is root.
2545 bool may_move_pid(pid_t r
, uid_t r_uid
, pid_t v
)
2547 uid_t v_uid
, tmpuid
;
2554 get_pid_creds(v
, &v_uid
, &v_gid
);
2557 if (hostuid_to_ns(r_uid
, r
, &tmpuid
) && tmpuid
== 0
2558 && hostuid_to_ns(v_uid
, r
, &tmpuid
))
2563 static bool do_write_pids(pid_t tpid
, uid_t tuid
, const char *contrl
, const char *cg
,
2564 const char *file
, const char *buf
)
2566 int sock
[2] = {-1, -1};
2567 pid_t qpid
, cpid
= -1;
2568 FILE *pids_file
= NULL
;
2569 bool answer
= false, fail
= false;
2571 pids_file
= open_pids_file(contrl
, cg
);
2576 * write the pids to a socket, have helper in writer's pidns
2577 * call movepid for us
2579 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2580 perror("socketpair");
2588 if (!cpid
) { // child
2590 pid_from_ns_wrapper(sock
[1], tpid
);
2593 const char *ptr
= buf
;
2594 while (sscanf(ptr
, "%d", &qpid
) == 1) {
2598 if (write(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2599 lxcfs_error("Error writing pid to child: %s.\n", strerror(errno
));
2603 if (recv_creds(sock
[0], &cred
, &v
)) {
2605 if (!may_move_pid(tpid
, tuid
, cred
.pid
)) {
2609 if (fprintf(pids_file
, "%d", (int) cred
.pid
) < 0)
2614 ptr
= strchr(ptr
, '\n');
2620 /* All good, write the value */
2622 if (write(sock
[0], &qpid
,sizeof(qpid
)) != sizeof(qpid
))
2623 lxcfs_error("%s\n", "Warning: failed to ask child to exit.");
2631 if (sock
[0] != -1) {
2636 if (fclose(pids_file
) != 0)
2642 int cg_write(const char *path
, const char *buf
, size_t size
, off_t offset
,
2643 struct fuse_file_info
*fi
)
2645 struct fuse_context
*fc
= fuse_get_context();
2646 char *localbuf
= NULL
;
2647 struct cgfs_files
*k
= NULL
;
2648 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2651 if (f
->type
!= LXC_TYPE_CGFILE
) {
2652 lxcfs_error("%s\n", "Internal error: directory cache info used in cg_write.");
2662 localbuf
= alloca(size
+1);
2663 localbuf
[size
] = '\0';
2664 memcpy(localbuf
, buf
, size
);
2666 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
2671 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_WRONLY
)) {
2676 if (strcmp(f
->file
, "tasks") == 0 ||
2677 strcmp(f
->file
, "/tasks") == 0 ||
2678 strcmp(f
->file
, "/cgroup.procs") == 0 ||
2679 strcmp(f
->file
, "cgroup.procs") == 0)
2680 // special case - we have to translate the pids
2681 r
= do_write_pids(fc
->pid
, fc
->uid
, f
->controller
, f
->cgroup
, f
->file
, localbuf
);
2683 r
= cgfs_set_value(f
->controller
, f
->cgroup
, f
->file
, localbuf
);
2693 int cg_chown(const char *path
, uid_t uid
, gid_t gid
)
2695 struct fuse_context
*fc
= fuse_get_context();
2696 char *cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
2697 struct cgfs_files
*k
= NULL
;
2704 if (strcmp(path
, "/cgroup") == 0)
2707 controller
= pick_controller_from_path(fc
, path
);
2709 return errno
== ENOENT
? -EPERM
: -errno
;
2711 cgroup
= find_cgroup_in_path(path
);
2713 /* this is just /cgroup/controller */
2716 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2726 if (is_child_cgroup(controller
, path1
, path2
)) {
2727 // get uid, gid, from '/tasks' file and make up a mode
2728 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
2729 k
= cgfs_get_key(controller
, cgroup
, "tasks");
2732 k
= cgfs_get_key(controller
, path1
, path2
);
2740 * This being a fuse request, the uid and gid must be valid
2741 * in the caller's namespace. So we can just check to make
2742 * sure that the caller is root in his uid, and privileged
2743 * over the file's current owner.
2745 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_REQD
)) {
2750 ret
= cgfs_chown_file(controller
, cgroup
, uid
, gid
);
2759 int cg_chmod(const char *path
, mode_t mode
)
2761 struct fuse_context
*fc
= fuse_get_context();
2762 char * cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
2763 struct cgfs_files
*k
= NULL
;
2770 if (strcmp(path
, "/cgroup") == 0)
2773 controller
= pick_controller_from_path(fc
, path
);
2775 return errno
== ENOENT
? -EPERM
: -errno
;
2777 cgroup
= find_cgroup_in_path(path
);
2779 /* this is just /cgroup/controller */
2782 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2792 if (is_child_cgroup(controller
, path1
, path2
)) {
2793 // get uid, gid, from '/tasks' file and make up a mode
2794 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
2795 k
= cgfs_get_key(controller
, cgroup
, "tasks");
2798 k
= cgfs_get_key(controller
, path1
, path2
);
2806 * This being a fuse request, the uid and gid must be valid
2807 * in the caller's namespace. So we can just check to make
2808 * sure that the caller is root in his uid, and privileged
2809 * over the file's current owner.
2811 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
2816 if (!cgfs_chmod_file(controller
, cgroup
, mode
)) {
2828 int cg_mkdir(const char *path
, mode_t mode
)
2830 struct fuse_context
*fc
= fuse_get_context();
2831 char *last
= NULL
, *path1
, *cgdir
= NULL
, *controller
, *next
= NULL
;
2838 controller
= pick_controller_from_path(fc
, path
);
2840 return errno
== ENOENT
? -EPERM
: -errno
;
2842 cgroup
= find_cgroup_in_path(path
);
2846 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2852 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2855 if (!caller_is_in_ancestor(initpid
, controller
, path1
, &next
)) {
2858 else if (last
&& strcmp(next
, last
) == 0)
2865 if (!fc_may_access(fc
, controller
, path1
, NULL
, O_RDWR
)) {
2869 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
2874 ret
= cgfs_create(controller
, cgroup
, fc
->uid
, fc
->gid
);
2882 int cg_rmdir(const char *path
)
2884 struct fuse_context
*fc
= fuse_get_context();
2885 char *last
= NULL
, *cgdir
= NULL
, *controller
, *next
= NULL
;
2892 controller
= pick_controller_from_path(fc
, path
);
2893 if (!controller
) /* Someone's trying to delete "/cgroup". */
2896 cgroup
= find_cgroup_in_path(path
);
2897 if (!cgroup
) /* Someone's trying to delete a controller e.g. "/blkio". */
2900 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2902 /* Someone's trying to delete a cgroup on the same level as the
2903 * "/lxc" cgroup e.g. rmdir "/cgroup/blkio/lxc" or
2904 * rmdir "/cgroup/blkio/init.slice".
2910 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2913 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, &next
)) {
2914 if (!last
|| strcmp(next
, last
) == 0)
2921 if (!fc_may_access(fc
, controller
, cgdir
, NULL
, O_WRONLY
)) {
2925 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
2930 if (!cgfs_remove(controller
, cgroup
)) {
2943 static bool startswith(const char *line
, const char *pref
)
2945 if (strncmp(line
, pref
, strlen(pref
)) == 0)
2950 static void parse_memstat(char *memstat
, unsigned long *cached
,
2951 unsigned long *active_anon
, unsigned long *inactive_anon
,
2952 unsigned long *active_file
, unsigned long *inactive_file
,
2953 unsigned long *unevictable
)
2958 if (startswith(memstat
, "cache")) {
2959 sscanf(memstat
+ 11, "%lu", cached
);
2961 } else if (startswith(memstat
, "active_anon")) {
2962 sscanf(memstat
+ 11, "%lu", active_anon
);
2963 *active_anon
/= 1024;
2964 } else if (startswith(memstat
, "inactive_anon")) {
2965 sscanf(memstat
+ 11, "%lu", inactive_anon
);
2966 *inactive_anon
/= 1024;
2967 } else if (startswith(memstat
, "active_file")) {
2968 sscanf(memstat
+ 11, "%lu", active_file
);
2969 *active_file
/= 1024;
2970 } else if (startswith(memstat
, "inactive_file")) {
2971 sscanf(memstat
+ 11, "%lu", inactive_file
);
2972 *inactive_file
/= 1024;
2973 } else if (startswith(memstat
, "unevictable")) {
2974 sscanf(memstat
+ 11, "%lu", unevictable
);
2975 *unevictable
/= 1024;
2977 eol
= strchr(memstat
, '\n');
2984 static void get_blkio_io_value(char *str
, unsigned major
, unsigned minor
, char *iotype
, unsigned long *v
)
2990 snprintf(key
, 32, "%u:%u %s", major
, minor
, iotype
);
2992 size_t len
= strlen(key
);
2996 if (startswith(str
, key
)) {
2997 sscanf(str
+ len
, "%lu", v
);
3000 eol
= strchr(str
, '\n');
3007 static int read_file(const char *path
, char *buf
, size_t size
,
3008 struct file_info
*d
)
3010 size_t linelen
= 0, total_len
= 0, rv
= 0;
3012 char *cache
= d
->buf
;
3013 size_t cache_size
= d
->buflen
;
3014 FILE *f
= fopen(path
, "r");
3018 while (getline(&line
, &linelen
, f
) != -1) {
3019 ssize_t l
= snprintf(cache
, cache_size
, "%s", line
);
3021 perror("Error writing to cache");
3025 if (l
>= cache_size
) {
3026 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3035 d
->size
= total_len
;
3036 if (total_len
> size
)
3039 /* read from off 0 */
3040 memcpy(buf
, d
->buf
, total_len
);
3049 * FUSE ops for /proc
3052 static unsigned long get_memlimit(const char *cgroup
)
3054 char *memlimit_str
= NULL
;
3055 unsigned long memlimit
= -1;
3057 if (cgfs_get_value("memory", cgroup
, "memory.limit_in_bytes", &memlimit_str
))
3058 memlimit
= strtoul(memlimit_str
, NULL
, 10);
3065 static unsigned long get_min_memlimit(const char *cgroup
)
3067 char *copy
= strdupa(cgroup
);
3068 unsigned long memlimit
= 0, retlimit
;
3070 retlimit
= get_memlimit(copy
);
3072 while (strcmp(copy
, "/") != 0) {
3073 copy
= dirname(copy
);
3074 memlimit
= get_memlimit(copy
);
3075 if (memlimit
!= -1 && memlimit
< retlimit
)
3076 retlimit
= memlimit
;
3082 static int proc_meminfo_read(char *buf
, size_t size
, off_t offset
,
3083 struct fuse_file_info
*fi
)
3085 struct fuse_context
*fc
= fuse_get_context();
3086 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3088 char *memusage_str
= NULL
, *memstat_str
= NULL
,
3089 *memswlimit_str
= NULL
, *memswusage_str
= NULL
,
3090 *memswlimit_default_str
= NULL
, *memswusage_default_str
= NULL
;
3091 unsigned long memlimit
= 0, memusage
= 0, memswlimit
= 0, memswusage
= 0,
3092 cached
= 0, hosttotal
= 0, active_anon
= 0, inactive_anon
= 0,
3093 active_file
= 0, inactive_file
= 0, unevictable
= 0;
3095 size_t linelen
= 0, total_len
= 0, rv
= 0;
3096 char *cache
= d
->buf
;
3097 size_t cache_size
= d
->buflen
;
3101 if (offset
> d
->size
)
3105 int left
= d
->size
- offset
;
3106 total_len
= left
> size
? size
: left
;
3107 memcpy(buf
, cache
+ offset
, total_len
);
3111 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3114 cg
= get_pid_cgroup(initpid
, "memory");
3116 return read_file("/proc/meminfo", buf
, size
, d
);
3117 prune_init_slice(cg
);
3119 memlimit
= get_min_memlimit(cg
);
3120 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
3122 if (!cgfs_get_value("memory", cg
, "memory.stat", &memstat_str
))
3125 // Following values are allowed to fail, because swapaccount might be turned
3126 // off for current kernel
3127 if(cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
) &&
3128 cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
))
3130 /* If swapaccounting is turned on, then default value is assumed to be that of cgroup / */
3131 if (!cgfs_get_value("memory", "/", "memory.memsw.limit_in_bytes", &memswlimit_default_str
))
3133 if (!cgfs_get_value("memory", "/", "memory.memsw.usage_in_bytes", &memswusage_default_str
))
3136 memswlimit
= strtoul(memswlimit_str
, NULL
, 10);
3137 memswusage
= strtoul(memswusage_str
, NULL
, 10);
3139 if (!strcmp(memswlimit_str
, memswlimit_default_str
))
3141 if (!strcmp(memswusage_str
, memswusage_default_str
))
3144 memswlimit
= memswlimit
/ 1024;
3145 memswusage
= memswusage
/ 1024;
3148 memusage
= strtoul(memusage_str
, NULL
, 10);
3152 parse_memstat(memstat_str
, &cached
, &active_anon
,
3153 &inactive_anon
, &active_file
, &inactive_file
,
3156 f
= fopen("/proc/meminfo", "r");
3160 while (getline(&line
, &linelen
, f
) != -1) {
3162 char *printme
, lbuf
[100];
3164 memset(lbuf
, 0, 100);
3165 if (startswith(line
, "MemTotal:")) {
3166 sscanf(line
+14, "%lu", &hosttotal
);
3167 if (hosttotal
< memlimit
)
3168 memlimit
= hosttotal
;
3169 snprintf(lbuf
, 100, "MemTotal: %8lu kB\n", memlimit
);
3171 } else if (startswith(line
, "MemFree:")) {
3172 snprintf(lbuf
, 100, "MemFree: %8lu kB\n", memlimit
- memusage
);
3174 } else if (startswith(line
, "MemAvailable:")) {
3175 snprintf(lbuf
, 100, "MemAvailable: %8lu kB\n", memlimit
- memusage
);
3177 } else if (startswith(line
, "SwapTotal:") && memswlimit
> 0) {
3178 snprintf(lbuf
, 100, "SwapTotal: %8lu kB\n", memswlimit
- memlimit
);
3180 } else if (startswith(line
, "SwapFree:") && memswlimit
> 0 && memswusage
> 0) {
3181 unsigned long swaptotal
= memswlimit
- memlimit
,
3182 swapusage
= memswusage
- memusage
,
3183 swapfree
= swapusage
< swaptotal
? swaptotal
- swapusage
: 0;
3184 snprintf(lbuf
, 100, "SwapFree: %8lu kB\n", swapfree
);
3186 } else if (startswith(line
, "Slab:")) {
3187 snprintf(lbuf
, 100, "Slab: %8lu kB\n", 0UL);
3189 } else if (startswith(line
, "Buffers:")) {
3190 snprintf(lbuf
, 100, "Buffers: %8lu kB\n", 0UL);
3192 } else if (startswith(line
, "Cached:")) {
3193 snprintf(lbuf
, 100, "Cached: %8lu kB\n", cached
);
3195 } else if (startswith(line
, "SwapCached:")) {
3196 snprintf(lbuf
, 100, "SwapCached: %8lu kB\n", 0UL);
3198 } else if (startswith(line
, "Active")) {
3199 snprintf(lbuf
, 100, "Active: %8lu kB\n",
3200 active_anon
+ active_file
);
3202 } else if (startswith(line
, "Inactive")) {
3203 snprintf(lbuf
, 100, "Inactive: %8lu kB\n",
3204 inactive_anon
+ inactive_file
);
3206 } else if (startswith(line
, "Active(anon)")) {
3207 snprintf(lbuf
, 100, "Active(anon): %8lu kB\n", active_anon
);
3209 } else if (startswith(line
, "Inactive(anon)")) {
3210 snprintf(lbuf
, 100, "Inactive(anon): %8lu kB\n", inactive_anon
);
3212 } else if (startswith(line
, "Active(file)")) {
3213 snprintf(lbuf
, 100, "Active(file): %8lu kB\n", active_file
);
3215 } else if (startswith(line
, "Inactive(file)")) {
3216 snprintf(lbuf
, 100, "Inactive(file): %8lu kB\n", inactive_file
);
3218 } else if (startswith(line
, "Unevictable")) {
3219 snprintf(lbuf
, 100, "Unevictable: %8lu kB\n", unevictable
);
3221 } else if (startswith(line
, "SReclaimable")) {
3222 snprintf(lbuf
, 100, "SReclaimable: %8lu kB\n", 0UL);
3224 } else if (startswith(line
, "SUnreclaim")) {
3225 snprintf(lbuf
, 100, "SUnreclaim: %8lu kB\n", 0UL);
3230 l
= snprintf(cache
, cache_size
, "%s", printme
);
3232 perror("Error writing to cache");
3237 if (l
>= cache_size
) {
3238 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3249 d
->size
= total_len
;
3250 if (total_len
> size
) total_len
= size
;
3251 memcpy(buf
, d
->buf
, total_len
);
3260 free(memswlimit_str
);
3261 free(memswusage_str
);
3263 free(memswlimit_default_str
);
3264 free(memswusage_default_str
);
3269 * Read the cpuset.cpus for cg
3270 * Return the answer in a newly allocated string which must be freed
3272 static char *get_cpuset(const char *cg
)
3276 if (!cgfs_get_value("cpuset", cg
, "cpuset.cpus", &answer
))
3281 bool cpu_in_cpuset(int cpu
, const char *cpuset
);
3283 static bool cpuline_in_cpuset(const char *line
, const char *cpuset
)
3287 if (sscanf(line
, "processor : %d", &cpu
) != 1)
3289 return cpu_in_cpuset(cpu
, cpuset
);
3293 * check whether this is a '^processor" line in /proc/cpuinfo
3295 static bool is_processor_line(const char *line
)
3299 if (sscanf(line
, "processor : %d", &cpu
) == 1)
3304 static int proc_cpuinfo_read(char *buf
, size_t size
, off_t offset
,
3305 struct fuse_file_info
*fi
)
3307 struct fuse_context
*fc
= fuse_get_context();
3308 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3310 char *cpuset
= NULL
;
3312 size_t linelen
= 0, total_len
= 0, rv
= 0;
3313 bool am_printing
= false, firstline
= true, is_s390x
= false;
3314 int curcpu
= -1, cpu
;
3315 char *cache
= d
->buf
;
3316 size_t cache_size
= d
->buflen
;
3320 if (offset
> d
->size
)
3324 int left
= d
->size
- offset
;
3325 total_len
= left
> size
? size
: left
;
3326 memcpy(buf
, cache
+ offset
, total_len
);
3330 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3333 cg
= get_pid_cgroup(initpid
, "cpuset");
3335 return read_file("proc/cpuinfo", buf
, size
, d
);
3336 prune_init_slice(cg
);
3338 cpuset
= get_cpuset(cg
);
3342 f
= fopen("/proc/cpuinfo", "r");
3346 while (getline(&line
, &linelen
, f
) != -1) {
3350 if (strstr(line
, "IBM/S390") != NULL
) {
3356 if (strncmp(line
, "# processors:", 12) == 0)
3358 if (is_processor_line(line
)) {
3359 am_printing
= cpuline_in_cpuset(line
, cpuset
);
3362 l
= snprintf(cache
, cache_size
, "processor : %d\n", curcpu
);
3364 perror("Error writing to cache");
3368 if (l
>= cache_size
) {
3369 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3378 } else if (is_s390x
&& sscanf(line
, "processor %d:", &cpu
) == 1) {
3380 if (!cpu_in_cpuset(cpu
, cpuset
))
3383 p
= strchr(line
, ':');
3387 l
= snprintf(cache
, cache_size
, "processor %d:%s", curcpu
, p
);
3389 perror("Error writing to cache");
3393 if (l
>= cache_size
) {
3394 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3405 l
= snprintf(cache
, cache_size
, "%s", line
);
3407 perror("Error writing to cache");
3411 if (l
>= cache_size
) {
3412 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3423 char *origcache
= d
->buf
;
3426 d
->buf
= malloc(d
->buflen
);
3429 cache_size
= d
->buflen
;
3431 l
= snprintf(cache
, cache_size
, "vendor_id : IBM/S390\n");
3432 if (l
< 0 || l
>= cache_size
) {
3439 l
= snprintf(cache
, cache_size
, "# processors : %d\n", curcpu
+ 1);
3440 if (l
< 0 || l
>= cache_size
) {
3447 l
= snprintf(cache
, cache_size
, "%s", origcache
);
3449 if (l
< 0 || l
>= cache_size
)
3455 d
->size
= total_len
;
3456 if (total_len
> size
) total_len
= size
;
3458 /* read from off 0 */
3459 memcpy(buf
, d
->buf
, total_len
);
3470 static int proc_stat_read(char *buf
, size_t size
, off_t offset
,
3471 struct fuse_file_info
*fi
)
3473 struct fuse_context
*fc
= fuse_get_context();
3474 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3476 char *cpuset
= NULL
;
3478 size_t linelen
= 0, total_len
= 0, rv
= 0;
3479 int curcpu
= -1; /* cpu numbering starts at 0 */
3480 unsigned long user
= 0, nice
= 0, system
= 0, idle
= 0, iowait
= 0, irq
= 0, softirq
= 0, steal
= 0, guest
= 0;
3481 unsigned long user_sum
= 0, nice_sum
= 0, system_sum
= 0, idle_sum
= 0, iowait_sum
= 0,
3482 irq_sum
= 0, softirq_sum
= 0, steal_sum
= 0, guest_sum
= 0;
3483 #define CPUALL_MAX_SIZE BUF_RESERVE_SIZE
3484 char cpuall
[CPUALL_MAX_SIZE
];
3485 /* reserve for cpu all */
3486 char *cache
= d
->buf
+ CPUALL_MAX_SIZE
;
3487 size_t cache_size
= d
->buflen
- CPUALL_MAX_SIZE
;
3491 if (offset
> d
->size
)
3495 int left
= d
->size
- offset
;
3496 total_len
= left
> size
? size
: left
;
3497 memcpy(buf
, d
->buf
+ offset
, total_len
);
3501 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3504 cg
= get_pid_cgroup(initpid
, "cpuset");
3506 return read_file("/proc/stat", buf
, size
, d
);
3507 prune_init_slice(cg
);
3509 cpuset
= get_cpuset(cg
);
3513 f
= fopen("/proc/stat", "r");
3518 if (getline(&line
, &linelen
, f
) < 0) {
3519 lxcfs_error("%s\n", "proc_stat_read read first line failed.");
3523 while (getline(&line
, &linelen
, f
) != -1) {
3526 char cpu_char
[10]; /* That's a lot of cores */
3529 if (strlen(line
) == 0)
3531 if (sscanf(line
, "cpu%9[^ ]", cpu_char
) != 1) {
3532 /* not a ^cpuN line containing a number N, just print it */
3533 l
= snprintf(cache
, cache_size
, "%s", line
);
3535 perror("Error writing to cache");
3539 if (l
>= cache_size
) {
3540 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3550 if (sscanf(cpu_char
, "%d", &cpu
) != 1)
3552 if (!cpu_in_cpuset(cpu
, cpuset
))
3556 c
= strchr(line
, ' ');
3559 l
= snprintf(cache
, cache_size
, "cpu%d%s", curcpu
, c
);
3561 perror("Error writing to cache");
3566 if (l
>= cache_size
) {
3567 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3576 if (sscanf(line
, "%*s %lu %lu %lu %lu %lu %lu %lu %lu %lu", &user
, &nice
, &system
, &idle
, &iowait
, &irq
,
3577 &softirq
, &steal
, &guest
) != 9)
3581 system_sum
+= system
;
3583 iowait_sum
+= iowait
;
3585 softirq_sum
+= softirq
;
3592 int cpuall_len
= snprintf(cpuall
, CPUALL_MAX_SIZE
, "%s %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
3593 "cpu ", user_sum
, nice_sum
, system_sum
, idle_sum
, iowait_sum
, irq_sum
, softirq_sum
, steal_sum
, guest_sum
);
3594 if (cpuall_len
> 0 && cpuall_len
< CPUALL_MAX_SIZE
){
3595 memcpy(cache
, cpuall
, cpuall_len
);
3596 cache
+= cpuall_len
;
3598 /* shouldn't happen */
3599 lxcfs_error("proc_stat_read copy cpuall failed, cpuall_len=%d.", cpuall_len
);
3603 memmove(cache
, d
->buf
+ CPUALL_MAX_SIZE
, total_len
);
3604 total_len
+= cpuall_len
;
3606 d
->size
= total_len
;
3607 if (total_len
> size
) total_len
= size
;
3609 memcpy(buf
, d
->buf
, total_len
);
3621 static long int getreaperage(pid_t pid
)
3628 qpid
= lookup_initpid_in_store(pid
);
3632 ret
= snprintf(fnam
, 100, "/proc/%d", qpid
);
3633 if (ret
< 0 || ret
>= 100)
3636 if (lstat(fnam
, &sb
) < 0)
3639 return time(NULL
) - sb
.st_ctime
;
3642 static unsigned long get_reaper_busy(pid_t task
)
3644 pid_t initpid
= lookup_initpid_in_store(task
);
3645 char *cgroup
= NULL
, *usage_str
= NULL
;
3646 unsigned long usage
= 0;
3651 cgroup
= get_pid_cgroup(initpid
, "cpuacct");
3654 prune_init_slice(cgroup
);
3655 if (!cgfs_get_value("cpuacct", cgroup
, "cpuacct.usage", &usage_str
))
3657 usage
= strtoul(usage_str
, NULL
, 10);
3658 usage
/= 1000000000;
3671 fd
= creat("/tmp/lxcfs-iwashere", 0644);
3678 * We read /proc/uptime and reuse its second field.
3679 * For the first field, we use the mtime for the reaper for
3680 * the calling pid as returned by getreaperage
3682 static int proc_uptime_read(char *buf
, size_t size
, off_t offset
,
3683 struct fuse_file_info
*fi
)
3685 struct fuse_context
*fc
= fuse_get_context();
3686 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3687 long int reaperage
= getreaperage(fc
->pid
);
3688 unsigned long int busytime
= get_reaper_busy(fc
->pid
), idletime
;
3689 char *cache
= d
->buf
;
3690 ssize_t total_len
= 0;
3697 if (offset
> d
->size
)
3701 int left
= d
->size
- offset
;
3702 total_len
= left
> size
? size
: left
;
3703 memcpy(buf
, cache
+ offset
, total_len
);
3707 idletime
= reaperage
- busytime
;
3708 if (idletime
> reaperage
)
3709 idletime
= reaperage
;
3711 total_len
= snprintf(d
->buf
, d
->size
, "%ld.0 %lu.0\n", reaperage
, idletime
);
3713 perror("Error writing to cache");
3717 d
->size
= (int)total_len
;
3720 if (total_len
> size
) total_len
= size
;
3722 memcpy(buf
, d
->buf
, total_len
);
3726 static int proc_diskstats_read(char *buf
, size_t size
, off_t offset
,
3727 struct fuse_file_info
*fi
)
3730 struct fuse_context
*fc
= fuse_get_context();
3731 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3733 char *io_serviced_str
= NULL
, *io_merged_str
= NULL
, *io_service_bytes_str
= NULL
,
3734 *io_wait_time_str
= NULL
, *io_service_time_str
= NULL
;
3735 unsigned long read
= 0, write
= 0;
3736 unsigned long read_merged
= 0, write_merged
= 0;
3737 unsigned long read_sectors
= 0, write_sectors
= 0;
3738 unsigned long read_ticks
= 0, write_ticks
= 0;
3739 unsigned long ios_pgr
= 0, tot_ticks
= 0, rq_ticks
= 0;
3740 unsigned long rd_svctm
= 0, wr_svctm
= 0, rd_wait
= 0, wr_wait
= 0;
3741 char *cache
= d
->buf
;
3742 size_t cache_size
= d
->buflen
;
3744 size_t linelen
= 0, total_len
= 0, rv
= 0;
3745 unsigned int major
= 0, minor
= 0;
3750 if (offset
> d
->size
)
3754 int left
= d
->size
- offset
;
3755 total_len
= left
> size
? size
: left
;
3756 memcpy(buf
, cache
+ offset
, total_len
);
3760 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3763 cg
= get_pid_cgroup(initpid
, "blkio");
3765 return read_file("/proc/diskstats", buf
, size
, d
);
3766 prune_init_slice(cg
);
3768 if (!cgfs_get_value("blkio", cg
, "blkio.io_serviced_recursive", &io_serviced_str
))
3770 if (!cgfs_get_value("blkio", cg
, "blkio.io_merged_recursive", &io_merged_str
))
3772 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_bytes_recursive", &io_service_bytes_str
))
3774 if (!cgfs_get_value("blkio", cg
, "blkio.io_wait_time_recursive", &io_wait_time_str
))
3776 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_time_recursive", &io_service_time_str
))
3780 f
= fopen("/proc/diskstats", "r");
3784 while (getline(&line
, &linelen
, f
) != -1) {
3788 i
= sscanf(line
, "%u %u %71s", &major
, &minor
, dev_name
);
3792 get_blkio_io_value(io_serviced_str
, major
, minor
, "Read", &read
);
3793 get_blkio_io_value(io_serviced_str
, major
, minor
, "Write", &write
);
3794 get_blkio_io_value(io_merged_str
, major
, minor
, "Read", &read_merged
);
3795 get_blkio_io_value(io_merged_str
, major
, minor
, "Write", &write_merged
);
3796 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Read", &read_sectors
);
3797 read_sectors
= read_sectors
/512;
3798 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Write", &write_sectors
);
3799 write_sectors
= write_sectors
/512;
3801 get_blkio_io_value(io_service_time_str
, major
, minor
, "Read", &rd_svctm
);
3802 rd_svctm
= rd_svctm
/1000000;
3803 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Read", &rd_wait
);
3804 rd_wait
= rd_wait
/1000000;
3805 read_ticks
= rd_svctm
+ rd_wait
;
3807 get_blkio_io_value(io_service_time_str
, major
, minor
, "Write", &wr_svctm
);
3808 wr_svctm
= wr_svctm
/1000000;
3809 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Write", &wr_wait
);
3810 wr_wait
= wr_wait
/1000000;
3811 write_ticks
= wr_svctm
+ wr_wait
;
3813 get_blkio_io_value(io_service_time_str
, major
, minor
, "Total", &tot_ticks
);
3814 tot_ticks
= tot_ticks
/1000000;
3816 memset(lbuf
, 0, 256);
3817 if (read
|| write
|| read_merged
|| write_merged
|| read_sectors
|| write_sectors
|| read_ticks
|| write_ticks
)
3818 snprintf(lbuf
, 256, "%u %u %s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
3819 major
, minor
, dev_name
, read
, read_merged
, read_sectors
, read_ticks
,
3820 write
, write_merged
, write_sectors
, write_ticks
, ios_pgr
, tot_ticks
, rq_ticks
);
3824 l
= snprintf(cache
, cache_size
, "%s", lbuf
);
3826 perror("Error writing to fuse buf");
3830 if (l
>= cache_size
) {
3831 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3841 d
->size
= total_len
;
3842 if (total_len
> size
) total_len
= size
;
3843 memcpy(buf
, d
->buf
, total_len
);
3851 free(io_serviced_str
);
3852 free(io_merged_str
);
3853 free(io_service_bytes_str
);
3854 free(io_wait_time_str
);
3855 free(io_service_time_str
);
3859 static int proc_swaps_read(char *buf
, size_t size
, off_t offset
,
3860 struct fuse_file_info
*fi
)
3862 struct fuse_context
*fc
= fuse_get_context();
3863 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3865 char *memswlimit_str
= NULL
, *memlimit_str
= NULL
, *memusage_str
= NULL
, *memswusage_str
= NULL
,
3866 *memswlimit_default_str
= NULL
, *memswusage_default_str
= NULL
;
3867 unsigned long memswlimit
= 0, memlimit
= 0, memusage
= 0, memswusage
= 0, swap_total
= 0, swap_free
= 0;
3868 ssize_t total_len
= 0, rv
= 0;
3870 char *cache
= d
->buf
;
3873 if (offset
> d
->size
)
3877 int left
= d
->size
- offset
;
3878 total_len
= left
> size
? size
: left
;
3879 memcpy(buf
, cache
+ offset
, total_len
);
3883 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3886 cg
= get_pid_cgroup(initpid
, "memory");
3888 return read_file("/proc/swaps", buf
, size
, d
);
3889 prune_init_slice(cg
);
3891 if (!cgfs_get_value("memory", cg
, "memory.limit_in_bytes", &memlimit_str
))
3894 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
3897 memlimit
= strtoul(memlimit_str
, NULL
, 10);
3898 memusage
= strtoul(memusage_str
, NULL
, 10);
3900 if (cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
) &&
3901 cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
)) {
3903 /* If swap accounting is turned on, then default value is assumed to be that of cgroup / */
3904 if (!cgfs_get_value("memory", "/", "memory.memsw.limit_in_bytes", &memswlimit_default_str
))
3906 if (!cgfs_get_value("memory", "/", "memory.memsw.usage_in_bytes", &memswusage_default_str
))
3909 memswlimit
= strtoul(memswlimit_str
, NULL
, 10);
3910 memswusage
= strtoul(memswusage_str
, NULL
, 10);
3912 if (!strcmp(memswlimit_str
, memswlimit_default_str
))
3914 if (!strcmp(memswusage_str
, memswusage_default_str
))
3917 swap_total
= (memswlimit
- memlimit
) / 1024;
3918 swap_free
= (memswusage
- memusage
) / 1024;
3921 total_len
= snprintf(d
->buf
, d
->size
, "Filename\t\t\t\tType\t\tSize\tUsed\tPriority\n");
3923 /* When no mem + swap limit is specified or swapaccount=0*/
3927 FILE *f
= fopen("/proc/meminfo", "r");
3932 while (getline(&line
, &linelen
, f
) != -1) {
3933 if (startswith(line
, "SwapTotal:")) {
3934 sscanf(line
, "SwapTotal: %8lu kB", &swap_total
);
3935 } else if (startswith(line
, "SwapFree:")) {
3936 sscanf(line
, "SwapFree: %8lu kB", &swap_free
);
3944 if (swap_total
> 0) {
3945 l
= snprintf(d
->buf
+ total_len
, d
->size
- total_len
,
3946 "none%*svirtual\t\t%lu\t%lu\t0\n", 36, " ",
3947 swap_total
, swap_free
);
3951 if (total_len
< 0 || l
< 0) {
3952 perror("Error writing to cache");
3958 d
->size
= (int)total_len
;
3960 if (total_len
> size
) total_len
= size
;
3961 memcpy(buf
, d
->buf
, total_len
);
3966 free(memswlimit_str
);
3969 free(memswusage_str
);
3970 free(memswusage_default_str
);
3971 free(memswlimit_default_str
);
3975 static off_t
get_procfile_size(const char *which
)
3977 FILE *f
= fopen(which
, "r");
3980 ssize_t sz
, answer
= 0;
3984 while ((sz
= getline(&line
, &len
, f
)) != -1)
3992 int proc_getattr(const char *path
, struct stat
*sb
)
3994 struct timespec now
;
3996 memset(sb
, 0, sizeof(struct stat
));
3997 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
3999 sb
->st_uid
= sb
->st_gid
= 0;
4000 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
4001 if (strcmp(path
, "/proc") == 0) {
4002 sb
->st_mode
= S_IFDIR
| 00555;
4006 if (strcmp(path
, "/proc/meminfo") == 0 ||
4007 strcmp(path
, "/proc/cpuinfo") == 0 ||
4008 strcmp(path
, "/proc/uptime") == 0 ||
4009 strcmp(path
, "/proc/stat") == 0 ||
4010 strcmp(path
, "/proc/diskstats") == 0 ||
4011 strcmp(path
, "/proc/swaps") == 0) {
4013 sb
->st_mode
= S_IFREG
| 00444;
4021 int proc_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
4022 struct fuse_file_info
*fi
)
4024 if (filler(buf
, ".", NULL
, 0) != 0 ||
4025 filler(buf
, "..", NULL
, 0) != 0 ||
4026 filler(buf
, "cpuinfo", NULL
, 0) != 0 ||
4027 filler(buf
, "meminfo", NULL
, 0) != 0 ||
4028 filler(buf
, "stat", NULL
, 0) != 0 ||
4029 filler(buf
, "uptime", NULL
, 0) != 0 ||
4030 filler(buf
, "diskstats", NULL
, 0) != 0 ||
4031 filler(buf
, "swaps", NULL
, 0) != 0)
4036 int proc_open(const char *path
, struct fuse_file_info
*fi
)
4039 struct file_info
*info
;
4041 if (strcmp(path
, "/proc/meminfo") == 0)
4042 type
= LXC_TYPE_PROC_MEMINFO
;
4043 else if (strcmp(path
, "/proc/cpuinfo") == 0)
4044 type
= LXC_TYPE_PROC_CPUINFO
;
4045 else if (strcmp(path
, "/proc/uptime") == 0)
4046 type
= LXC_TYPE_PROC_UPTIME
;
4047 else if (strcmp(path
, "/proc/stat") == 0)
4048 type
= LXC_TYPE_PROC_STAT
;
4049 else if (strcmp(path
, "/proc/diskstats") == 0)
4050 type
= LXC_TYPE_PROC_DISKSTATS
;
4051 else if (strcmp(path
, "/proc/swaps") == 0)
4052 type
= LXC_TYPE_PROC_SWAPS
;
4056 info
= malloc(sizeof(*info
));
4060 memset(info
, 0, sizeof(*info
));
4063 info
->buflen
= get_procfile_size(path
) + BUF_RESERVE_SIZE
;
4065 info
->buf
= malloc(info
->buflen
);
4066 } while (!info
->buf
);
4067 memset(info
->buf
, 0, info
->buflen
);
4068 /* set actual size to buffer size */
4069 info
->size
= info
->buflen
;
4071 fi
->fh
= (unsigned long)info
;
4075 int proc_access(const char *path
, int mask
)
4077 if (strcmp(path
, "/proc") == 0 && access(path
, R_OK
) == 0)
4080 /* these are all read-only */
4081 if ((mask
& ~R_OK
) != 0)
4086 int proc_release(const char *path
, struct fuse_file_info
*fi
)
4088 do_release_file_info(fi
);
4092 int proc_read(const char *path
, char *buf
, size_t size
, off_t offset
,
4093 struct fuse_file_info
*fi
)
4095 struct file_info
*f
= (struct file_info
*) fi
->fh
;
4098 case LXC_TYPE_PROC_MEMINFO
:
4099 return proc_meminfo_read(buf
, size
, offset
, fi
);
4100 case LXC_TYPE_PROC_CPUINFO
:
4101 return proc_cpuinfo_read(buf
, size
, offset
, fi
);
4102 case LXC_TYPE_PROC_UPTIME
:
4103 return proc_uptime_read(buf
, size
, offset
, fi
);
4104 case LXC_TYPE_PROC_STAT
:
4105 return proc_stat_read(buf
, size
, offset
, fi
);
4106 case LXC_TYPE_PROC_DISKSTATS
:
4107 return proc_diskstats_read(buf
, size
, offset
, fi
);
4108 case LXC_TYPE_PROC_SWAPS
:
4109 return proc_swaps_read(buf
, size
, offset
, fi
);
4116 * Functions needed to setup cgroups in the __constructor__.
4119 static bool mkdir_p(const char *dir
, mode_t mode
)
4121 const char *tmp
= dir
;
4122 const char *orig
= dir
;
4126 dir
= tmp
+ strspn(tmp
, "/");
4127 tmp
= dir
+ strcspn(dir
, "/");
4128 makeme
= strndup(orig
, dir
- orig
);
4131 if (mkdir(makeme
, mode
) && errno
!= EEXIST
) {
4132 lxcfs_error("Failed to create directory '%s': %s.\n",
4133 makeme
, strerror(errno
));
4138 } while(tmp
!= dir
);
4143 static bool umount_if_mounted(void)
4145 if (umount2(BASEDIR
, MNT_DETACH
) < 0 && errno
!= EINVAL
) {
4146 lxcfs_error("Failed to unmount %s: %s.\n", BASEDIR
, strerror(errno
));
4152 static int pivot_enter(void)
4154 int ret
= -1, oldroot
= -1, newroot
= -1;
4156 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
);
4158 lxcfs_error("%s\n", "Failed to open old root for fchdir.");
4162 newroot
= open(ROOTDIR
, O_DIRECTORY
| O_RDONLY
);
4164 lxcfs_error("%s\n", "Failed to open new root for fchdir.");
4168 /* change into new root fs */
4169 if (fchdir(newroot
) < 0) {
4170 lxcfs_error("Failed to change directory to new rootfs: %s.\n", ROOTDIR
);
4174 /* pivot_root into our new root fs */
4175 if (pivot_root(".", ".") < 0) {
4176 lxcfs_error("pivot_root() syscall failed: %s.\n", strerror(errno
));
4181 * At this point the old-root is mounted on top of our new-root.
4182 * To unmounted it we must not be chdir'd into it, so escape back
4185 if (fchdir(oldroot
) < 0) {
4186 lxcfs_error("%s\n", "Failed to enter old root.");
4189 if (umount2(".", MNT_DETACH
) < 0) {
4190 lxcfs_error("%s\n", "Failed to detach old root.");
4194 if (fchdir(newroot
) < 0) {
4195 lxcfs_error("%s\n", "Failed to re-enter new root.");
4209 /* Prepare our new clean root. */
4210 static int pivot_prepare(void)
4212 if (mkdir(ROOTDIR
, 0700) < 0 && errno
!= EEXIST
) {
4213 lxcfs_error("%s\n", "Failed to create directory for new root.");
4217 if (mount("/", ROOTDIR
, NULL
, MS_BIND
, 0) < 0) {
4218 lxcfs_error("Failed to bind-mount / for new root: %s.\n", strerror(errno
));
4222 if (mount(RUNTIME_PATH
, ROOTDIR RUNTIME_PATH
, NULL
, MS_BIND
, 0) < 0) {
4223 lxcfs_error("Failed to bind-mount /run into new root: %s.\n", strerror(errno
));
4227 if (mount(BASEDIR
, ROOTDIR BASEDIR
, NULL
, MS_REC
| MS_MOVE
, 0) < 0) {
4228 printf("Failed to move " BASEDIR
" into new root: %s.\n", strerror(errno
));
4235 static bool pivot_new_root(void)
4237 /* Prepare new root. */
4238 if (pivot_prepare() < 0)
4241 /* Pivot into new root. */
4242 if (pivot_enter() < 0)
4248 static bool setup_cgfs_dir(void)
4250 if (!mkdir_p(BASEDIR
, 0700)) {
4251 lxcfs_error("%s\n", "Failed to create lxcfs cgroup mountpoint.");
4255 if (!umount_if_mounted()) {
4256 lxcfs_error("%s\n", "Failed to clean up old lxcfs cgroup mountpoint.");
4260 if (unshare(CLONE_NEWNS
) < 0) {
4261 lxcfs_error("Failed to unshare mount namespace: %s.\n", strerror(errno
));
4265 if (mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, 0) < 0) {
4266 lxcfs_error("Failed to remount / private: %s.\n", strerror(errno
));
4270 if (mount("tmpfs", BASEDIR
, "tmpfs", 0, "size=100000,mode=700") < 0) {
4271 lxcfs_error("%s\n", "Failed to mount tmpfs over lxcfs cgroup mountpoint.");
4278 static bool do_mount_cgroups(void)
4284 for (i
= 0; i
< num_hierarchies
; i
++) {
4285 char *controller
= hierarchies
[i
];
4286 clen
= strlen(controller
);
4287 len
= strlen(BASEDIR
) + clen
+ 2;
4288 target
= malloc(len
);
4291 ret
= snprintf(target
, len
, "%s/%s", BASEDIR
, controller
);
4292 if (ret
< 0 || ret
>= len
) {
4296 if (mkdir(target
, 0755) < 0 && errno
!= EEXIST
) {
4300 if (mount(controller
, target
, "cgroup", 0, controller
) < 0) {
4301 lxcfs_error("Failed mounting cgroup %s\n", controller
);
4306 fd_hierarchies
[i
] = open(target
, O_DIRECTORY
);
4307 if (fd_hierarchies
[i
] < 0) {
4316 static bool cgfs_setup_controllers(void)
4318 if (!setup_cgfs_dir())
4321 if (!do_mount_cgroups()) {
4322 lxcfs_error("%s\n", "Failed to set up private lxcfs cgroup mounts.");
4326 if (!pivot_new_root())
4332 static int preserve_ns(int pid
)
4335 size_t len
= 5 /* /proc */ + 21 /* /int_as_str */ + 7 /* /ns/mnt */ + 1 /* \0 */;
4338 ret
= snprintf(path
, len
, "/proc/%d/ns/mnt", pid
);
4339 if (ret
< 0 || (size_t)ret
>= len
)
4342 return open(path
, O_RDONLY
| O_CLOEXEC
);
4345 static void __attribute__((constructor
)) collect_and_mount_subsystems(void)
4348 char *cret
, *line
= NULL
;
4349 char cwd
[MAXPATHLEN
];
4351 int i
, init_ns
= -1;
4353 if ((f
= fopen("/proc/self/cgroup", "r")) == NULL
) {
4354 lxcfs_error("Error opening /proc/self/cgroup: %s\n", strerror(errno
));
4358 while (getline(&line
, &len
, f
) != -1) {
4361 p
= strchr(line
, ':');
4366 p2
= strrchr(p
, ':');
4371 /* With cgroupv2 /proc/self/cgroup can contain entries of the
4372 * form: 0::/ This will cause lxcfs to fail the cgroup mounts
4373 * because it parses out the empty string "" and later on passes
4374 * it to mount(). Let's skip such entries.
4379 if (!store_hierarchy(line
, p
))
4383 /* Preserve initial namespace. */
4384 init_ns
= preserve_ns(getpid());
4386 lxcfs_error("%s\n", "Failed to preserve initial mount namespace.");
4390 fd_hierarchies
= malloc(sizeof(int *) * num_hierarchies
);
4391 if (!fd_hierarchies
) {
4392 lxcfs_error("%s\n", strerror(errno
));
4396 for (i
= 0; i
< num_hierarchies
; i
++)
4397 fd_hierarchies
[i
] = -1;
4399 cret
= getcwd(cwd
, MAXPATHLEN
);
4401 lxcfs_debug("Could not retrieve current working directory: %s.\n", strerror(errno
));
4403 /* This function calls unshare(CLONE_NEWNS) our initial mount namespace
4404 * to privately mount lxcfs cgroups. */
4405 if (!cgfs_setup_controllers()) {
4406 lxcfs_error("%s\n", "Failed to setup private cgroup mounts for lxcfs.");
4410 if (setns(init_ns
, 0) < 0) {
4411 lxcfs_error("Failed to switch back to initial mount namespace: %s.\n", strerror(errno
));
4415 if (!cret
|| chdir(cwd
) < 0)
4416 lxcfs_debug("Could not change back to original working directory: %s.\n", strerror(errno
));
4427 static void __attribute__((destructor
)) free_subsystems(void)
4431 lxcfs_debug("%s\n", "Running destructor for liblxcfs.");
4433 for (i
= 0; i
< num_hierarchies
; i
++) {
4435 free(hierarchies
[i
]);
4436 if (fd_hierarchies
&& fd_hierarchies
[i
] >= 0)
4437 close(fd_hierarchies
[i
]);
4440 free(fd_hierarchies
);