3 * Copyright © 2014-2016 Canonical, Inc
4 * Author: Serge Hallyn <serge.hallyn@ubuntu.com>
6 * See COPYING file for details.
9 #define FUSE_USE_VERSION 26
25 #include <linux/sched.h>
26 #include <sys/epoll.h>
28 #include <sys/mount.h>
29 #include <sys/param.h>
30 #include <sys/socket.h>
31 #include <sys/syscall.h>
34 #include "config.h" // for VERSION
36 /* Define pivot_root() if missing from the C library */
37 #ifndef HAVE_PIVOT_ROOT
38 static int pivot_root(const char * new_root
, const char * put_old
)
40 #ifdef __NR_pivot_root
41 return syscall(__NR_pivot_root
, new_root
, put_old
);
48 extern int pivot_root(const char * new_root
, const char * put_old
);
52 #define lxcfs_debug(format, ...) \
54 fprintf(stderr, "%s: %d: %s: " format, __FILE__, __LINE__, \
55 __func__, __VA_ARGS__); \
58 #define lxcfs_debug(format, ...)
64 LXC_TYPE_PROC_MEMINFO
,
65 LXC_TYPE_PROC_CPUINFO
,
68 LXC_TYPE_PROC_DISKSTATS
,
77 char *buf
; // unused as of yet
79 int size
; //actual data size
83 /* reserve buffer size, for cpuall in /proc/stat */
84 #define BUF_RESERVE_SIZE 256
87 * A table caching which pid is init for a pid namespace.
88 * When looking up which pid is init for $qpid, we first
89 * 1. Stat /proc/$qpid/ns/pid.
90 * 2. Check whether the ino_t is in our store.
91 * a. if not, fork a child in qpid's ns to send us
92 * ucred.pid = 1, and read the initpid. Cache
93 * initpid and creation time for /proc/initpid
94 * in a new store entry.
95 * b. if so, verify that /proc/initpid still matches
96 * what we have saved. If not, clear the store
97 * entry and go back to a. If so, return the
100 struct pidns_init_store
{
101 ino_t ino
; // inode number for /proc/$pid/ns/pid
102 pid_t initpid
; // the pid of nit in that ns
103 long int ctime
; // the time at which /proc/$initpid was created
104 struct pidns_init_store
*next
;
108 /* lol - look at how they are allocated in the kernel */
109 #define PIDNS_HASH_SIZE 4096
110 #define HASH(x) ((x) % PIDNS_HASH_SIZE)
112 static struct pidns_init_store
*pidns_hash_table
[PIDNS_HASH_SIZE
];
113 static pthread_mutex_t pidns_store_mutex
= PTHREAD_MUTEX_INITIALIZER
;
114 static void lock_mutex(pthread_mutex_t
*l
)
118 if ((ret
= pthread_mutex_lock(l
)) != 0) {
119 fprintf(stderr
, "pthread_mutex_lock returned:%d %s\n", ret
, strerror(ret
));
124 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
125 * Number of hierarchies mounted. */
126 static int num_hierarchies
;
128 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
129 * Hierachies mounted {cpuset, blkio, ...}:
130 * Initialized via __constructor__ collect_and_mount_subsystems(). */
131 static char **hierarchies
;
133 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
134 * Open file descriptors:
135 * @fd_hierarchies[i] refers to cgroup @hierarchies[i]. They are mounted in a
136 * private mount namespace.
137 * Initialized via __constructor__ collect_and_mount_subsystems().
138 * @fd_hierarchies[i] can be used to perform file operations on the cgroup
139 * mounts and respective files in the private namespace even when located in
140 * another namespace using the *at() family of functions
141 * {openat(), fchownat(), ...}. */
142 static int *fd_hierarchies
;
144 static void unlock_mutex(pthread_mutex_t
*l
)
148 if ((ret
= pthread_mutex_unlock(l
)) != 0) {
149 fprintf(stderr
, "pthread_mutex_unlock returned:%d %s\n", ret
, strerror(ret
));
154 static void store_lock(void)
156 lock_mutex(&pidns_store_mutex
);
159 static void store_unlock(void)
161 unlock_mutex(&pidns_store_mutex
);
164 /* Must be called under store_lock */
165 static bool initpid_still_valid(struct pidns_init_store
*e
, struct stat
*nsfdsb
)
170 snprintf(fnam
, 100, "/proc/%d", e
->initpid
);
171 if (stat(fnam
, &initsb
) < 0)
174 lxcfs_debug("Comparing ctime %ld == %ld for pid %d.\n", e
->ctime
,
175 initsb
.st_ctime
, e
->initpid
);
177 if (e
->ctime
!= initsb
.st_ctime
)
182 /* Must be called under store_lock */
183 static void remove_initpid(struct pidns_init_store
*e
)
185 struct pidns_init_store
*tmp
;
188 lxcfs_debug("Remove_initpid: removing entry for %d.\n", e
->initpid
);
191 if (pidns_hash_table
[h
] == e
) {
192 pidns_hash_table
[h
] = e
->next
;
197 tmp
= pidns_hash_table
[h
];
199 if (tmp
->next
== e
) {
209 /* Must be called under store_lock */
210 static void prune_initpid_store(void)
212 static long int last_prune
= 0;
213 struct pidns_init_store
*e
, *prev
, *delme
;
214 long int now
, threshold
;
218 last_prune
= time(NULL
);
222 if (now
< last_prune
+ PURGE_SECS
)
225 lxcfs_debug("%s\n", "Pruning.");
228 threshold
= now
- 2 * PURGE_SECS
;
230 for (i
= 0; i
< PIDNS_HASH_SIZE
; i
++) {
231 for (prev
= NULL
, e
= pidns_hash_table
[i
]; e
; ) {
232 if (e
->lastcheck
< threshold
) {
234 lxcfs_debug("Removing cached entry for %d.\n", e
->initpid
);
238 prev
->next
= e
->next
;
240 pidns_hash_table
[i
] = e
->next
;
251 /* Must be called under store_lock */
252 static void save_initpid(struct stat
*sb
, pid_t pid
)
254 struct pidns_init_store
*e
;
259 lxcfs_debug("Save_initpid: adding entry for %d.\n", pid
);
261 snprintf(fpath
, 100, "/proc/%d", pid
);
262 if (stat(fpath
, &procsb
) < 0)
265 e
= malloc(sizeof(*e
));
269 e
->ctime
= procsb
.st_ctime
;
271 e
->next
= pidns_hash_table
[h
];
272 e
->lastcheck
= time(NULL
);
273 pidns_hash_table
[h
] = e
;
277 * Given the stat(2) info for a nsfd pid inode, lookup the init_pid_store
278 * entry for the inode number and creation time. Verify that the init pid
279 * is still valid. If not, remove it. Return the entry if valid, NULL
281 * Must be called under store_lock
283 static struct pidns_init_store
*lookup_verify_initpid(struct stat
*sb
)
285 int h
= HASH(sb
->st_ino
);
286 struct pidns_init_store
*e
= pidns_hash_table
[h
];
289 if (e
->ino
== sb
->st_ino
) {
290 if (initpid_still_valid(e
, sb
)) {
291 e
->lastcheck
= time(NULL
);
303 static int is_dir(const char *path
, int fd
)
306 int ret
= fstatat(fd
, path
, &statbuf
, fd
);
307 if (ret
== 0 && S_ISDIR(statbuf
.st_mode
))
312 static char *must_copy_string(const char *str
)
324 static inline void drop_trailing_newlines(char *s
)
328 for (l
=strlen(s
); l
>0 && s
[l
-1] == '\n'; l
--)
332 #define BATCH_SIZE 50
333 static void dorealloc(char **mem
, size_t oldlen
, size_t newlen
)
335 int newbatches
= (newlen
/ BATCH_SIZE
) + 1;
336 int oldbatches
= (oldlen
/ BATCH_SIZE
) + 1;
338 if (!*mem
|| newbatches
> oldbatches
) {
341 tmp
= realloc(*mem
, newbatches
* BATCH_SIZE
);
346 static void append_line(char **contents
, size_t *len
, char *line
, ssize_t linelen
)
348 size_t newlen
= *len
+ linelen
;
349 dorealloc(contents
, *len
, newlen
+ 1);
350 memcpy(*contents
+ *len
, line
, linelen
+1);
354 static char *slurp_file(const char *from
, int fd
)
357 char *contents
= NULL
;
358 FILE *f
= fdopen(fd
, "r");
359 size_t len
= 0, fulllen
= 0;
365 while ((linelen
= getline(&line
, &len
, f
)) != -1) {
366 append_line(&contents
, &fulllen
, line
, linelen
);
371 drop_trailing_newlines(contents
);
376 static bool write_string(const char *fnam
, const char *string
, int fd
)
381 if (!(f
= fdopen(fd
, "w")))
383 len
= strlen(string
);
384 ret
= fwrite(string
, 1, len
, f
);
386 fprintf(stderr
, "Error writing to file: %s\n", strerror(errno
));
391 fprintf(stderr
, "Error writing to file: %s\n", strerror(errno
));
404 static bool store_hierarchy(char *stridx
, char *h
)
406 if (num_hierarchies
% ALLOC_NUM
== 0) {
407 size_t n
= (num_hierarchies
/ ALLOC_NUM
) + 1;
409 char **tmp
= realloc(hierarchies
, n
* sizeof(char *));
411 fprintf(stderr
, "Out of memory\n");
417 hierarchies
[num_hierarchies
++] = must_copy_string(h
);
421 static void print_subsystems(void)
425 fprintf(stderr
, "hierarchies:\n");
426 for (i
= 0; i
< num_hierarchies
; i
++) {
428 fprintf(stderr
, " %d: %s\n", i
, hierarchies
[i
]);
432 static bool in_comma_list(const char *needle
, const char *haystack
)
434 const char *s
= haystack
, *e
;
435 size_t nlen
= strlen(needle
);
437 while (*s
&& (e
= strchr(s
, ','))) {
442 if (strncmp(needle
, s
, nlen
) == 0)
446 if (strcmp(needle
, s
) == 0)
451 /* do we need to do any massaging here? I'm not sure... */
452 /* Return the mounted controller and store the corresponding open file descriptor
453 * referring to the controller mountpoint in the private lxcfs namespace in
456 static char *find_mounted_controller(const char *controller
, int *cfd
)
460 for (i
= 0; i
< num_hierarchies
; i
++) {
463 if (strcmp(hierarchies
[i
], controller
) == 0) {
464 *cfd
= fd_hierarchies
[i
];
465 return hierarchies
[i
];
467 if (in_comma_list(controller
, hierarchies
[i
])) {
468 *cfd
= fd_hierarchies
[i
];
469 return hierarchies
[i
];
476 bool cgfs_set_value(const char *controller
, const char *cgroup
, const char *file
,
483 tmpc
= find_mounted_controller(controller
, &cfd
);
487 /* Make sure we pass a relative path to *at() family of functions.
488 * . + /cgroup + / + file + \0
490 len
= strlen(cgroup
) + strlen(file
) + 3;
492 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, file
);
493 if (ret
< 0 || (size_t)ret
>= len
)
496 fd
= openat(cfd
, fnam
, O_WRONLY
);
500 return write_string(fnam
, value
, fd
);
503 // Chown all the files in the cgroup directory. We do this when we create
504 // a cgroup on behalf of a user.
505 static void chown_all_cgroup_files(const char *dirname
, uid_t uid
, gid_t gid
, int fd
)
507 struct dirent
*direntp
;
508 char path
[MAXPATHLEN
];
513 len
= strlen(dirname
);
514 if (len
>= MAXPATHLEN
) {
515 fprintf(stderr
, "chown_all_cgroup_files: pathname too long: %s\n", dirname
);
519 fd1
= openat(fd
, dirname
, O_DIRECTORY
);
525 fprintf(stderr
, "chown_all_cgroup_files: failed to open %s\n", dirname
);
529 while ((direntp
= readdir(d
))) {
530 if (!strcmp(direntp
->d_name
, ".") || !strcmp(direntp
->d_name
, ".."))
532 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
533 if (ret
< 0 || ret
>= MAXPATHLEN
) {
534 fprintf(stderr
, "chown_all_cgroup_files: pathname too long under %s\n", dirname
);
537 if (fchownat(fd
, path
, uid
, gid
, 0) < 0)
538 fprintf(stderr
, "Failed to chown file %s to %u:%u", path
, uid
, gid
);
543 int cgfs_create(const char *controller
, const char *cg
, uid_t uid
, gid_t gid
)
549 tmpc
= find_mounted_controller(controller
, &cfd
);
553 /* Make sure we pass a relative path to *at() family of functions.
556 len
= strlen(cg
) + 2;
557 dirnam
= alloca(len
);
558 snprintf(dirnam
, len
, "%s%s", *cg
== '/' ? "." : "", cg
);
560 if (mkdirat(cfd
, dirnam
, 0755) < 0)
563 if (uid
== 0 && gid
== 0)
566 if (fchownat(cfd
, dirnam
, uid
, gid
, 0) < 0)
569 chown_all_cgroup_files(dirnam
, uid
, gid
, cfd
);
574 static bool recursive_rmdir(const char *dirname
, int fd
)
576 struct dirent
*direntp
;
579 char pathname
[MAXPATHLEN
];
582 dupfd
= dup(fd
); // fdopendir() does bad things once it uses an fd.
586 dir
= fdopendir(dupfd
);
588 lxcfs_debug("Failed to open %s: %s.\n", dirname
, strerror(errno
));
592 while ((direntp
= readdir(dir
))) {
599 if (!strcmp(direntp
->d_name
, ".") ||
600 !strcmp(direntp
->d_name
, ".."))
603 rc
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
604 if (rc
< 0 || rc
>= MAXPATHLEN
) {
605 fprintf(stderr
, "pathname too long\n");
609 ret
= fstatat(fd
, pathname
, &mystat
, AT_SYMLINK_NOFOLLOW
);
611 lxcfs_debug("Failed to stat %s: %s.\n", pathname
, strerror(errno
));
614 if (S_ISDIR(mystat
.st_mode
))
615 if (!recursive_rmdir(pathname
, fd
))
616 lxcfs_debug("Error removing %s.\n", pathname
);
620 if (closedir(dir
) < 0) {
621 fprintf(stderr
, "%s: failed to close directory %s: %s\n", __func__
, dirname
, strerror(errno
));
625 if (unlinkat(fd
, dirname
, AT_REMOVEDIR
) < 0) {
626 lxcfs_debug("Failed to delete %s: %s.\n", dirname
, strerror(errno
));
634 bool cgfs_remove(const char *controller
, const char *cg
)
640 tmpc
= find_mounted_controller(controller
, &cfd
);
644 /* Make sure we pass a relative path to *at() family of functions.
647 len
= strlen(cg
) + 2;
648 dirnam
= alloca(len
);
649 snprintf(dirnam
, len
, "%s%s", *cg
== '/' ? "." : "", cg
);
651 fd
= openat(cfd
, dirnam
, O_DIRECTORY
);
655 return recursive_rmdir(dirnam
, fd
);
658 bool cgfs_chmod_file(const char *controller
, const char *file
, mode_t mode
)
662 char *pathname
, *tmpc
;
664 tmpc
= find_mounted_controller(controller
, &cfd
);
668 /* Make sure we pass a relative path to *at() family of functions.
671 len
= strlen(file
) + 2;
672 pathname
= alloca(len
);
673 snprintf(pathname
, len
, "%s%s", *file
== '/' ? "." : "", file
);
674 if (fchmodat(cfd
, pathname
, mode
, 0) < 0)
679 static int chown_tasks_files(const char *dirname
, uid_t uid
, gid_t gid
, int fd
)
684 len
= strlen(dirname
) + strlen("/cgroup.procs") + 1;
686 snprintf(fname
, len
, "%s/tasks", dirname
);
687 if (fchownat(fd
, fname
, uid
, gid
, 0) != 0)
689 snprintf(fname
, len
, "%s/cgroup.procs", dirname
);
690 if (fchownat(fd
, fname
, uid
, gid
, 0) != 0)
695 int cgfs_chown_file(const char *controller
, const char *file
, uid_t uid
, gid_t gid
)
699 char *pathname
, *tmpc
;
701 tmpc
= find_mounted_controller(controller
, &cfd
);
705 /* Make sure we pass a relative path to *at() family of functions.
708 len
= strlen(file
) + 2;
709 pathname
= alloca(len
);
710 snprintf(pathname
, len
, "%s%s", *file
== '/' ? "." : "", file
);
711 if (fchownat(cfd
, pathname
, uid
, gid
, 0) < 0)
714 if (is_dir(pathname
, cfd
))
715 // like cgmanager did, we want to chown the tasks file as well
716 return chown_tasks_files(pathname
, uid
, gid
, cfd
);
721 FILE *open_pids_file(const char *controller
, const char *cgroup
)
725 char *pathname
, *tmpc
;
727 tmpc
= find_mounted_controller(controller
, &cfd
);
731 /* Make sure we pass a relative path to *at() family of functions.
732 * . + /cgroup + / "cgroup.procs" + \0
734 len
= strlen(cgroup
) + strlen("cgroup.procs") + 3;
735 pathname
= alloca(len
);
736 snprintf(pathname
, len
, "%s%s/cgroup.procs", *cgroup
== '/' ? "." : "", cgroup
);
738 fd
= openat(cfd
, pathname
, O_WRONLY
);
742 return fdopen(fd
, "w");
745 static bool cgfs_iterate_cgroup(const char *controller
, const char *cgroup
, bool directories
,
746 void ***list
, size_t typesize
,
747 void* (*iterator
)(const char*, const char*, const char*))
752 char pathname
[MAXPATHLEN
];
753 size_t sz
= 0, asz
= 0;
754 struct dirent
*dirent
;
757 tmpc
= find_mounted_controller(controller
, &cfd
);
762 /* Make sure we pass a relative path to *at() family of functions. */
763 len
= strlen(cgroup
) + 1 /* . */ + 1 /* \0 */;
765 ret
= snprintf(cg
, len
, "%s%s", *cgroup
== '/' ? "." : "", cgroup
);
766 if (ret
< 0 || (size_t)ret
>= len
) {
767 fprintf(stderr
, "%s: pathname too long under %s\n", __func__
, cgroup
);
771 fd
= openat(cfd
, cg
, O_DIRECTORY
);
779 while ((dirent
= readdir(dir
))) {
782 if (!strcmp(dirent
->d_name
, ".") ||
783 !strcmp(dirent
->d_name
, ".."))
786 ret
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", cg
, dirent
->d_name
);
787 if (ret
< 0 || ret
>= MAXPATHLEN
) {
788 fprintf(stderr
, "%s: pathname too long under %s\n", __func__
, cg
);
792 ret
= fstatat(cfd
, pathname
, &mystat
, AT_SYMLINK_NOFOLLOW
);
794 fprintf(stderr
, "%s: failed to stat %s: %s\n", __func__
, pathname
, strerror(errno
));
797 if ((!directories
&& !S_ISREG(mystat
.st_mode
)) ||
798 (directories
&& !S_ISDIR(mystat
.st_mode
)))
805 tmp
= realloc(*list
, asz
* typesize
);
809 (*list
)[sz
] = (*iterator
)(controller
, cg
, dirent
->d_name
);
810 (*list
)[sz
+1] = NULL
;
813 if (closedir(dir
) < 0) {
814 fprintf(stderr
, "%s: failed closedir for %s: %s\n", __func__
, cgroup
, strerror(errno
));
820 static void *make_children_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
824 dup
= strdup(dir_entry
);
829 bool cgfs_list_children(const char *controller
, const char *cgroup
, char ***list
)
831 return cgfs_iterate_cgroup(controller
, cgroup
, true, (void***)list
, sizeof(*list
), &make_children_list_entry
);
834 void free_key(struct cgfs_files
*k
)
842 void free_keys(struct cgfs_files
**keys
)
848 for (i
= 0; keys
[i
]; i
++) {
854 bool cgfs_get_value(const char *controller
, const char *cgroup
, const char *file
, char **value
)
860 tmpc
= find_mounted_controller(controller
, &cfd
);
864 /* Make sure we pass a relative path to *at() family of functions.
865 * . + /cgroup + / + file + \0
867 len
= strlen(cgroup
) + strlen(file
) + 3;
869 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, file
);
870 if (ret
< 0 || (size_t)ret
>= len
)
873 fd
= openat(cfd
, fnam
, O_RDONLY
);
877 *value
= slurp_file(fnam
, fd
);
878 return *value
!= NULL
;
881 struct cgfs_files
*cgfs_get_key(const char *controller
, const char *cgroup
, const char *file
)
887 struct cgfs_files
*newkey
;
889 tmpc
= find_mounted_controller(controller
, &cfd
);
893 if (file
&& *file
== '/')
896 if (file
&& strchr(file
, '/'))
899 /* Make sure we pass a relative path to *at() family of functions.
900 * . + /cgroup + / + file + \0
902 len
= strlen(cgroup
) + 3;
904 len
+= strlen(file
) + 1;
906 snprintf(fnam
, len
, "%s%s%s%s", *cgroup
== '/' ? "." : "", cgroup
,
907 file
? "/" : "", file
? file
: "");
909 ret
= fstatat(cfd
, fnam
, &sb
, 0);
914 newkey
= malloc(sizeof(struct cgfs_files
));
917 newkey
->name
= must_copy_string(file
);
918 else if (strrchr(cgroup
, '/'))
919 newkey
->name
= must_copy_string(strrchr(cgroup
, '/'));
921 newkey
->name
= must_copy_string(cgroup
);
922 newkey
->uid
= sb
.st_uid
;
923 newkey
->gid
= sb
.st_gid
;
924 newkey
->mode
= sb
.st_mode
;
929 static void *make_key_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
931 struct cgfs_files
*entry
= cgfs_get_key(controller
, cgroup
, dir_entry
);
933 fprintf(stderr
, "%s: Error getting files under %s:%s\n",
934 __func__
, controller
, cgroup
);
939 bool cgfs_list_keys(const char *controller
, const char *cgroup
, struct cgfs_files
***keys
)
941 return cgfs_iterate_cgroup(controller
, cgroup
, false, (void***)keys
, sizeof(*keys
), &make_key_list_entry
);
944 bool is_child_cgroup(const char *controller
, const char *cgroup
, const char *f
)
952 tmpc
= find_mounted_controller(controller
, &cfd
);
956 /* Make sure we pass a relative path to *at() family of functions.
957 * . + /cgroup + / + f + \0
959 len
= strlen(cgroup
) + strlen(f
) + 3;
961 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, f
);
962 if (ret
< 0 || (size_t)ret
>= len
)
965 ret
= fstatat(cfd
, fnam
, &sb
, 0);
966 if (ret
< 0 || !S_ISDIR(sb
.st_mode
))
972 #define SEND_CREDS_OK 0
973 #define SEND_CREDS_NOTSK 1
974 #define SEND_CREDS_FAIL 2
975 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
);
976 static int wait_for_pid(pid_t pid
);
977 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
);
978 static int send_creds_clone_wrapper(void *arg
);
981 * clone a task which switches to @task's namespace and writes '1'.
982 * over a unix sock so we can read the task's reaper's pid in our
985 * Note: glibc's fork() does not respect pidns, which can lead to failed
986 * assertions inside glibc (and thus failed forks) if the child's pid in
987 * the pidns and the parent pid outside are identical. Using clone prevents
990 static void write_task_init_pid_exit(int sock
, pid_t target
)
995 size_t stack_size
= sysconf(_SC_PAGESIZE
);
996 void *stack
= alloca(stack_size
);
998 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", (int)target
);
999 if (ret
< 0 || ret
>= sizeof(fnam
))
1002 fd
= open(fnam
, O_RDONLY
);
1004 perror("write_task_init_pid_exit open of ns/pid");
1008 perror("write_task_init_pid_exit setns 1");
1012 pid
= clone(send_creds_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &sock
);
1016 if (!wait_for_pid(pid
))
1022 static int send_creds_clone_wrapper(void *arg
) {
1025 int sock
= *(int *)arg
;
1027 /* we are the child */
1032 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
)
1037 static pid_t
get_init_pid_for_task(pid_t task
)
1045 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
1046 perror("socketpair");
1055 write_task_init_pid_exit(sock
[0], task
);
1059 if (!recv_creds(sock
[1], &cred
, &v
))
1071 static pid_t
lookup_initpid_in_store(pid_t qpid
)
1075 struct pidns_init_store
*e
;
1078 snprintf(fnam
, 100, "/proc/%d/ns/pid", qpid
);
1080 if (stat(fnam
, &sb
) < 0)
1082 e
= lookup_verify_initpid(&sb
);
1084 answer
= e
->initpid
;
1087 answer
= get_init_pid_for_task(qpid
);
1089 save_initpid(&sb
, answer
);
1092 /* we prune at end in case we are returning
1093 * the value we were about to return */
1094 prune_initpid_store();
1099 static int wait_for_pid(pid_t pid
)
1107 ret
= waitpid(pid
, &status
, 0);
1115 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
1122 * append pid to *src.
1123 * src: a pointer to a char* in which ot append the pid.
1124 * sz: the number of characters printed so far, minus trailing \0.
1125 * asz: the allocated size so far
1126 * pid: the pid to append
1128 static void must_strcat_pid(char **src
, size_t *sz
, size_t *asz
, pid_t pid
)
1132 int tmplen
= sprintf(tmp
, "%d\n", (int)pid
);
1134 if (!*src
|| tmplen
+ *sz
+ 1 >= *asz
) {
1137 tmp
= realloc(*src
, *asz
+ BUF_RESERVE_SIZE
);
1140 *asz
+= BUF_RESERVE_SIZE
;
1142 memcpy((*src
) +*sz
, tmp
, tmplen
+1); /* include the \0 */
1147 * Given a open file * to /proc/pid/{u,g}id_map, and an id
1148 * valid in the caller's namespace, return the id mapped into
1150 * Returns the mapped id, or -1 on error.
1153 convert_id_to_ns(FILE *idfile
, unsigned int in_id
)
1155 unsigned int nsuid
, // base id for a range in the idfile's namespace
1156 hostuid
, // base id for a range in the caller's namespace
1157 count
; // number of ids in this range
1161 fseek(idfile
, 0L, SEEK_SET
);
1162 while (fgets(line
, 400, idfile
)) {
1163 ret
= sscanf(line
, "%u %u %u\n", &nsuid
, &hostuid
, &count
);
1166 if (hostuid
+ count
< hostuid
|| nsuid
+ count
< nsuid
) {
1168 * uids wrapped around - unexpected as this is a procfile,
1171 fprintf(stderr
, "pid wrapparound at entry %u %u %u in %s\n",
1172 nsuid
, hostuid
, count
, line
);
1175 if (hostuid
<= in_id
&& hostuid
+count
> in_id
) {
1177 * now since hostuid <= in_id < hostuid+count, and
1178 * hostuid+count and nsuid+count do not wrap around,
1179 * we know that nsuid+(in_id-hostuid) which must be
1180 * less that nsuid+(count) must not wrap around
1182 return (in_id
- hostuid
) + nsuid
;
1191 * for is_privileged_over,
1192 * specify whether we require the calling uid to be root in his
1195 #define NS_ROOT_REQD true
1196 #define NS_ROOT_OPT false
1200 static bool is_privileged_over(pid_t pid
, uid_t uid
, uid_t victim
, bool req_ns_root
)
1202 char fpath
[PROCLEN
];
1204 bool answer
= false;
1207 if (victim
== -1 || uid
== -1)
1211 * If the request is one not requiring root in the namespace,
1212 * then having the same uid suffices. (i.e. uid 1000 has write
1213 * access to files owned by uid 1000
1215 if (!req_ns_root
&& uid
== victim
)
1218 ret
= snprintf(fpath
, PROCLEN
, "/proc/%d/uid_map", pid
);
1219 if (ret
< 0 || ret
>= PROCLEN
)
1221 FILE *f
= fopen(fpath
, "r");
1225 /* if caller's not root in his namespace, reject */
1226 nsuid
= convert_id_to_ns(f
, uid
);
1231 * If victim is not mapped into caller's ns, reject.
1232 * XXX I'm not sure this check is needed given that fuse
1233 * will be sending requests where the vfs has converted
1235 nsuid
= convert_id_to_ns(f
, victim
);
1246 static bool perms_include(int fmode
, mode_t req_mode
)
1250 switch (req_mode
& O_ACCMODE
) {
1258 r
= S_IROTH
| S_IWOTH
;
1263 return ((fmode
& r
) == r
);
1269 * querycg is /a/b/c/d/e
1272 static char *get_next_cgroup_dir(const char *taskcg
, const char *querycg
)
1276 if (strlen(taskcg
) <= strlen(querycg
)) {
1277 fprintf(stderr
, "%s: I was fed bad input\n", __func__
);
1281 if ((strcmp(querycg
, "/") == 0) || (strcmp(querycg
, "./") == 0))
1282 start
= strdup(taskcg
+ 1);
1284 start
= strdup(taskcg
+ strlen(querycg
) + 1);
1287 end
= strchr(start
, '/');
1293 static void stripnewline(char *x
)
1295 size_t l
= strlen(x
);
1296 if (l
&& x
[l
-1] == '\n')
1300 static char *get_pid_cgroup(pid_t pid
, const char *contrl
)
1305 char *answer
= NULL
;
1309 const char *h
= find_mounted_controller(contrl
, &cfd
);
1313 ret
= snprintf(fnam
, PROCLEN
, "/proc/%d/cgroup", pid
);
1314 if (ret
< 0 || ret
>= PROCLEN
)
1316 if (!(f
= fopen(fnam
, "r")))
1319 while (getline(&line
, &len
, f
) != -1) {
1323 c1
= strchr(line
, ':');
1327 c2
= strchr(c1
, ':');
1331 if (strcmp(c1
, h
) != 0)
1336 answer
= strdup(c2
);
1348 * check whether a fuse context may access a cgroup dir or file
1350 * If file is not null, it is a cgroup file to check under cg.
1351 * If file is null, then we are checking perms on cg itself.
1353 * For files we can check the mode of the list_keys result.
1354 * For cgroups, we must make assumptions based on the files under the
1355 * cgroup, because cgmanager doesn't tell us ownership/perms of cgroups
1358 static bool fc_may_access(struct fuse_context
*fc
, const char *contrl
, const char *cg
, const char *file
, mode_t mode
)
1360 struct cgfs_files
*k
= NULL
;
1363 k
= cgfs_get_key(contrl
, cg
, file
);
1367 if (is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
1368 if (perms_include(k
->mode
>> 6, mode
)) {
1373 if (fc
->gid
== k
->gid
) {
1374 if (perms_include(k
->mode
>> 3, mode
)) {
1379 ret
= perms_include(k
->mode
, mode
);
1386 #define INITSCOPE "/init.scope"
1387 static void prune_init_slice(char *cg
)
1390 size_t cg_len
= strlen(cg
), initscope_len
= strlen(INITSCOPE
);
1392 if (cg_len
< initscope_len
)
1395 point
= cg
+ cg_len
- initscope_len
;
1396 if (strcmp(point
, INITSCOPE
) == 0) {
1405 * If pid is in /a/b/c/d, he may only act on things under cg=/a/b/c/d.
1406 * If pid is in /a, he may act on /a/b, but not on /b.
1407 * if the answer is false and nextcg is not NULL, then *nextcg will point
1408 * to a string containing the next cgroup directory under cg, which must be
1409 * freed by the caller.
1411 static bool caller_is_in_ancestor(pid_t pid
, const char *contrl
, const char *cg
, char **nextcg
)
1413 bool answer
= false;
1414 char *c2
= get_pid_cgroup(pid
, contrl
);
1419 prune_init_slice(c2
);
1422 * callers pass in '/' or './' (openat()) for root cgroup, otherwise
1423 * they pass in a cgroup without leading '/'
1425 * The original line here was:
1426 * linecmp = *cg == '/' ? c2 : c2+1;
1427 * TODO: I'm not sure why you'd want to increment when *cg != '/'?
1428 * Serge, do you know?
1430 if (*cg
== '/' || !strncmp(cg
, "./", 2))
1434 if (strncmp(linecmp
, cg
, strlen(linecmp
)) != 0) {
1436 *nextcg
= get_next_cgroup_dir(linecmp
, cg
);
1448 * If pid is in /a/b/c, he may see that /a exists, but not /b or /a/c.
1450 static bool caller_may_see_dir(pid_t pid
, const char *contrl
, const char *cg
)
1452 bool answer
= false;
1454 size_t target_len
, task_len
;
1456 if (strcmp(cg
, "/") == 0 || strcmp(cg
, "./") == 0)
1459 c2
= get_pid_cgroup(pid
, contrl
);
1462 prune_init_slice(c2
);
1465 target_len
= strlen(cg
);
1466 task_len
= strlen(task_cg
);
1467 if (task_len
== 0) {
1468 /* Task is in the root cg, it can see everything. This case is
1469 * not handled by the strmcps below, since they test for the
1470 * last /, but that is the first / that we've chopped off
1476 if (strcmp(cg
, task_cg
) == 0) {
1480 if (target_len
< task_len
) {
1481 /* looking up a parent dir */
1482 if (strncmp(task_cg
, cg
, target_len
) == 0 && task_cg
[target_len
] == '/')
1486 if (target_len
> task_len
) {
1487 /* looking up a child dir */
1488 if (strncmp(task_cg
, cg
, task_len
) == 0 && cg
[task_len
] == '/')
1499 * given /cgroup/freezer/a/b, return "freezer".
1500 * the returned char* should NOT be freed.
1502 static char *pick_controller_from_path(struct fuse_context
*fc
, const char *path
)
1505 char *contr
, *slash
;
1507 if (strlen(path
) < 9)
1509 if (*(path
+7) != '/')
1512 contr
= strdupa(p1
);
1515 slash
= strstr(contr
, "/");
1520 for (i
= 0; i
< num_hierarchies
; i
++) {
1521 if (hierarchies
[i
] && strcmp(hierarchies
[i
], contr
) == 0)
1522 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)
1537 p1
= strstr(path
+8, "/");
1544 * split the last path element from the path in @cg.
1545 * @dir is newly allocated and should be freed, @last not
1547 static void get_cgdir_and_path(const char *cg
, char **dir
, char **last
)
1554 *last
= strrchr(cg
, '/');
1559 p
= strrchr(*dir
, '/');
1564 * FUSE ops for /cgroup
1567 int cg_getattr(const char *path
, struct stat
*sb
)
1569 struct timespec now
;
1570 struct fuse_context
*fc
= fuse_get_context();
1571 char * cgdir
= NULL
;
1572 char *last
= NULL
, *path1
, *path2
;
1573 struct cgfs_files
*k
= NULL
;
1575 const char *controller
= NULL
;
1582 memset(sb
, 0, sizeof(struct stat
));
1584 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
1587 sb
->st_uid
= sb
->st_gid
= 0;
1588 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
1591 if (strcmp(path
, "/cgroup") == 0) {
1592 sb
->st_mode
= S_IFDIR
| 00755;
1597 controller
= pick_controller_from_path(fc
, path
);
1600 cgroup
= find_cgroup_in_path(path
);
1602 /* this is just /cgroup/controller, return it as a dir */
1603 sb
->st_mode
= S_IFDIR
| 00755;
1608 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
1618 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1621 /* check that cgcopy is either a child cgroup of cgdir, or listed in its keys.
1622 * Then check that caller's cgroup is under path if last is a child
1623 * cgroup, or cgdir if last is a file */
1625 if (is_child_cgroup(controller
, path1
, path2
)) {
1626 if (!caller_may_see_dir(initpid
, controller
, cgroup
)) {
1630 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
1631 /* this is just /cgroup/controller, return it as a dir */
1632 sb
->st_mode
= S_IFDIR
| 00555;
1637 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
)) {
1642 // get uid, gid, from '/tasks' file and make up a mode
1643 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
1644 sb
->st_mode
= S_IFDIR
| 00755;
1645 k
= cgfs_get_key(controller
, cgroup
, NULL
);
1647 sb
->st_uid
= sb
->st_gid
= 0;
1649 sb
->st_uid
= k
->uid
;
1650 sb
->st_gid
= k
->gid
;
1658 if ((k
= cgfs_get_key(controller
, path1
, path2
)) != NULL
) {
1659 sb
->st_mode
= S_IFREG
| k
->mode
;
1661 sb
->st_uid
= k
->uid
;
1662 sb
->st_gid
= k
->gid
;
1665 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
1669 if (!fc_may_access(fc
, controller
, path1
, path2
, O_RDONLY
)) {
1682 int cg_opendir(const char *path
, struct fuse_file_info
*fi
)
1684 struct fuse_context
*fc
= fuse_get_context();
1686 struct file_info
*dir_info
;
1687 char *controller
= NULL
;
1692 if (strcmp(path
, "/cgroup") == 0) {
1696 // return list of keys for the controller, and list of child cgroups
1697 controller
= pick_controller_from_path(fc
, path
);
1701 cgroup
= find_cgroup_in_path(path
);
1703 /* this is just /cgroup/controller, return its contents */
1708 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1712 if (!caller_may_see_dir(initpid
, controller
, cgroup
))
1714 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
))
1718 /* we'll free this at cg_releasedir */
1719 dir_info
= malloc(sizeof(*dir_info
));
1722 dir_info
->controller
= must_copy_string(controller
);
1723 dir_info
->cgroup
= must_copy_string(cgroup
);
1724 dir_info
->type
= LXC_TYPE_CGDIR
;
1725 dir_info
->buf
= NULL
;
1726 dir_info
->file
= NULL
;
1727 dir_info
->buflen
= 0;
1729 fi
->fh
= (unsigned long)dir_info
;
1733 int cg_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
1734 struct fuse_file_info
*fi
)
1736 struct file_info
*d
= (struct file_info
*)fi
->fh
;
1737 struct cgfs_files
**list
= NULL
;
1739 char *nextcg
= NULL
;
1740 struct fuse_context
*fc
= fuse_get_context();
1741 char **clist
= NULL
;
1743 if (d
->type
!= LXC_TYPE_CGDIR
) {
1744 fprintf(stderr
, "Internal error: file cache info used in readdir\n");
1747 if (!d
->cgroup
&& !d
->controller
) {
1748 // ls /var/lib/lxcfs/cgroup - just show list of controllers
1751 for (i
= 0; i
< num_hierarchies
; i
++) {
1752 if (hierarchies
[i
] && filler(buf
, hierarchies
[i
], NULL
, 0) != 0) {
1759 if (!cgfs_list_keys(d
->controller
, d
->cgroup
, &list
)) {
1760 // not a valid cgroup
1765 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1768 if (!caller_is_in_ancestor(initpid
, d
->controller
, d
->cgroup
, &nextcg
)) {
1770 ret
= filler(buf
, nextcg
, NULL
, 0);
1781 for (i
= 0; list
[i
]; i
++) {
1782 if (filler(buf
, list
[i
]->name
, NULL
, 0) != 0) {
1788 // now get the list of child cgroups
1790 if (!cgfs_list_children(d
->controller
, d
->cgroup
, &clist
)) {
1795 for (i
= 0; clist
[i
]; i
++) {
1796 if (filler(buf
, clist
[i
], NULL
, 0) != 0) {
1807 for (i
= 0; clist
[i
]; i
++)
1814 static void do_release_file_info(struct fuse_file_info
*fi
)
1816 struct file_info
*f
= (struct file_info
*)fi
->fh
;
1823 free(f
->controller
);
1824 f
->controller
= NULL
;
1834 int cg_releasedir(const char *path
, struct fuse_file_info
*fi
)
1836 do_release_file_info(fi
);
1840 int cg_open(const char *path
, struct fuse_file_info
*fi
)
1843 char *last
= NULL
, *path1
, *path2
, * cgdir
= NULL
, *controller
;
1844 struct cgfs_files
*k
= NULL
;
1845 struct file_info
*file_info
;
1846 struct fuse_context
*fc
= fuse_get_context();
1852 controller
= pick_controller_from_path(fc
, path
);
1855 cgroup
= find_cgroup_in_path(path
);
1859 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
1868 k
= cgfs_get_key(controller
, path1
, path2
);
1875 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1878 if (!caller_may_see_dir(initpid
, controller
, path1
)) {
1882 if (!fc_may_access(fc
, controller
, path1
, path2
, fi
->flags
)) {
1887 /* we'll free this at cg_release */
1888 file_info
= malloc(sizeof(*file_info
));
1893 file_info
->controller
= must_copy_string(controller
);
1894 file_info
->cgroup
= must_copy_string(path1
);
1895 file_info
->file
= must_copy_string(path2
);
1896 file_info
->type
= LXC_TYPE_CGFILE
;
1897 file_info
->buf
= NULL
;
1898 file_info
->buflen
= 0;
1900 fi
->fh
= (unsigned long)file_info
;
1908 int cg_access(const char *path
, int mode
)
1911 char *last
= NULL
, *path1
, *path2
, * cgdir
= NULL
, *controller
;
1912 struct cgfs_files
*k
= NULL
;
1913 struct fuse_context
*fc
= fuse_get_context();
1919 controller
= pick_controller_from_path(fc
, path
);
1922 cgroup
= find_cgroup_in_path(path
);
1924 // access("/sys/fs/cgroup/systemd", mode) - rx allowed, w not
1925 if ((mode
& W_OK
) == 0)
1930 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
1939 k
= cgfs_get_key(controller
, path1
, path2
);
1941 if ((mode
& W_OK
) == 0)
1949 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1952 if (!caller_may_see_dir(initpid
, controller
, path1
)) {
1956 if (!fc_may_access(fc
, controller
, path1
, path2
, mode
)) {
1968 int cg_release(const char *path
, struct fuse_file_info
*fi
)
1970 do_release_file_info(fi
);
1974 #define POLLIN_SET ( EPOLLIN | EPOLLHUP | EPOLLRDHUP )
1976 static bool wait_for_sock(int sock
, int timeout
)
1978 struct epoll_event ev
;
1979 int epfd
, ret
, now
, starttime
, deltatime
, saved_errno
;
1981 if ((starttime
= time(NULL
)) < 0)
1984 if ((epfd
= epoll_create(1)) < 0) {
1985 fprintf(stderr
, "Failed to create epoll socket: %m\n");
1989 ev
.events
= POLLIN_SET
;
1991 if (epoll_ctl(epfd
, EPOLL_CTL_ADD
, sock
, &ev
) < 0) {
1992 fprintf(stderr
, "Failed adding socket to epoll: %m\n");
1998 if ((now
= time(NULL
)) < 0) {
2003 deltatime
= (starttime
+ timeout
) - now
;
2004 if (deltatime
< 0) { // timeout
2009 ret
= epoll_wait(epfd
, &ev
, 1, 1000*deltatime
+ 1);
2010 if (ret
< 0 && errno
== EINTR
)
2012 saved_errno
= errno
;
2016 errno
= saved_errno
;
2022 static int msgrecv(int sockfd
, void *buf
, size_t len
)
2024 if (!wait_for_sock(sockfd
, 2))
2026 return recv(sockfd
, buf
, len
, MSG_DONTWAIT
);
2029 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
)
2031 struct msghdr msg
= { 0 };
2033 struct cmsghdr
*cmsg
;
2034 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
2039 if (msgrecv(sock
, buf
, 1) != 1) {
2040 fprintf(stderr
, "%s: Error getting reply from server over socketpair\n",
2042 return SEND_CREDS_FAIL
;
2046 msg
.msg_control
= cmsgbuf
;
2047 msg
.msg_controllen
= sizeof(cmsgbuf
);
2049 cmsg
= CMSG_FIRSTHDR(&msg
);
2050 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct ucred
));
2051 cmsg
->cmsg_level
= SOL_SOCKET
;
2052 cmsg
->cmsg_type
= SCM_CREDENTIALS
;
2053 memcpy(CMSG_DATA(cmsg
), cred
, sizeof(*cred
));
2055 msg
.msg_name
= NULL
;
2056 msg
.msg_namelen
= 0;
2060 iov
.iov_len
= sizeof(buf
);
2064 if (sendmsg(sock
, &msg
, 0) < 0) {
2065 fprintf(stderr
, "%s: failed at sendmsg: %s\n", __func__
,
2068 return SEND_CREDS_NOTSK
;
2069 return SEND_CREDS_FAIL
;
2072 return SEND_CREDS_OK
;
2075 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
)
2077 struct msghdr msg
= { 0 };
2079 struct cmsghdr
*cmsg
;
2080 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
2091 if (setsockopt(sock
, SOL_SOCKET
, SO_PASSCRED
, &optval
, sizeof(optval
)) == -1) {
2092 fprintf(stderr
, "Failed to set passcred: %s\n", strerror(errno
));
2096 if (write(sock
, buf
, 1) != 1) {
2097 fprintf(stderr
, "Failed to start write on scm fd: %s\n", strerror(errno
));
2101 msg
.msg_name
= NULL
;
2102 msg
.msg_namelen
= 0;
2103 msg
.msg_control
= cmsgbuf
;
2104 msg
.msg_controllen
= sizeof(cmsgbuf
);
2107 iov
.iov_len
= sizeof(buf
);
2111 if (!wait_for_sock(sock
, 2)) {
2112 fprintf(stderr
, "Timed out waiting for scm_cred: %s\n",
2116 ret
= recvmsg(sock
, &msg
, MSG_DONTWAIT
);
2118 fprintf(stderr
, "Failed to receive scm_cred: %s\n",
2123 cmsg
= CMSG_FIRSTHDR(&msg
);
2125 if (cmsg
&& cmsg
->cmsg_len
== CMSG_LEN(sizeof(struct ucred
)) &&
2126 cmsg
->cmsg_level
== SOL_SOCKET
&&
2127 cmsg
->cmsg_type
== SCM_CREDENTIALS
) {
2128 memcpy(cred
, CMSG_DATA(cmsg
), sizeof(*cred
));
2135 struct pid_ns_clone_args
{
2139 int (*wrapped
) (int, pid_t
); // pid_from_ns or pid_to_ns
2143 * pid_ns_clone_wrapper - wraps pid_to_ns or pid_from_ns for usage
2144 * with clone(). This simply writes '1' as ACK back to the parent
2145 * before calling the actual wrapped function.
2147 static int pid_ns_clone_wrapper(void *arg
) {
2148 struct pid_ns_clone_args
* args
= (struct pid_ns_clone_args
*) arg
;
2151 close(args
->cpipe
[0]);
2152 if (write(args
->cpipe
[1], &b
, sizeof(char)) < 0) {
2153 fprintf(stderr
, "%s (child): error on write: %s\n",
2154 __func__
, strerror(errno
));
2156 close(args
->cpipe
[1]);
2157 return args
->wrapped(args
->sock
, args
->tpid
);
2161 * pid_to_ns - reads pids from a ucred over a socket, then writes the
2162 * int value back over the socket. This shifts the pid from the
2163 * sender's pidns into tpid's pidns.
2165 static int pid_to_ns(int sock
, pid_t tpid
)
2170 while (recv_creds(sock
, &cred
, &v
)) {
2173 if (write(sock
, &cred
.pid
, sizeof(pid_t
)) != sizeof(pid_t
))
2181 * pid_to_ns_wrapper: when you setns into a pidns, you yourself remain
2182 * in your old pidns. Only children which you clone will be in the target
2183 * pidns. So the pid_to_ns_wrapper does the setns, then clones a child to
2184 * actually convert pids.
2186 * Note: glibc's fork() does not respect pidns, which can lead to failed
2187 * assertions inside glibc (and thus failed forks) if the child's pid in
2188 * the pidns and the parent pid outside are identical. Using clone prevents
2191 static void pid_to_ns_wrapper(int sock
, pid_t tpid
)
2193 int newnsfd
= -1, ret
, cpipe
[2];
2198 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
2199 if (ret
< 0 || ret
>= sizeof(fnam
))
2201 newnsfd
= open(fnam
, O_RDONLY
);
2204 if (setns(newnsfd
, 0) < 0)
2208 if (pipe(cpipe
) < 0)
2211 struct pid_ns_clone_args args
= {
2215 .wrapped
= &pid_to_ns
2217 size_t stack_size
= sysconf(_SC_PAGESIZE
);
2218 void *stack
= alloca(stack_size
);
2220 cpid
= clone(pid_ns_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &args
);
2224 // give the child 1 second to be done forking and
2226 if (!wait_for_sock(cpipe
[0], 1))
2228 ret
= read(cpipe
[0], &v
, 1);
2229 if (ret
!= sizeof(char) || v
!= '1')
2232 if (!wait_for_pid(cpid
))
2238 * To read cgroup files with a particular pid, we will setns into the child
2239 * pidns, open a pipe, fork a child - which will be the first to really be in
2240 * the child ns - which does the cgfs_get_value and writes the data to the pipe.
2242 bool do_read_pids(pid_t tpid
, const char *contrl
, const char *cg
, const char *file
, char **d
)
2244 int sock
[2] = {-1, -1};
2245 char *tmpdata
= NULL
;
2247 pid_t qpid
, cpid
= -1;
2248 bool answer
= false;
2251 size_t sz
= 0, asz
= 0;
2253 if (!cgfs_get_value(contrl
, cg
, file
, &tmpdata
))
2257 * Now we read the pids from returned data one by one, pass
2258 * them into a child in the target namespace, read back the
2259 * translated pids, and put them into our to-return data
2262 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2263 perror("socketpair");
2272 if (!cpid
) // child - exits when done
2273 pid_to_ns_wrapper(sock
[1], tpid
);
2275 char *ptr
= tmpdata
;
2278 while (sscanf(ptr
, "%d\n", &qpid
) == 1) {
2280 ret
= send_creds(sock
[0], &cred
, v
, true);
2282 if (ret
== SEND_CREDS_NOTSK
)
2284 if (ret
== SEND_CREDS_FAIL
)
2287 // read converted results
2288 if (!wait_for_sock(sock
[0], 2)) {
2289 fprintf(stderr
, "%s: timed out waiting for pid from child: %s\n",
2290 __func__
, strerror(errno
));
2293 if (read(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2294 fprintf(stderr
, "%s: error reading pid from child: %s\n",
2295 __func__
, strerror(errno
));
2298 must_strcat_pid(d
, &sz
, &asz
, qpid
);
2300 ptr
= strchr(ptr
, '\n');
2306 cred
.pid
= getpid();
2308 if (send_creds(sock
[0], &cred
, v
, true) != SEND_CREDS_OK
) {
2309 // failed to ask child to exit
2310 fprintf(stderr
, "%s: failed to ask child to exit: %s\n",
2311 __func__
, strerror(errno
));
2321 if (sock
[0] != -1) {
2328 int cg_read(const char *path
, char *buf
, size_t size
, off_t offset
,
2329 struct fuse_file_info
*fi
)
2331 struct fuse_context
*fc
= fuse_get_context();
2332 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2333 struct cgfs_files
*k
= NULL
;
2338 if (f
->type
!= LXC_TYPE_CGFILE
) {
2339 fprintf(stderr
, "Internal error: directory cache info used in cg_read\n");
2352 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
2358 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_RDONLY
)) {
2363 if (strcmp(f
->file
, "tasks") == 0 ||
2364 strcmp(f
->file
, "/tasks") == 0 ||
2365 strcmp(f
->file
, "/cgroup.procs") == 0 ||
2366 strcmp(f
->file
, "cgroup.procs") == 0)
2367 // special case - we have to translate the pids
2368 r
= do_read_pids(fc
->pid
, f
->controller
, f
->cgroup
, f
->file
, &data
);
2370 r
= cgfs_get_value(f
->controller
, f
->cgroup
, f
->file
, &data
);
2384 memcpy(buf
, data
, s
);
2385 if (s
> 0 && s
< size
&& data
[s
-1] != '\n')
2395 static int pid_from_ns(int sock
, pid_t tpid
)
2405 if (!wait_for_sock(sock
, 2)) {
2406 fprintf(stderr
, "%s: timeout reading from parent\n", __func__
);
2409 if ((ret
= read(sock
, &vpid
, sizeof(pid_t
))) != sizeof(pid_t
)) {
2410 fprintf(stderr
, "%s: bad read from parent: %s\n",
2411 __func__
, strerror(errno
));
2414 if (vpid
== -1) // done
2418 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
) {
2420 cred
.pid
= getpid();
2421 if (send_creds(sock
, &cred
, v
, false) != SEND_CREDS_OK
)
2428 static void pid_from_ns_wrapper(int sock
, pid_t tpid
)
2430 int newnsfd
= -1, ret
, cpipe
[2];
2435 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
2436 if (ret
< 0 || ret
>= sizeof(fnam
))
2438 newnsfd
= open(fnam
, O_RDONLY
);
2441 if (setns(newnsfd
, 0) < 0)
2445 if (pipe(cpipe
) < 0)
2448 struct pid_ns_clone_args args
= {
2452 .wrapped
= &pid_from_ns
2454 size_t stack_size
= sysconf(_SC_PAGESIZE
);
2455 void *stack
= alloca(stack_size
);
2457 cpid
= clone(pid_ns_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &args
);
2461 // give the child 1 second to be done forking and
2463 if (!wait_for_sock(cpipe
[0], 1))
2465 ret
= read(cpipe
[0], &v
, 1);
2466 if (ret
!= sizeof(char) || v
!= '1')
2469 if (!wait_for_pid(cpid
))
2475 * Given host @uid, return the uid to which it maps in
2476 * @pid's user namespace, or -1 if none.
2478 bool hostuid_to_ns(uid_t uid
, pid_t pid
, uid_t
*answer
)
2483 sprintf(line
, "/proc/%d/uid_map", pid
);
2484 if ((f
= fopen(line
, "r")) == NULL
) {
2488 *answer
= convert_id_to_ns(f
, uid
);
2497 * get_pid_creds: get the real uid and gid of @pid from
2499 * (XXX should we use euid here?)
2501 void get_pid_creds(pid_t pid
, uid_t
*uid
, gid_t
*gid
)
2510 sprintf(line
, "/proc/%d/status", pid
);
2511 if ((f
= fopen(line
, "r")) == NULL
) {
2512 fprintf(stderr
, "Error opening %s: %s\n", line
, strerror(errno
));
2515 while (fgets(line
, 400, f
)) {
2516 if (strncmp(line
, "Uid:", 4) == 0) {
2517 if (sscanf(line
+4, "%u", &u
) != 1) {
2518 fprintf(stderr
, "bad uid line for pid %u\n", pid
);
2523 } else if (strncmp(line
, "Gid:", 4) == 0) {
2524 if (sscanf(line
+4, "%u", &g
) != 1) {
2525 fprintf(stderr
, "bad gid line for pid %u\n", pid
);
2536 * May the requestor @r move victim @v to a new cgroup?
2537 * This is allowed if
2538 * . they are the same task
2539 * . they are ownedy by the same uid
2540 * . @r is root on the host, or
2541 * . @v's uid is mapped into @r's where @r is root.
2543 bool may_move_pid(pid_t r
, uid_t r_uid
, pid_t v
)
2545 uid_t v_uid
, tmpuid
;
2552 get_pid_creds(v
, &v_uid
, &v_gid
);
2555 if (hostuid_to_ns(r_uid
, r
, &tmpuid
) && tmpuid
== 0
2556 && hostuid_to_ns(v_uid
, r
, &tmpuid
))
2561 static bool do_write_pids(pid_t tpid
, uid_t tuid
, const char *contrl
, const char *cg
,
2562 const char *file
, const char *buf
)
2564 int sock
[2] = {-1, -1};
2565 pid_t qpid
, cpid
= -1;
2566 FILE *pids_file
= NULL
;
2567 bool answer
= false, fail
= false;
2569 pids_file
= open_pids_file(contrl
, cg
);
2574 * write the pids to a socket, have helper in writer's pidns
2575 * call movepid for us
2577 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2578 perror("socketpair");
2586 if (!cpid
) { // child
2588 pid_from_ns_wrapper(sock
[1], tpid
);
2591 const char *ptr
= buf
;
2592 while (sscanf(ptr
, "%d", &qpid
) == 1) {
2596 if (write(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2597 fprintf(stderr
, "%s: error writing pid to child: %s\n",
2598 __func__
, strerror(errno
));
2602 if (recv_creds(sock
[0], &cred
, &v
)) {
2604 if (!may_move_pid(tpid
, tuid
, cred
.pid
)) {
2608 if (fprintf(pids_file
, "%d", (int) cred
.pid
) < 0)
2613 ptr
= strchr(ptr
, '\n');
2619 /* All good, write the value */
2621 if (write(sock
[0], &qpid
,sizeof(qpid
)) != sizeof(qpid
))
2622 fprintf(stderr
, "Warning: failed to ask child to exit\n");
2630 if (sock
[0] != -1) {
2635 if (fclose(pids_file
) != 0)
2641 int cg_write(const char *path
, const char *buf
, size_t size
, off_t offset
,
2642 struct fuse_file_info
*fi
)
2644 struct fuse_context
*fc
= fuse_get_context();
2645 char *localbuf
= NULL
;
2646 struct cgfs_files
*k
= NULL
;
2647 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2650 if (f
->type
!= LXC_TYPE_CGFILE
) {
2651 fprintf(stderr
, "Internal error: directory cache info used in cg_write\n");
2661 localbuf
= alloca(size
+1);
2662 localbuf
[size
] = '\0';
2663 memcpy(localbuf
, buf
, size
);
2665 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
2670 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_WRONLY
)) {
2675 if (strcmp(f
->file
, "tasks") == 0 ||
2676 strcmp(f
->file
, "/tasks") == 0 ||
2677 strcmp(f
->file
, "/cgroup.procs") == 0 ||
2678 strcmp(f
->file
, "cgroup.procs") == 0)
2679 // special case - we have to translate the pids
2680 r
= do_write_pids(fc
->pid
, fc
->uid
, f
->controller
, f
->cgroup
, f
->file
, localbuf
);
2682 r
= cgfs_set_value(f
->controller
, f
->cgroup
, f
->file
, localbuf
);
2692 int cg_chown(const char *path
, uid_t uid
, gid_t gid
)
2694 struct fuse_context
*fc
= fuse_get_context();
2695 char *cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
2696 struct cgfs_files
*k
= NULL
;
2703 if (strcmp(path
, "/cgroup") == 0)
2706 controller
= pick_controller_from_path(fc
, path
);
2709 cgroup
= find_cgroup_in_path(path
);
2711 /* this is just /cgroup/controller */
2714 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2724 if (is_child_cgroup(controller
, path1
, path2
)) {
2725 // get uid, gid, from '/tasks' file and make up a mode
2726 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
2727 k
= cgfs_get_key(controller
, cgroup
, "tasks");
2730 k
= cgfs_get_key(controller
, path1
, path2
);
2738 * This being a fuse request, the uid and gid must be valid
2739 * in the caller's namespace. So we can just check to make
2740 * sure that the caller is root in his uid, and privileged
2741 * over the file's current owner.
2743 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_REQD
)) {
2748 ret
= cgfs_chown_file(controller
, cgroup
, uid
, gid
);
2757 int cg_chmod(const char *path
, mode_t mode
)
2759 struct fuse_context
*fc
= fuse_get_context();
2760 char * cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
2761 struct cgfs_files
*k
= NULL
;
2768 if (strcmp(path
, "/cgroup") == 0)
2771 controller
= pick_controller_from_path(fc
, path
);
2774 cgroup
= find_cgroup_in_path(path
);
2776 /* this is just /cgroup/controller */
2779 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2789 if (is_child_cgroup(controller
, path1
, path2
)) {
2790 // get uid, gid, from '/tasks' file and make up a mode
2791 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
2792 k
= cgfs_get_key(controller
, cgroup
, "tasks");
2795 k
= cgfs_get_key(controller
, path1
, path2
);
2803 * This being a fuse request, the uid and gid must be valid
2804 * in the caller's namespace. So we can just check to make
2805 * sure that the caller is root in his uid, and privileged
2806 * over the file's current owner.
2808 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
2813 if (!cgfs_chmod_file(controller
, cgroup
, mode
)) {
2825 int cg_mkdir(const char *path
, mode_t mode
)
2827 struct fuse_context
*fc
= fuse_get_context();
2828 char *last
= NULL
, *path1
, *cgdir
= NULL
, *controller
, *next
= NULL
;
2836 controller
= pick_controller_from_path(fc
, path
);
2840 cgroup
= find_cgroup_in_path(path
);
2844 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2850 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2853 if (!caller_is_in_ancestor(initpid
, controller
, path1
, &next
)) {
2856 else if (last
&& strcmp(next
, last
) == 0)
2863 if (!fc_may_access(fc
, controller
, path1
, NULL
, O_RDWR
)) {
2867 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
2872 ret
= cgfs_create(controller
, cgroup
, fc
->uid
, fc
->gid
);
2880 int cg_rmdir(const char *path
)
2882 struct fuse_context
*fc
= fuse_get_context();
2883 char *last
= NULL
, *cgdir
= NULL
, *controller
, *next
= NULL
;
2890 controller
= pick_controller_from_path(fc
, path
);
2894 cgroup
= find_cgroup_in_path(path
);
2898 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2904 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2907 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, &next
)) {
2908 if (!last
|| strcmp(next
, last
) == 0)
2915 if (!fc_may_access(fc
, controller
, cgdir
, NULL
, O_WRONLY
)) {
2919 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
2924 if (!cgfs_remove(controller
, cgroup
)) {
2937 static bool startswith(const char *line
, const char *pref
)
2939 if (strncmp(line
, pref
, strlen(pref
)) == 0)
2944 static void parse_memstat(char *memstat
, unsigned long *cached
,
2945 unsigned long *active_anon
, unsigned long *inactive_anon
,
2946 unsigned long *active_file
, unsigned long *inactive_file
,
2947 unsigned long *unevictable
)
2952 if (startswith(memstat
, "cache")) {
2953 sscanf(memstat
+ 11, "%lu", cached
);
2955 } else if (startswith(memstat
, "active_anon")) {
2956 sscanf(memstat
+ 11, "%lu", active_anon
);
2957 *active_anon
/= 1024;
2958 } else if (startswith(memstat
, "inactive_anon")) {
2959 sscanf(memstat
+ 11, "%lu", inactive_anon
);
2960 *inactive_anon
/= 1024;
2961 } else if (startswith(memstat
, "active_file")) {
2962 sscanf(memstat
+ 11, "%lu", active_file
);
2963 *active_file
/= 1024;
2964 } else if (startswith(memstat
, "inactive_file")) {
2965 sscanf(memstat
+ 11, "%lu", inactive_file
);
2966 *inactive_file
/= 1024;
2967 } else if (startswith(memstat
, "unevictable")) {
2968 sscanf(memstat
+ 11, "%lu", unevictable
);
2969 *unevictable
/= 1024;
2971 eol
= strchr(memstat
, '\n');
2978 static void get_blkio_io_value(char *str
, unsigned major
, unsigned minor
, char *iotype
, unsigned long *v
)
2984 snprintf(key
, 32, "%u:%u %s", major
, minor
, iotype
);
2986 size_t len
= strlen(key
);
2990 if (startswith(str
, key
)) {
2991 sscanf(str
+ len
, "%lu", v
);
2994 eol
= strchr(str
, '\n');
3001 static int read_file(const char *path
, char *buf
, size_t size
,
3002 struct file_info
*d
)
3004 size_t linelen
= 0, total_len
= 0, rv
= 0;
3006 char *cache
= d
->buf
;
3007 size_t cache_size
= d
->buflen
;
3008 FILE *f
= fopen(path
, "r");
3012 while (getline(&line
, &linelen
, f
) != -1) {
3013 ssize_t l
= snprintf(cache
, cache_size
, "%s", line
);
3015 perror("Error writing to cache");
3019 if (l
>= cache_size
) {
3020 fprintf(stderr
, "Internal error: truncated write to cache\n");
3029 d
->size
= total_len
;
3030 if (total_len
> size
)
3033 /* read from off 0 */
3034 memcpy(buf
, d
->buf
, total_len
);
3043 * FUSE ops for /proc
3046 static unsigned long get_memlimit(const char *cgroup
)
3048 char *memlimit_str
= NULL
;
3049 unsigned long memlimit
= -1;
3051 if (cgfs_get_value("memory", cgroup
, "memory.limit_in_bytes", &memlimit_str
))
3052 memlimit
= strtoul(memlimit_str
, NULL
, 10);
3059 static unsigned long get_min_memlimit(const char *cgroup
)
3061 char *copy
= strdupa(cgroup
);
3062 unsigned long memlimit
= 0, retlimit
;
3064 retlimit
= get_memlimit(copy
);
3066 while (strcmp(copy
, "/") != 0) {
3067 copy
= dirname(copy
);
3068 memlimit
= get_memlimit(copy
);
3069 if (memlimit
!= -1 && memlimit
< retlimit
)
3070 retlimit
= memlimit
;
3076 static int proc_meminfo_read(char *buf
, size_t size
, off_t offset
,
3077 struct fuse_file_info
*fi
)
3079 struct fuse_context
*fc
= fuse_get_context();
3080 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3082 char *memusage_str
= NULL
, *memstat_str
= NULL
,
3083 *memswlimit_str
= NULL
, *memswusage_str
= NULL
,
3084 *memswlimit_default_str
= NULL
, *memswusage_default_str
= NULL
;
3085 unsigned long memlimit
= 0, memusage
= 0, memswlimit
= 0, memswusage
= 0,
3086 cached
= 0, hosttotal
= 0, active_anon
= 0, inactive_anon
= 0,
3087 active_file
= 0, inactive_file
= 0, unevictable
= 0;
3089 size_t linelen
= 0, total_len
= 0, rv
= 0;
3090 char *cache
= d
->buf
;
3091 size_t cache_size
= d
->buflen
;
3095 if (offset
> d
->size
)
3099 int left
= d
->size
- offset
;
3100 total_len
= left
> size
? size
: left
;
3101 memcpy(buf
, cache
+ offset
, total_len
);
3105 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3108 cg
= get_pid_cgroup(initpid
, "memory");
3110 return read_file("/proc/meminfo", buf
, size
, d
);
3111 prune_init_slice(cg
);
3113 memlimit
= get_min_memlimit(cg
);
3114 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
3116 if (!cgfs_get_value("memory", cg
, "memory.stat", &memstat_str
))
3119 // Following values are allowed to fail, because swapaccount might be turned
3120 // off for current kernel
3121 if(cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
) &&
3122 cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
))
3124 /* If swapaccounting is turned on, then default value is assumed to be that of cgroup / */
3125 if (!cgfs_get_value("memory", "/", "memory.memsw.limit_in_bytes", &memswlimit_default_str
))
3127 if (!cgfs_get_value("memory", "/", "memory.memsw.usage_in_bytes", &memswusage_default_str
))
3130 memswlimit
= strtoul(memswlimit_str
, NULL
, 10);
3131 memswusage
= strtoul(memswusage_str
, NULL
, 10);
3133 if (!strcmp(memswlimit_str
, memswlimit_default_str
))
3135 if (!strcmp(memswusage_str
, memswusage_default_str
))
3138 memswlimit
= memswlimit
/ 1024;
3139 memswusage
= memswusage
/ 1024;
3142 memusage
= strtoul(memusage_str
, NULL
, 10);
3146 parse_memstat(memstat_str
, &cached
, &active_anon
,
3147 &inactive_anon
, &active_file
, &inactive_file
,
3150 f
= fopen("/proc/meminfo", "r");
3154 while (getline(&line
, &linelen
, f
) != -1) {
3156 char *printme
, lbuf
[100];
3158 memset(lbuf
, 0, 100);
3159 if (startswith(line
, "MemTotal:")) {
3160 sscanf(line
+14, "%lu", &hosttotal
);
3161 if (hosttotal
< memlimit
)
3162 memlimit
= hosttotal
;
3163 snprintf(lbuf
, 100, "MemTotal: %8lu kB\n", memlimit
);
3165 } else if (startswith(line
, "MemFree:")) {
3166 snprintf(lbuf
, 100, "MemFree: %8lu kB\n", memlimit
- memusage
);
3168 } else if (startswith(line
, "MemAvailable:")) {
3169 snprintf(lbuf
, 100, "MemAvailable: %8lu kB\n", memlimit
- memusage
);
3171 } else if (startswith(line
, "SwapTotal:") && memswlimit
> 0) {
3172 snprintf(lbuf
, 100, "SwapTotal: %8lu kB\n", memswlimit
- memlimit
);
3174 } else if (startswith(line
, "SwapFree:") && memswlimit
> 0 && memswusage
> 0) {
3175 unsigned long swaptotal
= memswlimit
- memlimit
,
3176 swapusage
= memswusage
- memusage
,
3177 swapfree
= swapusage
< swaptotal
? swaptotal
- swapusage
: 0;
3178 snprintf(lbuf
, 100, "SwapFree: %8lu kB\n", swapfree
);
3180 } else if (startswith(line
, "Slab:")) {
3181 snprintf(lbuf
, 100, "Slab: %8lu kB\n", 0UL);
3183 } else if (startswith(line
, "Buffers:")) {
3184 snprintf(lbuf
, 100, "Buffers: %8lu kB\n", 0UL);
3186 } else if (startswith(line
, "Cached:")) {
3187 snprintf(lbuf
, 100, "Cached: %8lu kB\n", cached
);
3189 } else if (startswith(line
, "SwapCached:")) {
3190 snprintf(lbuf
, 100, "SwapCached: %8lu kB\n", 0UL);
3192 } else if (startswith(line
, "Active")) {
3193 snprintf(lbuf
, 100, "Active: %8lu kB\n",
3194 active_anon
+ active_file
);
3196 } else if (startswith(line
, "Inactive")) {
3197 snprintf(lbuf
, 100, "Inactive: %8lu kB\n",
3198 inactive_anon
+ inactive_file
);
3200 } else if (startswith(line
, "Active(anon)")) {
3201 snprintf(lbuf
, 100, "Active(anon): %8lu kB\n", active_anon
);
3203 } else if (startswith(line
, "Inactive(anon)")) {
3204 snprintf(lbuf
, 100, "Inactive(anon): %8lu kB\n", inactive_anon
);
3206 } else if (startswith(line
, "Active(file)")) {
3207 snprintf(lbuf
, 100, "Active(file): %8lu kB\n", active_file
);
3209 } else if (startswith(line
, "Inactive(file)")) {
3210 snprintf(lbuf
, 100, "Inactive(file): %8lu kB\n", inactive_file
);
3212 } else if (startswith(line
, "Unevictable")) {
3213 snprintf(lbuf
, 100, "Unevictable: %8lu kB\n", unevictable
);
3215 } else if (startswith(line
, "SReclaimable")) {
3216 snprintf(lbuf
, 100, "SReclaimable: %8lu kB\n", 0UL);
3218 } else if (startswith(line
, "SUnreclaim")) {
3219 snprintf(lbuf
, 100, "SUnreclaim: %8lu kB\n", 0UL);
3224 l
= snprintf(cache
, cache_size
, "%s", printme
);
3226 perror("Error writing to cache");
3231 if (l
>= cache_size
) {
3232 fprintf(stderr
, "Internal error: truncated write to cache\n");
3243 d
->size
= total_len
;
3244 if (total_len
> size
) total_len
= size
;
3245 memcpy(buf
, d
->buf
, total_len
);
3254 free(memswlimit_str
);
3255 free(memswusage_str
);
3257 free(memswlimit_default_str
);
3258 free(memswusage_default_str
);
3263 * Read the cpuset.cpus for cg
3264 * Return the answer in a newly allocated string which must be freed
3266 static char *get_cpuset(const char *cg
)
3270 if (!cgfs_get_value("cpuset", cg
, "cpuset.cpus", &answer
))
3275 bool cpu_in_cpuset(int cpu
, const char *cpuset
);
3277 static bool cpuline_in_cpuset(const char *line
, const char *cpuset
)
3281 if (sscanf(line
, "processor : %d", &cpu
) != 1)
3283 return cpu_in_cpuset(cpu
, cpuset
);
3287 * check whether this is a '^processor" line in /proc/cpuinfo
3289 static bool is_processor_line(const char *line
)
3293 if (sscanf(line
, "processor : %d", &cpu
) == 1)
3298 static int proc_cpuinfo_read(char *buf
, size_t size
, off_t offset
,
3299 struct fuse_file_info
*fi
)
3301 struct fuse_context
*fc
= fuse_get_context();
3302 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3304 char *cpuset
= NULL
;
3306 size_t linelen
= 0, total_len
= 0, rv
= 0;
3307 bool am_printing
= false, firstline
= true, is_s390x
= false;
3308 int curcpu
= -1, cpu
;
3309 char *cache
= d
->buf
;
3310 size_t cache_size
= d
->buflen
;
3314 if (offset
> d
->size
)
3318 int left
= d
->size
- offset
;
3319 total_len
= left
> size
? size
: left
;
3320 memcpy(buf
, cache
+ offset
, total_len
);
3324 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3327 cg
= get_pid_cgroup(initpid
, "cpuset");
3329 return read_file("proc/cpuinfo", buf
, size
, d
);
3330 prune_init_slice(cg
);
3332 cpuset
= get_cpuset(cg
);
3336 f
= fopen("/proc/cpuinfo", "r");
3340 while (getline(&line
, &linelen
, f
) != -1) {
3344 if (strstr(line
, "IBM/S390") != NULL
) {
3350 if (strncmp(line
, "# processors:", 12) == 0)
3352 if (is_processor_line(line
)) {
3353 am_printing
= cpuline_in_cpuset(line
, cpuset
);
3356 l
= snprintf(cache
, cache_size
, "processor : %d\n", curcpu
);
3358 perror("Error writing to cache");
3362 if (l
>= cache_size
) {
3363 fprintf(stderr
, "Internal error: truncated write to cache\n");
3372 } else if (is_s390x
&& sscanf(line
, "processor %d:", &cpu
) == 1) {
3374 if (!cpu_in_cpuset(cpu
, cpuset
))
3377 p
= strchr(line
, ':');
3381 l
= snprintf(cache
, cache_size
, "processor %d:%s", curcpu
, p
);
3383 perror("Error writing to cache");
3387 if (l
>= cache_size
) {
3388 fprintf(stderr
, "Internal error: truncated write to cache\n");
3399 l
= snprintf(cache
, cache_size
, "%s", line
);
3401 perror("Error writing to cache");
3405 if (l
>= cache_size
) {
3406 fprintf(stderr
, "Internal error: truncated write to cache\n");
3417 char *origcache
= d
->buf
;
3420 d
->buf
= malloc(d
->buflen
);
3423 cache_size
= d
->buflen
;
3425 l
= snprintf(cache
, cache_size
, "vendor_id : IBM/S390\n");
3426 if (l
< 0 || l
>= cache_size
) {
3433 l
= snprintf(cache
, cache_size
, "# processors : %d\n", curcpu
+ 1);
3434 if (l
< 0 || l
>= cache_size
) {
3441 l
= snprintf(cache
, cache_size
, "%s", origcache
);
3443 if (l
< 0 || l
>= cache_size
)
3449 d
->size
= total_len
;
3450 if (total_len
> size
) total_len
= size
;
3452 /* read from off 0 */
3453 memcpy(buf
, d
->buf
, total_len
);
3464 static int proc_stat_read(char *buf
, size_t size
, off_t offset
,
3465 struct fuse_file_info
*fi
)
3467 struct fuse_context
*fc
= fuse_get_context();
3468 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3470 char *cpuset
= NULL
;
3472 size_t linelen
= 0, total_len
= 0, rv
= 0;
3473 int curcpu
= -1; /* cpu numbering starts at 0 */
3474 unsigned long user
= 0, nice
= 0, system
= 0, idle
= 0, iowait
= 0, irq
= 0, softirq
= 0, steal
= 0, guest
= 0;
3475 unsigned long user_sum
= 0, nice_sum
= 0, system_sum
= 0, idle_sum
= 0, iowait_sum
= 0,
3476 irq_sum
= 0, softirq_sum
= 0, steal_sum
= 0, guest_sum
= 0;
3477 #define CPUALL_MAX_SIZE BUF_RESERVE_SIZE
3478 char cpuall
[CPUALL_MAX_SIZE
];
3479 /* reserve for cpu all */
3480 char *cache
= d
->buf
+ CPUALL_MAX_SIZE
;
3481 size_t cache_size
= d
->buflen
- CPUALL_MAX_SIZE
;
3485 if (offset
> d
->size
)
3489 int left
= d
->size
- offset
;
3490 total_len
= left
> size
? size
: left
;
3491 memcpy(buf
, d
->buf
+ offset
, total_len
);
3495 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3498 cg
= get_pid_cgroup(initpid
, "cpuset");
3500 return read_file("/proc/stat", buf
, size
, d
);
3501 prune_init_slice(cg
);
3503 cpuset
= get_cpuset(cg
);
3507 f
= fopen("/proc/stat", "r");
3512 if (getline(&line
, &linelen
, f
) < 0) {
3513 fprintf(stderr
, "proc_stat_read read first line failed\n");
3517 while (getline(&line
, &linelen
, f
) != -1) {
3520 char cpu_char
[10]; /* That's a lot of cores */
3523 if (strlen(line
) == 0)
3525 if (sscanf(line
, "cpu%9[^ ]", cpu_char
) != 1) {
3526 /* not a ^cpuN line containing a number N, just print it */
3527 l
= snprintf(cache
, cache_size
, "%s", line
);
3529 perror("Error writing to cache");
3533 if (l
>= cache_size
) {
3534 fprintf(stderr
, "Internal error: truncated write to cache\n");
3544 if (sscanf(cpu_char
, "%d", &cpu
) != 1)
3546 if (!cpu_in_cpuset(cpu
, cpuset
))
3550 c
= strchr(line
, ' ');
3553 l
= snprintf(cache
, cache_size
, "cpu%d%s", curcpu
, c
);
3555 perror("Error writing to cache");
3560 if (l
>= cache_size
) {
3561 fprintf(stderr
, "Internal error: truncated write to cache\n");
3570 if (sscanf(line
, "%*s %lu %lu %lu %lu %lu %lu %lu %lu %lu", &user
, &nice
, &system
, &idle
, &iowait
, &irq
,
3571 &softirq
, &steal
, &guest
) != 9)
3575 system_sum
+= system
;
3577 iowait_sum
+= iowait
;
3579 softirq_sum
+= softirq
;
3586 int cpuall_len
= snprintf(cpuall
, CPUALL_MAX_SIZE
, "%s %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
3587 "cpu ", user_sum
, nice_sum
, system_sum
, idle_sum
, iowait_sum
, irq_sum
, softirq_sum
, steal_sum
, guest_sum
);
3588 if (cpuall_len
> 0 && cpuall_len
< CPUALL_MAX_SIZE
){
3589 memcpy(cache
, cpuall
, cpuall_len
);
3590 cache
+= cpuall_len
;
3592 /* shouldn't happen */
3593 fprintf(stderr
, "proc_stat_read copy cpuall failed, cpuall_len=%d\n", cpuall_len
);
3597 memmove(cache
, d
->buf
+ CPUALL_MAX_SIZE
, total_len
);
3598 total_len
+= cpuall_len
;
3600 d
->size
= total_len
;
3601 if (total_len
> size
) total_len
= size
;
3603 memcpy(buf
, d
->buf
, total_len
);
3615 static long int getreaperage(pid_t pid
)
3622 qpid
= lookup_initpid_in_store(pid
);
3626 ret
= snprintf(fnam
, 100, "/proc/%d", qpid
);
3627 if (ret
< 0 || ret
>= 100)
3630 if (lstat(fnam
, &sb
) < 0)
3633 return time(NULL
) - sb
.st_ctime
;
3636 static unsigned long get_reaper_busy(pid_t task
)
3638 pid_t initpid
= lookup_initpid_in_store(task
);
3639 char *cgroup
= NULL
, *usage_str
= NULL
;
3640 unsigned long usage
= 0;
3645 cgroup
= get_pid_cgroup(initpid
, "cpuacct");
3648 prune_init_slice(cgroup
);
3649 if (!cgfs_get_value("cpuacct", cgroup
, "cpuacct.usage", &usage_str
))
3651 usage
= strtoul(usage_str
, NULL
, 10);
3652 usage
/= 1000000000;
3665 fd
= creat("/tmp/lxcfs-iwashere", 0644);
3672 * We read /proc/uptime and reuse its second field.
3673 * For the first field, we use the mtime for the reaper for
3674 * the calling pid as returned by getreaperage
3676 static int proc_uptime_read(char *buf
, size_t size
, off_t offset
,
3677 struct fuse_file_info
*fi
)
3679 struct fuse_context
*fc
= fuse_get_context();
3680 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3681 long int reaperage
= getreaperage(fc
->pid
);
3682 unsigned long int busytime
= get_reaper_busy(fc
->pid
), idletime
;
3683 char *cache
= d
->buf
;
3684 ssize_t total_len
= 0;
3691 if (offset
> d
->size
)
3695 int left
= d
->size
- offset
;
3696 total_len
= left
> size
? size
: left
;
3697 memcpy(buf
, cache
+ offset
, total_len
);
3701 idletime
= reaperage
- busytime
;
3702 if (idletime
> reaperage
)
3703 idletime
= reaperage
;
3705 total_len
= snprintf(d
->buf
, d
->size
, "%ld.0 %lu.0\n", reaperage
, idletime
);
3707 perror("Error writing to cache");
3711 d
->size
= (int)total_len
;
3714 if (total_len
> size
) total_len
= size
;
3716 memcpy(buf
, d
->buf
, total_len
);
3720 static int proc_diskstats_read(char *buf
, size_t size
, off_t offset
,
3721 struct fuse_file_info
*fi
)
3724 struct fuse_context
*fc
= fuse_get_context();
3725 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3727 char *io_serviced_str
= NULL
, *io_merged_str
= NULL
, *io_service_bytes_str
= NULL
,
3728 *io_wait_time_str
= NULL
, *io_service_time_str
= NULL
;
3729 unsigned long read
= 0, write
= 0;
3730 unsigned long read_merged
= 0, write_merged
= 0;
3731 unsigned long read_sectors
= 0, write_sectors
= 0;
3732 unsigned long read_ticks
= 0, write_ticks
= 0;
3733 unsigned long ios_pgr
= 0, tot_ticks
= 0, rq_ticks
= 0;
3734 unsigned long rd_svctm
= 0, wr_svctm
= 0, rd_wait
= 0, wr_wait
= 0;
3735 char *cache
= d
->buf
;
3736 size_t cache_size
= d
->buflen
;
3738 size_t linelen
= 0, total_len
= 0, rv
= 0;
3739 unsigned int major
= 0, minor
= 0;
3744 if (offset
> d
->size
)
3748 int left
= d
->size
- offset
;
3749 total_len
= left
> size
? size
: left
;
3750 memcpy(buf
, cache
+ offset
, total_len
);
3754 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3757 cg
= get_pid_cgroup(initpid
, "blkio");
3759 return read_file("/proc/diskstats", buf
, size
, d
);
3760 prune_init_slice(cg
);
3762 if (!cgfs_get_value("blkio", cg
, "blkio.io_serviced_recursive", &io_serviced_str
))
3764 if (!cgfs_get_value("blkio", cg
, "blkio.io_merged_recursive", &io_merged_str
))
3766 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_bytes_recursive", &io_service_bytes_str
))
3768 if (!cgfs_get_value("blkio", cg
, "blkio.io_wait_time_recursive", &io_wait_time_str
))
3770 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_time_recursive", &io_service_time_str
))
3774 f
= fopen("/proc/diskstats", "r");
3778 while (getline(&line
, &linelen
, f
) != -1) {
3782 i
= sscanf(line
, "%u %u %71s", &major
, &minor
, dev_name
);
3786 get_blkio_io_value(io_serviced_str
, major
, minor
, "Read", &read
);
3787 get_blkio_io_value(io_serviced_str
, major
, minor
, "Write", &write
);
3788 get_blkio_io_value(io_merged_str
, major
, minor
, "Read", &read_merged
);
3789 get_blkio_io_value(io_merged_str
, major
, minor
, "Write", &write_merged
);
3790 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Read", &read_sectors
);
3791 read_sectors
= read_sectors
/512;
3792 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Write", &write_sectors
);
3793 write_sectors
= write_sectors
/512;
3795 get_blkio_io_value(io_service_time_str
, major
, minor
, "Read", &rd_svctm
);
3796 rd_svctm
= rd_svctm
/1000000;
3797 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Read", &rd_wait
);
3798 rd_wait
= rd_wait
/1000000;
3799 read_ticks
= rd_svctm
+ rd_wait
;
3801 get_blkio_io_value(io_service_time_str
, major
, minor
, "Write", &wr_svctm
);
3802 wr_svctm
= wr_svctm
/1000000;
3803 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Write", &wr_wait
);
3804 wr_wait
= wr_wait
/1000000;
3805 write_ticks
= wr_svctm
+ wr_wait
;
3807 get_blkio_io_value(io_service_time_str
, major
, minor
, "Total", &tot_ticks
);
3808 tot_ticks
= tot_ticks
/1000000;
3810 memset(lbuf
, 0, 256);
3811 if (read
|| write
|| read_merged
|| write_merged
|| read_sectors
|| write_sectors
|| read_ticks
|| write_ticks
)
3812 snprintf(lbuf
, 256, "%u %u %s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
3813 major
, minor
, dev_name
, read
, read_merged
, read_sectors
, read_ticks
,
3814 write
, write_merged
, write_sectors
, write_ticks
, ios_pgr
, tot_ticks
, rq_ticks
);
3818 l
= snprintf(cache
, cache_size
, "%s", lbuf
);
3820 perror("Error writing to fuse buf");
3824 if (l
>= cache_size
) {
3825 fprintf(stderr
, "Internal error: truncated write to cache\n");
3835 d
->size
= total_len
;
3836 if (total_len
> size
) total_len
= size
;
3837 memcpy(buf
, d
->buf
, total_len
);
3845 free(io_serviced_str
);
3846 free(io_merged_str
);
3847 free(io_service_bytes_str
);
3848 free(io_wait_time_str
);
3849 free(io_service_time_str
);
3853 static int proc_swaps_read(char *buf
, size_t size
, off_t offset
,
3854 struct fuse_file_info
*fi
)
3856 struct fuse_context
*fc
= fuse_get_context();
3857 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3859 char *memswlimit_str
= NULL
, *memlimit_str
= NULL
, *memusage_str
= NULL
, *memswusage_str
= NULL
,
3860 *memswlimit_default_str
= NULL
, *memswusage_default_str
= NULL
;
3861 unsigned long memswlimit
= 0, memlimit
= 0, memusage
= 0, memswusage
= 0, swap_total
= 0, swap_free
= 0;
3862 ssize_t total_len
= 0, rv
= 0;
3864 char *cache
= d
->buf
;
3867 if (offset
> d
->size
)
3871 int left
= d
->size
- offset
;
3872 total_len
= left
> size
? size
: left
;
3873 memcpy(buf
, cache
+ offset
, total_len
);
3877 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3880 cg
= get_pid_cgroup(initpid
, "memory");
3882 return read_file("/proc/swaps", buf
, size
, d
);
3883 prune_init_slice(cg
);
3885 if (!cgfs_get_value("memory", cg
, "memory.limit_in_bytes", &memlimit_str
))
3888 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
3891 memlimit
= strtoul(memlimit_str
, NULL
, 10);
3892 memusage
= strtoul(memusage_str
, NULL
, 10);
3894 if (cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
) &&
3895 cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
)) {
3897 /* If swap accounting is turned on, then default value is assumed to be that of cgroup / */
3898 if (!cgfs_get_value("memory", "/", "memory.memsw.limit_in_bytes", &memswlimit_default_str
))
3900 if (!cgfs_get_value("memory", "/", "memory.memsw.usage_in_bytes", &memswusage_default_str
))
3903 memswlimit
= strtoul(memswlimit_str
, NULL
, 10);
3904 memswusage
= strtoul(memswusage_str
, NULL
, 10);
3906 if (!strcmp(memswlimit_str
, memswlimit_default_str
))
3908 if (!strcmp(memswusage_str
, memswusage_default_str
))
3911 swap_total
= (memswlimit
- memlimit
) / 1024;
3912 swap_free
= (memswusage
- memusage
) / 1024;
3915 total_len
= snprintf(d
->buf
, d
->size
, "Filename\t\t\t\tType\t\tSize\tUsed\tPriority\n");
3917 /* When no mem + swap limit is specified or swapaccount=0*/
3921 FILE *f
= fopen("/proc/meminfo", "r");
3926 while (getline(&line
, &linelen
, f
) != -1) {
3927 if (startswith(line
, "SwapTotal:")) {
3928 sscanf(line
, "SwapTotal: %8lu kB", &swap_total
);
3929 } else if (startswith(line
, "SwapFree:")) {
3930 sscanf(line
, "SwapFree: %8lu kB", &swap_free
);
3938 if (swap_total
> 0) {
3939 l
= snprintf(d
->buf
+ total_len
, d
->size
- total_len
,
3940 "none%*svirtual\t\t%lu\t%lu\t0\n", 36, " ",
3941 swap_total
, swap_free
);
3945 if (total_len
< 0 || l
< 0) {
3946 perror("Error writing to cache");
3952 d
->size
= (int)total_len
;
3954 if (total_len
> size
) total_len
= size
;
3955 memcpy(buf
, d
->buf
, total_len
);
3960 free(memswlimit_str
);
3963 free(memswusage_str
);
3964 free(memswusage_default_str
);
3965 free(memswlimit_default_str
);
3969 static off_t
get_procfile_size(const char *which
)
3971 FILE *f
= fopen(which
, "r");
3974 ssize_t sz
, answer
= 0;
3978 while ((sz
= getline(&line
, &len
, f
)) != -1)
3986 int proc_getattr(const char *path
, struct stat
*sb
)
3988 struct timespec now
;
3990 memset(sb
, 0, sizeof(struct stat
));
3991 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
3993 sb
->st_uid
= sb
->st_gid
= 0;
3994 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
3995 if (strcmp(path
, "/proc") == 0) {
3996 sb
->st_mode
= S_IFDIR
| 00555;
4000 if (strcmp(path
, "/proc/meminfo") == 0 ||
4001 strcmp(path
, "/proc/cpuinfo") == 0 ||
4002 strcmp(path
, "/proc/uptime") == 0 ||
4003 strcmp(path
, "/proc/stat") == 0 ||
4004 strcmp(path
, "/proc/diskstats") == 0 ||
4005 strcmp(path
, "/proc/swaps") == 0) {
4007 sb
->st_mode
= S_IFREG
| 00444;
4015 int proc_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
4016 struct fuse_file_info
*fi
)
4018 if (filler(buf
, "cpuinfo", NULL
, 0) != 0 ||
4019 filler(buf
, "meminfo", NULL
, 0) != 0 ||
4020 filler(buf
, "stat", NULL
, 0) != 0 ||
4021 filler(buf
, "uptime", NULL
, 0) != 0 ||
4022 filler(buf
, "diskstats", NULL
, 0) != 0 ||
4023 filler(buf
, "swaps", NULL
, 0) != 0)
4028 int proc_open(const char *path
, struct fuse_file_info
*fi
)
4031 struct file_info
*info
;
4033 if (strcmp(path
, "/proc/meminfo") == 0)
4034 type
= LXC_TYPE_PROC_MEMINFO
;
4035 else if (strcmp(path
, "/proc/cpuinfo") == 0)
4036 type
= LXC_TYPE_PROC_CPUINFO
;
4037 else if (strcmp(path
, "/proc/uptime") == 0)
4038 type
= LXC_TYPE_PROC_UPTIME
;
4039 else if (strcmp(path
, "/proc/stat") == 0)
4040 type
= LXC_TYPE_PROC_STAT
;
4041 else if (strcmp(path
, "/proc/diskstats") == 0)
4042 type
= LXC_TYPE_PROC_DISKSTATS
;
4043 else if (strcmp(path
, "/proc/swaps") == 0)
4044 type
= LXC_TYPE_PROC_SWAPS
;
4048 info
= malloc(sizeof(*info
));
4052 memset(info
, 0, sizeof(*info
));
4055 info
->buflen
= get_procfile_size(path
) + BUF_RESERVE_SIZE
;
4057 info
->buf
= malloc(info
->buflen
);
4058 } while (!info
->buf
);
4059 memset(info
->buf
, 0, info
->buflen
);
4060 /* set actual size to buffer size */
4061 info
->size
= info
->buflen
;
4063 fi
->fh
= (unsigned long)info
;
4067 int proc_access(const char *path
, int mask
)
4069 /* these are all read-only */
4070 if ((mask
& ~R_OK
) != 0)
4075 int proc_release(const char *path
, struct fuse_file_info
*fi
)
4077 do_release_file_info(fi
);
4081 int proc_read(const char *path
, char *buf
, size_t size
, off_t offset
,
4082 struct fuse_file_info
*fi
)
4084 struct file_info
*f
= (struct file_info
*) fi
->fh
;
4087 case LXC_TYPE_PROC_MEMINFO
:
4088 return proc_meminfo_read(buf
, size
, offset
, fi
);
4089 case LXC_TYPE_PROC_CPUINFO
:
4090 return proc_cpuinfo_read(buf
, size
, offset
, fi
);
4091 case LXC_TYPE_PROC_UPTIME
:
4092 return proc_uptime_read(buf
, size
, offset
, fi
);
4093 case LXC_TYPE_PROC_STAT
:
4094 return proc_stat_read(buf
, size
, offset
, fi
);
4095 case LXC_TYPE_PROC_DISKSTATS
:
4096 return proc_diskstats_read(buf
, size
, offset
, fi
);
4097 case LXC_TYPE_PROC_SWAPS
:
4098 return proc_swaps_read(buf
, size
, offset
, fi
);
4105 * Functions needed to setup cgroups in the __constructor__.
4108 static bool mkdir_p(const char *dir
, mode_t mode
)
4110 const char *tmp
= dir
;
4111 const char *orig
= dir
;
4115 dir
= tmp
+ strspn(tmp
, "/");
4116 tmp
= dir
+ strcspn(dir
, "/");
4117 makeme
= strndup(orig
, dir
- orig
);
4120 if (mkdir(makeme
, mode
) && errno
!= EEXIST
) {
4121 fprintf(stderr
, "failed to create directory '%s': %s",
4122 makeme
, strerror(errno
));
4127 } while(tmp
!= dir
);
4132 static bool umount_if_mounted(void)
4134 if (umount2(BASEDIR
, MNT_DETACH
) < 0 && errno
!= EINVAL
) {
4135 fprintf(stderr
, "failed to unmount %s: %s.\n", BASEDIR
, strerror(errno
));
4141 static int pivot_enter(void)
4143 int ret
= -1, oldroot
= -1, newroot
= -1;
4145 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
);
4147 fprintf(stderr
, "%s: Failed to open old root for fchdir.\n", __func__
);
4151 newroot
= open(ROOTDIR
, O_DIRECTORY
| O_RDONLY
);
4153 fprintf(stderr
, "%s: Failed to open new root for fchdir.\n", __func__
);
4157 /* change into new root fs */
4158 if (fchdir(newroot
) < 0) {
4159 fprintf(stderr
, "%s: Failed to change directory to new rootfs: %s.\n", __func__
, ROOTDIR
);
4163 /* pivot_root into our new root fs */
4164 if (pivot_root(".", ".") < 0) {
4165 fprintf(stderr
, "%s: pivot_root() syscall failed: %s.\n", __func__
, strerror(errno
));
4170 * At this point the old-root is mounted on top of our new-root.
4171 * To unmounted it we must not be chdir'd into it, so escape back
4174 if (fchdir(oldroot
) < 0) {
4175 fprintf(stderr
, "%s: Failed to enter old root.\n", __func__
);
4178 if (umount2(".", MNT_DETACH
) < 0) {
4179 fprintf(stderr
, "%s: Failed to detach old root.\n", __func__
);
4183 if (fchdir(newroot
) < 0) {
4184 fprintf(stderr
, "%s: Failed to re-enter new root.\n", __func__
);
4198 /* Prepare our new clean root. */
4199 static int pivot_prepare(void)
4201 if (mkdir(ROOTDIR
, 0700) < 0 && errno
!= EEXIST
) {
4202 fprintf(stderr
, "%s: Failed to create directory for new root.\n", __func__
);
4206 if (mount("/", ROOTDIR
, NULL
, MS_BIND
, 0) < 0) {
4207 fprintf(stderr
, "%s: Failed to bind-mount / for new root: %s.\n", __func__
, strerror(errno
));
4211 if (mount(RUNTIME_PATH
, ROOTDIR RUNTIME_PATH
, NULL
, MS_BIND
, 0) < 0) {
4212 fprintf(stderr
, "%s: Failed to bind-mount /run into new root: %s.\n", __func__
, strerror(errno
));
4216 if (mount(BASEDIR
, ROOTDIR BASEDIR
, NULL
, MS_REC
| MS_MOVE
, 0) < 0) {
4217 printf("%s: failed to move " BASEDIR
" into new root: %s.\n", __func__
, strerror(errno
));
4224 static bool pivot_new_root(void)
4226 /* Prepare new root. */
4227 if (pivot_prepare() < 0)
4230 /* Pivot into new root. */
4231 if (pivot_enter() < 0)
4237 static bool setup_cgfs_dir(void)
4239 if (!mkdir_p(BASEDIR
, 0700)) {
4240 fprintf(stderr
, "Failed to create lxcfs cgroup mountpoint.\n");
4244 if (!umount_if_mounted()) {
4245 fprintf(stderr
, "Failed to clean up old lxcfs cgroup mountpoint.\n");
4249 if (unshare(CLONE_NEWNS
) < 0) {
4250 fprintf(stderr
, "%s: Failed to unshare mount namespace: %s.\n", __func__
, strerror(errno
));
4254 if (mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, 0) < 0) {
4255 fprintf(stderr
, "%s: Failed to remount / private: %s.\n", __func__
, strerror(errno
));
4259 if (mount("tmpfs", BASEDIR
, "tmpfs", 0, "size=100000,mode=700") < 0) {
4260 fprintf(stderr
, "Failed to mount tmpfs over lxcfs cgroup mountpoint.\n");
4267 static bool do_mount_cgroups(void)
4273 for (i
= 0; i
< num_hierarchies
; i
++) {
4274 char *controller
= hierarchies
[i
];
4275 clen
= strlen(controller
);
4276 len
= strlen(BASEDIR
) + clen
+ 2;
4277 target
= malloc(len
);
4280 ret
= snprintf(target
, len
, "%s/%s", BASEDIR
, controller
);
4281 if (ret
< 0 || ret
>= len
) {
4285 if (mkdir(target
, 0755) < 0 && errno
!= EEXIST
) {
4289 if (mount(controller
, target
, "cgroup", 0, controller
) < 0) {
4290 fprintf(stderr
, "Failed mounting cgroup %s\n", controller
);
4295 fd_hierarchies
[i
] = open(target
, O_DIRECTORY
);
4296 if (fd_hierarchies
[i
] < 0) {
4305 static bool cgfs_setup_controllers(void)
4307 if (!setup_cgfs_dir())
4310 if (!do_mount_cgroups()) {
4311 fprintf(stderr
, "Failed to set up private lxcfs cgroup mounts.\n");
4315 if (!pivot_new_root())
4321 static int preserve_ns(int pid
)
4324 size_t len
= 5 /* /proc */ + 21 /* /int_as_str */ + 7 /* /ns/mnt */ + 1 /* \0 */;
4327 ret
= snprintf(path
, len
, "/proc/%d/ns/mnt", pid
);
4328 if (ret
< 0 || (size_t)ret
>= len
)
4331 return open(path
, O_RDONLY
| O_CLOEXEC
);
4334 static void __attribute__((constructor
)) collect_and_mount_subsystems(void)
4339 int i
, init_ns
= -1;
4341 if ((f
= fopen("/proc/self/cgroup", "r")) == NULL
) {
4342 fprintf(stderr
, "Error opening /proc/self/cgroup: %s\n", strerror(errno
));
4345 while (getline(&line
, &len
, f
) != -1) {
4348 p
= strchr(line
, ':');
4353 p2
= strrchr(p
, ':');
4358 /* With cgroupv2 /proc/self/cgroup can contain entries of the
4359 * form: 0::/ This will cause lxcfs to fail the cgroup mounts
4360 * because it parses out the empty string "" and later on passes
4361 * it to mount(). Let's skip such entries.
4366 if (!store_hierarchy(line
, p
))
4370 /* Preserve initial namespace. */
4371 init_ns
= preserve_ns(getpid());
4375 fd_hierarchies
= malloc(sizeof(int *) * num_hierarchies
);
4376 if (!fd_hierarchies
)
4379 for (i
= 0; i
< num_hierarchies
; i
++)
4380 fd_hierarchies
[i
] = -1;
4382 /* This function calls unshare(CLONE_NEWNS) our initial mount namespace
4383 * to privately mount lxcfs cgroups. */
4384 if (!cgfs_setup_controllers())
4387 if (setns(init_ns
, 0) < 0)
4399 static void __attribute__((destructor
)) free_subsystems(void)
4403 for (i
= 0; i
< num_hierarchies
; i
++) {
4405 free(hierarchies
[i
]);
4406 if (fd_hierarchies
&& fd_hierarchies
[i
] >= 0)
4407 close(fd_hierarchies
[i
]);
4410 free(fd_hierarchies
);