3 * Copyright © 2014 Canonical, Inc
4 * Author: Serge Hallyn <serge.hallyn@ubuntu.com>
6 * See COPYING file for details.
10 * NOTES - make sure to run this as -s to avoid threading.
11 * TODO - can we enforce that here from the code?
13 #define FUSE_USE_VERSION 26
27 #include <linux/sched.h>
28 #include <sys/socket.h>
29 #include <sys/mount.h>
32 #include <nih/alloc.h>
33 #include <nih/string.h>
35 #include "cgmanager.h"
39 * a null-terminated, nih-allocated list of the mounted subsystems. We
40 * detect this at startup.
44 #define LXCFS_DATA ((struct lxcfs_state *) fuse_get_context()->private_data)
47 * TODO - return value should denote whether child exited with failure
48 * so callers can return errors. Esp read/write of tasks and cgroup.procs
50 static int wait_for_pid(pid_t pid
)
55 ret
= waitpid(pid
, &status
, 0);
63 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
69 * Given a open file * to /proc/pid/{u,g}id_map, and an id
70 * valid in the caller's namespace, return the id mapped into
72 * Returns the mapped id, or -1 on error.
75 convert_id_to_ns(FILE *idfile
, unsigned int in_id
)
77 unsigned int nsuid
, // base id for a range in the idfile's namespace
78 hostuid
, // base id for a range in the caller's namespace
79 count
; // number of ids in this range
83 fseek(idfile
, 0L, SEEK_SET
);
84 while (fgets(line
, 400, idfile
)) {
85 ret
= sscanf(line
, "%u %u %u\n", &nsuid
, &hostuid
, &count
);
88 if (hostuid
+ count
< hostuid
|| nsuid
+ count
< nsuid
) {
90 * uids wrapped around - unexpected as this is a procfile,
93 fprintf(stderr
, "pid wrapparound at entry %u %u %u in %s\n",
94 nsuid
, hostuid
, count
, line
);
97 if (hostuid
<= in_id
&& hostuid
+count
> in_id
) {
99 * now since hostuid <= in_id < hostuid+count, and
100 * hostuid+count and nsuid+count do not wrap around,
101 * we know that nsuid+(in_id-hostuid) which must be
102 * less that nsuid+(count) must not wrap around
104 return (in_id
- hostuid
) + nsuid
;
113 * for is_privileged_over,
114 * specify whether we require the calling uid to be root in his
117 #define NS_ROOT_REQD true
118 #define NS_ROOT_OPT false
120 static bool is_privileged_over(pid_t pid
, uid_t uid
, uid_t victim
, bool req_ns_root
)
122 nih_local
char *fpath
= NULL
;
126 if (victim
== -1 || uid
== -1)
130 * If the request is one not requiring root in the namespace,
131 * then having the same uid suffices. (i.e. uid 1000 has write
132 * access to files owned by uid 1000
134 if (!req_ns_root
&& uid
== victim
)
137 fpath
= NIH_MUST( nih_sprintf(NULL
, "/proc/%d/uid_map", pid
) );
138 FILE *f
= fopen(fpath
, "r");
142 /* if caller's not root in his namespace, reject */
143 nsuid
= convert_id_to_ns(f
, uid
);
148 * If victim is not mapped into caller's ns, reject.
149 * XXX I'm not sure this check is needed given that fuse
150 * will be sending requests where the vfs has converted
152 nsuid
= convert_id_to_ns(f
, victim
);
163 static bool perms_include(int fmode
, mode_t req_mode
)
167 switch (req_mode
& O_ACCMODE
) {
175 r
= S_IROTH
| S_IWOTH
;
180 return ((fmode
& r
) == r
);
183 static char *get_next_cgroup_dir(const char *taskcg
, const char *querycg
)
187 if (strlen(taskcg
) <= strlen(querycg
)) {
188 fprintf(stderr
, "%s: I was fed bad input\n", __func__
);
192 if (strcmp(querycg
, "/") == 0)
193 start
= NIH_MUST( nih_strdup(NULL
, taskcg
+ 1) );
195 start
= NIH_MUST( nih_strdup(NULL
, taskcg
+ strlen(querycg
) + 1) );
196 end
= strchr(start
, '/');
203 * check whether a fuse context may access a cgroup dir or file
205 * If file is not null, it is a cgroup file to check under cg.
206 * If file is null, then we are checking perms on cg itself.
208 * For files we can check the mode of the list_keys result.
209 * For cgroups, we must make assumptions based on the files under the
210 * cgroup, because cgmanager doesn't tell us ownership/perms of cgroups
213 static bool fc_may_access(struct fuse_context
*fc
, const char *contrl
, const char *cg
, const char *file
, mode_t mode
)
215 nih_local
struct cgm_keys
**list
= NULL
;
224 if (!cgm_list_keys(contrl
, cg
, &list
))
226 for (i
= 0; list
[i
]; i
++) {
227 if (strcmp(list
[i
]->name
, file
) == 0) {
228 struct cgm_keys
*k
= list
[i
];
229 if (is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
230 if (perms_include(k
->mode
>> 6, mode
))
233 if (fc
->gid
== k
->gid
) {
234 if (perms_include(k
->mode
>> 3, mode
))
237 return perms_include(k
->mode
, mode
);
244 static void stripnewline(char *x
)
246 size_t l
= strlen(x
);
247 if (l
&& x
[l
-1] == '\n')
252 * If caller is in /a/b/c/d, he may only act on things under cg=/a/b/c/d.
253 * If caller is in /a, he may act on /a/b, but not on /b.
254 * if the answer is false and nextcg is not NULL, then *nextcg will point
255 * to a nih_alloc'd string containing the next cgroup directory under cg
257 static bool caller_is_in_ancestor(pid_t pid
, const char *contrl
, const char *cg
, char **nextcg
)
259 nih_local
char *fnam
= NULL
;
265 fnam
= NIH_MUST( nih_sprintf(NULL
, "/proc/%d/cgroup", pid
) );
266 if (!(f
= fopen(fnam
, "r")))
269 while (getline(&line
, &len
, f
) != -1) {
270 char *c1
, *c2
, *linecmp
;
273 c1
= strchr(line
, ':');
277 c2
= strchr(c1
, ':');
281 if (strcmp(c1
, contrl
) != 0)
286 * callers pass in '/' for root cgroup, otherwise they pass
287 * in a cgroup without leading '/'
289 linecmp
= *cg
== '/' ? c2
: c2
+1;
290 if (strncmp(linecmp
, cg
, strlen(linecmp
)) != 0) {
292 *nextcg
= get_next_cgroup_dir(linecmp
, cg
);
306 * given /cgroup/freezer/a/b, return "freezer". this will be nih-allocated
307 * and needs to be nih_freed.
309 static char *pick_controller_from_path(struct fuse_context
*fc
, const char *path
)
314 if (strlen(path
) < 9)
317 ret
= nih_strdup(NULL
, p1
);
320 slash
= strstr(ret
, "/");
324 /* verify that it is a subsystem */
325 char **list
= LXCFS_DATA
? LXCFS_DATA
->subsystems
: NULL
;
331 for (i
= 0; list
[i
]; i
++) {
332 if (strcmp(list
[i
], ret
) == 0)
340 * Find the start of cgroup in /cgroup/controller/the/cgroup/path
341 * Note that the returned value may include files (keynames) etc
343 static const char *find_cgroup_in_path(const char *path
)
347 if (strlen(path
) < 9)
349 p1
= strstr(path
+8, "/");
355 static bool is_child_cgroup(const char *contr
, const char *dir
, const char *f
)
357 nih_local
char **list
= NULL
;
365 if (!cgm_list_children(contr
, dir
, &list
))
367 for (i
= 0; list
[i
]; i
++) {
368 if (strcmp(list
[i
], f
) == 0)
375 static struct cgm_keys
*get_cgroup_key(const char *contr
, const char *dir
, const char *f
)
377 nih_local
struct cgm_keys
**list
= NULL
;
385 if (!cgm_list_keys(contr
, dir
, &list
))
387 for (i
= 0; list
[i
]; i
++) {
388 if (strcmp(list
[i
]->name
, f
) == 0) {
389 k
= NIH_MUST( nih_alloc(NULL
, (sizeof(*k
))) );
390 k
->name
= NIH_MUST( nih_strdup(k
, list
[i
]->name
) );
391 k
->uid
= list
[i
]->uid
;
392 k
->gid
= list
[i
]->gid
;
393 k
->mode
= list
[i
]->mode
;
401 static void get_cgdir_and_path(const char *cg
, char **dir
, char **file
)
405 *dir
= NIH_MUST( nih_strdup(NULL
, cg
) );
406 *file
= strrchr(cg
, '/');
411 p
= strrchr(*dir
, '/');
415 static size_t get_file_size(const char *contrl
, const char *cg
, const char *f
)
417 nih_local
char *data
= NULL
;
419 if (!cgm_get_value(contrl
, cg
, f
, &data
))
426 * FUSE ops for /cgroup
429 static int cg_getattr(const char *path
, struct stat
*sb
)
432 struct fuse_context
*fc
= fuse_get_context();
433 nih_local
char * cgdir
= NULL
;
434 char *fpath
= NULL
, *path1
, *path2
;
435 nih_local
struct cgm_keys
*k
= NULL
;
437 nih_local
char *controller
= NULL
;
443 memset(sb
, 0, sizeof(struct stat
));
445 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
448 sb
->st_uid
= sb
->st_gid
= 0;
449 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
452 if (strcmp(path
, "/cgroup") == 0) {
453 sb
->st_mode
= S_IFDIR
| 00755;
458 controller
= pick_controller_from_path(fc
, path
);
461 cgroup
= find_cgroup_in_path(path
);
463 /* this is just /cgroup/controller, return it as a dir */
464 sb
->st_mode
= S_IFDIR
| 00755;
469 get_cgdir_and_path(cgroup
, &cgdir
, &fpath
);
479 /* check that cgcopy is either a child cgroup of cgdir, or listed in its keys.
480 * Then check that caller's cgroup is under path if fpath is a child
481 * cgroup, or cgdir if fpath is a file */
483 if (is_child_cgroup(controller
, path1
, path2
)) {
484 if (!caller_is_in_ancestor(fc
->pid
, controller
, cgroup
, NULL
)) {
485 /* this is just /cgroup/controller, return it as a dir */
486 sb
->st_mode
= S_IFDIR
| 00555;
490 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
))
493 // get uid, gid, from '/tasks' file and make up a mode
494 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
495 sb
->st_mode
= S_IFDIR
| 00755;
496 k
= get_cgroup_key(controller
, cgroup
, "tasks");
498 sb
->st_uid
= sb
->st_gid
= 0;
507 if ((k
= get_cgroup_key(controller
, path1
, path2
)) != NULL
) {
508 if (!caller_is_in_ancestor(fc
->pid
, controller
, path1
, NULL
))
510 if (!fc_may_access(fc
, controller
, path1
, path2
, O_RDONLY
))
513 sb
->st_mode
= S_IFREG
| k
->mode
;
517 sb
->st_size
= get_file_size(controller
, path1
, path2
);
525 * TODO - cache these results in a table for use in opendir, free
528 static int cg_opendir(const char *path
, struct fuse_file_info
*fi
)
530 struct fuse_context
*fc
= fuse_get_context();
531 nih_local
struct cgm_keys
**list
= NULL
;
533 nih_local
char *controller
= NULL
;
534 nih_local
char *nextcg
= NULL
;
539 if (strcmp(path
, "/cgroup") == 0)
542 // return list of keys for the controller, and list of child cgroups
543 controller
= pick_controller_from_path(fc
, path
);
547 cgroup
= find_cgroup_in_path(path
);
549 /* this is just /cgroup/controller, return its contents */
553 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
))
558 static int cg_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
559 struct fuse_file_info
*fi
)
561 struct fuse_context
*fc
= fuse_get_context();
566 if (strcmp(path
, "/cgroup") == 0) {
567 // get list of controllers
568 char **list
= LXCFS_DATA
? LXCFS_DATA
->subsystems
: NULL
;
574 for (i
= 0; list
[i
]; i
++) {
575 if (filler(buf
, list
[i
], NULL
, 0) != 0) {
582 // return list of keys for the controller, and list of child cgroups
583 nih_local
struct cgm_keys
**list
= NULL
;
585 nih_local
char *controller
= NULL
;
587 nih_local
char *nextcg
= NULL
;
589 controller
= pick_controller_from_path(fc
, path
);
593 cgroup
= find_cgroup_in_path(path
);
595 /* this is just /cgroup/controller, return its contents */
599 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
))
602 if (!cgm_list_keys(controller
, cgroup
, &list
))
603 // not a valid cgroup
606 if (!caller_is_in_ancestor(fc
->pid
, controller
, cgroup
, &nextcg
)) {
609 ret
= filler(buf
, nextcg
, NULL
, 0);
616 for (i
= 0; list
[i
]; i
++) {
617 if (filler(buf
, list
[i
]->name
, NULL
, 0) != 0) {
622 // now get the list of child cgroups
623 nih_local
char **clist
;
625 if (!cgm_list_children(controller
, cgroup
, &clist
))
627 for (i
= 0; clist
[i
]; i
++) {
628 if (filler(buf
, clist
[i
], NULL
, 0) != 0) {
635 static int cg_releasedir(const char *path
, struct fuse_file_info
*fi
)
641 * TODO - cache info here for read/write, release in cg_release.
643 static int cg_open(const char *path
, struct fuse_file_info
*fi
)
645 nih_local
char *controller
= NULL
;
647 char *fpath
= NULL
, *path1
, *path2
;
648 nih_local
char * cgdir
= NULL
;
649 nih_local
struct cgm_keys
*k
= NULL
;
650 struct fuse_context
*fc
= fuse_get_context();
655 controller
= pick_controller_from_path(fc
, path
);
658 cgroup
= find_cgroup_in_path(path
);
662 get_cgdir_and_path(cgroup
, &cgdir
, &fpath
);
671 if ((k
= get_cgroup_key(controller
, path1
, path2
)) != NULL
) {
672 if (!fc_may_access(fc
, controller
, path1
, path2
, fi
->flags
))
673 // should never get here
682 static int msgrecv(int sockfd
, void *buf
, size_t len
)
688 FD_SET(sockfd
, &rfds
);
692 if (select(sockfd
+1, &rfds
, NULL
, NULL
, &tv
) < 0)
694 return recv(sockfd
, buf
, len
, MSG_DONTWAIT
);
697 #define SEND_CREDS_OK 0
698 #define SEND_CREDS_NOTSK 1
699 #define SEND_CREDS_FAIL 2
700 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
)
702 struct msghdr msg
= { 0 };
704 struct cmsghdr
*cmsg
;
705 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
710 if (msgrecv(sock
, buf
, 1) != 1) {
711 fprintf(stderr
, "%s: Error getting reply from server over socketpair\n",
713 return SEND_CREDS_FAIL
;
717 msg
.msg_control
= cmsgbuf
;
718 msg
.msg_controllen
= sizeof(cmsgbuf
);
720 cmsg
= CMSG_FIRSTHDR(&msg
);
721 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct ucred
));
722 cmsg
->cmsg_level
= SOL_SOCKET
;
723 cmsg
->cmsg_type
= SCM_CREDENTIALS
;
724 memcpy(CMSG_DATA(cmsg
), cred
, sizeof(*cred
));
731 iov
.iov_len
= sizeof(buf
);
735 if (sendmsg(sock
, &msg
, 0) < 0) {
736 fprintf(stderr
, "%s: failed at sendmsg: %s\n", __func__
,
739 return SEND_CREDS_NOTSK
;
740 return SEND_CREDS_FAIL
;
743 return SEND_CREDS_OK
;
746 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
)
748 struct msghdr msg
= { 0 };
750 struct cmsghdr
*cmsg
;
751 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
762 if (setsockopt(sock
, SOL_SOCKET
, SO_PASSCRED
, &optval
, sizeof(optval
)) == -1) {
763 fprintf(stderr
, "Failed to set passcred: %s\n", strerror(errno
));
767 if (write(sock
, buf
, 1) != 1) {
768 fprintf(stderr
, "Failed to start write on scm fd: %s\n", strerror(errno
));
774 msg
.msg_control
= cmsgbuf
;
775 msg
.msg_controllen
= sizeof(cmsgbuf
);
778 iov
.iov_len
= sizeof(buf
);
782 // retry logic is not ideal, especially as we are not
783 // threaded. Sleep at most 1 second waiting for the client
784 // to send us the scm_cred
785 ret
= recvmsg(sock
, &msg
, 0);
787 fprintf(stderr
, "Failed to receive scm_cred: %s\n",
792 cmsg
= CMSG_FIRSTHDR(&msg
);
794 if (cmsg
&& cmsg
->cmsg_len
== CMSG_LEN(sizeof(struct ucred
)) &&
795 cmsg
->cmsg_level
== SOL_SOCKET
&&
796 cmsg
->cmsg_type
== SCM_CREDENTIALS
) {
797 memcpy(cred
, CMSG_DATA(cmsg
), sizeof(*cred
));
806 * pid_to_ns - reads pids from a ucred over a socket, then writes the
807 * int value back over the socket. This shifts the pid from the
808 * sender's pidns into tpid's pidns.
810 static void pid_to_ns(int sock
, pid_t tpid
)
815 while (recv_creds(sock
, &cred
, &v
)) {
818 if (write(sock
, &cred
.pid
, sizeof(pid_t
)) != sizeof(pid_t
))
825 * pid_to_ns_wrapper: when you setns into a pidns, you yourself remain
826 * in your old pidns. Only children which you fork will be in the target
827 * pidns. So the pid_to_ns_wrapper does the setns, then forks a child to
828 * actually convert pids
830 static void pid_to_ns_wrapper(int sock
, pid_t tpid
)
836 sprintf(fnam
, "/proc/%d/ns/pid", tpid
);
837 newnsfd
= open(fnam
, O_RDONLY
);
840 if (setns(newnsfd
, 0) < 0)
849 pid_to_ns(sock
, tpid
);
850 if (!wait_for_pid(cpid
))
856 * To read cgroup files with a particular pid, we will setns into the child
857 * pidns, open a pipe, fork a child - which will be the first to really be in
858 * the child ns - which does the cgm_get_value and writes the data to the pipe.
860 static bool do_read_pids(pid_t tpid
, const char *contrl
, const char *cg
, const char *file
, char **d
)
862 int sock
[2] = {-1, -1};
863 nih_local
char *tmpdata
= NULL
;
865 pid_t qpid
, cpid
= -1;
872 if (!cgm_get_value(contrl
, cg
, file
, &tmpdata
))
876 * Now we read the pids from returned data one by one, pass
877 * them into a child in the target namespace, read back the
878 * translated pids, and put them into our to-return data
881 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
882 perror("socketpair");
891 pid_to_ns_wrapper(sock
[1], tpid
);
896 while (sscanf(ptr
, "%d\n", &qpid
) == 1) {
898 ret
= send_creds(sock
[0], &cred
, v
, true);
900 if (ret
== SEND_CREDS_NOTSK
)
902 if (ret
== SEND_CREDS_FAIL
)
905 // read converted results
910 ret
= select(sock
[0]+1, &s
, NULL
, NULL
, &tv
);
915 if (read(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
920 NIH_MUST( nih_strcat_sprintf(d
, NULL
, "%d\n", qpid
) );
922 ptr
= strchr(ptr
, '\n');
930 if (send_creds(sock
[0], &cred
, v
, true) != SEND_CREDS_OK
) {
931 // failed to ask child to exit
948 static int cg_read(const char *path
, char *buf
, size_t size
, off_t offset
,
949 struct fuse_file_info
*fi
)
951 nih_local
char *controller
= NULL
;
953 char *fpath
= NULL
, *path1
, *path2
;
954 struct fuse_context
*fc
= fuse_get_context();
955 nih_local
char * cgdir
= NULL
;
956 nih_local
struct cgm_keys
*k
= NULL
;
964 controller
= pick_controller_from_path(fc
, path
);
967 cgroup
= find_cgroup_in_path(path
);
971 get_cgdir_and_path(cgroup
, &cgdir
, &fpath
);
980 if ((k
= get_cgroup_key(controller
, path1
, path2
)) != NULL
) {
981 nih_local
char *data
= NULL
;
985 if (!fc_may_access(fc
, controller
, path1
, path2
, O_RDONLY
))
986 // should never get here
989 if (strcmp(path2
, "tasks") == 0 ||
990 strcmp(path2
, "/tasks") == 0 ||
991 strcmp(path2
, "/cgroup.procs") == 0 ||
992 strcmp(path2
, "cgroup.procs") == 0)
993 // special case - we have to translate the pids
994 r
= do_read_pids(fc
->pid
, controller
, path1
, path2
, &data
);
996 r
= cgm_get_value(controller
, path1
, path2
, &data
);
1006 memcpy(buf
, data
, s
);
1014 static void pid_from_ns(int sock
, pid_t tpid
)
1022 while (read(sock
, &vpid
, sizeof(pid_t
)) == sizeof(pid_t
)) {
1023 if (vpid
== -1) // done
1027 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
) {
1029 cred
.pid
= getpid();
1030 if (send_creds(sock
, &cred
, v
, false) != SEND_CREDS_OK
)
1037 static void pid_from_ns_wrapper(int sock
, pid_t tpid
)
1043 sprintf(fnam
, "/proc/%d/ns/pid", tpid
);
1044 newnsfd
= open(fnam
, O_RDONLY
);
1047 if (setns(newnsfd
, 0) < 0)
1056 pid_from_ns(sock
, tpid
);
1057 if (!wait_for_pid(cpid
))
1062 static bool do_write_pids(pid_t tpid
, const char *contrl
, const char *cg
, const char *file
, const char *buf
)
1064 int sock
[2] = {-1, -1};
1065 pid_t qpid
, cpid
= -1;
1066 bool answer
= false, fail
= false;
1069 * write the pids to a socket, have helper in writer's pidns
1070 * call movepid for us
1072 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
1073 perror("socketpair");
1082 pid_from_ns_wrapper(sock
[1], tpid
);
1084 const char *ptr
= buf
;
1085 while (sscanf(ptr
, "%d", &qpid
) == 1) {
1089 if (write(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
1090 kill(cpid
, SIGTERM
);
1095 if (recv_creds(sock
[0], &cred
, &v
)) {
1097 if (!cgm_move_pid(contrl
, cg
, cred
.pid
))
1102 ptr
= strchr(ptr
, '\n');
1108 /* All good, write the value */
1110 if (write(sock
[0], &qpid
,sizeof(qpid
)) != sizeof(qpid
))
1111 fprintf(stderr
, "Warning: failed to ask child to exit\n");
1119 if (sock
[0] != -1) {
1126 int cg_write(const char *path
, const char *buf
, size_t size
, off_t offset
,
1127 struct fuse_file_info
*fi
)
1129 nih_local
char *controller
= NULL
;
1131 char *fpath
= NULL
, *path1
, *path2
;
1132 struct fuse_context
*fc
= fuse_get_context();
1133 nih_local
char * cgdir
= NULL
;
1134 nih_local
struct cgm_keys
*k
= NULL
;
1135 nih_local
char *localbuf
= NULL
;
1143 localbuf
= NIH_MUST( nih_alloc(NULL
, size
+1) );
1144 localbuf
[size
] = '\0';
1145 memcpy(localbuf
, buf
, size
);
1146 controller
= pick_controller_from_path(fc
, path
);
1149 cgroup
= find_cgroup_in_path(path
);
1153 get_cgdir_and_path(cgroup
, &cgdir
, &fpath
);
1162 if ((k
= get_cgroup_key(controller
, path1
, path2
)) != NULL
) {
1165 if (!fc_may_access(fc
, controller
, path1
, path2
, O_WRONLY
))
1168 if (strcmp(path2
, "tasks") == 0 ||
1169 strcmp(path2
, "/tasks") == 0 ||
1170 strcmp(path2
, "/cgroup.procs") == 0 ||
1171 strcmp(path2
, "cgroup.procs") == 0)
1172 // special case - we have to translate the pids
1173 r
= do_write_pids(fc
->pid
, controller
, path1
, path2
, localbuf
);
1175 r
= cgm_set_value(controller
, path1
, path2
, localbuf
);
1186 int cg_chown(const char *path
, uid_t uid
, gid_t gid
)
1188 struct fuse_context
*fc
= fuse_get_context();
1189 nih_local
char * cgdir
= NULL
;
1190 char *fpath
= NULL
, *path1
, *path2
;
1191 nih_local
struct cgm_keys
*k
= NULL
;
1193 nih_local
char *controller
= NULL
;
1199 if (strcmp(path
, "/cgroup") == 0)
1202 controller
= pick_controller_from_path(fc
, path
);
1205 cgroup
= find_cgroup_in_path(path
);
1207 /* this is just /cgroup/controller */
1210 get_cgdir_and_path(cgroup
, &cgdir
, &fpath
);
1220 if (is_child_cgroup(controller
, path1
, path2
)) {
1221 // get uid, gid, from '/tasks' file and make up a mode
1222 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
1223 k
= get_cgroup_key(controller
, cgroup
, "tasks");
1226 k
= get_cgroup_key(controller
, path1
, path2
);
1232 * This being a fuse request, the uid and gid must be valid
1233 * in the caller's namespace. So we can just check to make
1234 * sure that the caller is root in his uid, and privileged
1235 * over the file's current owner.
1237 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_REQD
))
1240 if (!cgm_chown_file(controller
, cgroup
, uid
, gid
))
1245 int cg_chmod(const char *path
, mode_t mode
)
1247 struct fuse_context
*fc
= fuse_get_context();
1248 nih_local
char * cgdir
= NULL
;
1249 char *fpath
= NULL
, *path1
, *path2
;
1250 nih_local
struct cgm_keys
*k
= NULL
;
1252 nih_local
char *controller
= NULL
;
1257 if (strcmp(path
, "/cgroup") == 0)
1260 controller
= pick_controller_from_path(fc
, path
);
1263 cgroup
= find_cgroup_in_path(path
);
1265 /* this is just /cgroup/controller */
1268 get_cgdir_and_path(cgroup
, &cgdir
, &fpath
);
1278 if (is_child_cgroup(controller
, path1
, path2
)) {
1279 // get uid, gid, from '/tasks' file and make up a mode
1280 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
1281 k
= get_cgroup_key(controller
, cgroup
, "tasks");
1284 k
= get_cgroup_key(controller
, path1
, path2
);
1290 * This being a fuse request, the uid and gid must be valid
1291 * in the caller's namespace. So we can just check to make
1292 * sure that the caller is root in his uid, and privileged
1293 * over the file's current owner.
1295 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
))
1298 if (!cgm_chmod_file(controller
, cgroup
, mode
))
1303 int cg_mkdir(const char *path
, mode_t mode
)
1305 struct fuse_context
*fc
= fuse_get_context();
1306 nih_local
struct cgm_keys
**list
= NULL
;
1307 char *fpath
= NULL
, *path1
;
1308 nih_local
char * cgdir
= NULL
;
1310 nih_local
char *controller
= NULL
;
1316 controller
= pick_controller_from_path(fc
, path
);
1320 cgroup
= find_cgroup_in_path(path
);
1324 get_cgdir_and_path(cgroup
, &cgdir
, &fpath
);
1330 if (!fc_may_access(fc
, controller
, path1
, NULL
, O_RDWR
))
1334 if (!cgm_create(controller
, cgroup
, fc
->uid
, fc
->gid
))
1340 static int cg_rmdir(const char *path
)
1342 struct fuse_context
*fc
= fuse_get_context();
1343 nih_local
struct cgm_keys
**list
= NULL
;
1345 nih_local
char * cgdir
= NULL
;
1347 nih_local
char *controller
= NULL
;
1353 controller
= pick_controller_from_path(fc
, path
);
1357 cgroup
= find_cgroup_in_path(path
);
1361 get_cgdir_and_path(cgroup
, &cgdir
, &fpath
);
1365 if (!fc_may_access(fc
, controller
, cgdir
, NULL
, O_WRONLY
))
1368 if (!cgm_remove(controller
, cgroup
))
1374 static bool startswith(const char *line
, const char *pref
)
1376 if (strncmp(line
, pref
, strlen(pref
)) == 0)
1381 static void get_mem_cached(char *memstat
, unsigned long *v
)
1387 if (startswith(memstat
, "total_cache")) {
1388 sscanf(memstat
+ 11, "%lu", v
);
1392 eol
= strchr(memstat
, '\n');
1399 static char *get_pid_cgroup(pid_t pid
, const char *contrl
)
1401 nih_local
char *fnam
= NULL
;
1403 char *answer
= NULL
;
1407 fnam
= NIH_MUST( nih_sprintf(NULL
, "/proc/%d/cgroup", pid
) );
1408 if (!(f
= fopen(fnam
, "r")))
1411 while (getline(&line
, &len
, f
) != -1) {
1415 c1
= strchr(line
, ':');
1419 c2
= strchr(c1
, ':');
1423 if (strcmp(c1
, contrl
) != 0)
1427 answer
= NIH_MUST( nih_strdup(NULL
, c2
) );
1438 * FUSE ops for /proc
1441 static int proc_meminfo_read(char *buf
, size_t size
, off_t offset
,
1442 struct fuse_file_info
*fi
)
1444 struct fuse_context
*fc
= fuse_get_context();
1445 nih_local
char *cg
= get_pid_cgroup(fc
->pid
, "memory");
1446 nih_local
char *memlimit_str
= NULL
, *memusage_str
= NULL
, *memstat_str
= NULL
;
1447 unsigned long memlimit
= 0, memusage
= 0, cached
= 0, hosttotal
= 0;
1449 size_t linelen
= 0, total_len
= 0;
1458 if (!cgm_get_value("memory", cg
, "memory.limit_in_bytes", &memlimit_str
))
1460 if (!cgm_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
1462 if (!cgm_get_value("memory", cg
, "memory.stat", &memstat_str
))
1464 memlimit
= strtoul(memlimit_str
, NULL
, 10);
1465 memusage
= strtoul(memusage_str
, NULL
, 10);
1468 get_mem_cached(memstat_str
, &cached
);
1470 f
= fopen("/proc/meminfo", "r");
1474 while (getline(&line
, &linelen
, f
) != -1) {
1476 char *printme
, lbuf
[100];
1478 memset(lbuf
, 0, 100);
1479 if (startswith(line
, "MemTotal:")) {
1480 sscanf(line
+14, "%lu", &hosttotal
);
1481 if (hosttotal
< memlimit
)
1482 memlimit
= hosttotal
;
1483 snprintf(lbuf
, 100, "MemTotal: %8lu kB\n", memlimit
);
1485 } else if (startswith(line
, "MemFree:")) {
1486 snprintf(lbuf
, 100, "MemFree: %8lu kB\n", memlimit
- memusage
);
1488 } else if (startswith(line
, "MemAvailable:")) {
1489 snprintf(lbuf
, 100, "MemAvailable: %8lu kB\n", memlimit
- memusage
);
1491 } else if (startswith(line
, "Buffers:")) {
1492 snprintf(lbuf
, 100, "Buffers: %8lu kB\n", 0UL);
1494 } else if (startswith(line
, "Cached:")) {
1495 snprintf(lbuf
, 100, "Cached: %8lu kB\n", cached
);
1497 } else if (startswith(line
, "SwapCached:")) {
1498 snprintf(lbuf
, 100, "SwapCached: %8lu kB\n", 0UL);
1502 l
= snprintf(buf
, size
, "%s", printme
);
1514 * Read the cpuset.cpus for cg
1515 * Return the answer in a nih_alloced string
1517 static char *get_cpuset(const char *cg
)
1521 if (!cgm_get_value("cpuset", cg
, "cpuset.cpus", &answer
))
1527 * Helper functions for cpuset_in-set
1529 char *cpuset_nexttok(const char *c
)
1531 char *r
= strchr(c
+1, ',');
1537 int cpuset_getrange(const char *c
, int *a
, int *b
)
1541 ret
= sscanf(c
, "%d-%d", a
, b
);
1546 * cpusets are in format "1,2-3,4"
1547 * iow, comma-delimited ranges
1549 static bool cpu_in_cpuset(int cpu
, const char *cpuset
)
1553 for (c
= cpuset
; c
; c
= cpuset_nexttok(c
)) {
1556 ret
= cpuset_getrange(c
, &a
, &b
);
1557 if (ret
== 1 && cpu
== a
)
1559 if (ret
!= 2) // bad cpuset!
1561 if (cpu
>= a
&& cpu
<= b
)
1568 static bool cpuline_in_cpuset(const char *line
, const char *cpuset
)
1572 if (sscanf(line
, "processor : %d", &cpu
) != 1)
1574 return cpu_in_cpuset(cpu
, cpuset
);
1578 * check whether this is a '^processor" line in /proc/cpuinfo
1580 static bool is_processor_line(const char *line
)
1584 if (sscanf(line
, "processor : %d", &cpu
) == 1)
1589 static int proc_cpuinfo_read(char *buf
, size_t size
, off_t offset
,
1590 struct fuse_file_info
*fi
)
1592 struct fuse_context
*fc
= fuse_get_context();
1593 nih_local
char *cg
= get_pid_cgroup(fc
->pid
, "cpuset");
1594 nih_local
char *cpuset
= NULL
;
1596 size_t linelen
= 0, total_len
= 0;
1597 bool am_printing
= false;
1607 cpuset
= get_cpuset(cg
);
1611 f
= fopen("/proc/cpuinfo", "r");
1615 while (getline(&line
, &linelen
, f
) != -1) {
1617 if (is_processor_line(line
)) {
1618 am_printing
= cpuline_in_cpuset(line
, cpuset
);
1621 l
= snprintf(buf
, size
, "processor : %d\n", curcpu
);
1629 l
= snprintf(buf
, size
, "%s", line
);
1641 static int proc_stat_read(char *buf
, size_t size
, off_t offset
,
1642 struct fuse_file_info
*fi
)
1644 struct fuse_context
*fc
= fuse_get_context();
1645 nih_local
char *cg
= get_pid_cgroup(fc
->pid
, "cpuset");
1646 nih_local
char *cpuset
= NULL
;
1648 size_t linelen
= 0, total_len
= 0;
1649 int curcpu
= -1; /* cpu numbering starts at 0 */
1658 cpuset
= get_cpuset(cg
);
1662 f
= fopen("/proc/stat", "r");
1666 while (getline(&line
, &linelen
, f
) != -1) {
1669 char cpu_char
[10]; /* That's a lot of cores */
1672 if (sscanf(line
, "cpu%9[^ ]", cpu_char
) != 1) {
1673 /* not a ^cpuN line containing a number N, just print it */
1674 l
= snprintf(buf
, size
, "%s", line
);
1681 if (sscanf(cpu_char
, "%d", &cpu
) != 1)
1683 if (!cpu_in_cpuset(cpu
, cpuset
))
1687 c
= strchr(line
, ' ');
1690 l
= snprintf(buf
, size
, "cpu%d %s", curcpu
, c
);
1702 * How to guess what to present for uptime?
1703 * One thing we could do would be to take the date on the caller's
1704 * memory.usage_in_bytes file, which should equal the time of creation
1705 * of his cgroup. However, a task could be in a sub-cgroup of the
1706 * container. The same problem exists if we try to look at the ages
1707 * of processes in the caller's cgroup.
1709 * So we'll fork a task that will enter the caller's pidns, mount a
1710 * fresh procfs, get the age of /proc/1, and pass that back over a pipe.
1712 * For the second uptime #, we'll do as Stéphane had done, just copy
1713 * the number from /proc/uptime. Not sure how to best emulate 'idle'
1714 * time. Maybe someone can come up with a good algorithm and submit a
1715 * patch. Maybe something based on cpushare info?
1718 /* return age of the reaper for $pid, taken from ctime of its procdir */
1719 static long int get_pid1_time(pid_t pid
)
1727 if (unshare(CLONE_NEWNS
))
1730 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
)) {
1731 perror("rslave mount failed");
1735 sprintf(fnam
, "/proc/%d/ns/pid", pid
);
1736 fd
= open(fnam
, O_RDONLY
);
1738 perror("get_pid1_time open of ns/pid");
1742 perror("get_pid1_time setns 1");
1752 // child will do the writing for us
1757 umount2("/proc", MNT_DETACH
);
1759 if (mount("proc", "/proc", "proc", 0, NULL
)) {
1760 perror("get_pid1_time mount");
1763 ret
= lstat("/proc/1", &sb
);
1765 perror("get_pid1_time lstat");
1768 return time(NULL
) - sb
.st_ctime
;
1771 static long int getreaperage(pid_t qpid
)
1773 int pid
, mypipe
[2], ret
;
1776 long int mtime
, answer
= 0;
1784 if (!pid
) { // child
1785 mtime
= get_pid1_time(qpid
);
1786 if (write(mypipe
[1], &mtime
, sizeof(mtime
)) != sizeof(mtime
))
1787 fprintf(stderr
, "Warning: bad write from getreaperage\n");
1793 FD_SET(mypipe
[0], &s
);
1796 ret
= select(mypipe
[0]+1, &s
, NULL
, NULL
, &tv
);
1802 fprintf(stderr
, "timed out\n");
1805 if (read(mypipe
[0], &mtime
, sizeof(mtime
)) != sizeof(mtime
)) {
1817 static long int getprocidle(void)
1819 FILE *f
= fopen("/proc/uptime", "r");
1824 ret
= fscanf(f
, "%ld %ld", &age
, &idle
);
1832 * We read /proc/uptime and reuse its second field.
1833 * For the first field, we use the mtime for the reaper for
1834 * the calling pid as returned by getreaperage
1836 static int proc_uptime_read(char *buf
, size_t size
, off_t offset
,
1837 struct fuse_file_info
*fi
)
1839 struct fuse_context
*fc
= fuse_get_context();
1840 long int reaperage
= getreaperage(fc
->pid
);;
1841 long int idletime
= getprocidle();
1845 return snprintf(buf
, size
, "%ld %ld\n", reaperage
, idletime
);
1848 static off_t
get_procfile_size(const char *which
)
1850 FILE *f
= fopen(which
, "r");
1853 ssize_t sz
, answer
= 0;
1857 while ((sz
= getline(&line
, &len
, f
)) != -1)
1865 static int proc_getattr(const char *path
, struct stat
*sb
)
1867 struct timespec now
;
1869 memset(sb
, 0, sizeof(struct stat
));
1870 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
1872 sb
->st_uid
= sb
->st_gid
= 0;
1873 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
1874 if (strcmp(path
, "/proc") == 0) {
1875 sb
->st_mode
= S_IFDIR
| 00555;
1879 if (strcmp(path
, "/proc/meminfo") == 0 ||
1880 strcmp(path
, "/proc/cpuinfo") == 0 ||
1881 strcmp(path
, "/proc/uptime") == 0 ||
1882 strcmp(path
, "/proc/stat") == 0) {
1884 sb
->st_size
= get_procfile_size(path
);
1885 sb
->st_mode
= S_IFREG
| 00444;
1893 static int proc_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
1894 struct fuse_file_info
*fi
)
1896 if (filler(buf
, "cpuinfo", NULL
, 0) != 0 ||
1897 filler(buf
, "meminfo", NULL
, 0) != 0 ||
1898 filler(buf
, "stat", NULL
, 0) != 0 ||
1899 filler(buf
, "uptime", NULL
, 0) != 0)
1904 static int proc_open(const char *path
, struct fuse_file_info
*fi
)
1906 if (strcmp(path
, "/proc/meminfo") == 0 ||
1907 strcmp(path
, "/proc/cpuinfo") == 0 ||
1908 strcmp(path
, "/proc/uptime") == 0 ||
1909 strcmp(path
, "/proc/stat") == 0)
1914 static int proc_read(const char *path
, char *buf
, size_t size
, off_t offset
,
1915 struct fuse_file_info
*fi
)
1917 if (strcmp(path
, "/proc/meminfo") == 0)
1918 return proc_meminfo_read(buf
, size
, offset
, fi
);
1919 if (strcmp(path
, "/proc/cpuinfo") == 0)
1920 return proc_cpuinfo_read(buf
, size
, offset
, fi
);
1921 if (strcmp(path
, "/proc/uptime") == 0)
1922 return proc_uptime_read(buf
, size
, offset
, fi
);
1923 if (strcmp(path
, "/proc/stat") == 0)
1924 return proc_stat_read(buf
, size
, offset
, fi
);
1930 * these just delegate to the /proc and /cgroup ops as
1934 static int lxcfs_getattr(const char *path
, struct stat
*sb
)
1936 if (strcmp(path
, "/") == 0) {
1937 sb
->st_mode
= S_IFDIR
| 00755;
1941 if (strncmp(path
, "/cgroup", 7) == 0) {
1942 return cg_getattr(path
, sb
);
1944 if (strncmp(path
, "/proc", 5) == 0) {
1945 return proc_getattr(path
, sb
);
1950 static int lxcfs_opendir(const char *path
, struct fuse_file_info
*fi
)
1952 if (strcmp(path
, "/") == 0)
1955 if (strncmp(path
, "/cgroup", 7) == 0) {
1956 return cg_opendir(path
, fi
);
1958 if (strcmp(path
, "/proc") == 0)
1963 static int lxcfs_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
1964 struct fuse_file_info
*fi
)
1966 if (strcmp(path
, "/") == 0) {
1967 if (filler(buf
, "proc", NULL
, 0) != 0 ||
1968 filler(buf
, "cgroup", NULL
, 0) != 0)
1972 if (strncmp(path
, "/cgroup", 7) == 0)
1973 return cg_readdir(path
, buf
, filler
, offset
, fi
);
1974 if (strcmp(path
, "/proc") == 0)
1975 return proc_readdir(path
, buf
, filler
, offset
, fi
);
1979 static int lxcfs_releasedir(const char *path
, struct fuse_file_info
*fi
)
1981 if (strcmp(path
, "/") == 0)
1983 if (strncmp(path
, "/cgroup", 7) == 0) {
1984 return cg_releasedir(path
, fi
);
1986 if (strcmp(path
, "/proc") == 0)
1991 static int lxcfs_open(const char *path
, struct fuse_file_info
*fi
)
1993 if (strncmp(path
, "/cgroup", 7) == 0)
1994 return cg_open(path
, fi
);
1995 if (strncmp(path
, "/proc", 5) == 0)
1996 return proc_open(path
, fi
);
2001 static int lxcfs_read(const char *path
, char *buf
, size_t size
, off_t offset
,
2002 struct fuse_file_info
*fi
)
2004 if (strncmp(path
, "/cgroup", 7) == 0)
2005 return cg_read(path
, buf
, size
, offset
, fi
);
2006 if (strncmp(path
, "/proc", 5) == 0)
2007 return proc_read(path
, buf
, size
, offset
, fi
);
2012 int lxcfs_write(const char *path
, const char *buf
, size_t size
, off_t offset
,
2013 struct fuse_file_info
*fi
)
2015 if (strncmp(path
, "/cgroup", 7) == 0) {
2016 return cg_write(path
, buf
, size
, offset
, fi
);
2022 static int lxcfs_flush(const char *path
, struct fuse_file_info
*fi
)
2027 static int lxcfs_release(const char *path
, struct fuse_file_info
*fi
)
2032 static int lxcfs_fsync(const char *path
, int datasync
, struct fuse_file_info
*fi
)
2037 int lxcfs_mkdir(const char *path
, mode_t mode
)
2039 if (strncmp(path
, "/cgroup", 7) == 0)
2040 return cg_mkdir(path
, mode
);
2045 int lxcfs_chown(const char *path
, uid_t uid
, gid_t gid
)
2047 if (strncmp(path
, "/cgroup", 7) == 0)
2048 return cg_chown(path
, uid
, gid
);
2054 * cat first does a truncate before doing ops->write. This doesn't
2055 * really make sense for cgroups. So just return 0 always but do
2058 int lxcfs_truncate(const char *path
, off_t newsize
)
2060 if (strncmp(path
, "/cgroup", 7) == 0)
2065 int lxcfs_rmdir(const char *path
)
2067 if (strncmp(path
, "/cgroup", 7) == 0)
2068 return cg_rmdir(path
);
2072 int lxcfs_chmod(const char *path
, mode_t mode
)
2074 if (strncmp(path
, "/cgroup", 7) == 0)
2075 return cg_chmod(path
, mode
);
2079 const struct fuse_operations lxcfs_ops
= {
2080 .getattr
= lxcfs_getattr
,
2084 .mkdir
= lxcfs_mkdir
,
2086 .rmdir
= lxcfs_rmdir
,
2090 .chmod
= lxcfs_chmod
,
2091 .chown
= lxcfs_chown
,
2092 .truncate
= lxcfs_truncate
,
2097 .release
= lxcfs_release
,
2098 .write
= lxcfs_write
,
2101 .flush
= lxcfs_flush
,
2102 .fsync
= lxcfs_fsync
,
2107 .removexattr
= NULL
,
2109 .opendir
= lxcfs_opendir
,
2110 .readdir
= lxcfs_readdir
,
2111 .releasedir
= lxcfs_releasedir
,
2122 static void usage(const char *me
)
2124 fprintf(stderr
, "Usage:\n");
2125 fprintf(stderr
, "\n");
2126 fprintf(stderr
, "%s [FUSE and mount options] mountpoint\n", me
);
2130 static bool is_help(char *w
)
2132 if (strcmp(w
, "-h") == 0 ||
2133 strcmp(w
, "--help") == 0 ||
2134 strcmp(w
, "-help") == 0 ||
2135 strcmp(w
, "help") == 0)
2140 int main(int argc
, char *argv
[])
2143 struct lxcfs_state
*d
;
2145 if (argc
< 2 || is_help(argv
[1]))
2148 d
= malloc(sizeof(*d
));
2152 if (!cgm_escape_cgroup())
2153 fprintf(stderr
, "WARNING: failed to escape to root cgroup\n");
2155 if (!cgm_get_controllers(&d
->subsystems
))
2158 ret
= fuse_main(argc
, argv
, &lxcfs_ops
, d
);