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
,
50 char *buf
; // unused as of yet
52 int size
; //actual data size
56 /* reserve buffer size, for cpuall in /proc/stat */
57 #define BUF_RESERVE_SIZE 256
60 * A table caching which pid is init for a pid namespace.
61 * When looking up which pid is init for $qpid, we first
62 * 1. Stat /proc/$qpid/ns/pid.
63 * 2. Check whether the ino_t is in our store.
64 * a. if not, fork a child in qpid's ns to send us
65 * ucred.pid = 1, and read the initpid. Cache
66 * initpid and creation time for /proc/initpid
67 * in a new store entry.
68 * b. if so, verify that /proc/initpid still matches
69 * what we have saved. If not, clear the store
70 * entry and go back to a. If so, return the
73 struct pidns_init_store
{
74 ino_t ino
; // inode number for /proc/$pid/ns/pid
75 pid_t initpid
; // the pid of nit in that ns
76 long int ctime
; // the time at which /proc/$initpid was created
77 struct pidns_init_store
*next
;
81 /* lol - look at how they are allocated in the kernel */
82 #define PIDNS_HASH_SIZE 4096
83 #define HASH(x) ((x) % PIDNS_HASH_SIZE)
85 static struct pidns_init_store
*pidns_hash_table
[PIDNS_HASH_SIZE
];
86 static pthread_mutex_t pidns_store_mutex
= PTHREAD_MUTEX_INITIALIZER
;
87 static void lock_mutex(pthread_mutex_t
*l
)
91 if ((ret
= pthread_mutex_lock(l
)) != 0) {
92 fprintf(stderr
, "pthread_mutex_lock returned:%d %s\n", ret
, strerror(ret
));
97 static void unlock_mutex(pthread_mutex_t
*l
)
101 if ((ret
= pthread_mutex_unlock(l
)) != 0) {
102 fprintf(stderr
, "pthread_mutex_unlock returned:%d %s\n", ret
, strerror(ret
));
107 static void store_lock(void)
109 lock_mutex(&pidns_store_mutex
);
112 static void store_unlock(void)
114 unlock_mutex(&pidns_store_mutex
);
117 /* Must be called under store_lock */
118 static bool initpid_still_valid(struct pidns_init_store
*e
, struct stat
*nsfdsb
)
123 snprintf(fnam
, 100, "/proc/%d", e
->initpid
);
124 if (stat(fnam
, &initsb
) < 0)
127 fprintf(stderr
, "comparing ctime %ld %ld for pid %d\n",
128 e
->ctime
, initsb
.st_ctime
, e
->initpid
);
130 if (e
->ctime
!= initsb
.st_ctime
)
135 /* Must be called under store_lock */
136 static void remove_initpid(struct pidns_init_store
*e
)
138 struct pidns_init_store
*tmp
;
142 fprintf(stderr
, "remove_initpid: removing entry for %d\n", e
->initpid
);
145 if (pidns_hash_table
[h
] == e
) {
146 pidns_hash_table
[h
] = e
->next
;
151 tmp
= pidns_hash_table
[h
];
153 if (tmp
->next
== e
) {
163 /* Must be called under store_lock */
164 static void prune_initpid_store(void)
166 static long int last_prune
= 0;
167 struct pidns_init_store
*e
, *prev
, *delme
;
168 long int now
, threshold
;
172 last_prune
= time(NULL
);
176 if (now
< last_prune
+ PURGE_SECS
)
179 fprintf(stderr
, "pruning\n");
182 threshold
= now
- 2 * PURGE_SECS
;
184 for (i
= 0; i
< PIDNS_HASH_SIZE
; i
++) {
185 for (prev
= NULL
, e
= pidns_hash_table
[i
]; e
; ) {
186 if (e
->lastcheck
< threshold
) {
188 fprintf(stderr
, "Removing cached entry for %d\n", e
->initpid
);
192 prev
->next
= e
->next
;
194 pidns_hash_table
[i
] = e
->next
;
205 /* Must be called under store_lock */
206 static void save_initpid(struct stat
*sb
, pid_t pid
)
208 struct pidns_init_store
*e
;
214 fprintf(stderr
, "save_initpid: adding entry for %d\n", pid
);
216 snprintf(fpath
, 100, "/proc/%d", pid
);
217 if (stat(fpath
, &procsb
) < 0)
220 e
= malloc(sizeof(*e
));
224 e
->ctime
= procsb
.st_ctime
;
226 e
->next
= pidns_hash_table
[h
];
227 e
->lastcheck
= time(NULL
);
228 pidns_hash_table
[h
] = e
;
232 * Given the stat(2) info for a nsfd pid inode, lookup the init_pid_store
233 * entry for the inode number and creation time. Verify that the init pid
234 * is still valid. If not, remove it. Return the entry if valid, NULL
236 * Must be called under store_lock
238 static struct pidns_init_store
*lookup_verify_initpid(struct stat
*sb
)
240 int h
= HASH(sb
->st_ino
);
241 struct pidns_init_store
*e
= pidns_hash_table
[h
];
244 if (e
->ino
== sb
->st_ino
) {
245 if (initpid_still_valid(e
, sb
)) {
246 e
->lastcheck
= time(NULL
);
258 static int is_dir(const char *path
)
261 int ret
= stat(path
, &statbuf
);
262 if (ret
== 0 && S_ISDIR(statbuf
.st_mode
))
267 static char *must_copy_string(const char *str
)
279 static inline void drop_trailing_newlines(char *s
)
283 for (l
=strlen(s
); l
>0 && s
[l
-1] == '\n'; l
--)
287 #define BATCH_SIZE 50
288 static void dorealloc(char **mem
, size_t oldlen
, size_t newlen
)
290 int newbatches
= (newlen
/ BATCH_SIZE
) + 1;
291 int oldbatches
= (oldlen
/ BATCH_SIZE
) + 1;
293 if (!*mem
|| newbatches
> oldbatches
) {
296 tmp
= realloc(*mem
, newbatches
* BATCH_SIZE
);
301 static void append_line(char **contents
, size_t *len
, char *line
, ssize_t linelen
)
303 size_t newlen
= *len
+ linelen
;
304 dorealloc(contents
, *len
, newlen
+ 1);
305 memcpy(*contents
+ *len
, line
, linelen
+1);
309 static char *slurp_file(const char *from
)
312 char *contents
= NULL
;
313 FILE *f
= fopen(from
, "r");
314 size_t len
= 0, fulllen
= 0;
320 while ((linelen
= getline(&line
, &len
, f
)) != -1) {
321 append_line(&contents
, &fulllen
, line
, linelen
);
326 drop_trailing_newlines(contents
);
331 static bool write_string(const char *fnam
, const char *string
)
336 if (!(f
= fopen(fnam
, "w")))
338 len
= strlen(string
);
339 ret
= fwrite(string
, 1, len
, f
);
341 fprintf(stderr
, "Error writing to file: %s\n", strerror(errno
));
346 fprintf(stderr
, "Error writing to file: %s\n", strerror(errno
));
353 * hierarchies, i.e. 'cpu,cpuacct'
365 static bool store_hierarchy(char *stridx
, char *h
)
367 if (num_hierarchies
% ALLOC_NUM
== 0) {
368 size_t n
= (num_hierarchies
/ ALLOC_NUM
) + 1;
370 char **tmp
= realloc(hierarchies
, n
* sizeof(char *));
372 fprintf(stderr
, "Out of memory\n");
378 hierarchies
[num_hierarchies
++] = must_copy_string(h
);
382 static void print_subsystems(void)
386 fprintf(stderr
, "hierarchies:");
387 for (i
= 0; i
< num_hierarchies
; i
++) {
389 fprintf(stderr
, " %d: %s\n", i
, hierarchies
[i
]);
393 static bool in_comma_list(const char *needle
, const char *haystack
)
395 const char *s
= haystack
, *e
;
396 size_t nlen
= strlen(needle
);
398 while (*s
&& (e
= index(s
, ','))) {
403 if (strncmp(needle
, s
, nlen
) == 0)
407 if (strcmp(needle
, s
) == 0)
412 /* do we need to do any massaging here? I'm not sure... */
413 static char *find_mounted_controller(const char *controller
)
417 for (i
= 0; i
< num_hierarchies
; i
++) {
420 if (strcmp(hierarchies
[i
], controller
) == 0)
421 return hierarchies
[i
];
422 if (in_comma_list(controller
, hierarchies
[i
]))
423 return hierarchies
[i
];
429 bool cgfs_set_value(const char *controller
, const char *cgroup
, const char *file
,
433 char *fnam
, *tmpc
= find_mounted_controller(controller
);
437 /* basedir / tmpc / cgroup / file \0 */
438 len
= strlen(basedir
) + strlen(tmpc
) + strlen(cgroup
) + strlen(file
) + 4;
440 snprintf(fnam
, len
, "%s/%s/%s/%s", basedir
, tmpc
, cgroup
, file
);
442 return write_string(fnam
, value
);
445 // Chown all the files in the cgroup directory. We do this when we create
446 // a cgroup on behalf of a user.
447 static void chown_all_cgroup_files(const char *dirname
, uid_t uid
, gid_t gid
)
449 struct dirent dirent
, *direntp
;
450 char path
[MAXPATHLEN
];
455 len
= strlen(dirname
);
456 if (len
>= MAXPATHLEN
) {
457 fprintf(stderr
, "chown_all_cgroup_files: pathname too long: %s\n", dirname
);
461 d
= opendir(dirname
);
463 fprintf(stderr
, "chown_all_cgroup_files: failed to open %s\n", dirname
);
467 while (readdir_r(d
, &dirent
, &direntp
) == 0 && direntp
) {
468 if (!strcmp(direntp
->d_name
, ".") || !strcmp(direntp
->d_name
, ".."))
470 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
471 if (ret
< 0 || ret
>= MAXPATHLEN
) {
472 fprintf(stderr
, "chown_all_cgroup_files: pathname too long under %s\n", dirname
);
475 if (chown(path
, uid
, gid
) < 0)
476 fprintf(stderr
, "Failed to chown file %s to %u:%u", path
, uid
, gid
);
481 int cgfs_create(const char *controller
, const char *cg
, uid_t uid
, gid_t gid
)
484 char *dirnam
, *tmpc
= find_mounted_controller(controller
);
488 /* basedir / tmpc / cg \0 */
489 len
= strlen(basedir
) + strlen(tmpc
) + strlen(cg
) + 3;
490 dirnam
= alloca(len
);
491 snprintf(dirnam
, len
, "%s/%s/%s", basedir
,tmpc
, cg
);
493 if (mkdir(dirnam
, 0755) < 0)
496 if (uid
== 0 && gid
== 0)
499 if (chown(dirnam
, uid
, gid
) < 0)
502 chown_all_cgroup_files(dirnam
, uid
, gid
);
507 static bool recursive_rmdir(const char *dirname
)
509 struct dirent dirent
, *direntp
;
512 char pathname
[MAXPATHLEN
];
514 dir
= opendir(dirname
);
517 fprintf(stderr
, "%s: failed to open %s: %s\n", __func__
, dirname
, strerror(errno
));
522 while (!readdir_r(dir
, &dirent
, &direntp
)) {
529 if (!strcmp(direntp
->d_name
, ".") ||
530 !strcmp(direntp
->d_name
, ".."))
533 rc
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
534 if (rc
< 0 || rc
>= MAXPATHLEN
) {
535 fprintf(stderr
, "pathname too long\n");
539 ret
= lstat(pathname
, &mystat
);
542 fprintf(stderr
, "%s: failed to stat %s: %s\n", __func__
, pathname
, strerror(errno
));
546 if (S_ISDIR(mystat
.st_mode
)) {
547 if (!recursive_rmdir(pathname
)) {
549 fprintf(stderr
, "Error removing %s\n", pathname
);
556 if (closedir(dir
) < 0) {
557 fprintf(stderr
, "%s: failed to close directory %s: %s\n", __func__
, dirname
, strerror(errno
));
561 if (rmdir(dirname
) < 0) {
563 fprintf(stderr
, "%s: failed to delete %s: %s\n", __func__
, dirname
, strerror(errno
));
571 bool cgfs_remove(const char *controller
, const char *cg
)
574 char *dirnam
, *tmpc
= find_mounted_controller(controller
);
578 /* basedir / tmpc / cg \0 */
579 len
= strlen(basedir
) + strlen(tmpc
) + strlen(cg
) + 3;
580 dirnam
= alloca(len
);
581 snprintf(dirnam
, len
, "%s/%s/%s", basedir
,tmpc
, cg
);
582 return recursive_rmdir(dirnam
);
585 bool cgfs_chmod_file(const char *controller
, const char *file
, mode_t mode
)
588 char *pathname
, *tmpc
= find_mounted_controller(controller
);
592 /* basedir / tmpc / file \0 */
593 len
= strlen(basedir
) + strlen(tmpc
) + strlen(file
) + 3;
594 pathname
= alloca(len
);
595 snprintf(pathname
, len
, "%s/%s/%s", basedir
, tmpc
, file
);
596 if (chmod(pathname
, mode
) < 0)
601 static int chown_tasks_files(const char *dirname
, uid_t uid
, gid_t gid
)
606 len
= strlen(dirname
) + strlen("/cgroup.procs") + 1;
608 snprintf(fname
, len
, "%s/tasks", dirname
);
609 if (chown(fname
, uid
, gid
) != 0)
611 snprintf(fname
, len
, "%s/cgroup.procs", dirname
);
612 if (chown(fname
, uid
, gid
) != 0)
617 int cgfs_chown_file(const char *controller
, const char *file
, uid_t uid
, gid_t gid
)
620 char *pathname
, *tmpc
= find_mounted_controller(controller
);
624 /* basedir / tmpc / file \0 */
625 len
= strlen(basedir
) + strlen(tmpc
) + strlen(file
) + 3;
626 pathname
= alloca(len
);
627 snprintf(pathname
, len
, "%s/%s/%s", basedir
, tmpc
, file
);
628 if (chown(pathname
, uid
, gid
) < 0)
631 if (is_dir(pathname
))
632 // like cgmanager did, we want to chown the tasks file as well
633 return chown_tasks_files(pathname
, uid
, gid
);
638 FILE *open_pids_file(const char *controller
, const char *cgroup
)
641 char *pathname
, *tmpc
= find_mounted_controller(controller
);
645 /* basedir / tmpc / cgroup / "cgroup.procs" \0 */
646 len
= strlen(basedir
) + strlen(tmpc
) + strlen(cgroup
) + 4 + strlen("cgroup.procs");
647 pathname
= alloca(len
);
648 snprintf(pathname
, len
, "%s/%s/%s/cgroup.procs", basedir
, tmpc
, cgroup
);
649 return fopen(pathname
, "w");
652 static bool cgfs_iterate_cgroup(const char *controller
, const char *cgroup
, bool directories
,
653 void ***list
, size_t typesize
,
654 void* (*iterator
)(const char*, const char*, const char*))
657 char *dirname
, *tmpc
= find_mounted_controller(controller
);
658 char pathname
[MAXPATHLEN
];
659 size_t sz
= 0, asz
= 0;
660 struct dirent dirent
, *direntp
;
668 /* basedir / tmpc / cgroup \0 */
669 len
= strlen(basedir
) + strlen(tmpc
) + strlen(cgroup
) + 3;
670 dirname
= alloca(len
);
671 snprintf(dirname
, len
, "%s/%s/%s", basedir
, tmpc
, cgroup
);
673 dir
= opendir(dirname
);
677 while (!readdir_r(dir
, &dirent
, &direntp
)) {
684 if (!strcmp(direntp
->d_name
, ".") ||
685 !strcmp(direntp
->d_name
, ".."))
688 rc
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
689 if (rc
< 0 || rc
>= MAXPATHLEN
) {
690 fprintf(stderr
, "%s: pathname too long under %s\n", __func__
, dirname
);
694 ret
= lstat(pathname
, &mystat
);
696 fprintf(stderr
, "%s: failed to stat %s: %s\n", __func__
, pathname
, strerror(errno
));
699 if ((!directories
&& !S_ISREG(mystat
.st_mode
)) ||
700 (directories
&& !S_ISDIR(mystat
.st_mode
)))
707 tmp
= realloc(*list
, asz
* typesize
);
711 (*list
)[sz
] = (*iterator
)(controller
, cgroup
, direntp
->d_name
);
712 (*list
)[sz
+1] = NULL
;
715 if (closedir(dir
) < 0) {
716 fprintf(stderr
, "%s: failed closedir for %s: %s\n", __func__
, dirname
, strerror(errno
));
722 static void *make_children_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
726 dup
= strdup(dir_entry
);
731 bool cgfs_list_children(const char *controller
, const char *cgroup
, char ***list
)
733 return cgfs_iterate_cgroup(controller
, cgroup
, true, (void***)list
, sizeof(*list
), &make_children_list_entry
);
736 void free_key(struct cgfs_files
*k
)
744 void free_keys(struct cgfs_files
**keys
)
750 for (i
= 0; keys
[i
]; i
++) {
756 bool cgfs_get_value(const char *controller
, const char *cgroup
, const char *file
, char **value
)
759 char *fnam
, *tmpc
= find_mounted_controller(controller
);
763 /* basedir / tmpc / cgroup / file \0 */
764 len
= strlen(basedir
) + strlen(tmpc
) + strlen(cgroup
) + strlen(file
) + 4;
766 snprintf(fnam
, len
, "%s/%s/%s/%s", basedir
, tmpc
, cgroup
, file
);
768 *value
= slurp_file(fnam
);
769 return *value
!= NULL
;
772 struct cgfs_files
*cgfs_get_key(const char *controller
, const char *cgroup
, const char *file
)
775 char *fnam
, *tmpc
= find_mounted_controller(controller
);
777 struct cgfs_files
*newkey
;
783 if (file
&& *file
== '/')
786 if (file
&& index(file
, '/'))
789 /* basedir / tmpc / cgroup / file \0 */
790 len
= strlen(basedir
) + strlen(tmpc
) + strlen(cgroup
) + 3;
792 len
+= strlen(file
) + 1;
794 snprintf(fnam
, len
, "%s/%s/%s%s%s", basedir
, tmpc
, cgroup
,
795 file
? "/" : "", file
? file
: "");
797 ret
= stat(fnam
, &sb
);
802 newkey
= malloc(sizeof(struct cgfs_files
));
805 newkey
->name
= must_copy_string(file
);
806 else if (rindex(cgroup
, '/'))
807 newkey
->name
= must_copy_string(rindex(cgroup
, '/'));
809 newkey
->name
= must_copy_string(cgroup
);
810 newkey
->uid
= sb
.st_uid
;
811 newkey
->gid
= sb
.st_gid
;
812 newkey
->mode
= sb
.st_mode
;
817 static void *make_key_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
819 struct cgfs_files
*entry
= cgfs_get_key(controller
, cgroup
, dir_entry
);
821 fprintf(stderr
, "%s: Error getting files under %s:%s\n",
822 __func__
, controller
, cgroup
);
827 bool cgfs_list_keys(const char *controller
, const char *cgroup
, struct cgfs_files
***keys
)
829 return cgfs_iterate_cgroup(controller
, cgroup
, false, (void***)keys
, sizeof(*keys
), &make_key_list_entry
);
832 bool is_child_cgroup(const char *controller
, const char *cgroup
, const char *f
)
834 char *fnam
, *tmpc
= find_mounted_controller(controller
);
840 /* basedir / tmpc / cgroup / f \0 */
841 len
= strlen(basedir
) + strlen(tmpc
) + strlen(cgroup
) + strlen(f
) + 4;
843 snprintf(fnam
, len
, "%s/%s/%s/%s", basedir
, tmpc
, cgroup
, f
);
845 ret
= stat(fnam
, &sb
);
846 if (ret
< 0 || !S_ISDIR(sb
.st_mode
))
851 #define SEND_CREDS_OK 0
852 #define SEND_CREDS_NOTSK 1
853 #define SEND_CREDS_FAIL 2
854 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
);
855 static int wait_for_pid(pid_t pid
);
856 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
);
859 * fork a task which switches to @task's namespace and writes '1'.
860 * over a unix sock so we can read the task's reaper's pid in our
863 static void write_task_init_pid_exit(int sock
, pid_t target
)
871 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", (int)target
);
872 if (ret
< 0 || ret
>= sizeof(fnam
))
875 fd
= open(fnam
, O_RDONLY
);
877 perror("write_task_init_pid_exit open of ns/pid");
881 perror("write_task_init_pid_exit setns 1");
889 if (!wait_for_pid(pid
))
894 /* we are the child */
899 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
)
904 static pid_t
get_init_pid_for_task(pid_t task
)
912 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
913 perror("socketpair");
922 write_task_init_pid_exit(sock
[0], task
);
926 if (!recv_creds(sock
[1], &cred
, &v
))
938 static pid_t
lookup_initpid_in_store(pid_t qpid
)
942 struct pidns_init_store
*e
;
945 snprintf(fnam
, 100, "/proc/%d/ns/pid", qpid
);
947 if (stat(fnam
, &sb
) < 0)
949 e
= lookup_verify_initpid(&sb
);
954 answer
= get_init_pid_for_task(qpid
);
956 save_initpid(&sb
, answer
);
959 /* we prune at end in case we are returning
960 * the value we were about to return */
961 prune_initpid_store();
966 static int wait_for_pid(pid_t pid
)
974 ret
= waitpid(pid
, &status
, 0);
982 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
989 * append pid to *src.
990 * src: a pointer to a char* in which ot append the pid.
991 * sz: the number of characters printed so far, minus trailing \0.
992 * asz: the allocated size so far
993 * pid: the pid to append
995 static void must_strcat_pid(char **src
, size_t *sz
, size_t *asz
, pid_t pid
)
999 int tmplen
= sprintf(tmp
, "%d\n", (int)pid
);
1001 if (!*src
|| tmplen
+ *sz
+ 1 >= *asz
) {
1004 tmp
= realloc(*src
, *asz
+ BUF_RESERVE_SIZE
);
1007 *asz
+= BUF_RESERVE_SIZE
;
1009 memcpy((*src
) +*sz
, tmp
, tmplen
+1); /* include the \0 */
1014 * Given a open file * to /proc/pid/{u,g}id_map, and an id
1015 * valid in the caller's namespace, return the id mapped into
1017 * Returns the mapped id, or -1 on error.
1020 convert_id_to_ns(FILE *idfile
, unsigned int in_id
)
1022 unsigned int nsuid
, // base id for a range in the idfile's namespace
1023 hostuid
, // base id for a range in the caller's namespace
1024 count
; // number of ids in this range
1028 fseek(idfile
, 0L, SEEK_SET
);
1029 while (fgets(line
, 400, idfile
)) {
1030 ret
= sscanf(line
, "%u %u %u\n", &nsuid
, &hostuid
, &count
);
1033 if (hostuid
+ count
< hostuid
|| nsuid
+ count
< nsuid
) {
1035 * uids wrapped around - unexpected as this is a procfile,
1038 fprintf(stderr
, "pid wrapparound at entry %u %u %u in %s\n",
1039 nsuid
, hostuid
, count
, line
);
1042 if (hostuid
<= in_id
&& hostuid
+count
> in_id
) {
1044 * now since hostuid <= in_id < hostuid+count, and
1045 * hostuid+count and nsuid+count do not wrap around,
1046 * we know that nsuid+(in_id-hostuid) which must be
1047 * less that nsuid+(count) must not wrap around
1049 return (in_id
- hostuid
) + nsuid
;
1058 * for is_privileged_over,
1059 * specify whether we require the calling uid to be root in his
1062 #define NS_ROOT_REQD true
1063 #define NS_ROOT_OPT false
1067 static bool is_privileged_over(pid_t pid
, uid_t uid
, uid_t victim
, bool req_ns_root
)
1069 char fpath
[PROCLEN
];
1071 bool answer
= false;
1074 if (victim
== -1 || uid
== -1)
1078 * If the request is one not requiring root in the namespace,
1079 * then having the same uid suffices. (i.e. uid 1000 has write
1080 * access to files owned by uid 1000
1082 if (!req_ns_root
&& uid
== victim
)
1085 ret
= snprintf(fpath
, PROCLEN
, "/proc/%d/uid_map", pid
);
1086 if (ret
< 0 || ret
>= PROCLEN
)
1088 FILE *f
= fopen(fpath
, "r");
1092 /* if caller's not root in his namespace, reject */
1093 nsuid
= convert_id_to_ns(f
, uid
);
1098 * If victim is not mapped into caller's ns, reject.
1099 * XXX I'm not sure this check is needed given that fuse
1100 * will be sending requests where the vfs has converted
1102 nsuid
= convert_id_to_ns(f
, victim
);
1113 static bool perms_include(int fmode
, mode_t req_mode
)
1117 switch (req_mode
& O_ACCMODE
) {
1125 r
= S_IROTH
| S_IWOTH
;
1130 return ((fmode
& r
) == r
);
1136 * querycg is /a/b/c/d/e
1139 static char *get_next_cgroup_dir(const char *taskcg
, const char *querycg
)
1143 if (strlen(taskcg
) <= strlen(querycg
)) {
1144 fprintf(stderr
, "%s: I was fed bad input\n", __func__
);
1148 if (strcmp(querycg
, "/") == 0)
1149 start
= strdup(taskcg
+ 1);
1151 start
= strdup(taskcg
+ strlen(querycg
) + 1);
1154 end
= strchr(start
, '/');
1160 static void stripnewline(char *x
)
1162 size_t l
= strlen(x
);
1163 if (l
&& x
[l
-1] == '\n')
1167 static char *get_pid_cgroup(pid_t pid
, const char *contrl
)
1171 char *answer
= NULL
;
1175 const char *h
= find_mounted_controller(contrl
);
1179 ret
= snprintf(fnam
, PROCLEN
, "/proc/%d/cgroup", pid
);
1180 if (ret
< 0 || ret
>= PROCLEN
)
1182 if (!(f
= fopen(fnam
, "r")))
1185 while (getline(&line
, &len
, f
) != -1) {
1189 c1
= strchr(line
, ':');
1193 c2
= strchr(c1
, ':');
1197 if (strcmp(c1
, h
) != 0)
1202 answer
= strdup(c2
);
1214 * check whether a fuse context may access a cgroup dir or file
1216 * If file is not null, it is a cgroup file to check under cg.
1217 * If file is null, then we are checking perms on cg itself.
1219 * For files we can check the mode of the list_keys result.
1220 * For cgroups, we must make assumptions based on the files under the
1221 * cgroup, because cgmanager doesn't tell us ownership/perms of cgroups
1224 static bool fc_may_access(struct fuse_context
*fc
, const char *contrl
, const char *cg
, const char *file
, mode_t mode
)
1226 struct cgfs_files
*k
= NULL
;
1229 k
= cgfs_get_key(contrl
, cg
, file
);
1233 if (is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
1234 if (perms_include(k
->mode
>> 6, mode
)) {
1239 if (fc
->gid
== k
->gid
) {
1240 if (perms_include(k
->mode
>> 3, mode
)) {
1245 ret
= perms_include(k
->mode
, mode
);
1252 #define INITSCOPE "/init.scope"
1253 static void prune_init_slice(char *cg
)
1256 size_t cg_len
= strlen(cg
), initscope_len
= strlen(INITSCOPE
);
1258 if (cg_len
< initscope_len
)
1261 point
= cg
+ cg_len
- initscope_len
;
1262 if (strcmp(point
, INITSCOPE
) == 0) {
1271 * If pid is in /a/b/c/d, he may only act on things under cg=/a/b/c/d.
1272 * If pid is in /a, he may act on /a/b, but not on /b.
1273 * if the answer is false and nextcg is not NULL, then *nextcg will point
1274 * to a string containing the next cgroup directory under cg, which must be
1275 * freed by the caller.
1277 static bool caller_is_in_ancestor(pid_t pid
, const char *contrl
, const char *cg
, char **nextcg
)
1279 bool answer
= false;
1280 char *c2
= get_pid_cgroup(pid
, contrl
);
1285 prune_init_slice(c2
);
1288 * callers pass in '/' for root cgroup, otherwise they pass
1289 * in a cgroup without leading '/'
1291 linecmp
= *cg
== '/' ? c2
: c2
+1;
1292 if (strncmp(linecmp
, cg
, strlen(linecmp
)) != 0) {
1294 *nextcg
= get_next_cgroup_dir(linecmp
, cg
);
1306 * If pid is in /a/b/c, he may see that /a exists, but not /b or /a/c.
1308 static bool caller_may_see_dir(pid_t pid
, const char *contrl
, const char *cg
)
1310 bool answer
= false;
1312 size_t target_len
, task_len
;
1314 if (strcmp(cg
, "/") == 0)
1317 c2
= get_pid_cgroup(pid
, contrl
);
1320 prune_init_slice(c2
);
1323 target_len
= strlen(cg
);
1324 task_len
= strlen(task_cg
);
1325 if (task_len
== 0) {
1326 /* Task is in the root cg, it can see everything. This case is
1327 * not handled by the strmcps below, since they test for the
1328 * last /, but that is the first / that we've chopped off
1334 if (strcmp(cg
, task_cg
) == 0) {
1338 if (target_len
< task_len
) {
1339 /* looking up a parent dir */
1340 if (strncmp(task_cg
, cg
, target_len
) == 0 && task_cg
[target_len
] == '/')
1344 if (target_len
> task_len
) {
1345 /* looking up a child dir */
1346 if (strncmp(task_cg
, cg
, task_len
) == 0 && cg
[task_len
] == '/')
1357 * given /cgroup/freezer/a/b, return "freezer".
1358 * the returned char* should NOT be freed.
1360 static char *pick_controller_from_path(struct fuse_context
*fc
, const char *path
)
1363 char *contr
, *slash
;
1365 if (strlen(path
) < 9)
1367 if (*(path
+7) != '/')
1370 contr
= strdupa(p1
);
1373 slash
= strstr(contr
, "/");
1378 for (i
= 0; i
< num_hierarchies
; i
++) {
1379 if (hierarchies
[i
] && strcmp(hierarchies
[i
], contr
) == 0)
1380 return hierarchies
[i
];
1386 * Find the start of cgroup in /cgroup/controller/the/cgroup/path
1387 * Note that the returned value may include files (keynames) etc
1389 static const char *find_cgroup_in_path(const char *path
)
1393 if (strlen(path
) < 9)
1395 p1
= strstr(path
+8, "/");
1402 * split the last path element from the path in @cg.
1403 * @dir is newly allocated and should be freed, @last not
1405 static void get_cgdir_and_path(const char *cg
, char **dir
, char **last
)
1412 *last
= strrchr(cg
, '/');
1417 p
= strrchr(*dir
, '/');
1422 * FUSE ops for /cgroup
1425 int cg_getattr(const char *path
, struct stat
*sb
)
1427 struct timespec now
;
1428 struct fuse_context
*fc
= fuse_get_context();
1429 char * cgdir
= NULL
;
1430 char *last
= NULL
, *path1
, *path2
;
1431 struct cgfs_files
*k
= NULL
;
1433 const char *controller
= NULL
;
1440 memset(sb
, 0, sizeof(struct stat
));
1442 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
1445 sb
->st_uid
= sb
->st_gid
= 0;
1446 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
1449 if (strcmp(path
, "/cgroup") == 0) {
1450 sb
->st_mode
= S_IFDIR
| 00755;
1455 controller
= pick_controller_from_path(fc
, path
);
1458 cgroup
= find_cgroup_in_path(path
);
1460 /* this is just /cgroup/controller, return it as a dir */
1461 sb
->st_mode
= S_IFDIR
| 00755;
1466 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
1476 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1479 /* check that cgcopy is either a child cgroup of cgdir, or listed in its keys.
1480 * Then check that caller's cgroup is under path if last is a child
1481 * cgroup, or cgdir if last is a file */
1483 if (is_child_cgroup(controller
, path1
, path2
)) {
1484 if (!caller_may_see_dir(initpid
, controller
, cgroup
)) {
1488 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
1489 /* this is just /cgroup/controller, return it as a dir */
1490 sb
->st_mode
= S_IFDIR
| 00555;
1495 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
)) {
1500 // get uid, gid, from '/tasks' file and make up a mode
1501 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
1502 sb
->st_mode
= S_IFDIR
| 00755;
1503 k
= cgfs_get_key(controller
, cgroup
, NULL
);
1505 sb
->st_uid
= sb
->st_gid
= 0;
1507 sb
->st_uid
= k
->uid
;
1508 sb
->st_gid
= k
->gid
;
1516 if ((k
= cgfs_get_key(controller
, path1
, path2
)) != NULL
) {
1517 sb
->st_mode
= S_IFREG
| k
->mode
;
1519 sb
->st_uid
= k
->uid
;
1520 sb
->st_gid
= k
->gid
;
1523 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
1527 if (!fc_may_access(fc
, controller
, path1
, path2
, O_RDONLY
)) {
1540 int cg_opendir(const char *path
, struct fuse_file_info
*fi
)
1542 struct fuse_context
*fc
= fuse_get_context();
1544 struct file_info
*dir_info
;
1545 char *controller
= NULL
;
1550 if (strcmp(path
, "/cgroup") == 0) {
1554 // return list of keys for the controller, and list of child cgroups
1555 controller
= pick_controller_from_path(fc
, path
);
1559 cgroup
= find_cgroup_in_path(path
);
1561 /* this is just /cgroup/controller, return its contents */
1566 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1570 if (!caller_may_see_dir(initpid
, controller
, cgroup
))
1572 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
))
1576 /* we'll free this at cg_releasedir */
1577 dir_info
= malloc(sizeof(*dir_info
));
1580 dir_info
->controller
= must_copy_string(controller
);
1581 dir_info
->cgroup
= must_copy_string(cgroup
);
1582 dir_info
->type
= LXC_TYPE_CGDIR
;
1583 dir_info
->buf
= NULL
;
1584 dir_info
->file
= NULL
;
1585 dir_info
->buflen
= 0;
1587 fi
->fh
= (unsigned long)dir_info
;
1591 int cg_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
1592 struct fuse_file_info
*fi
)
1594 struct file_info
*d
= (struct file_info
*)fi
->fh
;
1595 struct cgfs_files
**list
= NULL
;
1597 char *nextcg
= NULL
;
1598 struct fuse_context
*fc
= fuse_get_context();
1599 char **clist
= NULL
;
1601 if (d
->type
!= LXC_TYPE_CGDIR
) {
1602 fprintf(stderr
, "Internal error: file cache info used in readdir\n");
1605 if (!d
->cgroup
&& !d
->controller
) {
1606 // ls /var/lib/lxcfs/cgroup - just show list of controllers
1609 for (i
= 0; i
< num_hierarchies
; i
++) {
1610 if (hierarchies
[i
] && filler(buf
, hierarchies
[i
], NULL
, 0) != 0) {
1617 if (!cgfs_list_keys(d
->controller
, d
->cgroup
, &list
)) {
1618 // not a valid cgroup
1623 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1626 if (!caller_is_in_ancestor(initpid
, d
->controller
, d
->cgroup
, &nextcg
)) {
1628 ret
= filler(buf
, nextcg
, NULL
, 0);
1639 for (i
= 0; list
[i
]; i
++) {
1640 if (filler(buf
, list
[i
]->name
, NULL
, 0) != 0) {
1646 // now get the list of child cgroups
1648 if (!cgfs_list_children(d
->controller
, d
->cgroup
, &clist
)) {
1653 for (i
= 0; clist
[i
]; i
++) {
1654 if (filler(buf
, clist
[i
], NULL
, 0) != 0) {
1665 for (i
= 0; clist
[i
]; i
++)
1672 static void do_release_file_info(struct file_info
*f
)
1676 free(f
->controller
);
1683 int cg_releasedir(const char *path
, struct fuse_file_info
*fi
)
1685 struct file_info
*d
= (struct file_info
*)fi
->fh
;
1687 do_release_file_info(d
);
1691 int cg_open(const char *path
, struct fuse_file_info
*fi
)
1694 char *last
= NULL
, *path1
, *path2
, * cgdir
= NULL
, *controller
;
1695 struct cgfs_files
*k
= NULL
;
1696 struct file_info
*file_info
;
1697 struct fuse_context
*fc
= fuse_get_context();
1703 controller
= pick_controller_from_path(fc
, path
);
1706 cgroup
= find_cgroup_in_path(path
);
1710 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
1719 k
= cgfs_get_key(controller
, path1
, path2
);
1726 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1729 if (!caller_may_see_dir(initpid
, controller
, path1
)) {
1733 if (!fc_may_access(fc
, controller
, path1
, path2
, fi
->flags
)) {
1734 // should never get here
1739 /* we'll free this at cg_release */
1740 file_info
= malloc(sizeof(*file_info
));
1745 file_info
->controller
= must_copy_string(controller
);
1746 file_info
->cgroup
= must_copy_string(path1
);
1747 file_info
->file
= must_copy_string(path2
);
1748 file_info
->type
= LXC_TYPE_CGFILE
;
1749 file_info
->buf
= NULL
;
1750 file_info
->buflen
= 0;
1752 fi
->fh
= (unsigned long)file_info
;
1760 int cg_release(const char *path
, struct fuse_file_info
*fi
)
1762 struct file_info
*f
= (struct file_info
*)fi
->fh
;
1764 do_release_file_info(f
);
1768 #define POLLIN_SET ( EPOLLIN | EPOLLHUP | EPOLLRDHUP )
1770 static bool wait_for_sock(int sock
, int timeout
)
1772 struct epoll_event ev
;
1773 int epfd
, ret
, now
, starttime
, deltatime
, saved_errno
;
1775 if ((starttime
= time(NULL
)) < 0)
1778 if ((epfd
= epoll_create(1)) < 0) {
1779 fprintf(stderr
, "Failed to create epoll socket: %m\n");
1783 ev
.events
= POLLIN_SET
;
1785 if (epoll_ctl(epfd
, EPOLL_CTL_ADD
, sock
, &ev
) < 0) {
1786 fprintf(stderr
, "Failed adding socket to epoll: %m\n");
1792 if ((now
= time(NULL
)) < 0) {
1797 deltatime
= (starttime
+ timeout
) - now
;
1798 if (deltatime
< 0) { // timeout
1803 ret
= epoll_wait(epfd
, &ev
, 1, 1000*deltatime
+ 1);
1804 if (ret
< 0 && errno
== EINTR
)
1806 saved_errno
= errno
;
1810 errno
= saved_errno
;
1816 static int msgrecv(int sockfd
, void *buf
, size_t len
)
1818 if (!wait_for_sock(sockfd
, 2))
1820 return recv(sockfd
, buf
, len
, MSG_DONTWAIT
);
1823 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
)
1825 struct msghdr msg
= { 0 };
1827 struct cmsghdr
*cmsg
;
1828 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
1833 if (msgrecv(sock
, buf
, 1) != 1) {
1834 fprintf(stderr
, "%s: Error getting reply from server over socketpair\n",
1836 return SEND_CREDS_FAIL
;
1840 msg
.msg_control
= cmsgbuf
;
1841 msg
.msg_controllen
= sizeof(cmsgbuf
);
1843 cmsg
= CMSG_FIRSTHDR(&msg
);
1844 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct ucred
));
1845 cmsg
->cmsg_level
= SOL_SOCKET
;
1846 cmsg
->cmsg_type
= SCM_CREDENTIALS
;
1847 memcpy(CMSG_DATA(cmsg
), cred
, sizeof(*cred
));
1849 msg
.msg_name
= NULL
;
1850 msg
.msg_namelen
= 0;
1854 iov
.iov_len
= sizeof(buf
);
1858 if (sendmsg(sock
, &msg
, 0) < 0) {
1859 fprintf(stderr
, "%s: failed at sendmsg: %s\n", __func__
,
1862 return SEND_CREDS_NOTSK
;
1863 return SEND_CREDS_FAIL
;
1866 return SEND_CREDS_OK
;
1869 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
)
1871 struct msghdr msg
= { 0 };
1873 struct cmsghdr
*cmsg
;
1874 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
1885 if (setsockopt(sock
, SOL_SOCKET
, SO_PASSCRED
, &optval
, sizeof(optval
)) == -1) {
1886 fprintf(stderr
, "Failed to set passcred: %s\n", strerror(errno
));
1890 if (write(sock
, buf
, 1) != 1) {
1891 fprintf(stderr
, "Failed to start write on scm fd: %s\n", strerror(errno
));
1895 msg
.msg_name
= NULL
;
1896 msg
.msg_namelen
= 0;
1897 msg
.msg_control
= cmsgbuf
;
1898 msg
.msg_controllen
= sizeof(cmsgbuf
);
1901 iov
.iov_len
= sizeof(buf
);
1905 if (!wait_for_sock(sock
, 2)) {
1906 fprintf(stderr
, "Timed out waiting for scm_cred: %s\n",
1910 ret
= recvmsg(sock
, &msg
, MSG_DONTWAIT
);
1912 fprintf(stderr
, "Failed to receive scm_cred: %s\n",
1917 cmsg
= CMSG_FIRSTHDR(&msg
);
1919 if (cmsg
&& cmsg
->cmsg_len
== CMSG_LEN(sizeof(struct ucred
)) &&
1920 cmsg
->cmsg_level
== SOL_SOCKET
&&
1921 cmsg
->cmsg_type
== SCM_CREDENTIALS
) {
1922 memcpy(cred
, CMSG_DATA(cmsg
), sizeof(*cred
));
1931 * pid_to_ns - reads pids from a ucred over a socket, then writes the
1932 * int value back over the socket. This shifts the pid from the
1933 * sender's pidns into tpid's pidns.
1935 static void pid_to_ns(int sock
, pid_t tpid
)
1940 while (recv_creds(sock
, &cred
, &v
)) {
1943 if (write(sock
, &cred
.pid
, sizeof(pid_t
)) != sizeof(pid_t
))
1950 * pid_to_ns_wrapper: when you setns into a pidns, you yourself remain
1951 * in your old pidns. Only children which you fork will be in the target
1952 * pidns. So the pid_to_ns_wrapper does the setns, then forks a child to
1953 * actually convert pids
1955 static void pid_to_ns_wrapper(int sock
, pid_t tpid
)
1957 int newnsfd
= -1, ret
, cpipe
[2];
1962 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
1963 if (ret
< 0 || ret
>= sizeof(fnam
))
1965 newnsfd
= open(fnam
, O_RDONLY
);
1968 if (setns(newnsfd
, 0) < 0)
1972 if (pipe(cpipe
) < 0)
1982 if (write(cpipe
[1], &b
, sizeof(char)) < 0) {
1983 fprintf(stderr
, "%s (child): erorr on write: %s\n",
1984 __func__
, strerror(errno
));
1987 pid_to_ns(sock
, tpid
);
1988 _exit(1); // not reached
1990 // give the child 1 second to be done forking and
1992 if (!wait_for_sock(cpipe
[0], 1))
1994 ret
= read(cpipe
[0], &v
, 1);
1995 if (ret
!= sizeof(char) || v
!= '1')
1998 if (!wait_for_pid(cpid
))
2004 * To read cgroup files with a particular pid, we will setns into the child
2005 * pidns, open a pipe, fork a child - which will be the first to really be in
2006 * the child ns - which does the cgfs_get_value and writes the data to the pipe.
2008 bool do_read_pids(pid_t tpid
, const char *contrl
, const char *cg
, const char *file
, char **d
)
2010 int sock
[2] = {-1, -1};
2011 char *tmpdata
= NULL
;
2013 pid_t qpid
, cpid
= -1;
2014 bool answer
= false;
2017 size_t sz
= 0, asz
= 0;
2019 if (!cgfs_get_value(contrl
, cg
, file
, &tmpdata
))
2023 * Now we read the pids from returned data one by one, pass
2024 * them into a child in the target namespace, read back the
2025 * translated pids, and put them into our to-return data
2028 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2029 perror("socketpair");
2038 if (!cpid
) // child - exits when done
2039 pid_to_ns_wrapper(sock
[1], tpid
);
2041 char *ptr
= tmpdata
;
2044 while (sscanf(ptr
, "%d\n", &qpid
) == 1) {
2046 ret
= send_creds(sock
[0], &cred
, v
, true);
2048 if (ret
== SEND_CREDS_NOTSK
)
2050 if (ret
== SEND_CREDS_FAIL
)
2053 // read converted results
2054 if (!wait_for_sock(sock
[0], 2)) {
2055 fprintf(stderr
, "%s: timed out waiting for pid from child: %s\n",
2056 __func__
, strerror(errno
));
2059 if (read(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2060 fprintf(stderr
, "%s: error reading pid from child: %s\n",
2061 __func__
, strerror(errno
));
2064 must_strcat_pid(d
, &sz
, &asz
, qpid
);
2066 ptr
= strchr(ptr
, '\n');
2072 cred
.pid
= getpid();
2074 if (send_creds(sock
[0], &cred
, v
, true) != SEND_CREDS_OK
) {
2075 // failed to ask child to exit
2076 fprintf(stderr
, "%s: failed to ask child to exit: %s\n",
2077 __func__
, strerror(errno
));
2087 if (sock
[0] != -1) {
2094 int cg_read(const char *path
, char *buf
, size_t size
, off_t offset
,
2095 struct fuse_file_info
*fi
)
2097 struct fuse_context
*fc
= fuse_get_context();
2098 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2099 struct cgfs_files
*k
= NULL
;
2104 if (f
->type
!= LXC_TYPE_CGFILE
) {
2105 fprintf(stderr
, "Internal error: directory cache info used in cg_read\n");
2118 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
2124 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_RDONLY
)) { // should never get here
2129 if (strcmp(f
->file
, "tasks") == 0 ||
2130 strcmp(f
->file
, "/tasks") == 0 ||
2131 strcmp(f
->file
, "/cgroup.procs") == 0 ||
2132 strcmp(f
->file
, "cgroup.procs") == 0)
2133 // special case - we have to translate the pids
2134 r
= do_read_pids(fc
->pid
, f
->controller
, f
->cgroup
, f
->file
, &data
);
2136 r
= cgfs_get_value(f
->controller
, f
->cgroup
, f
->file
, &data
);
2150 memcpy(buf
, data
, s
);
2151 if (s
> 0 && s
< size
&& data
[s
-1] != '\n')
2161 static void pid_from_ns(int sock
, pid_t tpid
)
2171 if (!wait_for_sock(sock
, 2)) {
2172 fprintf(stderr
, "%s: timeout reading from parent\n", __func__
);
2175 if ((ret
= read(sock
, &vpid
, sizeof(pid_t
))) != sizeof(pid_t
)) {
2176 fprintf(stderr
, "%s: bad read from parent: %s\n",
2177 __func__
, strerror(errno
));
2180 if (vpid
== -1) // done
2184 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
) {
2186 cred
.pid
= getpid();
2187 if (send_creds(sock
, &cred
, v
, false) != SEND_CREDS_OK
)
2194 static void pid_from_ns_wrapper(int sock
, pid_t tpid
)
2196 int newnsfd
= -1, ret
, cpipe
[2];
2201 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
2202 if (ret
< 0 || ret
>= sizeof(fnam
))
2204 newnsfd
= open(fnam
, O_RDONLY
);
2207 if (setns(newnsfd
, 0) < 0)
2211 if (pipe(cpipe
) < 0)
2223 if (write(cpipe
[1], &b
, sizeof(char)) < 0) {
2224 fprintf(stderr
, "%s (child): erorr on write: %s\n",
2225 __func__
, strerror(errno
));
2228 pid_from_ns(sock
, tpid
);
2231 // give the child 1 second to be done forking and
2233 if (!wait_for_sock(cpipe
[0], 1))
2235 ret
= read(cpipe
[0], &v
, 1);
2236 if (ret
!= sizeof(char) || v
!= '1') {
2240 if (!wait_for_pid(cpid
))
2245 kill(cpid
, SIGKILL
);
2251 * Given host @uid, return the uid to which it maps in
2252 * @pid's user namespace, or -1 if none.
2254 bool hostuid_to_ns(uid_t uid
, pid_t pid
, uid_t
*answer
)
2259 sprintf(line
, "/proc/%d/uid_map", pid
);
2260 if ((f
= fopen(line
, "r")) == NULL
) {
2264 *answer
= convert_id_to_ns(f
, uid
);
2273 * get_pid_creds: get the real uid and gid of @pid from
2275 * (XXX should we use euid here?)
2277 void get_pid_creds(pid_t pid
, uid_t
*uid
, gid_t
*gid
)
2286 sprintf(line
, "/proc/%d/status", pid
);
2287 if ((f
= fopen(line
, "r")) == NULL
) {
2288 fprintf(stderr
, "Error opening %s: %s\n", line
, strerror(errno
));
2291 while (fgets(line
, 400, f
)) {
2292 if (strncmp(line
, "Uid:", 4) == 0) {
2293 if (sscanf(line
+4, "%u", &u
) != 1) {
2294 fprintf(stderr
, "bad uid line for pid %u\n", pid
);
2299 } else if (strncmp(line
, "Gid:", 4) == 0) {
2300 if (sscanf(line
+4, "%u", &g
) != 1) {
2301 fprintf(stderr
, "bad gid line for pid %u\n", pid
);
2312 * May the requestor @r move victim @v to a new cgroup?
2313 * This is allowed if
2314 * . they are the same task
2315 * . they are ownedy by the same uid
2316 * . @r is root on the host, or
2317 * . @v's uid is mapped into @r's where @r is root.
2319 bool may_move_pid(pid_t r
, uid_t r_uid
, pid_t v
)
2321 uid_t v_uid
, tmpuid
;
2328 get_pid_creds(v
, &v_uid
, &v_gid
);
2331 if (hostuid_to_ns(r_uid
, r
, &tmpuid
) && tmpuid
== 0
2332 && hostuid_to_ns(v_uid
, r
, &tmpuid
))
2337 static bool do_write_pids(pid_t tpid
, uid_t tuid
, const char *contrl
, const char *cg
,
2338 const char *file
, const char *buf
)
2340 int sock
[2] = {-1, -1};
2341 pid_t qpid
, cpid
= -1;
2342 FILE *pids_file
= NULL
;
2343 bool answer
= false, fail
= false;
2345 pids_file
= open_pids_file(contrl
, cg
);
2350 * write the pids to a socket, have helper in writer's pidns
2351 * call movepid for us
2353 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2354 perror("socketpair");
2362 if (!cpid
) { // child
2364 pid_from_ns_wrapper(sock
[1], tpid
);
2367 const char *ptr
= buf
;
2368 while (sscanf(ptr
, "%d", &qpid
) == 1) {
2372 if (write(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2373 fprintf(stderr
, "%s: error writing pid to child: %s\n",
2374 __func__
, strerror(errno
));
2378 if (recv_creds(sock
[0], &cred
, &v
)) {
2380 if (!may_move_pid(tpid
, tuid
, cred
.pid
)) {
2384 if (fprintf(pids_file
, "%d", (int) cred
.pid
) < 0)
2389 ptr
= strchr(ptr
, '\n');
2395 /* All good, write the value */
2397 if (write(sock
[0], &qpid
,sizeof(qpid
)) != sizeof(qpid
))
2398 fprintf(stderr
, "Warning: failed to ask child to exit\n");
2406 if (sock
[0] != -1) {
2411 if (fclose(pids_file
) != 0)
2417 int cg_write(const char *path
, const char *buf
, size_t size
, off_t offset
,
2418 struct fuse_file_info
*fi
)
2420 struct fuse_context
*fc
= fuse_get_context();
2421 char *localbuf
= NULL
;
2422 struct cgfs_files
*k
= NULL
;
2423 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2426 if (f
->type
!= LXC_TYPE_CGFILE
) {
2427 fprintf(stderr
, "Internal error: directory cache info used in cg_write\n");
2437 localbuf
= alloca(size
+1);
2438 localbuf
[size
] = '\0';
2439 memcpy(localbuf
, buf
, size
);
2441 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
2446 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_WRONLY
)) {
2451 if (strcmp(f
->file
, "tasks") == 0 ||
2452 strcmp(f
->file
, "/tasks") == 0 ||
2453 strcmp(f
->file
, "/cgroup.procs") == 0 ||
2454 strcmp(f
->file
, "cgroup.procs") == 0)
2455 // special case - we have to translate the pids
2456 r
= do_write_pids(fc
->pid
, fc
->uid
, f
->controller
, f
->cgroup
, f
->file
, localbuf
);
2458 r
= cgfs_set_value(f
->controller
, f
->cgroup
, f
->file
, localbuf
);
2468 int cg_chown(const char *path
, uid_t uid
, gid_t gid
)
2470 struct fuse_context
*fc
= fuse_get_context();
2471 char *cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
2472 struct cgfs_files
*k
= NULL
;
2479 if (strcmp(path
, "/cgroup") == 0)
2482 controller
= pick_controller_from_path(fc
, path
);
2485 cgroup
= find_cgroup_in_path(path
);
2487 /* this is just /cgroup/controller */
2490 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2500 if (is_child_cgroup(controller
, path1
, path2
)) {
2501 // get uid, gid, from '/tasks' file and make up a mode
2502 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
2503 k
= cgfs_get_key(controller
, cgroup
, "tasks");
2506 k
= cgfs_get_key(controller
, path1
, path2
);
2514 * This being a fuse request, the uid and gid must be valid
2515 * in the caller's namespace. So we can just check to make
2516 * sure that the caller is root in his uid, and privileged
2517 * over the file's current owner.
2519 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_REQD
)) {
2524 ret
= cgfs_chown_file(controller
, cgroup
, uid
, gid
);
2533 int cg_chmod(const char *path
, mode_t mode
)
2535 struct fuse_context
*fc
= fuse_get_context();
2536 char * cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
2537 struct cgfs_files
*k
= NULL
;
2544 if (strcmp(path
, "/cgroup") == 0)
2547 controller
= pick_controller_from_path(fc
, path
);
2550 cgroup
= find_cgroup_in_path(path
);
2552 /* this is just /cgroup/controller */
2555 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2565 if (is_child_cgroup(controller
, path1
, path2
)) {
2566 // get uid, gid, from '/tasks' file and make up a mode
2567 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
2568 k
= cgfs_get_key(controller
, cgroup
, "tasks");
2571 k
= cgfs_get_key(controller
, path1
, path2
);
2579 * This being a fuse request, the uid and gid must be valid
2580 * in the caller's namespace. So we can just check to make
2581 * sure that the caller is root in his uid, and privileged
2582 * over the file's current owner.
2584 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
2589 if (!cgfs_chmod_file(controller
, cgroup
, mode
)) {
2601 int cg_mkdir(const char *path
, mode_t mode
)
2603 struct fuse_context
*fc
= fuse_get_context();
2604 char *last
= NULL
, *path1
, *cgdir
= NULL
, *controller
, *next
= NULL
;
2612 controller
= pick_controller_from_path(fc
, path
);
2616 cgroup
= find_cgroup_in_path(path
);
2620 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2626 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2629 if (!caller_is_in_ancestor(initpid
, controller
, path1
, &next
)) {
2632 else if (last
&& strcmp(next
, last
) == 0)
2639 if (!fc_may_access(fc
, controller
, path1
, NULL
, O_RDWR
)) {
2643 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
2648 ret
= cgfs_create(controller
, cgroup
, fc
->uid
, fc
->gid
);
2656 int cg_rmdir(const char *path
)
2658 struct fuse_context
*fc
= fuse_get_context();
2659 char *last
= NULL
, *cgdir
= NULL
, *controller
, *next
= NULL
;
2666 controller
= pick_controller_from_path(fc
, path
);
2670 cgroup
= find_cgroup_in_path(path
);
2674 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2680 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2683 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, &next
)) {
2684 if (!last
|| strcmp(next
, last
) == 0)
2691 if (!fc_may_access(fc
, controller
, cgdir
, NULL
, O_WRONLY
)) {
2695 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
2700 if (!cgfs_remove(controller
, cgroup
)) {
2713 static bool startswith(const char *line
, const char *pref
)
2715 if (strncmp(line
, pref
, strlen(pref
)) == 0)
2720 static void get_mem_cached(char *memstat
, unsigned long *v
)
2726 if (startswith(memstat
, "total_cache")) {
2727 sscanf(memstat
+ 11, "%lu", v
);
2731 eol
= strchr(memstat
, '\n');
2738 static void get_blkio_io_value(char *str
, unsigned major
, unsigned minor
, char *iotype
, unsigned long *v
)
2744 snprintf(key
, 32, "%u:%u %s", major
, minor
, iotype
);
2746 size_t len
= strlen(key
);
2750 if (startswith(str
, key
)) {
2751 sscanf(str
+ len
, "%lu", v
);
2754 eol
= strchr(str
, '\n');
2761 static int read_file(const char *path
, char *buf
, size_t size
,
2762 struct file_info
*d
)
2764 size_t linelen
= 0, total_len
= 0, rv
= 0;
2766 char *cache
= d
->buf
;
2767 size_t cache_size
= d
->buflen
;
2768 FILE *f
= fopen(path
, "r");
2772 while (getline(&line
, &linelen
, f
) != -1) {
2773 size_t l
= snprintf(cache
, cache_size
, "%s", line
);
2775 perror("Error writing to cache");
2779 if (l
>= cache_size
) {
2780 fprintf(stderr
, "Internal error: truncated write to cache\n");
2789 d
->size
= total_len
;
2790 if (total_len
> size
) total_len
= size
;
2792 /* read from off 0 */
2793 memcpy(buf
, d
->buf
, total_len
);
2802 * FUSE ops for /proc
2805 static unsigned long get_memlimit(const char *cgroup
)
2807 char *memlimit_str
= NULL
;
2808 unsigned long memlimit
= -1;
2810 if (cgfs_get_value("memory", cgroup
, "memory.limit_in_bytes", &memlimit_str
))
2811 memlimit
= strtoul(memlimit_str
, NULL
, 10);
2818 static unsigned long get_min_memlimit(const char *cgroup
)
2820 char *copy
= strdupa(cgroup
);
2821 unsigned long memlimit
= 0, retlimit
;
2823 retlimit
= get_memlimit(copy
);
2825 while (strcmp(copy
, "/") != 0) {
2826 copy
= dirname(copy
);
2827 memlimit
= get_memlimit(copy
);
2828 if (memlimit
!= -1 && memlimit
< retlimit
)
2829 retlimit
= memlimit
;
2835 static int proc_meminfo_read(char *buf
, size_t size
, off_t offset
,
2836 struct fuse_file_info
*fi
)
2838 struct fuse_context
*fc
= fuse_get_context();
2839 struct file_info
*d
= (struct file_info
*)fi
->fh
;
2841 char *memusage_str
= NULL
, *memstat_str
= NULL
,
2842 *memswlimit_str
= NULL
, *memswusage_str
= NULL
,
2843 *memswlimit_default_str
= NULL
, *memswusage_default_str
= NULL
;
2844 unsigned long memlimit
= 0, memusage
= 0, memswlimit
= 0, memswusage
= 0,
2845 cached
= 0, hosttotal
= 0;
2847 size_t linelen
= 0, total_len
= 0, rv
= 0;
2848 char *cache
= d
->buf
;
2849 size_t cache_size
= d
->buflen
;
2853 if (offset
> d
->size
)
2857 int left
= d
->size
- offset
;
2858 total_len
= left
> size
? size
: left
;
2859 memcpy(buf
, cache
+ offset
, total_len
);
2863 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2866 cg
= get_pid_cgroup(initpid
, "memory");
2868 return read_file("/proc/meminfo", buf
, size
, d
);
2870 memlimit
= get_min_memlimit(cg
);
2871 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
2873 if (!cgfs_get_value("memory", cg
, "memory.stat", &memstat_str
))
2876 // Following values are allowed to fail, because swapaccount might be turned
2877 // off for current kernel
2878 if(cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
) &&
2879 cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
))
2881 /* If swapaccounting is turned on, then default value is assumed to be that of cgroup / */
2882 if (!cgfs_get_value("memory", "/", "memory.memsw.limit_in_bytes", &memswlimit_default_str
))
2884 if (!cgfs_get_value("memory", "/", "memory.memsw.usage_in_bytes", &memswusage_default_str
))
2887 memswlimit
= strtoul(memswlimit_str
, NULL
, 10);
2888 memswusage
= strtoul(memswusage_str
, NULL
, 10);
2890 if (!strcmp(memswlimit_str
, memswlimit_default_str
))
2892 if (!strcmp(memswusage_str
, memswusage_default_str
))
2895 memswlimit
= memswlimit
/ 1024;
2896 memswusage
= memswusage
/ 1024;
2899 memusage
= strtoul(memusage_str
, NULL
, 10);
2903 get_mem_cached(memstat_str
, &cached
);
2905 f
= fopen("/proc/meminfo", "r");
2909 while (getline(&line
, &linelen
, f
) != -1) {
2911 char *printme
, lbuf
[100];
2913 memset(lbuf
, 0, 100);
2914 if (startswith(line
, "MemTotal:")) {
2915 sscanf(line
+14, "%lu", &hosttotal
);
2916 if (hosttotal
< memlimit
)
2917 memlimit
= hosttotal
;
2918 snprintf(lbuf
, 100, "MemTotal: %8lu kB\n", memlimit
);
2920 } else if (startswith(line
, "MemFree:")) {
2921 snprintf(lbuf
, 100, "MemFree: %8lu kB\n", memlimit
- memusage
);
2923 } else if (startswith(line
, "MemAvailable:")) {
2924 snprintf(lbuf
, 100, "MemAvailable: %8lu kB\n", memlimit
- memusage
);
2926 } else if (startswith(line
, "SwapTotal:") && memswlimit
> 0) {
2927 snprintf(lbuf
, 100, "SwapTotal: %8lu kB\n", memswlimit
- memlimit
);
2929 } else if (startswith(line
, "SwapFree:") && memswlimit
> 0 && memswusage
> 0) {
2930 snprintf(lbuf
, 100, "SwapFree: %8lu kB\n",
2931 (memswlimit
- memlimit
) - (memswusage
- memusage
));
2933 } else if (startswith(line
, "Buffers:")) {
2934 snprintf(lbuf
, 100, "Buffers: %8lu kB\n", 0UL);
2936 } else if (startswith(line
, "Cached:")) {
2937 snprintf(lbuf
, 100, "Cached: %8lu kB\n", cached
);
2939 } else if (startswith(line
, "SwapCached:")) {
2940 snprintf(lbuf
, 100, "SwapCached: %8lu kB\n", 0UL);
2945 l
= snprintf(cache
, cache_size
, "%s", printme
);
2947 perror("Error writing to cache");
2952 if (l
>= cache_size
) {
2953 fprintf(stderr
, "Internal error: truncated write to cache\n");
2964 d
->size
= total_len
;
2965 if (total_len
> size
) total_len
= size
;
2966 memcpy(buf
, d
->buf
, total_len
);
2975 free(memswlimit_str
);
2976 free(memswusage_str
);
2978 free(memswlimit_default_str
);
2979 free(memswusage_default_str
);
2984 * Read the cpuset.cpus for cg
2985 * Return the answer in a newly allocated string which must be freed
2987 static char *get_cpuset(const char *cg
)
2991 if (!cgfs_get_value("cpuset", cg
, "cpuset.cpus", &answer
))
2996 bool cpu_in_cpuset(int cpu
, const char *cpuset
);
2998 static bool cpuline_in_cpuset(const char *line
, const char *cpuset
)
3002 if (sscanf(line
, "processor : %d", &cpu
) != 1)
3004 return cpu_in_cpuset(cpu
, cpuset
);
3008 * check whether this is a '^processor" line in /proc/cpuinfo
3010 static bool is_processor_line(const char *line
)
3014 if (sscanf(line
, "processor : %d", &cpu
) == 1)
3019 static int proc_cpuinfo_read(char *buf
, size_t size
, off_t offset
,
3020 struct fuse_file_info
*fi
)
3022 struct fuse_context
*fc
= fuse_get_context();
3023 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3025 char *cpuset
= NULL
;
3027 size_t linelen
= 0, total_len
= 0, rv
= 0;
3028 bool am_printing
= false;
3030 char *cache
= d
->buf
;
3031 size_t cache_size
= d
->buflen
;
3035 if (offset
> d
->size
)
3039 int left
= d
->size
- offset
;
3040 total_len
= left
> size
? size
: left
;
3041 memcpy(buf
, cache
+ offset
, total_len
);
3045 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3048 cg
= get_pid_cgroup(initpid
, "cpuset");
3050 return read_file("proc/cpuinfo", buf
, size
, d
);
3052 cpuset
= get_cpuset(cg
);
3056 f
= fopen("/proc/cpuinfo", "r");
3060 while (getline(&line
, &linelen
, f
) != -1) {
3062 if (is_processor_line(line
)) {
3063 am_printing
= cpuline_in_cpuset(line
, cpuset
);
3066 l
= snprintf(cache
, cache_size
, "processor : %d\n", curcpu
);
3068 perror("Error writing to cache");
3072 if (l
>= cache_size
) {
3073 fprintf(stderr
, "Internal error: truncated write to cache\n");
3084 l
= snprintf(cache
, cache_size
, "%s", line
);
3086 perror("Error writing to cache");
3090 if (l
>= cache_size
) {
3091 fprintf(stderr
, "Internal error: truncated write to cache\n");
3102 d
->size
= total_len
;
3103 if (total_len
> size
) total_len
= size
;
3105 /* read from off 0 */
3106 memcpy(buf
, d
->buf
, total_len
);
3117 static int proc_stat_read(char *buf
, size_t size
, off_t offset
,
3118 struct fuse_file_info
*fi
)
3120 struct fuse_context
*fc
= fuse_get_context();
3121 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3123 char *cpuset
= NULL
;
3125 size_t linelen
= 0, total_len
= 0, rv
= 0;
3126 int curcpu
= -1; /* cpu numbering starts at 0 */
3127 unsigned long user
= 0, nice
= 0, system
= 0, idle
= 0, iowait
= 0, irq
= 0, softirq
= 0, steal
= 0, guest
= 0;
3128 unsigned long user_sum
= 0, nice_sum
= 0, system_sum
= 0, idle_sum
= 0, iowait_sum
= 0,
3129 irq_sum
= 0, softirq_sum
= 0, steal_sum
= 0, guest_sum
= 0;
3130 #define CPUALL_MAX_SIZE BUF_RESERVE_SIZE
3131 char cpuall
[CPUALL_MAX_SIZE
];
3132 /* reserve for cpu all */
3133 char *cache
= d
->buf
+ CPUALL_MAX_SIZE
;
3134 size_t cache_size
= d
->buflen
- CPUALL_MAX_SIZE
;
3138 if (offset
> d
->size
)
3142 int left
= d
->size
- offset
;
3143 total_len
= left
> size
? size
: left
;
3144 memcpy(buf
, d
->buf
+ offset
, total_len
);
3148 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3151 cg
= get_pid_cgroup(initpid
, "cpuset");
3153 return read_file("/proc/stat", buf
, size
, d
);
3155 cpuset
= get_cpuset(cg
);
3159 f
= fopen("/proc/stat", "r");
3164 if (getline(&line
, &linelen
, f
) < 0) {
3165 fprintf(stderr
, "proc_stat_read read first line failed\n");
3169 while (getline(&line
, &linelen
, f
) != -1) {
3172 char cpu_char
[10]; /* That's a lot of cores */
3175 if (sscanf(line
, "cpu%9[^ ]", cpu_char
) != 1) {
3176 /* not a ^cpuN line containing a number N, just print it */
3177 l
= snprintf(cache
, cache_size
, "%s", line
);
3179 perror("Error writing to cache");
3183 if (l
>= cache_size
) {
3184 fprintf(stderr
, "Internal error: truncated write to cache\n");
3194 if (sscanf(cpu_char
, "%d", &cpu
) != 1)
3196 if (!cpu_in_cpuset(cpu
, cpuset
))
3200 c
= strchr(line
, ' ');
3203 l
= snprintf(cache
, cache_size
, "cpu%d%s", curcpu
, c
);
3205 perror("Error writing to cache");
3210 if (l
>= cache_size
) {
3211 fprintf(stderr
, "Internal error: truncated write to cache\n");
3220 if (sscanf(line
, "%*s %lu %lu %lu %lu %lu %lu %lu %lu %lu", &user
, &nice
, &system
, &idle
, &iowait
, &irq
,
3221 &softirq
, &steal
, &guest
) != 9)
3225 system_sum
+= system
;
3227 iowait_sum
+= iowait
;
3229 softirq_sum
+= softirq
;
3236 int cpuall_len
= snprintf(cpuall
, CPUALL_MAX_SIZE
, "%s %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
3237 "cpu ", user_sum
, nice_sum
, system_sum
, idle_sum
, iowait_sum
, irq_sum
, softirq_sum
, steal_sum
, guest_sum
);
3238 if (cpuall_len
> 0 && cpuall_len
< CPUALL_MAX_SIZE
){
3239 memcpy(cache
, cpuall
, cpuall_len
);
3240 cache
+= cpuall_len
;
3242 /* shouldn't happen */
3243 fprintf(stderr
, "proc_stat_read copy cpuall failed, cpuall_len=%d\n", cpuall_len
);
3247 memmove(cache
, d
->buf
+ CPUALL_MAX_SIZE
, total_len
);
3248 total_len
+= cpuall_len
;
3250 d
->size
= total_len
;
3251 if (total_len
> size
) total_len
= size
;
3253 memcpy(buf
, d
->buf
, total_len
);
3265 static long int getreaperage(pid_t pid
)
3272 qpid
= lookup_initpid_in_store(pid
);
3276 ret
= snprintf(fnam
, 100, "/proc/%d", qpid
);
3277 if (ret
< 0 || ret
>= 100)
3280 if (lstat(fnam
, &sb
) < 0)
3283 return time(NULL
) - sb
.st_ctime
;
3286 static unsigned long get_reaper_busy(pid_t task
)
3288 pid_t initpid
= lookup_initpid_in_store(task
);
3289 char *cgroup
= NULL
, *usage_str
= NULL
;
3290 unsigned long usage
= 0;
3295 cgroup
= get_pid_cgroup(initpid
, "cpuacct");
3298 if (!cgfs_get_value("cpuacct", cgroup
, "cpuacct.usage", &usage_str
))
3300 usage
= strtoul(usage_str
, NULL
, 10);
3301 usage
/= 1000000000;
3312 char *name
, *cwd
= get_current_dir_name();
3318 len
= strlen(cwd
) + strlen("/iwashere") + 1;
3320 snprintf(name
, len
, "%s/iwashere", cwd
);
3322 fd
= creat(name
, 0755);
3329 * We read /proc/uptime and reuse its second field.
3330 * For the first field, we use the mtime for the reaper for
3331 * the calling pid as returned by getreaperage
3333 static int proc_uptime_read(char *buf
, size_t size
, off_t offset
,
3334 struct fuse_file_info
*fi
)
3336 struct fuse_context
*fc
= fuse_get_context();
3337 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3338 long int reaperage
= getreaperage(fc
->pid
);
3339 unsigned long int busytime
= get_reaper_busy(fc
->pid
), idletime
;
3340 char *cache
= d
->buf
;
3341 size_t total_len
= 0;
3348 if (offset
> d
->size
)
3352 int left
= d
->size
- offset
;
3353 total_len
= left
> size
? size
: left
;
3354 memcpy(buf
, cache
+ offset
, total_len
);
3358 idletime
= reaperage
- busytime
;
3359 if (idletime
> reaperage
)
3360 idletime
= reaperage
;
3362 total_len
= snprintf(d
->buf
, d
->size
, "%ld.0 %lu.0\n", reaperage
, idletime
);
3364 perror("Error writing to cache");
3368 d
->size
= (int)total_len
;
3371 if (total_len
> size
) total_len
= size
;
3373 memcpy(buf
, d
->buf
, total_len
);
3377 static int proc_diskstats_read(char *buf
, size_t size
, off_t offset
,
3378 struct fuse_file_info
*fi
)
3381 struct fuse_context
*fc
= fuse_get_context();
3382 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3384 char *io_serviced_str
= NULL
, *io_merged_str
= NULL
, *io_service_bytes_str
= NULL
,
3385 *io_wait_time_str
= NULL
, *io_service_time_str
= NULL
;
3386 unsigned long read
= 0, write
= 0;
3387 unsigned long read_merged
= 0, write_merged
= 0;
3388 unsigned long read_sectors
= 0, write_sectors
= 0;
3389 unsigned long read_ticks
= 0, write_ticks
= 0;
3390 unsigned long ios_pgr
= 0, tot_ticks
= 0, rq_ticks
= 0;
3391 unsigned long rd_svctm
= 0, wr_svctm
= 0, rd_wait
= 0, wr_wait
= 0;
3392 char *cache
= d
->buf
;
3393 size_t cache_size
= d
->buflen
;
3395 size_t linelen
= 0, total_len
= 0, rv
= 0;
3396 unsigned int major
= 0, minor
= 0;
3401 if (offset
> d
->size
)
3405 int left
= d
->size
- offset
;
3406 total_len
= left
> size
? size
: left
;
3407 memcpy(buf
, cache
+ offset
, total_len
);
3411 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3414 cg
= get_pid_cgroup(initpid
, "blkio");
3416 return read_file("/proc/diskstats", buf
, size
, d
);
3418 if (!cgfs_get_value("blkio", cg
, "blkio.io_serviced", &io_serviced_str
))
3420 if (!cgfs_get_value("blkio", cg
, "blkio.io_merged", &io_merged_str
))
3422 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_bytes", &io_service_bytes_str
))
3424 if (!cgfs_get_value("blkio", cg
, "blkio.io_wait_time", &io_wait_time_str
))
3426 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_time", &io_service_time_str
))
3430 f
= fopen("/proc/diskstats", "r");
3434 while (getline(&line
, &linelen
, f
) != -1) {
3436 char *printme
, lbuf
[256];
3438 i
= sscanf(line
, "%u %u %71s", &major
, &minor
, dev_name
);
3440 get_blkio_io_value(io_serviced_str
, major
, minor
, "Read", &read
);
3441 get_blkio_io_value(io_serviced_str
, major
, minor
, "Write", &write
);
3442 get_blkio_io_value(io_merged_str
, major
, minor
, "Read", &read_merged
);
3443 get_blkio_io_value(io_merged_str
, major
, minor
, "Write", &write_merged
);
3444 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Read", &read_sectors
);
3445 read_sectors
= read_sectors
/512;
3446 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Write", &write_sectors
);
3447 write_sectors
= write_sectors
/512;
3449 get_blkio_io_value(io_service_time_str
, major
, minor
, "Read", &rd_svctm
);
3450 rd_svctm
= rd_svctm
/1000000;
3451 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Read", &rd_wait
);
3452 rd_wait
= rd_wait
/1000000;
3453 read_ticks
= rd_svctm
+ rd_wait
;
3455 get_blkio_io_value(io_service_time_str
, major
, minor
, "Write", &wr_svctm
);
3456 wr_svctm
= wr_svctm
/1000000;
3457 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Write", &wr_wait
);
3458 wr_wait
= wr_wait
/1000000;
3459 write_ticks
= wr_svctm
+ wr_wait
;
3461 get_blkio_io_value(io_service_time_str
, major
, minor
, "Total", &tot_ticks
);
3462 tot_ticks
= tot_ticks
/1000000;
3467 memset(lbuf
, 0, 256);
3468 if (read
|| write
|| read_merged
|| write_merged
|| read_sectors
|| write_sectors
|| read_ticks
|| write_ticks
) {
3469 snprintf(lbuf
, 256, "%u %u %s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
3470 major
, minor
, dev_name
, read
, read_merged
, read_sectors
, read_ticks
,
3471 write
, write_merged
, write_sectors
, write_ticks
, ios_pgr
, tot_ticks
, rq_ticks
);
3476 l
= snprintf(cache
, cache_size
, "%s", printme
);
3478 perror("Error writing to fuse buf");
3482 if (l
>= cache_size
) {
3483 fprintf(stderr
, "Internal error: truncated write to cache\n");
3493 d
->size
= total_len
;
3494 if (total_len
> size
) total_len
= size
;
3495 memcpy(buf
, d
->buf
, total_len
);
3503 free(io_serviced_str
);
3504 free(io_merged_str
);
3505 free(io_service_bytes_str
);
3506 free(io_wait_time_str
);
3507 free(io_service_time_str
);
3511 static off_t
get_procfile_size(const char *which
)
3513 FILE *f
= fopen(which
, "r");
3516 ssize_t sz
, answer
= 0;
3520 while ((sz
= getline(&line
, &len
, f
)) != -1)
3528 int proc_getattr(const char *path
, struct stat
*sb
)
3530 struct timespec now
;
3532 memset(sb
, 0, sizeof(struct stat
));
3533 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
3535 sb
->st_uid
= sb
->st_gid
= 0;
3536 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
3537 if (strcmp(path
, "/proc") == 0) {
3538 sb
->st_mode
= S_IFDIR
| 00555;
3542 if (strcmp(path
, "/proc/meminfo") == 0 ||
3543 strcmp(path
, "/proc/cpuinfo") == 0 ||
3544 strcmp(path
, "/proc/uptime") == 0 ||
3545 strcmp(path
, "/proc/stat") == 0 ||
3546 strcmp(path
, "/proc/diskstats") == 0) {
3548 sb
->st_mode
= S_IFREG
| 00444;
3556 int proc_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
3557 struct fuse_file_info
*fi
)
3559 if (filler(buf
, "cpuinfo", NULL
, 0) != 0 ||
3560 filler(buf
, "meminfo", NULL
, 0) != 0 ||
3561 filler(buf
, "stat", NULL
, 0) != 0 ||
3562 filler(buf
, "uptime", NULL
, 0) != 0 ||
3563 filler(buf
, "diskstats", NULL
, 0) != 0)
3568 int proc_open(const char *path
, struct fuse_file_info
*fi
)
3571 struct file_info
*info
;
3573 if (strcmp(path
, "/proc/meminfo") == 0)
3574 type
= LXC_TYPE_PROC_MEMINFO
;
3575 else if (strcmp(path
, "/proc/cpuinfo") == 0)
3576 type
= LXC_TYPE_PROC_CPUINFO
;
3577 else if (strcmp(path
, "/proc/uptime") == 0)
3578 type
= LXC_TYPE_PROC_UPTIME
;
3579 else if (strcmp(path
, "/proc/stat") == 0)
3580 type
= LXC_TYPE_PROC_STAT
;
3581 else if (strcmp(path
, "/proc/diskstats") == 0)
3582 type
= LXC_TYPE_PROC_DISKSTATS
;
3586 info
= malloc(sizeof(*info
));
3590 memset(info
, 0, sizeof(*info
));
3593 info
->buflen
= get_procfile_size(path
) + BUF_RESERVE_SIZE
;
3595 info
->buf
= malloc(info
->buflen
);
3596 } while (!info
->buf
);
3597 memset(info
->buf
, 0, info
->buflen
);
3598 /* set actual size to buffer size */
3599 info
->size
= info
->buflen
;
3601 fi
->fh
= (unsigned long)info
;
3605 int proc_release(const char *path
, struct fuse_file_info
*fi
)
3607 struct file_info
*f
= (struct file_info
*)fi
->fh
;
3609 do_release_file_info(f
);
3613 int proc_read(const char *path
, char *buf
, size_t size
, off_t offset
,
3614 struct fuse_file_info
*fi
)
3616 struct file_info
*f
= (struct file_info
*) fi
->fh
;
3619 case LXC_TYPE_PROC_MEMINFO
:
3620 return proc_meminfo_read(buf
, size
, offset
, fi
);
3621 case LXC_TYPE_PROC_CPUINFO
:
3622 return proc_cpuinfo_read(buf
, size
, offset
, fi
);
3623 case LXC_TYPE_PROC_UPTIME
:
3624 return proc_uptime_read(buf
, size
, offset
, fi
);
3625 case LXC_TYPE_PROC_STAT
:
3626 return proc_stat_read(buf
, size
, offset
, fi
);
3627 case LXC_TYPE_PROC_DISKSTATS
:
3628 return proc_diskstats_read(buf
, size
, offset
, fi
);
3634 static void __attribute__((constructor
)) collect_subsystems(void)
3640 if ((f
= fopen("/proc/self/cgroup", "r")) == NULL
) {
3641 fprintf(stderr
, "Error opening /proc/self/cgroup: %s\n", strerror(errno
));
3644 while (getline(&line
, &len
, f
) != -1) {
3647 p
= strchr(line
, ':');
3652 p2
= strrchr(p
, ':');
3657 if (!store_hierarchy(line
, p
))
3668 static void __attribute__((destructor
)) free_subsystems(void)
3672 for (i
= 0; i
< num_hierarchies
; i
++)
3674 free(hierarchies
[i
]);