1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
25 #include <sys/types.h>
26 #include <sys/syscall.h>
27 #include <sys/mount.h>
33 #include <sys/prctl.h>
34 #include <sys/capability.h>
36 #include <sys/epoll.h>
38 #include <sys/signalfd.h>
43 #include "cgroup-util.h"
44 #include "sd-daemon.h"
47 static char *arg_directory = NULL;
49 static int help(void) {
51 printf("%s [OPTIONS...] [PATH] [ARGUMENTS...]\n\n"
52 "Spawn a minimal namespace container for debugging, testing and building.\n\n"
53 " -h --help Show this help\n"
54 " -D --directory=NAME Root directory for the container\n",
55 program_invocation_short_name);
60 static int parse_argv(int argc, char *argv[]) {
62 static const struct option options[] = {
63 { "help", no_argument, NULL, 'h' },
64 { "directory", required_argument, NULL, 'D' },
73 while ((c = getopt_long(argc, argv, "+hD:", options, NULL)) >= 0) {
83 if (!(arg_directory = strdup(optarg))) {
84 log_error("Failed to duplicate root directory.");
94 log_error("Unknown option code %c", c);
102 static int mount_all(const char *dest) {
104 typedef struct MountPoint {
113 static const MountPoint mount_table[] = {
114 { "proc", "/proc", "proc", NULL, MS_NOSUID|MS_NOEXEC|MS_NODEV, true },
115 { "/proc/sys", "/proc/sys", "bind", NULL, MS_BIND, true }, /* Bind mount first */
116 { "/proc/sys", "/proc/sys", "bind", NULL, MS_BIND|MS_RDONLY|MS_REMOUNT, true }, /* Then, make it r/o */
117 { "sysfs", "/sys", "sysfs", NULL, MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_RDONLY, true },
118 { "tmpfs", "/dev", "tmpfs", "mode=755", MS_NOSUID, true },
119 { "/dev/pts", "/dev/pts", "bind", NULL, MS_BIND, true },
120 { "tmpfs", "/dev/.run", "tmpfs", "mode=755", MS_NOSUID|MS_NOEXEC|MS_NODEV, true },
122 { "selinux", "/selinux", "selinuxfs", NULL, MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_RDONLY, false },
130 for (k = 0; k < ELEMENTSOF(mount_table); k++) {
133 if (asprintf(&where, "%s/%s", dest, mount_table[k].where) < 0) {
134 log_error("Out of memory");
142 if ((t = path_is_mount_point(where)) < 0) {
143 log_error("Failed to detect whether %s is a mount point: %s", where, strerror(-t));
152 mkdir_p(where, 0755);
154 if (mount(mount_table[k].what,
157 mount_table[k].flags,
158 mount_table[k].options) < 0 &&
159 mount_table[k].fatal) {
161 log_error("mount(%s) failed: %m", where);
170 /* Fix the timezone, if possible */
171 if (asprintf(&where, "%s/%s", dest, "/etc/localtime") >= 0) {
172 mount("/etc/localtime", where, "bind", MS_BIND, NULL);
173 mount("/etc/localtime", where, "bind", MS_BIND|MS_REMOUNT|MS_RDONLY, NULL);
180 static int copy_devnodes(const char *dest, const char *console) {
182 static const char devnodes[] =
197 char *from = NULL, *to = NULL;
204 NULSTR_FOREACH(d, devnodes) {
207 asprintf(&from, "/dev/%s", d);
208 asprintf(&to, "%s/dev/%s", dest, d);
211 log_error("Failed to allocate devnode path");
224 if (stat(from, &st) < 0) {
226 if (errno != ENOENT) {
227 log_error("Failed to stat %s: %m", from);
232 } else if (!S_ISCHR(st.st_mode) && !S_ISBLK(st.st_mode)) {
234 log_error("%s is not a char or block device, cannot copy.", from);
238 } else if (mknod(to, st.st_mode, st.st_rdev) < 0) {
240 log_error("mknod(%s) failed: %m", dest);
249 if (stat(console, &st) < 0) {
251 log_error("Failed to stat %s: %m", console);
257 } else if (!S_ISCHR(st.st_mode)) {
259 log_error("/dev/console is not a char device.");
266 if (asprintf(&to, "%s/dev/console", dest) < 0) {
268 log_error("Out of memory");
275 /* We need to bind mount the right tty to /dev/console since
276 * ptys can only exist on pts file systems. To have something
277 * to bind mount things on we create a device node first, that
278 * has the right major/minor (note that the major minor
279 * doesn't actually matter here, since we mount it over
282 if (mknod(to, (st.st_mode & ~07777) | 0600, st.st_rdev) < 0)
283 log_error("mknod for /dev/console failed: %m");
285 if (mount(console, to, "bind", MS_BIND, NULL) < 0) {
286 log_error("bind mount for /dev/console failed: %m");
294 if ((k = chmod_and_chown(console, 0600, 0, 0)) < 0) {
295 log_error("Failed to correct access mode for TTY: %s", strerror(-k));
308 static int drop_capabilities(void) {
309 static const unsigned long retain[] = {
319 CAP_NET_BIND_SERVICE,
335 for (l = 0; l <= MAX(63LU, (unsigned long) CAP_LAST_CAP); l ++) {
338 for (i = 0; i < ELEMENTSOF(retain); i++)
342 if (i < ELEMENTSOF(retain))
345 if (prctl(PR_CAPBSET_DROP, l) < 0) {
347 /* If this capability is not known, EINVAL
348 * will be returned, let's ignore this. */
352 log_error("PR_CAPBSET_DROP failed: %m");
360 static int is_os_tree(const char *path) {
363 /* We use /bin/sh as flag file if something is an OS */
365 if (asprintf(&p, "%s/bin/sh", path) < 0)
371 return r < 0 ? 0 : 1;
374 #define BUFFER_SIZE 1024
376 static int process_pty(int master, sigset_t *mask) {
377 char in_buffer[BUFFER_SIZE], out_buffer[BUFFER_SIZE];
378 size_t in_buffer_full = 0, out_buffer_full = 0;
379 struct epoll_event stdin_ev, stdout_ev, master_ev, signal_ev;
380 bool stdin_readable = false, stdout_writable = false, master_readable = false, master_writable = false;
381 int ep = -1, signal_fd = -1, r;
383 fd_nonblock(STDIN_FILENO, 1);
384 fd_nonblock(STDOUT_FILENO, 1);
385 fd_nonblock(master, 1);
387 if ((signal_fd = signalfd(-1, mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0) {
388 log_error("signalfd(): %m");
393 if ((ep = epoll_create1(EPOLL_CLOEXEC)) < 0) {
394 log_error("Failed to create epoll: %m");
400 stdin_ev.events = EPOLLIN|EPOLLET;
401 stdin_ev.data.fd = STDIN_FILENO;
404 stdout_ev.events = EPOLLOUT|EPOLLET;
405 stdout_ev.data.fd = STDOUT_FILENO;
408 master_ev.events = EPOLLIN|EPOLLOUT|EPOLLET;
409 master_ev.data.fd = master;
412 signal_ev.events = EPOLLIN;
413 signal_ev.data.fd = signal_fd;
415 if (epoll_ctl(ep, EPOLL_CTL_ADD, STDIN_FILENO, &stdin_ev) < 0 ||
416 epoll_ctl(ep, EPOLL_CTL_ADD, STDOUT_FILENO, &stdout_ev) < 0 ||
417 epoll_ctl(ep, EPOLL_CTL_ADD, master, &master_ev) < 0 ||
418 epoll_ctl(ep, EPOLL_CTL_ADD, signal_fd, &signal_ev) < 0) {
419 log_error("Failed to regiser fds in epoll: %m");
425 struct epoll_event ev[16];
429 if ((nfds = epoll_wait(ep, ev, ELEMENTSOF(ev), -1)) < 0) {
431 if (errno == EINTR || errno == EAGAIN)
434 log_error("epoll_wait(): %m");
441 for (i = 0; i < nfds; i++) {
442 if (ev[i].data.fd == STDIN_FILENO) {
444 if (ev[i].events & (EPOLLIN|EPOLLHUP))
445 stdin_readable = true;
447 } else if (ev[i].data.fd == STDOUT_FILENO) {
449 if (ev[i].events & (EPOLLOUT|EPOLLHUP))
450 stdout_writable = true;
452 } else if (ev[i].data.fd == master) {
454 if (ev[i].events & (EPOLLIN|EPOLLHUP))
455 master_readable = true;
457 if (ev[i].events & (EPOLLOUT|EPOLLHUP))
458 master_writable = true;
460 } else if (ev[i].data.fd == signal_fd) {
461 struct signalfd_siginfo sfsi;
464 if ((n = read(signal_fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
471 if (errno != EINTR && errno != EAGAIN) {
477 if (sfsi.ssi_signo == SIGWINCH) {
480 /* The window size changed, let's forward that. */
481 if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) >= 0)
482 ioctl(master, TIOCSWINSZ, &ws);
491 while ((stdin_readable && in_buffer_full <= 0) ||
492 (master_writable && in_buffer_full > 0) ||
493 (master_readable && out_buffer_full <= 0) ||
494 (stdout_writable && out_buffer_full > 0)) {
496 if (stdin_readable && in_buffer_full < BUFFER_SIZE) {
498 if ((k = read(STDIN_FILENO, in_buffer + in_buffer_full, BUFFER_SIZE - in_buffer_full)) < 0) {
500 if (errno == EAGAIN || errno == EPIPE || errno == ECONNRESET || errno == EIO)
501 stdin_readable = false;
503 log_error("read(): %m");
507 in_buffer_full += (size_t) k;
510 if (master_writable && in_buffer_full > 0) {
512 if ((k = write(master, in_buffer, in_buffer_full)) < 0) {
514 if (errno == EAGAIN || errno == EPIPE || errno == ECONNRESET || errno == EIO)
515 master_writable = false;
517 log_error("write(): %m");
522 assert(in_buffer_full >= (size_t) k);
523 memmove(in_buffer, in_buffer + k, in_buffer_full - k);
528 if (master_readable && out_buffer_full < BUFFER_SIZE) {
530 if ((k = read(master, out_buffer + out_buffer_full, BUFFER_SIZE - out_buffer_full)) < 0) {
532 if (errno == EAGAIN || errno == EPIPE || errno == ECONNRESET || errno == EIO)
533 master_readable = false;
535 log_error("read(): %m");
539 out_buffer_full += (size_t) k;
542 if (stdout_writable && out_buffer_full > 0) {
544 if ((k = write(STDOUT_FILENO, out_buffer, out_buffer_full)) < 0) {
546 if (errno == EAGAIN || errno == EPIPE || errno == ECONNRESET || errno == EIO)
547 stdout_writable = false;
549 log_error("write(): %m");
554 assert(out_buffer_full >= (size_t) k);
555 memmove(out_buffer, out_buffer + k, out_buffer_full - k);
556 out_buffer_full -= k;
564 close_nointr_nofail(ep);
567 close_nointr_nofail(signal_fd);
572 int main(int argc, char *argv[]) {
574 int r = EXIT_FAILURE, k;
575 char *oldcg = NULL, *newcg = NULL;
577 const char *console = NULL;
578 struct termios saved_attr, raw_attr;
580 bool saved_attr_valid = false;
583 log_parse_environment();
586 if ((r = parse_argv(argc, argv)) <= 0)
592 p = path_make_absolute_cwd(arg_directory);
596 arg_directory = get_current_dir_name();
598 if (!arg_directory) {
599 log_error("Failed to determine path");
603 path_kill_slashes(arg_directory);
605 if (geteuid() != 0) {
606 log_error("Need to be root.");
610 if (sd_booted() <= 0) {
611 log_error("Not running on a systemd system.");
615 if (path_equal(arg_directory, "/")) {
616 log_error("Spawning container on root directory not supported.");
620 if (is_os_tree(arg_directory) <= 0) {
621 log_error("Directory %s doesn't look like an OS root directory. Refusing.", arg_directory);
625 if ((k = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, 0, &oldcg)) < 0) {
626 log_error("Failed to determine current cgroup: %s", strerror(-k));
630 if (asprintf(&newcg, "%s/nspawn-%lu", oldcg, (unsigned long) getpid()) < 0) {
631 log_error("Failed to allocate cgroup path.");
635 if ((k = cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER, newcg, 0)) < 0) {
636 log_error("Failed to create cgroup: %s", strerror(-k));
640 if ((master = posix_openpt(O_RDWR|O_NOCTTY|O_CLOEXEC|O_NDELAY)) < 0) {
641 log_error("Failed to acquire pseudo tty: %m");
645 if (!(console = ptsname(master))) {
646 log_error("Failed to determine tty name: %m");
650 log_info("Spawning namespace container on %s (console is %s).", arg_directory, console);
652 if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) >= 0)
653 ioctl(master, TIOCSWINSZ, &ws);
655 if (unlockpt(master) < 0) {
656 log_error("Failed to unlock tty: %m");
660 if (tcgetattr(STDIN_FILENO, &saved_attr) < 0) {
661 log_error("Failed to get terminal attributes: %m");
665 saved_attr_valid = true;
667 raw_attr = saved_attr;
668 cfmakeraw(&raw_attr);
669 raw_attr.c_lflag &= ~ECHO;
671 if (tcsetattr(STDIN_FILENO, TCSANOW, &raw_attr) < 0) {
672 log_error("Failed to set terminal attributes: %m");
676 assert_se(sigemptyset(&mask) == 0);
677 sigset_add_many(&mask, SIGCHLD, SIGWINCH, SIGTERM, SIGINT, -1);
678 assert_se(sigprocmask(SIG_BLOCK, &mask, NULL) == 0);
680 if ((pid = syscall(__NR_clone, SIGCHLD|CLONE_NEWIPC|CLONE_NEWNS|CLONE_NEWPID|CLONE_NEWUTS, NULL)) < 0) {
681 log_error("clone() failed: %m");
689 const char *envp[] = {
691 "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
696 envp[2] = strv_find_prefix(environ, "TERM=");
698 close_nointr_nofail(master);
700 close_nointr(STDIN_FILENO);
701 close_nointr(STDOUT_FILENO);
702 close_nointr(STDERR_FILENO);
704 close_all_fds(NULL, 0);
706 reset_all_signal_handlers();
708 assert_se(sigemptyset(&mask) == 0);
709 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
714 if (prctl(PR_SET_PDEATHSIG, SIGKILL) < 0)
717 if (mount_all(arg_directory) < 0)
720 if (copy_devnodes(arg_directory, console) < 0)
723 if (chdir(arg_directory) < 0) {
724 log_error("chdir(%s) failed: %m", arg_directory);
728 if (open_terminal("dev/console", O_RDWR) != STDIN_FILENO ||
729 dup2(STDIN_FILENO, STDOUT_FILENO) != STDOUT_FILENO ||
730 dup2(STDIN_FILENO, STDERR_FILENO) != STDERR_FILENO)
733 if (mount(arg_directory, "/", "bind", MS_BIND|MS_MOVE, NULL) < 0) {
734 log_error("mount(MS_MOVE) failed: %m");
738 if (chroot(".") < 0) {
739 log_error("chroot() failed: %m");
743 if (chdir("/") < 0) {
744 log_error("chdir() failed: %m");
750 if (drop_capabilities() < 0)
753 if ((hn = file_name_from_path(arg_directory)))
754 sethostname(hn, strlen(hn));
757 execvpe(argv[optind], argv + optind, (char**) envp);
760 execle("/bin/bash", "-bash", NULL, (char**) envp);
763 log_error("execv() failed: %m");
769 if (process_pty(master, &mask) < 0)
772 if (saved_attr_valid) {
773 tcsetattr(STDIN_FILENO, TCSANOW, &saved_attr);
774 saved_attr_valid = false;
777 r = wait_for_terminate_and_warn(argc > optind ? argv[optind] : "bash", pid);
783 if (saved_attr_valid)
784 tcsetattr(STDIN_FILENO, TCSANOW, &saved_attr);
787 close_nointr_nofail(master);
790 cg_attach(SYSTEMD_CGROUP_CONTROLLER, oldcg, 0);
793 cg_kill_recursive_and_wait(SYSTEMD_CGROUP_CONTROLLER, newcg, true);