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
24 #include <linux/sched.h>
25 #include <sys/param.h>
26 #include <sys/socket.h>
27 #include <sys/mount.h>
28 #include <sys/epoll.h>
33 #include "config.h" // for VERSION
38 LXC_TYPE_PROC_MEMINFO
,
39 LXC_TYPE_PROC_CPUINFO
,
42 LXC_TYPE_PROC_DISKSTATS
,
51 char *buf
; // unused as of yet
53 int size
; //actual data size
57 /* reserve buffer size, for cpuall in /proc/stat */
58 #define BUF_RESERVE_SIZE 256
61 * A table caching which pid is init for a pid namespace.
62 * When looking up which pid is init for $qpid, we first
63 * 1. Stat /proc/$qpid/ns/pid.
64 * 2. Check whether the ino_t is in our store.
65 * a. if not, fork a child in qpid's ns to send us
66 * ucred.pid = 1, and read the initpid. Cache
67 * initpid and creation time for /proc/initpid
68 * in a new store entry.
69 * b. if so, verify that /proc/initpid still matches
70 * what we have saved. If not, clear the store
71 * entry and go back to a. If so, return the
74 struct pidns_init_store
{
75 ino_t ino
; // inode number for /proc/$pid/ns/pid
76 pid_t initpid
; // the pid of nit in that ns
77 long int ctime
; // the time at which /proc/$initpid was created
78 struct pidns_init_store
*next
;
82 /* lol - look at how they are allocated in the kernel */
83 #define PIDNS_HASH_SIZE 4096
84 #define HASH(x) ((x) % PIDNS_HASH_SIZE)
86 static struct pidns_init_store
*pidns_hash_table
[PIDNS_HASH_SIZE
];
87 static pthread_mutex_t pidns_store_mutex
= PTHREAD_MUTEX_INITIALIZER
;
88 static void lock_mutex(pthread_mutex_t
*l
)
92 if ((ret
= pthread_mutex_lock(l
)) != 0) {
93 fprintf(stderr
, "pthread_mutex_lock returned:%d %s\n", ret
, strerror(ret
));
98 static void unlock_mutex(pthread_mutex_t
*l
)
102 if ((ret
= pthread_mutex_unlock(l
)) != 0) {
103 fprintf(stderr
, "pthread_mutex_unlock returned:%d %s\n", ret
, strerror(ret
));
108 static void store_lock(void)
110 lock_mutex(&pidns_store_mutex
);
113 static void store_unlock(void)
115 unlock_mutex(&pidns_store_mutex
);
118 /* Must be called under store_lock */
119 static bool initpid_still_valid(struct pidns_init_store
*e
, struct stat
*nsfdsb
)
124 snprintf(fnam
, 100, "/proc/%d", e
->initpid
);
125 if (stat(fnam
, &initsb
) < 0)
128 fprintf(stderr
, "comparing ctime %ld %ld for pid %d\n",
129 e
->ctime
, initsb
.st_ctime
, e
->initpid
);
131 if (e
->ctime
!= initsb
.st_ctime
)
136 /* Must be called under store_lock */
137 static void remove_initpid(struct pidns_init_store
*e
)
139 struct pidns_init_store
*tmp
;
143 fprintf(stderr
, "remove_initpid: removing entry for %d\n", e
->initpid
);
146 if (pidns_hash_table
[h
] == e
) {
147 pidns_hash_table
[h
] = e
->next
;
152 tmp
= pidns_hash_table
[h
];
154 if (tmp
->next
== e
) {
164 /* Must be called under store_lock */
165 static void prune_initpid_store(void)
167 static long int last_prune
= 0;
168 struct pidns_init_store
*e
, *prev
, *delme
;
169 long int now
, threshold
;
173 last_prune
= time(NULL
);
177 if (now
< last_prune
+ PURGE_SECS
)
180 fprintf(stderr
, "pruning\n");
183 threshold
= now
- 2 * PURGE_SECS
;
185 for (i
= 0; i
< PIDNS_HASH_SIZE
; i
++) {
186 for (prev
= NULL
, e
= pidns_hash_table
[i
]; e
; ) {
187 if (e
->lastcheck
< threshold
) {
189 fprintf(stderr
, "Removing cached entry for %d\n", e
->initpid
);
193 prev
->next
= e
->next
;
195 pidns_hash_table
[i
] = e
->next
;
206 /* Must be called under store_lock */
207 static void save_initpid(struct stat
*sb
, pid_t pid
)
209 struct pidns_init_store
*e
;
215 fprintf(stderr
, "save_initpid: adding entry for %d\n", pid
);
217 snprintf(fpath
, 100, "/proc/%d", pid
);
218 if (stat(fpath
, &procsb
) < 0)
221 e
= malloc(sizeof(*e
));
225 e
->ctime
= procsb
.st_ctime
;
227 e
->next
= pidns_hash_table
[h
];
228 e
->lastcheck
= time(NULL
);
229 pidns_hash_table
[h
] = e
;
233 * Given the stat(2) info for a nsfd pid inode, lookup the init_pid_store
234 * entry for the inode number and creation time. Verify that the init pid
235 * is still valid. If not, remove it. Return the entry if valid, NULL
237 * Must be called under store_lock
239 static struct pidns_init_store
*lookup_verify_initpid(struct stat
*sb
)
241 int h
= HASH(sb
->st_ino
);
242 struct pidns_init_store
*e
= pidns_hash_table
[h
];
245 if (e
->ino
== sb
->st_ino
) {
246 if (initpid_still_valid(e
, sb
)) {
247 e
->lastcheck
= time(NULL
);
259 static int is_dir(const char *path
)
262 int ret
= stat(path
, &statbuf
);
263 if (ret
== 0 && S_ISDIR(statbuf
.st_mode
))
268 static char *must_copy_string(const char *str
)
280 static inline void drop_trailing_newlines(char *s
)
284 for (l
=strlen(s
); l
>0 && s
[l
-1] == '\n'; l
--)
288 #define BATCH_SIZE 50
289 static void dorealloc(char **mem
, size_t oldlen
, size_t newlen
)
291 int newbatches
= (newlen
/ BATCH_SIZE
) + 1;
292 int oldbatches
= (oldlen
/ BATCH_SIZE
) + 1;
294 if (!*mem
|| newbatches
> oldbatches
) {
297 tmp
= realloc(*mem
, newbatches
* BATCH_SIZE
);
302 static void append_line(char **contents
, size_t *len
, char *line
, ssize_t linelen
)
304 size_t newlen
= *len
+ linelen
;
305 dorealloc(contents
, *len
, newlen
+ 1);
306 memcpy(*contents
+ *len
, line
, linelen
+1);
310 static char *slurp_file(const char *from
)
313 char *contents
= NULL
;
314 FILE *f
= fopen(from
, "r");
315 size_t len
= 0, fulllen
= 0;
321 while ((linelen
= getline(&line
, &len
, f
)) != -1) {
322 append_line(&contents
, &fulllen
, line
, linelen
);
327 drop_trailing_newlines(contents
);
332 static bool write_string(const char *fnam
, const char *string
)
337 if (!(f
= fopen(fnam
, "w")))
339 len
= strlen(string
);
340 ret
= fwrite(string
, 1, len
, f
);
342 fprintf(stderr
, "Error writing to file: %s\n", strerror(errno
));
347 fprintf(stderr
, "Error writing to file: %s\n", strerror(errno
));
354 * hierarchies, i.e. 'cpu,cpuacct'
366 static bool store_hierarchy(char *stridx
, char *h
)
368 if (num_hierarchies
% ALLOC_NUM
== 0) {
369 size_t n
= (num_hierarchies
/ ALLOC_NUM
) + 1;
371 char **tmp
= realloc(hierarchies
, n
* sizeof(char *));
373 fprintf(stderr
, "Out of memory\n");
379 hierarchies
[num_hierarchies
++] = must_copy_string(h
);
383 static void print_subsystems(void)
387 fprintf(stderr
, "hierarchies:");
388 for (i
= 0; i
< num_hierarchies
; i
++) {
390 fprintf(stderr
, " %d: %s\n", i
, hierarchies
[i
]);
394 static bool in_comma_list(const char *needle
, const char *haystack
)
396 const char *s
= haystack
, *e
;
397 size_t nlen
= strlen(needle
);
399 while (*s
&& (e
= index(s
, ','))) {
404 if (strncmp(needle
, s
, nlen
) == 0)
408 if (strcmp(needle
, s
) == 0)
413 /* do we need to do any massaging here? I'm not sure... */
414 static char *find_mounted_controller(const char *controller
)
418 for (i
= 0; i
< num_hierarchies
; i
++) {
421 if (strcmp(hierarchies
[i
], controller
) == 0)
422 return hierarchies
[i
];
423 if (in_comma_list(controller
, hierarchies
[i
]))
424 return hierarchies
[i
];
430 bool cgfs_set_value(const char *controller
, const char *cgroup
, const char *file
,
434 char *fnam
, *tmpc
= find_mounted_controller(controller
);
438 /* basedir / tmpc / cgroup / file \0 */
439 len
= strlen(basedir
) + strlen(tmpc
) + strlen(cgroup
) + strlen(file
) + 4;
441 snprintf(fnam
, len
, "%s/%s/%s/%s", basedir
, tmpc
, cgroup
, file
);
443 return write_string(fnam
, value
);
446 // Chown all the files in the cgroup directory. We do this when we create
447 // a cgroup on behalf of a user.
448 static void chown_all_cgroup_files(const char *dirname
, uid_t uid
, gid_t gid
)
450 struct dirent dirent
, *direntp
;
451 char path
[MAXPATHLEN
];
456 len
= strlen(dirname
);
457 if (len
>= MAXPATHLEN
) {
458 fprintf(stderr
, "chown_all_cgroup_files: pathname too long: %s\n", dirname
);
462 d
= opendir(dirname
);
464 fprintf(stderr
, "chown_all_cgroup_files: failed to open %s\n", dirname
);
468 while (readdir_r(d
, &dirent
, &direntp
) == 0 && direntp
) {
469 if (!strcmp(direntp
->d_name
, ".") || !strcmp(direntp
->d_name
, ".."))
471 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
472 if (ret
< 0 || ret
>= MAXPATHLEN
) {
473 fprintf(stderr
, "chown_all_cgroup_files: pathname too long under %s\n", dirname
);
476 if (chown(path
, uid
, gid
) < 0)
477 fprintf(stderr
, "Failed to chown file %s to %u:%u", path
, uid
, gid
);
482 int cgfs_create(const char *controller
, const char *cg
, uid_t uid
, gid_t gid
)
485 char *dirnam
, *tmpc
= find_mounted_controller(controller
);
489 /* basedir / tmpc / cg \0 */
490 len
= strlen(basedir
) + strlen(tmpc
) + strlen(cg
) + 3;
491 dirnam
= alloca(len
);
492 snprintf(dirnam
, len
, "%s/%s/%s", basedir
,tmpc
, cg
);
494 if (mkdir(dirnam
, 0755) < 0)
497 if (uid
== 0 && gid
== 0)
500 if (chown(dirnam
, uid
, gid
) < 0)
503 chown_all_cgroup_files(dirnam
, uid
, gid
);
508 static bool recursive_rmdir(const char *dirname
)
510 struct dirent dirent
, *direntp
;
513 char pathname
[MAXPATHLEN
];
515 dir
= opendir(dirname
);
518 fprintf(stderr
, "%s: failed to open %s: %s\n", __func__
, dirname
, strerror(errno
));
523 while (!readdir_r(dir
, &dirent
, &direntp
)) {
530 if (!strcmp(direntp
->d_name
, ".") ||
531 !strcmp(direntp
->d_name
, ".."))
534 rc
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
535 if (rc
< 0 || rc
>= MAXPATHLEN
) {
536 fprintf(stderr
, "pathname too long\n");
540 ret
= lstat(pathname
, &mystat
);
543 fprintf(stderr
, "%s: failed to stat %s: %s\n", __func__
, pathname
, strerror(errno
));
547 if (S_ISDIR(mystat
.st_mode
)) {
548 if (!recursive_rmdir(pathname
)) {
550 fprintf(stderr
, "Error removing %s\n", pathname
);
557 if (closedir(dir
) < 0) {
558 fprintf(stderr
, "%s: failed to close directory %s: %s\n", __func__
, dirname
, strerror(errno
));
562 if (rmdir(dirname
) < 0) {
564 fprintf(stderr
, "%s: failed to delete %s: %s\n", __func__
, dirname
, strerror(errno
));
572 bool cgfs_remove(const char *controller
, const char *cg
)
575 char *dirnam
, *tmpc
= find_mounted_controller(controller
);
579 /* basedir / tmpc / cg \0 */
580 len
= strlen(basedir
) + strlen(tmpc
) + strlen(cg
) + 3;
581 dirnam
= alloca(len
);
582 snprintf(dirnam
, len
, "%s/%s/%s", basedir
,tmpc
, cg
);
583 return recursive_rmdir(dirnam
);
586 bool cgfs_chmod_file(const char *controller
, const char *file
, mode_t mode
)
589 char *pathname
, *tmpc
= find_mounted_controller(controller
);
593 /* basedir / tmpc / file \0 */
594 len
= strlen(basedir
) + strlen(tmpc
) + strlen(file
) + 3;
595 pathname
= alloca(len
);
596 snprintf(pathname
, len
, "%s/%s/%s", basedir
, tmpc
, file
);
597 if (chmod(pathname
, mode
) < 0)
602 static int chown_tasks_files(const char *dirname
, uid_t uid
, gid_t gid
)
607 len
= strlen(dirname
) + strlen("/cgroup.procs") + 1;
609 snprintf(fname
, len
, "%s/tasks", dirname
);
610 if (chown(fname
, uid
, gid
) != 0)
612 snprintf(fname
, len
, "%s/cgroup.procs", dirname
);
613 if (chown(fname
, uid
, gid
) != 0)
618 int cgfs_chown_file(const char *controller
, const char *file
, uid_t uid
, gid_t gid
)
621 char *pathname
, *tmpc
= find_mounted_controller(controller
);
625 /* basedir / tmpc / file \0 */
626 len
= strlen(basedir
) + strlen(tmpc
) + strlen(file
) + 3;
627 pathname
= alloca(len
);
628 snprintf(pathname
, len
, "%s/%s/%s", basedir
, tmpc
, file
);
629 if (chown(pathname
, uid
, gid
) < 0)
632 if (is_dir(pathname
))
633 // like cgmanager did, we want to chown the tasks file as well
634 return chown_tasks_files(pathname
, uid
, gid
);
639 FILE *open_pids_file(const char *controller
, const char *cgroup
)
642 char *pathname
, *tmpc
= find_mounted_controller(controller
);
646 /* basedir / tmpc / cgroup / "cgroup.procs" \0 */
647 len
= strlen(basedir
) + strlen(tmpc
) + strlen(cgroup
) + 4 + strlen("cgroup.procs");
648 pathname
= alloca(len
);
649 snprintf(pathname
, len
, "%s/%s/%s/cgroup.procs", basedir
, tmpc
, cgroup
);
650 return fopen(pathname
, "w");
653 static bool cgfs_iterate_cgroup(const char *controller
, const char *cgroup
, bool directories
,
654 void ***list
, size_t typesize
,
655 void* (*iterator
)(const char*, const char*, const char*))
658 char *dirname
, *tmpc
= find_mounted_controller(controller
);
659 char pathname
[MAXPATHLEN
];
660 size_t sz
= 0, asz
= 0;
661 struct dirent dirent
, *direntp
;
669 /* basedir / tmpc / cgroup \0 */
670 len
= strlen(basedir
) + strlen(tmpc
) + strlen(cgroup
) + 3;
671 dirname
= alloca(len
);
672 snprintf(dirname
, len
, "%s/%s/%s", basedir
, tmpc
, cgroup
);
674 dir
= opendir(dirname
);
678 while (!readdir_r(dir
, &dirent
, &direntp
)) {
685 if (!strcmp(direntp
->d_name
, ".") ||
686 !strcmp(direntp
->d_name
, ".."))
689 rc
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
690 if (rc
< 0 || rc
>= MAXPATHLEN
) {
691 fprintf(stderr
, "%s: pathname too long under %s\n", __func__
, dirname
);
695 ret
= lstat(pathname
, &mystat
);
697 fprintf(stderr
, "%s: failed to stat %s: %s\n", __func__
, pathname
, strerror(errno
));
700 if ((!directories
&& !S_ISREG(mystat
.st_mode
)) ||
701 (directories
&& !S_ISDIR(mystat
.st_mode
)))
708 tmp
= realloc(*list
, asz
* typesize
);
712 (*list
)[sz
] = (*iterator
)(controller
, cgroup
, direntp
->d_name
);
713 (*list
)[sz
+1] = NULL
;
716 if (closedir(dir
) < 0) {
717 fprintf(stderr
, "%s: failed closedir for %s: %s\n", __func__
, dirname
, strerror(errno
));
723 static void *make_children_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
727 dup
= strdup(dir_entry
);
732 bool cgfs_list_children(const char *controller
, const char *cgroup
, char ***list
)
734 return cgfs_iterate_cgroup(controller
, cgroup
, true, (void***)list
, sizeof(*list
), &make_children_list_entry
);
737 void free_key(struct cgfs_files
*k
)
745 void free_keys(struct cgfs_files
**keys
)
751 for (i
= 0; keys
[i
]; i
++) {
757 bool cgfs_get_value(const char *controller
, const char *cgroup
, const char *file
, char **value
)
760 char *fnam
, *tmpc
= find_mounted_controller(controller
);
764 /* basedir / tmpc / cgroup / file \0 */
765 len
= strlen(basedir
) + strlen(tmpc
) + strlen(cgroup
) + strlen(file
) + 4;
767 snprintf(fnam
, len
, "%s/%s/%s/%s", basedir
, tmpc
, cgroup
, file
);
769 *value
= slurp_file(fnam
);
770 return *value
!= NULL
;
773 struct cgfs_files
*cgfs_get_key(const char *controller
, const char *cgroup
, const char *file
)
776 char *fnam
, *tmpc
= find_mounted_controller(controller
);
778 struct cgfs_files
*newkey
;
784 if (file
&& *file
== '/')
787 if (file
&& index(file
, '/'))
790 /* basedir / tmpc / cgroup / file \0 */
791 len
= strlen(basedir
) + strlen(tmpc
) + strlen(cgroup
) + 3;
793 len
+= strlen(file
) + 1;
795 snprintf(fnam
, len
, "%s/%s/%s%s%s", basedir
, tmpc
, cgroup
,
796 file
? "/" : "", file
? file
: "");
798 ret
= stat(fnam
, &sb
);
803 newkey
= malloc(sizeof(struct cgfs_files
));
806 newkey
->name
= must_copy_string(file
);
807 else if (rindex(cgroup
, '/'))
808 newkey
->name
= must_copy_string(rindex(cgroup
, '/'));
810 newkey
->name
= must_copy_string(cgroup
);
811 newkey
->uid
= sb
.st_uid
;
812 newkey
->gid
= sb
.st_gid
;
813 newkey
->mode
= sb
.st_mode
;
818 static void *make_key_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
820 struct cgfs_files
*entry
= cgfs_get_key(controller
, cgroup
, dir_entry
);
822 fprintf(stderr
, "%s: Error getting files under %s:%s\n",
823 __func__
, controller
, cgroup
);
828 bool cgfs_list_keys(const char *controller
, const char *cgroup
, struct cgfs_files
***keys
)
830 return cgfs_iterate_cgroup(controller
, cgroup
, false, (void***)keys
, sizeof(*keys
), &make_key_list_entry
);
833 bool is_child_cgroup(const char *controller
, const char *cgroup
, const char *f
)
835 char *fnam
, *tmpc
= find_mounted_controller(controller
);
841 /* basedir / tmpc / cgroup / f \0 */
842 len
= strlen(basedir
) + strlen(tmpc
) + strlen(cgroup
) + strlen(f
) + 4;
844 snprintf(fnam
, len
, "%s/%s/%s/%s", basedir
, tmpc
, cgroup
, f
);
846 ret
= stat(fnam
, &sb
);
847 if (ret
< 0 || !S_ISDIR(sb
.st_mode
))
852 #define SEND_CREDS_OK 0
853 #define SEND_CREDS_NOTSK 1
854 #define SEND_CREDS_FAIL 2
855 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
);
856 static int wait_for_pid(pid_t pid
);
857 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
);
858 static int send_creds_clone_wrapper(void *arg
);
861 * clone a task which switches to @task's namespace and writes '1'.
862 * over a unix sock so we can read the task's reaper's pid in our
865 * Note: glibc's fork() does not respect pidns, which can lead to failed
866 * assertions inside glibc (and thus failed forks) if the child's pid in
867 * the pidns and the parent pid outside are identical. Using clone prevents
870 static void write_task_init_pid_exit(int sock
, pid_t target
)
875 size_t stack_size
= sysconf(_SC_PAGESIZE
);
876 void *stack
= alloca(stack_size
);
878 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", (int)target
);
879 if (ret
< 0 || ret
>= sizeof(fnam
))
882 fd
= open(fnam
, O_RDONLY
);
884 perror("write_task_init_pid_exit open of ns/pid");
888 perror("write_task_init_pid_exit setns 1");
892 pid
= clone(send_creds_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &sock
);
896 if (!wait_for_pid(pid
))
902 static int send_creds_clone_wrapper(void *arg
) {
905 int sock
= *(int *)arg
;
907 /* we are the child */
912 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
)
917 static pid_t
get_init_pid_for_task(pid_t task
)
925 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
926 perror("socketpair");
935 write_task_init_pid_exit(sock
[0], task
);
939 if (!recv_creds(sock
[1], &cred
, &v
))
951 static pid_t
lookup_initpid_in_store(pid_t qpid
)
955 struct pidns_init_store
*e
;
958 snprintf(fnam
, 100, "/proc/%d/ns/pid", qpid
);
960 if (stat(fnam
, &sb
) < 0)
962 e
= lookup_verify_initpid(&sb
);
967 answer
= get_init_pid_for_task(qpid
);
969 save_initpid(&sb
, answer
);
972 /* we prune at end in case we are returning
973 * the value we were about to return */
974 prune_initpid_store();
979 static int wait_for_pid(pid_t pid
)
987 ret
= waitpid(pid
, &status
, 0);
995 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
1002 * append pid to *src.
1003 * src: a pointer to a char* in which ot append the pid.
1004 * sz: the number of characters printed so far, minus trailing \0.
1005 * asz: the allocated size so far
1006 * pid: the pid to append
1008 static void must_strcat_pid(char **src
, size_t *sz
, size_t *asz
, pid_t pid
)
1012 int tmplen
= sprintf(tmp
, "%d\n", (int)pid
);
1014 if (!*src
|| tmplen
+ *sz
+ 1 >= *asz
) {
1017 tmp
= realloc(*src
, *asz
+ BUF_RESERVE_SIZE
);
1020 *asz
+= BUF_RESERVE_SIZE
;
1022 memcpy((*src
) +*sz
, tmp
, tmplen
+1); /* include the \0 */
1027 * Given a open file * to /proc/pid/{u,g}id_map, and an id
1028 * valid in the caller's namespace, return the id mapped into
1030 * Returns the mapped id, or -1 on error.
1033 convert_id_to_ns(FILE *idfile
, unsigned int in_id
)
1035 unsigned int nsuid
, // base id for a range in the idfile's namespace
1036 hostuid
, // base id for a range in the caller's namespace
1037 count
; // number of ids in this range
1041 fseek(idfile
, 0L, SEEK_SET
);
1042 while (fgets(line
, 400, idfile
)) {
1043 ret
= sscanf(line
, "%u %u %u\n", &nsuid
, &hostuid
, &count
);
1046 if (hostuid
+ count
< hostuid
|| nsuid
+ count
< nsuid
) {
1048 * uids wrapped around - unexpected as this is a procfile,
1051 fprintf(stderr
, "pid wrapparound at entry %u %u %u in %s\n",
1052 nsuid
, hostuid
, count
, line
);
1055 if (hostuid
<= in_id
&& hostuid
+count
> in_id
) {
1057 * now since hostuid <= in_id < hostuid+count, and
1058 * hostuid+count and nsuid+count do not wrap around,
1059 * we know that nsuid+(in_id-hostuid) which must be
1060 * less that nsuid+(count) must not wrap around
1062 return (in_id
- hostuid
) + nsuid
;
1071 * for is_privileged_over,
1072 * specify whether we require the calling uid to be root in his
1075 #define NS_ROOT_REQD true
1076 #define NS_ROOT_OPT false
1080 static bool is_privileged_over(pid_t pid
, uid_t uid
, uid_t victim
, bool req_ns_root
)
1082 char fpath
[PROCLEN
];
1084 bool answer
= false;
1087 if (victim
== -1 || uid
== -1)
1091 * If the request is one not requiring root in the namespace,
1092 * then having the same uid suffices. (i.e. uid 1000 has write
1093 * access to files owned by uid 1000
1095 if (!req_ns_root
&& uid
== victim
)
1098 ret
= snprintf(fpath
, PROCLEN
, "/proc/%d/uid_map", pid
);
1099 if (ret
< 0 || ret
>= PROCLEN
)
1101 FILE *f
= fopen(fpath
, "r");
1105 /* if caller's not root in his namespace, reject */
1106 nsuid
= convert_id_to_ns(f
, uid
);
1111 * If victim is not mapped into caller's ns, reject.
1112 * XXX I'm not sure this check is needed given that fuse
1113 * will be sending requests where the vfs has converted
1115 nsuid
= convert_id_to_ns(f
, victim
);
1126 static bool perms_include(int fmode
, mode_t req_mode
)
1130 switch (req_mode
& O_ACCMODE
) {
1138 r
= S_IROTH
| S_IWOTH
;
1143 return ((fmode
& r
) == r
);
1149 * querycg is /a/b/c/d/e
1152 static char *get_next_cgroup_dir(const char *taskcg
, const char *querycg
)
1156 if (strlen(taskcg
) <= strlen(querycg
)) {
1157 fprintf(stderr
, "%s: I was fed bad input\n", __func__
);
1161 if (strcmp(querycg
, "/") == 0)
1162 start
= strdup(taskcg
+ 1);
1164 start
= strdup(taskcg
+ strlen(querycg
) + 1);
1167 end
= strchr(start
, '/');
1173 static void stripnewline(char *x
)
1175 size_t l
= strlen(x
);
1176 if (l
&& x
[l
-1] == '\n')
1180 static char *get_pid_cgroup(pid_t pid
, const char *contrl
)
1184 char *answer
= NULL
;
1188 const char *h
= find_mounted_controller(contrl
);
1192 ret
= snprintf(fnam
, PROCLEN
, "/proc/%d/cgroup", pid
);
1193 if (ret
< 0 || ret
>= PROCLEN
)
1195 if (!(f
= fopen(fnam
, "r")))
1198 while (getline(&line
, &len
, f
) != -1) {
1202 c1
= strchr(line
, ':');
1206 c2
= strchr(c1
, ':');
1210 if (strcmp(c1
, h
) != 0)
1215 answer
= strdup(c2
);
1227 * check whether a fuse context may access a cgroup dir or file
1229 * If file is not null, it is a cgroup file to check under cg.
1230 * If file is null, then we are checking perms on cg itself.
1232 * For files we can check the mode of the list_keys result.
1233 * For cgroups, we must make assumptions based on the files under the
1234 * cgroup, because cgmanager doesn't tell us ownership/perms of cgroups
1237 static bool fc_may_access(struct fuse_context
*fc
, const char *contrl
, const char *cg
, const char *file
, mode_t mode
)
1239 struct cgfs_files
*k
= NULL
;
1242 k
= cgfs_get_key(contrl
, cg
, file
);
1246 if (is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
1247 if (perms_include(k
->mode
>> 6, mode
)) {
1252 if (fc
->gid
== k
->gid
) {
1253 if (perms_include(k
->mode
>> 3, mode
)) {
1258 ret
= perms_include(k
->mode
, mode
);
1265 #define INITSCOPE "/init.scope"
1266 static void prune_init_slice(char *cg
)
1269 size_t cg_len
= strlen(cg
), initscope_len
= strlen(INITSCOPE
);
1271 if (cg_len
< initscope_len
)
1274 point
= cg
+ cg_len
- initscope_len
;
1275 if (strcmp(point
, INITSCOPE
) == 0) {
1284 * If pid is in /a/b/c/d, he may only act on things under cg=/a/b/c/d.
1285 * If pid is in /a, he may act on /a/b, but not on /b.
1286 * if the answer is false and nextcg is not NULL, then *nextcg will point
1287 * to a string containing the next cgroup directory under cg, which must be
1288 * freed by the caller.
1290 static bool caller_is_in_ancestor(pid_t pid
, const char *contrl
, const char *cg
, char **nextcg
)
1292 bool answer
= false;
1293 char *c2
= get_pid_cgroup(pid
, contrl
);
1298 prune_init_slice(c2
);
1301 * callers pass in '/' for root cgroup, otherwise they pass
1302 * in a cgroup without leading '/'
1304 linecmp
= *cg
== '/' ? c2
: c2
+1;
1305 if (strncmp(linecmp
, cg
, strlen(linecmp
)) != 0) {
1307 *nextcg
= get_next_cgroup_dir(linecmp
, cg
);
1319 * If pid is in /a/b/c, he may see that /a exists, but not /b or /a/c.
1321 static bool caller_may_see_dir(pid_t pid
, const char *contrl
, const char *cg
)
1323 bool answer
= false;
1325 size_t target_len
, task_len
;
1327 if (strcmp(cg
, "/") == 0)
1330 c2
= get_pid_cgroup(pid
, contrl
);
1333 prune_init_slice(c2
);
1336 target_len
= strlen(cg
);
1337 task_len
= strlen(task_cg
);
1338 if (task_len
== 0) {
1339 /* Task is in the root cg, it can see everything. This case is
1340 * not handled by the strmcps below, since they test for the
1341 * last /, but that is the first / that we've chopped off
1347 if (strcmp(cg
, task_cg
) == 0) {
1351 if (target_len
< task_len
) {
1352 /* looking up a parent dir */
1353 if (strncmp(task_cg
, cg
, target_len
) == 0 && task_cg
[target_len
] == '/')
1357 if (target_len
> task_len
) {
1358 /* looking up a child dir */
1359 if (strncmp(task_cg
, cg
, task_len
) == 0 && cg
[task_len
] == '/')
1370 * given /cgroup/freezer/a/b, return "freezer".
1371 * the returned char* should NOT be freed.
1373 static char *pick_controller_from_path(struct fuse_context
*fc
, const char *path
)
1376 char *contr
, *slash
;
1378 if (strlen(path
) < 9)
1380 if (*(path
+7) != '/')
1383 contr
= strdupa(p1
);
1386 slash
= strstr(contr
, "/");
1391 for (i
= 0; i
< num_hierarchies
; i
++) {
1392 if (hierarchies
[i
] && strcmp(hierarchies
[i
], contr
) == 0)
1393 return hierarchies
[i
];
1399 * Find the start of cgroup in /cgroup/controller/the/cgroup/path
1400 * Note that the returned value may include files (keynames) etc
1402 static const char *find_cgroup_in_path(const char *path
)
1406 if (strlen(path
) < 9)
1408 p1
= strstr(path
+8, "/");
1415 * split the last path element from the path in @cg.
1416 * @dir is newly allocated and should be freed, @last not
1418 static void get_cgdir_and_path(const char *cg
, char **dir
, char **last
)
1425 *last
= strrchr(cg
, '/');
1430 p
= strrchr(*dir
, '/');
1435 * FUSE ops for /cgroup
1438 int cg_getattr(const char *path
, struct stat
*sb
)
1440 struct timespec now
;
1441 struct fuse_context
*fc
= fuse_get_context();
1442 char * cgdir
= NULL
;
1443 char *last
= NULL
, *path1
, *path2
;
1444 struct cgfs_files
*k
= NULL
;
1446 const char *controller
= NULL
;
1453 memset(sb
, 0, sizeof(struct stat
));
1455 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
1458 sb
->st_uid
= sb
->st_gid
= 0;
1459 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
1462 if (strcmp(path
, "/cgroup") == 0) {
1463 sb
->st_mode
= S_IFDIR
| 00755;
1468 controller
= pick_controller_from_path(fc
, path
);
1471 cgroup
= find_cgroup_in_path(path
);
1473 /* this is just /cgroup/controller, return it as a dir */
1474 sb
->st_mode
= S_IFDIR
| 00755;
1479 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
1489 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1492 /* check that cgcopy is either a child cgroup of cgdir, or listed in its keys.
1493 * Then check that caller's cgroup is under path if last is a child
1494 * cgroup, or cgdir if last is a file */
1496 if (is_child_cgroup(controller
, path1
, path2
)) {
1497 if (!caller_may_see_dir(initpid
, controller
, cgroup
)) {
1501 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
1502 /* this is just /cgroup/controller, return it as a dir */
1503 sb
->st_mode
= S_IFDIR
| 00555;
1508 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
)) {
1513 // get uid, gid, from '/tasks' file and make up a mode
1514 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
1515 sb
->st_mode
= S_IFDIR
| 00755;
1516 k
= cgfs_get_key(controller
, cgroup
, NULL
);
1518 sb
->st_uid
= sb
->st_gid
= 0;
1520 sb
->st_uid
= k
->uid
;
1521 sb
->st_gid
= k
->gid
;
1529 if ((k
= cgfs_get_key(controller
, path1
, path2
)) != NULL
) {
1530 sb
->st_mode
= S_IFREG
| k
->mode
;
1532 sb
->st_uid
= k
->uid
;
1533 sb
->st_gid
= k
->gid
;
1536 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
1540 if (!fc_may_access(fc
, controller
, path1
, path2
, O_RDONLY
)) {
1553 int cg_opendir(const char *path
, struct fuse_file_info
*fi
)
1555 struct fuse_context
*fc
= fuse_get_context();
1557 struct file_info
*dir_info
;
1558 char *controller
= NULL
;
1563 if (strcmp(path
, "/cgroup") == 0) {
1567 // return list of keys for the controller, and list of child cgroups
1568 controller
= pick_controller_from_path(fc
, path
);
1572 cgroup
= find_cgroup_in_path(path
);
1574 /* this is just /cgroup/controller, return its contents */
1579 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1583 if (!caller_may_see_dir(initpid
, controller
, cgroup
))
1585 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
))
1589 /* we'll free this at cg_releasedir */
1590 dir_info
= malloc(sizeof(*dir_info
));
1593 dir_info
->controller
= must_copy_string(controller
);
1594 dir_info
->cgroup
= must_copy_string(cgroup
);
1595 dir_info
->type
= LXC_TYPE_CGDIR
;
1596 dir_info
->buf
= NULL
;
1597 dir_info
->file
= NULL
;
1598 dir_info
->buflen
= 0;
1600 fi
->fh
= (unsigned long)dir_info
;
1604 int cg_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
1605 struct fuse_file_info
*fi
)
1607 struct file_info
*d
= (struct file_info
*)fi
->fh
;
1608 struct cgfs_files
**list
= NULL
;
1610 char *nextcg
= NULL
;
1611 struct fuse_context
*fc
= fuse_get_context();
1612 char **clist
= NULL
;
1614 if (d
->type
!= LXC_TYPE_CGDIR
) {
1615 fprintf(stderr
, "Internal error: file cache info used in readdir\n");
1618 if (!d
->cgroup
&& !d
->controller
) {
1619 // ls /var/lib/lxcfs/cgroup - just show list of controllers
1622 for (i
= 0; i
< num_hierarchies
; i
++) {
1623 if (hierarchies
[i
] && filler(buf
, hierarchies
[i
], NULL
, 0) != 0) {
1630 if (!cgfs_list_keys(d
->controller
, d
->cgroup
, &list
)) {
1631 // not a valid cgroup
1636 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1639 if (!caller_is_in_ancestor(initpid
, d
->controller
, d
->cgroup
, &nextcg
)) {
1641 ret
= filler(buf
, nextcg
, NULL
, 0);
1652 for (i
= 0; list
[i
]; i
++) {
1653 if (filler(buf
, list
[i
]->name
, NULL
, 0) != 0) {
1659 // now get the list of child cgroups
1661 if (!cgfs_list_children(d
->controller
, d
->cgroup
, &clist
)) {
1666 for (i
= 0; clist
[i
]; i
++) {
1667 if (filler(buf
, clist
[i
], NULL
, 0) != 0) {
1678 for (i
= 0; clist
[i
]; i
++)
1685 static void do_release_file_info(struct file_info
*f
)
1689 free(f
->controller
);
1696 int cg_releasedir(const char *path
, struct fuse_file_info
*fi
)
1698 struct file_info
*d
= (struct file_info
*)fi
->fh
;
1700 do_release_file_info(d
);
1704 int cg_open(const char *path
, struct fuse_file_info
*fi
)
1707 char *last
= NULL
, *path1
, *path2
, * cgdir
= NULL
, *controller
;
1708 struct cgfs_files
*k
= NULL
;
1709 struct file_info
*file_info
;
1710 struct fuse_context
*fc
= fuse_get_context();
1716 controller
= pick_controller_from_path(fc
, path
);
1719 cgroup
= find_cgroup_in_path(path
);
1723 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
1732 k
= cgfs_get_key(controller
, path1
, path2
);
1739 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1742 if (!caller_may_see_dir(initpid
, controller
, path1
)) {
1746 if (!fc_may_access(fc
, controller
, path1
, path2
, fi
->flags
)) {
1747 // should never get here
1752 /* we'll free this at cg_release */
1753 file_info
= malloc(sizeof(*file_info
));
1758 file_info
->controller
= must_copy_string(controller
);
1759 file_info
->cgroup
= must_copy_string(path1
);
1760 file_info
->file
= must_copy_string(path2
);
1761 file_info
->type
= LXC_TYPE_CGFILE
;
1762 file_info
->buf
= NULL
;
1763 file_info
->buflen
= 0;
1765 fi
->fh
= (unsigned long)file_info
;
1773 int cg_release(const char *path
, struct fuse_file_info
*fi
)
1775 struct file_info
*f
= (struct file_info
*)fi
->fh
;
1777 do_release_file_info(f
);
1781 #define POLLIN_SET ( EPOLLIN | EPOLLHUP | EPOLLRDHUP )
1783 static bool wait_for_sock(int sock
, int timeout
)
1785 struct epoll_event ev
;
1786 int epfd
, ret
, now
, starttime
, deltatime
, saved_errno
;
1788 if ((starttime
= time(NULL
)) < 0)
1791 if ((epfd
= epoll_create(1)) < 0) {
1792 fprintf(stderr
, "Failed to create epoll socket: %m\n");
1796 ev
.events
= POLLIN_SET
;
1798 if (epoll_ctl(epfd
, EPOLL_CTL_ADD
, sock
, &ev
) < 0) {
1799 fprintf(stderr
, "Failed adding socket to epoll: %m\n");
1805 if ((now
= time(NULL
)) < 0) {
1810 deltatime
= (starttime
+ timeout
) - now
;
1811 if (deltatime
< 0) { // timeout
1816 ret
= epoll_wait(epfd
, &ev
, 1, 1000*deltatime
+ 1);
1817 if (ret
< 0 && errno
== EINTR
)
1819 saved_errno
= errno
;
1823 errno
= saved_errno
;
1829 static int msgrecv(int sockfd
, void *buf
, size_t len
)
1831 if (!wait_for_sock(sockfd
, 2))
1833 return recv(sockfd
, buf
, len
, MSG_DONTWAIT
);
1836 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
)
1838 struct msghdr msg
= { 0 };
1840 struct cmsghdr
*cmsg
;
1841 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
1846 if (msgrecv(sock
, buf
, 1) != 1) {
1847 fprintf(stderr
, "%s: Error getting reply from server over socketpair\n",
1849 return SEND_CREDS_FAIL
;
1853 msg
.msg_control
= cmsgbuf
;
1854 msg
.msg_controllen
= sizeof(cmsgbuf
);
1856 cmsg
= CMSG_FIRSTHDR(&msg
);
1857 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct ucred
));
1858 cmsg
->cmsg_level
= SOL_SOCKET
;
1859 cmsg
->cmsg_type
= SCM_CREDENTIALS
;
1860 memcpy(CMSG_DATA(cmsg
), cred
, sizeof(*cred
));
1862 msg
.msg_name
= NULL
;
1863 msg
.msg_namelen
= 0;
1867 iov
.iov_len
= sizeof(buf
);
1871 if (sendmsg(sock
, &msg
, 0) < 0) {
1872 fprintf(stderr
, "%s: failed at sendmsg: %s\n", __func__
,
1875 return SEND_CREDS_NOTSK
;
1876 return SEND_CREDS_FAIL
;
1879 return SEND_CREDS_OK
;
1882 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
)
1884 struct msghdr msg
= { 0 };
1886 struct cmsghdr
*cmsg
;
1887 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
1898 if (setsockopt(sock
, SOL_SOCKET
, SO_PASSCRED
, &optval
, sizeof(optval
)) == -1) {
1899 fprintf(stderr
, "Failed to set passcred: %s\n", strerror(errno
));
1903 if (write(sock
, buf
, 1) != 1) {
1904 fprintf(stderr
, "Failed to start write on scm fd: %s\n", strerror(errno
));
1908 msg
.msg_name
= NULL
;
1909 msg
.msg_namelen
= 0;
1910 msg
.msg_control
= cmsgbuf
;
1911 msg
.msg_controllen
= sizeof(cmsgbuf
);
1914 iov
.iov_len
= sizeof(buf
);
1918 if (!wait_for_sock(sock
, 2)) {
1919 fprintf(stderr
, "Timed out waiting for scm_cred: %s\n",
1923 ret
= recvmsg(sock
, &msg
, MSG_DONTWAIT
);
1925 fprintf(stderr
, "Failed to receive scm_cred: %s\n",
1930 cmsg
= CMSG_FIRSTHDR(&msg
);
1932 if (cmsg
&& cmsg
->cmsg_len
== CMSG_LEN(sizeof(struct ucred
)) &&
1933 cmsg
->cmsg_level
== SOL_SOCKET
&&
1934 cmsg
->cmsg_type
== SCM_CREDENTIALS
) {
1935 memcpy(cred
, CMSG_DATA(cmsg
), sizeof(*cred
));
1944 * pid_to_ns - reads pids from a ucred over a socket, then writes the
1945 * int value back over the socket. This shifts the pid from the
1946 * sender's pidns into tpid's pidns.
1948 static void pid_to_ns(int sock
, pid_t tpid
)
1953 while (recv_creds(sock
, &cred
, &v
)) {
1956 if (write(sock
, &cred
.pid
, sizeof(pid_t
)) != sizeof(pid_t
))
1963 * pid_to_ns_wrapper: when you setns into a pidns, you yourself remain
1964 * in your old pidns. Only children which you fork will be in the target
1965 * pidns. So the pid_to_ns_wrapper does the setns, then forks a child to
1966 * actually convert pids
1968 static void pid_to_ns_wrapper(int sock
, pid_t tpid
)
1970 int newnsfd
= -1, ret
, cpipe
[2];
1975 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
1976 if (ret
< 0 || ret
>= sizeof(fnam
))
1978 newnsfd
= open(fnam
, O_RDONLY
);
1981 if (setns(newnsfd
, 0) < 0)
1985 if (pipe(cpipe
) < 0)
1995 if (write(cpipe
[1], &b
, sizeof(char)) < 0) {
1996 fprintf(stderr
, "%s (child): erorr on write: %s\n",
1997 __func__
, strerror(errno
));
2000 pid_to_ns(sock
, tpid
);
2001 _exit(1); // not reached
2003 // give the child 1 second to be done forking and
2005 if (!wait_for_sock(cpipe
[0], 1))
2007 ret
= read(cpipe
[0], &v
, 1);
2008 if (ret
!= sizeof(char) || v
!= '1')
2011 if (!wait_for_pid(cpid
))
2017 * To read cgroup files with a particular pid, we will setns into the child
2018 * pidns, open a pipe, fork a child - which will be the first to really be in
2019 * the child ns - which does the cgfs_get_value and writes the data to the pipe.
2021 bool do_read_pids(pid_t tpid
, const char *contrl
, const char *cg
, const char *file
, char **d
)
2023 int sock
[2] = {-1, -1};
2024 char *tmpdata
= NULL
;
2026 pid_t qpid
, cpid
= -1;
2027 bool answer
= false;
2030 size_t sz
= 0, asz
= 0;
2032 if (!cgfs_get_value(contrl
, cg
, file
, &tmpdata
))
2036 * Now we read the pids from returned data one by one, pass
2037 * them into a child in the target namespace, read back the
2038 * translated pids, and put them into our to-return data
2041 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2042 perror("socketpair");
2051 if (!cpid
) // child - exits when done
2052 pid_to_ns_wrapper(sock
[1], tpid
);
2054 char *ptr
= tmpdata
;
2057 while (sscanf(ptr
, "%d\n", &qpid
) == 1) {
2059 ret
= send_creds(sock
[0], &cred
, v
, true);
2061 if (ret
== SEND_CREDS_NOTSK
)
2063 if (ret
== SEND_CREDS_FAIL
)
2066 // read converted results
2067 if (!wait_for_sock(sock
[0], 2)) {
2068 fprintf(stderr
, "%s: timed out waiting for pid from child: %s\n",
2069 __func__
, strerror(errno
));
2072 if (read(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2073 fprintf(stderr
, "%s: error reading pid from child: %s\n",
2074 __func__
, strerror(errno
));
2077 must_strcat_pid(d
, &sz
, &asz
, qpid
);
2079 ptr
= strchr(ptr
, '\n');
2085 cred
.pid
= getpid();
2087 if (send_creds(sock
[0], &cred
, v
, true) != SEND_CREDS_OK
) {
2088 // failed to ask child to exit
2089 fprintf(stderr
, "%s: failed to ask child to exit: %s\n",
2090 __func__
, strerror(errno
));
2100 if (sock
[0] != -1) {
2107 int cg_read(const char *path
, char *buf
, size_t size
, off_t offset
,
2108 struct fuse_file_info
*fi
)
2110 struct fuse_context
*fc
= fuse_get_context();
2111 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2112 struct cgfs_files
*k
= NULL
;
2117 if (f
->type
!= LXC_TYPE_CGFILE
) {
2118 fprintf(stderr
, "Internal error: directory cache info used in cg_read\n");
2131 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
2137 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_RDONLY
)) { // should never get here
2142 if (strcmp(f
->file
, "tasks") == 0 ||
2143 strcmp(f
->file
, "/tasks") == 0 ||
2144 strcmp(f
->file
, "/cgroup.procs") == 0 ||
2145 strcmp(f
->file
, "cgroup.procs") == 0)
2146 // special case - we have to translate the pids
2147 r
= do_read_pids(fc
->pid
, f
->controller
, f
->cgroup
, f
->file
, &data
);
2149 r
= cgfs_get_value(f
->controller
, f
->cgroup
, f
->file
, &data
);
2163 memcpy(buf
, data
, s
);
2164 if (s
> 0 && s
< size
&& data
[s
-1] != '\n')
2174 static void pid_from_ns(int sock
, pid_t tpid
)
2184 if (!wait_for_sock(sock
, 2)) {
2185 fprintf(stderr
, "%s: timeout reading from parent\n", __func__
);
2188 if ((ret
= read(sock
, &vpid
, sizeof(pid_t
))) != sizeof(pid_t
)) {
2189 fprintf(stderr
, "%s: bad read from parent: %s\n",
2190 __func__
, strerror(errno
));
2193 if (vpid
== -1) // done
2197 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
) {
2199 cred
.pid
= getpid();
2200 if (send_creds(sock
, &cred
, v
, false) != SEND_CREDS_OK
)
2207 static void pid_from_ns_wrapper(int sock
, pid_t tpid
)
2209 int newnsfd
= -1, ret
, cpipe
[2];
2214 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
2215 if (ret
< 0 || ret
>= sizeof(fnam
))
2217 newnsfd
= open(fnam
, O_RDONLY
);
2220 if (setns(newnsfd
, 0) < 0)
2224 if (pipe(cpipe
) < 0)
2236 if (write(cpipe
[1], &b
, sizeof(char)) < 0) {
2237 fprintf(stderr
, "%s (child): erorr on write: %s\n",
2238 __func__
, strerror(errno
));
2241 pid_from_ns(sock
, tpid
);
2244 // give the child 1 second to be done forking and
2246 if (!wait_for_sock(cpipe
[0], 1))
2248 ret
= read(cpipe
[0], &v
, 1);
2249 if (ret
!= sizeof(char) || v
!= '1') {
2253 if (!wait_for_pid(cpid
))
2258 kill(cpid
, SIGKILL
);
2264 * Given host @uid, return the uid to which it maps in
2265 * @pid's user namespace, or -1 if none.
2267 bool hostuid_to_ns(uid_t uid
, pid_t pid
, uid_t
*answer
)
2272 sprintf(line
, "/proc/%d/uid_map", pid
);
2273 if ((f
= fopen(line
, "r")) == NULL
) {
2277 *answer
= convert_id_to_ns(f
, uid
);
2286 * get_pid_creds: get the real uid and gid of @pid from
2288 * (XXX should we use euid here?)
2290 void get_pid_creds(pid_t pid
, uid_t
*uid
, gid_t
*gid
)
2299 sprintf(line
, "/proc/%d/status", pid
);
2300 if ((f
= fopen(line
, "r")) == NULL
) {
2301 fprintf(stderr
, "Error opening %s: %s\n", line
, strerror(errno
));
2304 while (fgets(line
, 400, f
)) {
2305 if (strncmp(line
, "Uid:", 4) == 0) {
2306 if (sscanf(line
+4, "%u", &u
) != 1) {
2307 fprintf(stderr
, "bad uid line for pid %u\n", pid
);
2312 } else if (strncmp(line
, "Gid:", 4) == 0) {
2313 if (sscanf(line
+4, "%u", &g
) != 1) {
2314 fprintf(stderr
, "bad gid line for pid %u\n", pid
);
2325 * May the requestor @r move victim @v to a new cgroup?
2326 * This is allowed if
2327 * . they are the same task
2328 * . they are ownedy by the same uid
2329 * . @r is root on the host, or
2330 * . @v's uid is mapped into @r's where @r is root.
2332 bool may_move_pid(pid_t r
, uid_t r_uid
, pid_t v
)
2334 uid_t v_uid
, tmpuid
;
2341 get_pid_creds(v
, &v_uid
, &v_gid
);
2344 if (hostuid_to_ns(r_uid
, r
, &tmpuid
) && tmpuid
== 0
2345 && hostuid_to_ns(v_uid
, r
, &tmpuid
))
2350 static bool do_write_pids(pid_t tpid
, uid_t tuid
, const char *contrl
, const char *cg
,
2351 const char *file
, const char *buf
)
2353 int sock
[2] = {-1, -1};
2354 pid_t qpid
, cpid
= -1;
2355 FILE *pids_file
= NULL
;
2356 bool answer
= false, fail
= false;
2358 pids_file
= open_pids_file(contrl
, cg
);
2363 * write the pids to a socket, have helper in writer's pidns
2364 * call movepid for us
2366 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2367 perror("socketpair");
2375 if (!cpid
) { // child
2377 pid_from_ns_wrapper(sock
[1], tpid
);
2380 const char *ptr
= buf
;
2381 while (sscanf(ptr
, "%d", &qpid
) == 1) {
2385 if (write(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2386 fprintf(stderr
, "%s: error writing pid to child: %s\n",
2387 __func__
, strerror(errno
));
2391 if (recv_creds(sock
[0], &cred
, &v
)) {
2393 if (!may_move_pid(tpid
, tuid
, cred
.pid
)) {
2397 if (fprintf(pids_file
, "%d", (int) cred
.pid
) < 0)
2402 ptr
= strchr(ptr
, '\n');
2408 /* All good, write the value */
2410 if (write(sock
[0], &qpid
,sizeof(qpid
)) != sizeof(qpid
))
2411 fprintf(stderr
, "Warning: failed to ask child to exit\n");
2419 if (sock
[0] != -1) {
2424 if (fclose(pids_file
) != 0)
2430 int cg_write(const char *path
, const char *buf
, size_t size
, off_t offset
,
2431 struct fuse_file_info
*fi
)
2433 struct fuse_context
*fc
= fuse_get_context();
2434 char *localbuf
= NULL
;
2435 struct cgfs_files
*k
= NULL
;
2436 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2439 if (f
->type
!= LXC_TYPE_CGFILE
) {
2440 fprintf(stderr
, "Internal error: directory cache info used in cg_write\n");
2450 localbuf
= alloca(size
+1);
2451 localbuf
[size
] = '\0';
2452 memcpy(localbuf
, buf
, size
);
2454 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
2459 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_WRONLY
)) {
2464 if (strcmp(f
->file
, "tasks") == 0 ||
2465 strcmp(f
->file
, "/tasks") == 0 ||
2466 strcmp(f
->file
, "/cgroup.procs") == 0 ||
2467 strcmp(f
->file
, "cgroup.procs") == 0)
2468 // special case - we have to translate the pids
2469 r
= do_write_pids(fc
->pid
, fc
->uid
, f
->controller
, f
->cgroup
, f
->file
, localbuf
);
2471 r
= cgfs_set_value(f
->controller
, f
->cgroup
, f
->file
, localbuf
);
2481 int cg_chown(const char *path
, uid_t uid
, gid_t gid
)
2483 struct fuse_context
*fc
= fuse_get_context();
2484 char *cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
2485 struct cgfs_files
*k
= NULL
;
2492 if (strcmp(path
, "/cgroup") == 0)
2495 controller
= pick_controller_from_path(fc
, path
);
2498 cgroup
= find_cgroup_in_path(path
);
2500 /* this is just /cgroup/controller */
2503 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2513 if (is_child_cgroup(controller
, path1
, path2
)) {
2514 // get uid, gid, from '/tasks' file and make up a mode
2515 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
2516 k
= cgfs_get_key(controller
, cgroup
, "tasks");
2519 k
= cgfs_get_key(controller
, path1
, path2
);
2527 * This being a fuse request, the uid and gid must be valid
2528 * in the caller's namespace. So we can just check to make
2529 * sure that the caller is root in his uid, and privileged
2530 * over the file's current owner.
2532 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_REQD
)) {
2537 ret
= cgfs_chown_file(controller
, cgroup
, uid
, gid
);
2546 int cg_chmod(const char *path
, mode_t mode
)
2548 struct fuse_context
*fc
= fuse_get_context();
2549 char * cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
2550 struct cgfs_files
*k
= NULL
;
2557 if (strcmp(path
, "/cgroup") == 0)
2560 controller
= pick_controller_from_path(fc
, path
);
2563 cgroup
= find_cgroup_in_path(path
);
2565 /* this is just /cgroup/controller */
2568 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2578 if (is_child_cgroup(controller
, path1
, path2
)) {
2579 // get uid, gid, from '/tasks' file and make up a mode
2580 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
2581 k
= cgfs_get_key(controller
, cgroup
, "tasks");
2584 k
= cgfs_get_key(controller
, path1
, path2
);
2592 * This being a fuse request, the uid and gid must be valid
2593 * in the caller's namespace. So we can just check to make
2594 * sure that the caller is root in his uid, and privileged
2595 * over the file's current owner.
2597 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
2602 if (!cgfs_chmod_file(controller
, cgroup
, mode
)) {
2614 int cg_mkdir(const char *path
, mode_t mode
)
2616 struct fuse_context
*fc
= fuse_get_context();
2617 char *last
= NULL
, *path1
, *cgdir
= NULL
, *controller
, *next
= NULL
;
2625 controller
= pick_controller_from_path(fc
, path
);
2629 cgroup
= find_cgroup_in_path(path
);
2633 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2639 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2642 if (!caller_is_in_ancestor(initpid
, controller
, path1
, &next
)) {
2645 else if (last
&& strcmp(next
, last
) == 0)
2652 if (!fc_may_access(fc
, controller
, path1
, NULL
, O_RDWR
)) {
2656 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
2661 ret
= cgfs_create(controller
, cgroup
, fc
->uid
, fc
->gid
);
2669 int cg_rmdir(const char *path
)
2671 struct fuse_context
*fc
= fuse_get_context();
2672 char *last
= NULL
, *cgdir
= NULL
, *controller
, *next
= NULL
;
2679 controller
= pick_controller_from_path(fc
, path
);
2683 cgroup
= find_cgroup_in_path(path
);
2687 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2693 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2696 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, &next
)) {
2697 if (!last
|| strcmp(next
, last
) == 0)
2704 if (!fc_may_access(fc
, controller
, cgdir
, NULL
, O_WRONLY
)) {
2708 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
2713 if (!cgfs_remove(controller
, cgroup
)) {
2726 static bool startswith(const char *line
, const char *pref
)
2728 if (strncmp(line
, pref
, strlen(pref
)) == 0)
2733 static void get_mem_cached(char *memstat
, unsigned long *v
)
2739 if (startswith(memstat
, "total_cache")) {
2740 sscanf(memstat
+ 11, "%lu", v
);
2744 eol
= strchr(memstat
, '\n');
2751 static void get_blkio_io_value(char *str
, unsigned major
, unsigned minor
, char *iotype
, unsigned long *v
)
2757 snprintf(key
, 32, "%u:%u %s", major
, minor
, iotype
);
2759 size_t len
= strlen(key
);
2763 if (startswith(str
, key
)) {
2764 sscanf(str
+ len
, "%lu", v
);
2767 eol
= strchr(str
, '\n');
2774 static int read_file(const char *path
, char *buf
, size_t size
,
2775 struct file_info
*d
)
2777 size_t linelen
= 0, total_len
= 0, rv
= 0;
2779 char *cache
= d
->buf
;
2780 size_t cache_size
= d
->buflen
;
2781 FILE *f
= fopen(path
, "r");
2785 while (getline(&line
, &linelen
, f
) != -1) {
2786 size_t l
= snprintf(cache
, cache_size
, "%s", line
);
2788 perror("Error writing to cache");
2792 if (l
>= cache_size
) {
2793 fprintf(stderr
, "Internal error: truncated write to cache\n");
2802 d
->size
= total_len
;
2803 if (total_len
> size
) total_len
= size
;
2805 /* read from off 0 */
2806 memcpy(buf
, d
->buf
, total_len
);
2815 * FUSE ops for /proc
2818 static unsigned long get_memlimit(const char *cgroup
)
2820 char *memlimit_str
= NULL
;
2821 unsigned long memlimit
= -1;
2823 if (cgfs_get_value("memory", cgroup
, "memory.limit_in_bytes", &memlimit_str
))
2824 memlimit
= strtoul(memlimit_str
, NULL
, 10);
2831 static unsigned long get_min_memlimit(const char *cgroup
)
2833 char *copy
= strdupa(cgroup
);
2834 unsigned long memlimit
= 0, retlimit
;
2836 retlimit
= get_memlimit(copy
);
2838 while (strcmp(copy
, "/") != 0) {
2839 copy
= dirname(copy
);
2840 memlimit
= get_memlimit(copy
);
2841 if (memlimit
!= -1 && memlimit
< retlimit
)
2842 retlimit
= memlimit
;
2848 static int proc_meminfo_read(char *buf
, size_t size
, off_t offset
,
2849 struct fuse_file_info
*fi
)
2851 struct fuse_context
*fc
= fuse_get_context();
2852 struct file_info
*d
= (struct file_info
*)fi
->fh
;
2854 char *memusage_str
= NULL
, *memstat_str
= NULL
,
2855 *memswlimit_str
= NULL
, *memswusage_str
= NULL
,
2856 *memswlimit_default_str
= NULL
, *memswusage_default_str
= NULL
;
2857 unsigned long memlimit
= 0, memusage
= 0, memswlimit
= 0, memswusage
= 0,
2858 cached
= 0, hosttotal
= 0;
2860 size_t linelen
= 0, total_len
= 0, rv
= 0;
2861 char *cache
= d
->buf
;
2862 size_t cache_size
= d
->buflen
;
2866 if (offset
> d
->size
)
2870 int left
= d
->size
- offset
;
2871 total_len
= left
> size
? size
: left
;
2872 memcpy(buf
, cache
+ offset
, total_len
);
2876 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2879 cg
= get_pid_cgroup(initpid
, "memory");
2881 return read_file("/proc/meminfo", buf
, size
, d
);
2883 memlimit
= get_min_memlimit(cg
);
2884 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
2886 if (!cgfs_get_value("memory", cg
, "memory.stat", &memstat_str
))
2889 // Following values are allowed to fail, because swapaccount might be turned
2890 // off for current kernel
2891 if(cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
) &&
2892 cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
))
2894 /* If swapaccounting is turned on, then default value is assumed to be that of cgroup / */
2895 if (!cgfs_get_value("memory", "/", "memory.memsw.limit_in_bytes", &memswlimit_default_str
))
2897 if (!cgfs_get_value("memory", "/", "memory.memsw.usage_in_bytes", &memswusage_default_str
))
2900 memswlimit
= strtoul(memswlimit_str
, NULL
, 10);
2901 memswusage
= strtoul(memswusage_str
, NULL
, 10);
2903 if (!strcmp(memswlimit_str
, memswlimit_default_str
))
2905 if (!strcmp(memswusage_str
, memswusage_default_str
))
2908 memswlimit
= memswlimit
/ 1024;
2909 memswusage
= memswusage
/ 1024;
2912 memusage
= strtoul(memusage_str
, NULL
, 10);
2916 get_mem_cached(memstat_str
, &cached
);
2918 f
= fopen("/proc/meminfo", "r");
2922 while (getline(&line
, &linelen
, f
) != -1) {
2924 char *printme
, lbuf
[100];
2926 memset(lbuf
, 0, 100);
2927 if (startswith(line
, "MemTotal:")) {
2928 sscanf(line
+14, "%lu", &hosttotal
);
2929 if (hosttotal
< memlimit
)
2930 memlimit
= hosttotal
;
2931 snprintf(lbuf
, 100, "MemTotal: %8lu kB\n", memlimit
);
2933 } else if (startswith(line
, "MemFree:")) {
2934 snprintf(lbuf
, 100, "MemFree: %8lu kB\n", memlimit
- memusage
);
2936 } else if (startswith(line
, "MemAvailable:")) {
2937 snprintf(lbuf
, 100, "MemAvailable: %8lu kB\n", memlimit
- memusage
);
2939 } else if (startswith(line
, "SwapTotal:") && memswlimit
> 0) {
2940 snprintf(lbuf
, 100, "SwapTotal: %8lu kB\n", memswlimit
- memlimit
);
2942 } else if (startswith(line
, "SwapFree:") && memswlimit
> 0 && memswusage
> 0) {
2943 snprintf(lbuf
, 100, "SwapFree: %8lu kB\n",
2944 (memswlimit
- memlimit
) - (memswusage
- memusage
));
2946 } else if (startswith(line
, "Buffers:")) {
2947 snprintf(lbuf
, 100, "Buffers: %8lu kB\n", 0UL);
2949 } else if (startswith(line
, "Cached:")) {
2950 snprintf(lbuf
, 100, "Cached: %8lu kB\n", cached
);
2952 } else if (startswith(line
, "SwapCached:")) {
2953 snprintf(lbuf
, 100, "SwapCached: %8lu kB\n", 0UL);
2958 l
= snprintf(cache
, cache_size
, "%s", printme
);
2960 perror("Error writing to cache");
2965 if (l
>= cache_size
) {
2966 fprintf(stderr
, "Internal error: truncated write to cache\n");
2977 d
->size
= total_len
;
2978 if (total_len
> size
) total_len
= size
;
2979 memcpy(buf
, d
->buf
, total_len
);
2988 free(memswlimit_str
);
2989 free(memswusage_str
);
2991 free(memswlimit_default_str
);
2992 free(memswusage_default_str
);
2997 * Read the cpuset.cpus for cg
2998 * Return the answer in a newly allocated string which must be freed
3000 static char *get_cpuset(const char *cg
)
3004 if (!cgfs_get_value("cpuset", cg
, "cpuset.cpus", &answer
))
3009 bool cpu_in_cpuset(int cpu
, const char *cpuset
);
3011 static bool cpuline_in_cpuset(const char *line
, const char *cpuset
)
3015 if (sscanf(line
, "processor : %d", &cpu
) != 1)
3017 return cpu_in_cpuset(cpu
, cpuset
);
3021 * check whether this is a '^processor" line in /proc/cpuinfo
3023 static bool is_processor_line(const char *line
)
3027 if (sscanf(line
, "processor : %d", &cpu
) == 1)
3032 static int proc_cpuinfo_read(char *buf
, size_t size
, off_t offset
,
3033 struct fuse_file_info
*fi
)
3035 struct fuse_context
*fc
= fuse_get_context();
3036 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3038 char *cpuset
= NULL
;
3040 size_t linelen
= 0, total_len
= 0, rv
= 0;
3041 bool am_printing
= false;
3043 char *cache
= d
->buf
;
3044 size_t cache_size
= d
->buflen
;
3048 if (offset
> d
->size
)
3052 int left
= d
->size
- offset
;
3053 total_len
= left
> size
? size
: left
;
3054 memcpy(buf
, cache
+ offset
, total_len
);
3058 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3061 cg
= get_pid_cgroup(initpid
, "cpuset");
3063 return read_file("proc/cpuinfo", buf
, size
, d
);
3065 cpuset
= get_cpuset(cg
);
3069 f
= fopen("/proc/cpuinfo", "r");
3073 while (getline(&line
, &linelen
, f
) != -1) {
3075 if (is_processor_line(line
)) {
3076 am_printing
= cpuline_in_cpuset(line
, cpuset
);
3079 l
= snprintf(cache
, cache_size
, "processor : %d\n", curcpu
);
3081 perror("Error writing to cache");
3085 if (l
>= cache_size
) {
3086 fprintf(stderr
, "Internal error: truncated write to cache\n");
3097 l
= snprintf(cache
, cache_size
, "%s", line
);
3099 perror("Error writing to cache");
3103 if (l
>= cache_size
) {
3104 fprintf(stderr
, "Internal error: truncated write to cache\n");
3115 d
->size
= total_len
;
3116 if (total_len
> size
) total_len
= size
;
3118 /* read from off 0 */
3119 memcpy(buf
, d
->buf
, total_len
);
3130 static int proc_stat_read(char *buf
, size_t size
, off_t offset
,
3131 struct fuse_file_info
*fi
)
3133 struct fuse_context
*fc
= fuse_get_context();
3134 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3136 char *cpuset
= NULL
;
3138 size_t linelen
= 0, total_len
= 0, rv
= 0;
3139 int curcpu
= -1; /* cpu numbering starts at 0 */
3140 unsigned long user
= 0, nice
= 0, system
= 0, idle
= 0, iowait
= 0, irq
= 0, softirq
= 0, steal
= 0, guest
= 0;
3141 unsigned long user_sum
= 0, nice_sum
= 0, system_sum
= 0, idle_sum
= 0, iowait_sum
= 0,
3142 irq_sum
= 0, softirq_sum
= 0, steal_sum
= 0, guest_sum
= 0;
3143 #define CPUALL_MAX_SIZE BUF_RESERVE_SIZE
3144 char cpuall
[CPUALL_MAX_SIZE
];
3145 /* reserve for cpu all */
3146 char *cache
= d
->buf
+ CPUALL_MAX_SIZE
;
3147 size_t cache_size
= d
->buflen
- CPUALL_MAX_SIZE
;
3151 if (offset
> d
->size
)
3155 int left
= d
->size
- offset
;
3156 total_len
= left
> size
? size
: left
;
3157 memcpy(buf
, d
->buf
+ offset
, total_len
);
3161 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3164 cg
= get_pid_cgroup(initpid
, "cpuset");
3166 return read_file("/proc/stat", buf
, size
, d
);
3168 cpuset
= get_cpuset(cg
);
3172 f
= fopen("/proc/stat", "r");
3177 if (getline(&line
, &linelen
, f
) < 0) {
3178 fprintf(stderr
, "proc_stat_read read first line failed\n");
3182 while (getline(&line
, &linelen
, f
) != -1) {
3185 char cpu_char
[10]; /* That's a lot of cores */
3188 if (sscanf(line
, "cpu%9[^ ]", cpu_char
) != 1) {
3189 /* not a ^cpuN line containing a number N, just print it */
3190 l
= snprintf(cache
, cache_size
, "%s", line
);
3192 perror("Error writing to cache");
3196 if (l
>= cache_size
) {
3197 fprintf(stderr
, "Internal error: truncated write to cache\n");
3207 if (sscanf(cpu_char
, "%d", &cpu
) != 1)
3209 if (!cpu_in_cpuset(cpu
, cpuset
))
3213 c
= strchr(line
, ' ');
3216 l
= snprintf(cache
, cache_size
, "cpu%d%s", curcpu
, c
);
3218 perror("Error writing to cache");
3223 if (l
>= cache_size
) {
3224 fprintf(stderr
, "Internal error: truncated write to cache\n");
3233 if (sscanf(line
, "%*s %lu %lu %lu %lu %lu %lu %lu %lu %lu", &user
, &nice
, &system
, &idle
, &iowait
, &irq
,
3234 &softirq
, &steal
, &guest
) != 9)
3238 system_sum
+= system
;
3240 iowait_sum
+= iowait
;
3242 softirq_sum
+= softirq
;
3249 int cpuall_len
= snprintf(cpuall
, CPUALL_MAX_SIZE
, "%s %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
3250 "cpu ", user_sum
, nice_sum
, system_sum
, idle_sum
, iowait_sum
, irq_sum
, softirq_sum
, steal_sum
, guest_sum
);
3251 if (cpuall_len
> 0 && cpuall_len
< CPUALL_MAX_SIZE
){
3252 memcpy(cache
, cpuall
, cpuall_len
);
3253 cache
+= cpuall_len
;
3255 /* shouldn't happen */
3256 fprintf(stderr
, "proc_stat_read copy cpuall failed, cpuall_len=%d\n", cpuall_len
);
3260 memmove(cache
, d
->buf
+ CPUALL_MAX_SIZE
, total_len
);
3261 total_len
+= cpuall_len
;
3263 d
->size
= total_len
;
3264 if (total_len
> size
) total_len
= size
;
3266 memcpy(buf
, d
->buf
, total_len
);
3278 static long int getreaperage(pid_t pid
)
3285 qpid
= lookup_initpid_in_store(pid
);
3289 ret
= snprintf(fnam
, 100, "/proc/%d", qpid
);
3290 if (ret
< 0 || ret
>= 100)
3293 if (lstat(fnam
, &sb
) < 0)
3296 return time(NULL
) - sb
.st_ctime
;
3299 static unsigned long get_reaper_busy(pid_t task
)
3301 pid_t initpid
= lookup_initpid_in_store(task
);
3302 char *cgroup
= NULL
, *usage_str
= NULL
;
3303 unsigned long usage
= 0;
3308 cgroup
= get_pid_cgroup(initpid
, "cpuacct");
3311 if (!cgfs_get_value("cpuacct", cgroup
, "cpuacct.usage", &usage_str
))
3313 usage
= strtoul(usage_str
, NULL
, 10);
3314 usage
/= 1000000000;
3325 char *name
, *cwd
= get_current_dir_name();
3331 len
= strlen(cwd
) + strlen("/iwashere") + 1;
3333 snprintf(name
, len
, "%s/iwashere", cwd
);
3335 fd
= creat(name
, 0755);
3342 * We read /proc/uptime and reuse its second field.
3343 * For the first field, we use the mtime for the reaper for
3344 * the calling pid as returned by getreaperage
3346 static int proc_uptime_read(char *buf
, size_t size
, off_t offset
,
3347 struct fuse_file_info
*fi
)
3349 struct fuse_context
*fc
= fuse_get_context();
3350 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3351 long int reaperage
= getreaperage(fc
->pid
);
3352 unsigned long int busytime
= get_reaper_busy(fc
->pid
), idletime
;
3353 char *cache
= d
->buf
;
3354 size_t total_len
= 0;
3361 if (offset
> d
->size
)
3365 int left
= d
->size
- offset
;
3366 total_len
= left
> size
? size
: left
;
3367 memcpy(buf
, cache
+ offset
, total_len
);
3371 idletime
= reaperage
- busytime
;
3372 if (idletime
> reaperage
)
3373 idletime
= reaperage
;
3375 total_len
= snprintf(d
->buf
, d
->size
, "%ld.0 %lu.0\n", reaperage
, idletime
);
3377 perror("Error writing to cache");
3381 d
->size
= (int)total_len
;
3384 if (total_len
> size
) total_len
= size
;
3386 memcpy(buf
, d
->buf
, total_len
);
3390 static int proc_diskstats_read(char *buf
, size_t size
, off_t offset
,
3391 struct fuse_file_info
*fi
)
3394 struct fuse_context
*fc
= fuse_get_context();
3395 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3397 char *io_serviced_str
= NULL
, *io_merged_str
= NULL
, *io_service_bytes_str
= NULL
,
3398 *io_wait_time_str
= NULL
, *io_service_time_str
= NULL
;
3399 unsigned long read
= 0, write
= 0;
3400 unsigned long read_merged
= 0, write_merged
= 0;
3401 unsigned long read_sectors
= 0, write_sectors
= 0;
3402 unsigned long read_ticks
= 0, write_ticks
= 0;
3403 unsigned long ios_pgr
= 0, tot_ticks
= 0, rq_ticks
= 0;
3404 unsigned long rd_svctm
= 0, wr_svctm
= 0, rd_wait
= 0, wr_wait
= 0;
3405 char *cache
= d
->buf
;
3406 size_t cache_size
= d
->buflen
;
3408 size_t linelen
= 0, total_len
= 0, rv
= 0;
3409 unsigned int major
= 0, minor
= 0;
3414 if (offset
> d
->size
)
3418 int left
= d
->size
- offset
;
3419 total_len
= left
> size
? size
: left
;
3420 memcpy(buf
, cache
+ offset
, total_len
);
3424 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3427 cg
= get_pid_cgroup(initpid
, "blkio");
3429 return read_file("/proc/diskstats", buf
, size
, d
);
3431 if (!cgfs_get_value("blkio", cg
, "blkio.io_serviced", &io_serviced_str
))
3433 if (!cgfs_get_value("blkio", cg
, "blkio.io_merged", &io_merged_str
))
3435 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_bytes", &io_service_bytes_str
))
3437 if (!cgfs_get_value("blkio", cg
, "blkio.io_wait_time", &io_wait_time_str
))
3439 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_time", &io_service_time_str
))
3443 f
= fopen("/proc/diskstats", "r");
3447 while (getline(&line
, &linelen
, f
) != -1) {
3449 char *printme
, lbuf
[256];
3451 i
= sscanf(line
, "%u %u %71s", &major
, &minor
, dev_name
);
3453 get_blkio_io_value(io_serviced_str
, major
, minor
, "Read", &read
);
3454 get_blkio_io_value(io_serviced_str
, major
, minor
, "Write", &write
);
3455 get_blkio_io_value(io_merged_str
, major
, minor
, "Read", &read_merged
);
3456 get_blkio_io_value(io_merged_str
, major
, minor
, "Write", &write_merged
);
3457 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Read", &read_sectors
);
3458 read_sectors
= read_sectors
/512;
3459 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Write", &write_sectors
);
3460 write_sectors
= write_sectors
/512;
3462 get_blkio_io_value(io_service_time_str
, major
, minor
, "Read", &rd_svctm
);
3463 rd_svctm
= rd_svctm
/1000000;
3464 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Read", &rd_wait
);
3465 rd_wait
= rd_wait
/1000000;
3466 read_ticks
= rd_svctm
+ rd_wait
;
3468 get_blkio_io_value(io_service_time_str
, major
, minor
, "Write", &wr_svctm
);
3469 wr_svctm
= wr_svctm
/1000000;
3470 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Write", &wr_wait
);
3471 wr_wait
= wr_wait
/1000000;
3472 write_ticks
= wr_svctm
+ wr_wait
;
3474 get_blkio_io_value(io_service_time_str
, major
, minor
, "Total", &tot_ticks
);
3475 tot_ticks
= tot_ticks
/1000000;
3480 memset(lbuf
, 0, 256);
3481 if (read
|| write
|| read_merged
|| write_merged
|| read_sectors
|| write_sectors
|| read_ticks
|| write_ticks
) {
3482 snprintf(lbuf
, 256, "%u %u %s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
3483 major
, minor
, dev_name
, read
, read_merged
, read_sectors
, read_ticks
,
3484 write
, write_merged
, write_sectors
, write_ticks
, ios_pgr
, tot_ticks
, rq_ticks
);
3489 l
= snprintf(cache
, cache_size
, "%s", printme
);
3491 perror("Error writing to fuse buf");
3495 if (l
>= cache_size
) {
3496 fprintf(stderr
, "Internal error: truncated write to cache\n");
3506 d
->size
= total_len
;
3507 if (total_len
> size
) total_len
= size
;
3508 memcpy(buf
, d
->buf
, total_len
);
3516 free(io_serviced_str
);
3517 free(io_merged_str
);
3518 free(io_service_bytes_str
);
3519 free(io_wait_time_str
);
3520 free(io_service_time_str
);
3524 static int proc_swaps_read(char *buf
, size_t size
, off_t offset
,
3525 struct fuse_file_info
*fi
)
3527 struct fuse_context
*fc
= fuse_get_context();
3528 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3530 char *memswlimit_str
= NULL
, *memlimit_str
= NULL
, *memusage_str
= NULL
, *memswusage_str
= NULL
,
3531 *memswlimit_default_str
= NULL
, *memswusage_default_str
= NULL
;
3532 unsigned long memswlimit
= 0, memlimit
= 0, memusage
= 0, memswusage
= 0, swap_total
= 0, swap_free
= 0;
3533 size_t total_len
= 0, rv
= 0;
3534 char *cache
= d
->buf
;
3537 if (offset
> d
->size
)
3541 int left
= d
->size
- offset
;
3542 total_len
= left
> size
? size
: left
;
3543 memcpy(buf
, cache
+ offset
, total_len
);
3547 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3550 cg
= get_pid_cgroup(initpid
, "memory");
3552 return read_file("/proc/swaps", buf
, size
, d
);
3554 if (!cgfs_get_value("memory", cg
, "memory.limit_in_bytes", &memlimit_str
))
3557 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
3560 memlimit
= strtoul(memlimit_str
, NULL
, 10);
3561 memusage
= strtoul(memusage_str
, NULL
, 10);
3563 if (cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
) &&
3564 cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
)) {
3566 /* If swap accounting is turned on, then default value is assumed to be that of cgroup / */
3567 if (!cgfs_get_value("memory", "/", "memory.memsw.limit_in_bytes", &memswlimit_default_str
))
3569 if (!cgfs_get_value("memory", "/", "memory.memsw.usage_in_bytes", &memswusage_default_str
))
3572 memswlimit
= strtoul(memswlimit_str
, NULL
, 10);
3573 memswusage
= strtoul(memswusage_str
, NULL
, 10);
3575 if (!strcmp(memswlimit_str
, memswlimit_default_str
))
3577 if (!strcmp(memswusage_str
, memswusage_default_str
))
3580 swap_total
= (memswlimit
- memlimit
) / 1024;
3581 swap_free
= (memswusage
- memusage
) / 1024;
3584 total_len
= snprintf(d
->buf
, d
->size
, "Filename\t\t\t\tType\t\tSize\tUsed\tPriority\n");
3586 /* When no mem + swap limit is specified or swapaccount=0*/
3590 FILE *f
= fopen("/proc/meminfo", "r");
3595 while (getline(&line
, &linelen
, f
) != -1) {
3596 if (startswith(line
, "SwapTotal:")) {
3597 sscanf(line
, "SwapTotal: %8lu kB", &swap_total
);
3598 } else if (startswith(line
, "SwapFree:")) {
3599 sscanf(line
, "SwapFree: %8lu kB", &swap_free
);
3607 if (swap_total
> 0) {
3608 total_len
+= snprintf(d
->buf
+ total_len
, d
->size
- total_len
,
3609 "none%*svirtual\t\t%lu\t%lu\t0\n", 36, " ",
3610 swap_total
, swap_free
);
3613 if (total_len
< 0) {
3614 perror("Error writing to cache");
3620 d
->size
= (int)total_len
;
3622 if (total_len
> size
) total_len
= size
;
3623 memcpy(buf
, d
->buf
, total_len
);
3628 free(memswlimit_str
);
3631 free(memswusage_str
);
3632 free(memswusage_default_str
);
3633 free(memswlimit_default_str
);
3637 static off_t
get_procfile_size(const char *which
)
3639 FILE *f
= fopen(which
, "r");
3642 ssize_t sz
, answer
= 0;
3646 while ((sz
= getline(&line
, &len
, f
)) != -1)
3654 int proc_getattr(const char *path
, struct stat
*sb
)
3656 struct timespec now
;
3658 memset(sb
, 0, sizeof(struct stat
));
3659 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
3661 sb
->st_uid
= sb
->st_gid
= 0;
3662 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
3663 if (strcmp(path
, "/proc") == 0) {
3664 sb
->st_mode
= S_IFDIR
| 00555;
3668 if (strcmp(path
, "/proc/meminfo") == 0 ||
3669 strcmp(path
, "/proc/cpuinfo") == 0 ||
3670 strcmp(path
, "/proc/uptime") == 0 ||
3671 strcmp(path
, "/proc/stat") == 0 ||
3672 strcmp(path
, "/proc/diskstats") == 0 ||
3673 strcmp(path
, "/proc/swaps") == 0) {
3675 sb
->st_mode
= S_IFREG
| 00444;
3683 int proc_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
3684 struct fuse_file_info
*fi
)
3686 if (filler(buf
, "cpuinfo", NULL
, 0) != 0 ||
3687 filler(buf
, "meminfo", NULL
, 0) != 0 ||
3688 filler(buf
, "stat", NULL
, 0) != 0 ||
3689 filler(buf
, "uptime", NULL
, 0) != 0 ||
3690 filler(buf
, "diskstats", NULL
, 0) != 0 ||
3691 filler(buf
, "swaps", NULL
, 0) != 0)
3696 int proc_open(const char *path
, struct fuse_file_info
*fi
)
3699 struct file_info
*info
;
3701 if (strcmp(path
, "/proc/meminfo") == 0)
3702 type
= LXC_TYPE_PROC_MEMINFO
;
3703 else if (strcmp(path
, "/proc/cpuinfo") == 0)
3704 type
= LXC_TYPE_PROC_CPUINFO
;
3705 else if (strcmp(path
, "/proc/uptime") == 0)
3706 type
= LXC_TYPE_PROC_UPTIME
;
3707 else if (strcmp(path
, "/proc/stat") == 0)
3708 type
= LXC_TYPE_PROC_STAT
;
3709 else if (strcmp(path
, "/proc/diskstats") == 0)
3710 type
= LXC_TYPE_PROC_DISKSTATS
;
3711 else if (strcmp(path
, "/proc/swaps") == 0)
3712 type
= LXC_TYPE_PROC_SWAPS
;
3716 info
= malloc(sizeof(*info
));
3720 memset(info
, 0, sizeof(*info
));
3723 info
->buflen
= get_procfile_size(path
) + BUF_RESERVE_SIZE
;
3725 info
->buf
= malloc(info
->buflen
);
3726 } while (!info
->buf
);
3727 memset(info
->buf
, 0, info
->buflen
);
3728 /* set actual size to buffer size */
3729 info
->size
= info
->buflen
;
3731 fi
->fh
= (unsigned long)info
;
3735 int proc_release(const char *path
, struct fuse_file_info
*fi
)
3737 struct file_info
*f
= (struct file_info
*)fi
->fh
;
3739 do_release_file_info(f
);
3743 int proc_read(const char *path
, char *buf
, size_t size
, off_t offset
,
3744 struct fuse_file_info
*fi
)
3746 struct file_info
*f
= (struct file_info
*) fi
->fh
;
3749 case LXC_TYPE_PROC_MEMINFO
:
3750 return proc_meminfo_read(buf
, size
, offset
, fi
);
3751 case LXC_TYPE_PROC_CPUINFO
:
3752 return proc_cpuinfo_read(buf
, size
, offset
, fi
);
3753 case LXC_TYPE_PROC_UPTIME
:
3754 return proc_uptime_read(buf
, size
, offset
, fi
);
3755 case LXC_TYPE_PROC_STAT
:
3756 return proc_stat_read(buf
, size
, offset
, fi
);
3757 case LXC_TYPE_PROC_DISKSTATS
:
3758 return proc_diskstats_read(buf
, size
, offset
, fi
);
3759 case LXC_TYPE_PROC_SWAPS
:
3760 return proc_swaps_read(buf
, size
, offset
, fi
);
3766 static void __attribute__((constructor
)) collect_subsystems(void)
3772 if ((f
= fopen("/proc/self/cgroup", "r")) == NULL
) {
3773 fprintf(stderr
, "Error opening /proc/self/cgroup: %s\n", strerror(errno
));
3776 while (getline(&line
, &len
, f
) != -1) {
3779 p
= strchr(line
, ':');
3784 p2
= strrchr(p
, ':');
3789 if (!store_hierarchy(line
, p
))
3800 static void __attribute__((destructor
)) free_subsystems(void)
3804 for (i
= 0; i
< num_hierarchies
; i
++)
3806 free(hierarchies
[i
]);