1 /* SPDX-License-Identifier: LGPL-2.1+ */
7 #ifndef FUSE_USE_VERSION
8 #define FUSE_USE_VERSION 26
11 #define _FILE_OFFSET_BITS 64
19 #include <linux/magic.h>
20 #include <linux/sched.h>
29 #include <sys/epoll.h>
31 #include <sys/mount.h>
32 #include <sys/param.h>
33 #include <sys/socket.h>
34 #include <sys/syscall.h>
35 #include <sys/sysinfo.h>
41 #include "api_extensions.h"
43 #include "cgroup_fuse.h"
44 #include "cgroups/cgroup.h"
45 #include "cgroups/cgroup_utils.h"
47 #include "memory_utils.h"
48 #include "proc_cpuview.h"
49 #include "syscall_numbers.h"
52 static bool can_use_pidfd
;
54 static volatile sig_atomic_t reload_successful
;
56 bool liblxcfs_functional(void)
58 return reload_successful
!= 0;
61 /* Define pivot_root() if missing from the C library */
62 #ifndef HAVE_PIVOT_ROOT
63 static int pivot_root(const char *new_root
, const char *put_old
)
65 return syscall(__NR_pivot_root
, new_root
, put_old
);
68 extern int pivot_root(const char *new_root
, const char *put_old
);
72 * A table caching which pid is init for a pid namespace.
73 * When looking up which pid is init for $qpid, we first
74 * 1. Stat /proc/$qpid/ns/pid.
75 * 2. Check whether the ino_t is in our store.
76 * a. if not, fork a child in qpid's ns to send us
77 * ucred.pid = 1, and read the initpid. Cache
78 * initpid and creation time for /proc/initpid
79 * in a new store entry.
80 * b. if so, verify that /proc/initpid still matches
81 * what we have saved. If not, clear the store
82 * entry and go back to a. If so, return the
85 struct pidns_init_store
{
86 ino_t ino
; /* inode number for /proc/$pid/ns/pid */
87 pid_t initpid
; /* the pid of nit in that ns */
89 int64_t ctime
; /* the time at which /proc/$initpid was created */
90 struct pidns_init_store
*next
;
94 /* lol - look at how they are allocated in the kernel */
95 #define PIDNS_HASH_SIZE 4096
96 #define HASH(x) ((x) % PIDNS_HASH_SIZE)
98 static struct pidns_init_store
*pidns_hash_table
[PIDNS_HASH_SIZE
];
99 static pthread_mutex_t pidns_store_mutex
= PTHREAD_MUTEX_INITIALIZER
;
101 static void mutex_lock(pthread_mutex_t
*l
)
105 ret
= pthread_mutex_lock(l
);
107 log_exit("%s - returned %d\n", strerror(ret
), ret
);
110 struct cgroup_ops
*cgroup_ops
;
112 static void mutex_unlock(pthread_mutex_t
*l
)
116 ret
= pthread_mutex_unlock(l
);
118 log_exit("%s - returned %d\n", strerror(ret
), ret
);
121 static inline void store_lock(void)
123 mutex_lock(&pidns_store_mutex
);
126 static inline void store_unlock(void)
128 mutex_unlock(&pidns_store_mutex
);
133 * <pid-as-str> = INTTYPE_TO_STRLEN(pid_t)
137 #define LXCFS_PROC_PID_LEN \
138 (STRLITERALLEN("/proc/") + INTTYPE_TO_STRLEN(uint64_t) + +1)
140 static int initpid_still_valid_pidfd(struct pidns_init_store
*entry
)
144 if (entry
->init_pidfd
< 0)
145 return ret_errno(ENOSYS
);
147 ret
= pidfd_send_signal(entry
->init_pidfd
, 0, NULL
, 0);
150 return ret_errno(ENOSYS
);
158 static int initpid_still_valid_stat(struct pidns_init_store
*entry
)
161 char path
[LXCFS_PROC_PID_LEN
];
163 snprintf(path
, sizeof(path
), "/proc/%d", entry
->initpid
);
164 if (stat(path
, &st
) || entry
->ctime
!= st
.st_ctime
)
170 /* Must be called under store_lock */
171 static bool initpid_still_valid(struct pidns_init_store
*entry
)
175 ret
= initpid_still_valid_pidfd(entry
);
177 ret
= initpid_still_valid_stat(entry
);
182 /* Must be called under store_lock */
183 static void remove_initpid(struct pidns_init_store
*entry
)
185 struct pidns_init_store
*it
;
188 lxcfs_debug("Removing cached entry for pid %d from init pid cache",
191 ino_hash
= HASH(entry
->ino
);
192 if (pidns_hash_table
[ino_hash
] == entry
) {
193 pidns_hash_table
[ino_hash
] = entry
->next
;
194 close_prot_errno_disarm(entry
->init_pidfd
);
199 it
= pidns_hash_table
[ino_hash
];
201 if (it
->next
== entry
) {
202 it
->next
= entry
->next
;
203 close_prot_errno_disarm(entry
->init_pidfd
);
212 /* Must be called under store_lock */
213 static void prune_initpid_store(void)
215 static int64_t last_prune
= 0;
216 int64_t now
, threshold
;
219 last_prune
= time(NULL
);
224 if (now
< (last_prune
+ PURGE_SECS
))
227 lxcfs_debug("Pruning init pid cache");
230 threshold
= now
- 2 * PURGE_SECS
;
232 for (int i
= 0; i
< PIDNS_HASH_SIZE
; i
++) {
233 for (struct pidns_init_store
*entry
= pidns_hash_table
[i
], *prev
= NULL
; entry
;) {
234 if (entry
->lastcheck
< threshold
) {
235 struct pidns_init_store
*cur
= entry
;
237 lxcfs_debug("Removed cache entry for pid %d to init pid cache", cur
->initpid
);
240 prev
->next
= entry
->next
;
242 pidns_hash_table
[i
] = entry
->next
;
244 close_prot_errno_disarm(cur
->init_pidfd
);
254 /* Must be called under store_lock */
255 static void save_initpid(ino_t pidns_inode
, pid_t pid
)
257 __do_free
struct pidns_init_store
*entry
= NULL
;
258 __do_close
int pidfd
= -EBADF
;
259 const struct lxcfs_opts
*opts
= fuse_get_context()->private_data
;
260 char path
[LXCFS_PROC_PID_LEN
];
264 if (opts
&& opts
->use_pidfd
&& can_use_pidfd
) {
265 pidfd
= pidfd_open(pid
, 0);
270 snprintf(path
, sizeof(path
), "/proc/%d", pid
);
274 entry
= zalloc(sizeof(*entry
));
278 ino_hash
= HASH(pidns_inode
);
279 *entry
= (struct pidns_init_store
){
282 .ctime
= st
.st_ctime
,
283 .next
= pidns_hash_table
[ino_hash
],
284 .lastcheck
= time(NULL
),
285 .init_pidfd
= move_fd(pidfd
),
287 pidns_hash_table
[ino_hash
] = move_ptr(entry
);
289 lxcfs_debug("Added cache entry %d for pid %d to init pid cache", ino_hash
, pid
);
293 * Given the stat(2) info for a nsfd pid inode, lookup the init_pid_store
294 * entry for the inode number and creation time. Verify that the init pid
295 * is still valid. If not, remove it. Return the entry if valid, NULL
297 * Must be called under store_lock
299 static pid_t
lookup_verify_initpid(ino_t pidns_inode
)
301 struct pidns_init_store
*entry
= pidns_hash_table
[HASH(pidns_inode
)];
304 if (entry
->ino
== pidns_inode
) {
305 if (initpid_still_valid(entry
)) {
306 entry
->lastcheck
= time(NULL
);
307 return entry
->initpid
;
310 remove_initpid(entry
);
311 return ret_errno(ESRCH
);
316 return ret_errno(ESRCH
);
319 static int send_creds_clone_wrapper(void *arg
)
321 int sock
= PTR_TO_INT(arg
);
322 char v
= '1'; /* we are the child */
323 struct ucred cred
= {
329 return send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
;
333 * Let's use the "standard stack limit" (i.e. glibc thread size default) for
336 #define __LXCFS_STACK_SIZE (8 * 1024 * 1024)
337 pid_t
lxcfs_clone(int (*fn
)(void *), void *arg
, int flags
)
342 stack
= malloc(__LXCFS_STACK_SIZE
);
344 return ret_errno(ENOMEM
);
347 ret
= __clone2(fn
, stack
, __LXCFS_STACK_SIZE
, flags
| SIGCHLD
, arg
, NULL
);
349 ret
= clone(fn
, stack
+ __LXCFS_STACK_SIZE
, flags
| SIGCHLD
, arg
, NULL
);
354 #define LXCFS_PROC_PID_NS_LEN \
355 (STRLITERALLEN("/proc/") + INTTYPE_TO_STRLEN(uint64_t) + \
356 STRLITERALLEN("/ns/pid") + 1)
359 * clone a task which switches to @task's namespace and writes '1'.
360 * over a unix sock so we can read the task's reaper's pid in our
363 * Note: glibc's fork() does not respect pidns, which can lead to failed
364 * assertions inside glibc (and thus failed forks) if the child's pid in
365 * the pidns and the parent pid outside are identical. Using clone prevents
368 static void write_task_init_pid_exit(int sock
, pid_t target
)
370 __do_close
int fd
= -EBADF
;
371 char path
[LXCFS_PROC_PID_NS_LEN
];
374 snprintf(path
, sizeof(path
), "/proc/%d/ns/pid", (int)target
);
375 fd
= open(path
, O_RDONLY
| O_CLOEXEC
);
377 log_exit("write_task_init_pid_exit open of ns/pid");
380 log_exit("Failed to setns to pid namespace of process %d", target
);
382 pid
= lxcfs_clone(send_creds_clone_wrapper
, INT_TO_PTR(sock
), 0);
387 if (!wait_for_pid(pid
))
394 static pid_t
scm_init_pid(pid_t task
)
398 struct ucred cred
= {
406 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0)
415 write_task_init_pid_exit(sock
[0], task
);
419 if (!recv_creds(sock
[1], &cred
, &v
))
433 pid_t
lookup_initpid_in_store(pid_t pid
)
435 pid_t hashed_pid
= 0;
436 char path
[LXCFS_PROC_PID_NS_LEN
];
439 snprintf(path
, sizeof(path
), "/proc/%d/ns/pid", pid
);
441 return ret_errno(ESRCH
);
445 hashed_pid
= lookup_verify_initpid(st
.st_ino
);
446 if (hashed_pid
< 0) {
447 /* release the mutex as the following call is expensive */
450 hashed_pid
= scm_init_pid(pid
);
455 save_initpid(st
.st_ino
, hashed_pid
);
459 * Prune at the end in case we're pruning the value
460 * we were about to return.
462 prune_initpid_store();
469 * Functions needed to setup cgroups in the __constructor__.
472 static bool umount_if_mounted(void)
474 if (umount2(BASEDIR
, MNT_DETACH
) < 0 && errno
!= EINVAL
) {
475 lxcfs_error("Failed to unmount %s: %s.\n", BASEDIR
, strerror(errno
));
481 /* __typeof__ should be safe to use with all compilers. */
482 typedef __typeof__(((struct statfs
*)NULL
)->f_type
) fs_type_magic
;
483 static bool has_fs_type(const struct statfs
*fs
, fs_type_magic magic_val
)
485 return (fs
->f_type
== (fs_type_magic
)magic_val
);
489 * looking at fs/proc_namespace.c, it appears we can
490 * actually expect the rootfs entry to very specifically contain
491 * " - rootfs rootfs "
492 * IIUC, so long as we've chrooted so that rootfs is not our root,
493 * the rootfs entry should always be skipped in mountinfo contents.
495 static bool is_on_ramfs(void)
497 __do_free
char *line
= NULL
;
498 __do_free
void *fopen_cache
= NULL
;
499 __do_fclose
FILE *f
= NULL
;
502 f
= fopen_cached("/proc/self/mountinfo", "re", &fopen_cache
);
506 while (getline(&line
, &len
, f
) != -1) {
510 for (p
= line
, i
= 0; p
&& i
< 4; i
++)
511 p
= strchr(p
+ 1, ' ');
515 p2
= strchr(p
+ 1, ' ');
519 if (strcmp(p
+ 1, "/") == 0) {
520 /* This is '/'. Is it the ramfs? */
521 p
= strchr(p2
+ 1, '-');
522 if (p
&& strncmp(p
, "- rootfs rootfs ", 16) == 0)
530 static int pivot_enter()
532 __do_close
int oldroot
= -EBADF
, newroot
= -EBADF
;
534 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
| O_CLOEXEC
);
536 return log_error_errno(-1, errno
,
537 "Failed to open old root for fchdir");
539 newroot
= open(ROOTDIR
, O_DIRECTORY
| O_RDONLY
| O_CLOEXEC
);
541 return log_error_errno(-1, errno
,
542 "Failed to open new root for fchdir");
544 /* change into new root fs */
545 if (fchdir(newroot
) < 0)
546 return log_error_errno(-1,
547 errno
, "Failed to change directory to new rootfs: %s",
550 /* pivot_root into our new root fs */
551 if (pivot_root(".", ".") < 0)
552 return log_error_errno(-1, errno
,
553 "pivot_root() syscall failed: %s",
557 * At this point the old-root is mounted on top of our new-root.
558 * To unmounted it we must not be chdir'd into it, so escape back
561 if (fchdir(oldroot
) < 0)
562 return log_error_errno(-1, errno
, "Failed to enter old root");
564 if (umount2(".", MNT_DETACH
) < 0)
565 return log_error_errno(-1, errno
, "Failed to detach old root");
567 if (fchdir(newroot
) < 0)
568 return log_error_errno(-1, errno
, "Failed to re-enter new root");
573 static int chroot_enter()
575 if (mount(ROOTDIR
, "/", NULL
, MS_REC
| MS_BIND
, NULL
)) {
576 lxcfs_error("Failed to recursively bind-mount %s into /.", ROOTDIR
);
580 if (chroot(".") < 0) {
581 lxcfs_error("Call to chroot() failed: %s.\n", strerror(errno
));
585 if (chdir("/") < 0) {
586 lxcfs_error("Failed to change directory: %s.\n", strerror(errno
));
593 static int permute_and_enter(void)
597 if (statfs("/", &sb
) < 0) {
598 lxcfs_error("%s\n", "Could not stat / mountpoint.");
602 /* has_fs_type() is not reliable. When the ramfs is a tmpfs it will
603 * likely report TMPFS_MAGIC. Hence, when it reports no we still check
604 * /proc/1/mountinfo. */
605 if (has_fs_type(&sb
, RAMFS_MAGIC
) || is_on_ramfs())
606 return chroot_enter();
608 if (pivot_enter() < 0) {
609 lxcfs_error("%s\n", "Could not perform pivot root.");
616 /* Prepare our new clean root. */
617 static int permute_prepare(void)
619 if (mkdir(ROOTDIR
, 0700) < 0 && errno
!= EEXIST
) {
620 lxcfs_error("%s\n", "Failed to create directory for new root.");
624 if (mount("/", ROOTDIR
, NULL
, MS_BIND
, 0) < 0) {
625 lxcfs_error("Failed to bind-mount / for new root: %s.\n", strerror(errno
));
629 if (mount(RUNTIME_PATH
, ROOTDIR RUNTIME_PATH
, NULL
, MS_BIND
, 0) < 0) {
630 lxcfs_error("Failed to bind-mount /run into new root: %s.\n", strerror(errno
));
634 if (mount(BASEDIR
, ROOTDIR BASEDIR
, NULL
, MS_REC
| MS_MOVE
, 0) < 0) {
635 printf("Failed to move " BASEDIR
" into new root: %s.\n", strerror(errno
));
642 /* Calls chroot() on ramfs, pivot_root() in all other cases. */
643 static bool permute_root(void)
645 /* Prepare new root. */
646 if (permute_prepare() < 0)
649 /* Pivot into new root. */
650 if (permute_and_enter() < 0)
656 static bool cgfs_prepare_mounts(void)
658 if (!mkdir_p(BASEDIR
, 0700)) {
659 lxcfs_error("%s\n", "Failed to create lxcfs cgroup mountpoint.");
663 if (!umount_if_mounted()) {
664 lxcfs_error("%s\n", "Failed to clean up old lxcfs cgroup mountpoint.");
668 if (unshare(CLONE_NEWNS
) < 0) {
669 lxcfs_error("Failed to unshare mount namespace: %s.\n", strerror(errno
));
673 cgroup_ops
->mntns_fd
= preserve_ns(getpid(), "mnt");
674 if (cgroup_ops
->mntns_fd
< 0) {
675 lxcfs_error("Failed to preserve mount namespace: %s.\n", strerror(errno
));
679 if (mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, 0) < 0) {
680 lxcfs_error("Failed to remount / private: %s.\n", strerror(errno
));
684 if (mount("tmpfs", BASEDIR
, "tmpfs", 0, "size=100000,mode=700") < 0) {
685 lxcfs_error("%s\n", "Failed to mount tmpfs over lxcfs cgroup mountpoint.");
692 static bool cgfs_mount_hierarchies(void)
694 if (!mkdir_p(BASEDIR DEFAULT_CGROUP_MOUNTPOINT
, 0755))
697 if (!cgroup_ops
->mount(cgroup_ops
, BASEDIR
))
700 for (struct hierarchy
**h
= cgroup_ops
->hierarchies
; h
&& *h
; h
++) {
701 __do_free
char *path
= must_make_path(BASEDIR
, (*h
)->mountpoint
, NULL
);
702 (*h
)->fd
= open(path
, O_DIRECTORY
| O_CLOEXEC
| O_NOFOLLOW
);
710 static bool cgfs_setup_controllers(void)
712 if (!cgfs_prepare_mounts())
715 if (!cgfs_mount_hierarchies())
716 return log_error_errno(false, errno
, "Failed to set up private lxcfs cgroup mounts");
724 static void sigusr2_toggle_virtualization(int signo
, siginfo_t
*info
, void *extra
)
728 if (reload_successful
) {
729 reload_successful
= 0;
731 /* write() is async signal safe */
732 ret
= write(STDERR_FILENO
,
733 "Switched into non-virtualization mode\n",
734 STRLITERALLEN("Switched into non-virtualization mode\n"));
736 goto please_compiler
;
738 reload_successful
= 1;
740 /* write() is async signal safe */
741 ret
= write(STDERR_FILENO
, "Switched into virtualization mode\n",
742 STRLITERALLEN("Switched into virtualization mode\n"));
744 goto please_compiler
;
749 * The write() syscall is a function whose return value needs to be
750 * checked. Otherwise the compiler will warn. This is how we
751 * please our master. Another one could be to use
752 * syscall(__NR_write, ...) directly but whatever.
757 static void __attribute__((constructor
)) lxcfs_init(void)
759 __do_close
int init_ns
= -EBADF
, root_fd
= -EBADF
,
764 lxcfs_info("Running constructor %s to reload liblxcfs", __func__
);
766 cgroup_ops
= cgroup_init();
768 lxcfs_info("Failed to initialize cgroup support");
772 /* Preserve initial namespace. */
774 init_ns
= preserve_ns(pid
, "mnt");
776 lxcfs_info("Failed to preserve initial mount namespace");
780 /* This function calls unshare(CLONE_NEWNS) our initial mount namespace
781 * to privately mount lxcfs cgroups. */
782 if (!cgfs_setup_controllers()) {
783 log_exit("Failed to setup private cgroup mounts for lxcfs");
787 if (setns(init_ns
, 0) < 0) {
788 log_exit("%s - Failed to switch back to initial mount namespace", strerror(errno
));
792 if (!init_cpuview()) {
793 log_exit("Failed to init CPU view");
797 lxcfs_info("mount namespace: %d", cgroup_ops
->mntns_fd
);
798 lxcfs_info("hierarchies:");
800 for (struct hierarchy
**h
= cgroup_ops
->hierarchies
; h
&& *h
; h
++, i
++) {
801 char **controller_list
= (*h
)->controllers
;
802 __do_free
char *controllers
= NULL
;
803 if (controller_list
&& *controller_list
)
804 controllers
= lxc_string_join(",", (const char **)controller_list
, false);
805 lxcfs_info(" %2d: fd: %3d: %s", i
, (*h
)->fd
, controllers
?: "");
808 pidfd
= pidfd_open(pid
, 0);
809 if (pidfd
>= 0 && pidfd_send_signal(pidfd
, 0, NULL
, 0) == 0) {
810 can_use_pidfd
= true;
811 lxcfs_info("Kernel supports pidfds");
814 lxcfs_info("api_extensions:");
815 for (i
= 0; i
< nr_api_extensions
; i
++)
816 lxcfs_info("- %s", api_extensions
[i
]);
818 root_fd
= open("/", O_PATH
| O_CLOEXEC
);
820 lxcfs_info("%s - Failed to open root directory", strerror(errno
));
821 else if (fchdir(root_fd
) < 0)
822 lxcfs_info("%s - Failed to change to root directory", strerror(errno
));
824 if (install_signal_handler(SIGUSR2
, sigusr2_toggle_virtualization
)) {
825 lxcfs_info("%s - Failed to install SIGUSR2 signal handler", strerror(errno
));
829 reload_successful
= 1;
833 reload_successful
= 0;
834 lxcfs_info("Failed to run constructor %s to reload liblxcfs", __func__
);
837 static void __attribute__((destructor
)) lxcfs_exit(void)
839 lxcfs_info("Running destructor %s", __func__
);
842 cgroup_exit(cgroup_ops
);