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>
45 #include "cgroup-util.h"
46 #include "sd-daemon.h"
48 #include "loopback-setup.h"
50 static char *arg_directory = NULL;
51 static char *arg_user = NULL;
52 static bool arg_private_network = false;
54 static int help(void) {
56 printf("%s [OPTIONS...] [PATH] [ARGUMENTS...]\n\n"
57 "Spawn a minimal namespace container for debugging, testing and building.\n\n"
58 " -h --help Show this help\n"
59 " -D --directory=NAME Root directory for the container\n"
60 " -u --user=USER Run the command under specified user or uid\n"
61 " --private-network Disable network in container\n",
62 program_invocation_short_name);
67 static int parse_argv(int argc, char *argv[]) {
70 ARG_PRIVATE_NETWORK = 0x100
73 static const struct option options[] = {
74 { "help", no_argument, NULL, 'h' },
75 { "directory", required_argument, NULL, 'D' },
76 { "user", required_argument, NULL, 'u' },
77 { "private-network", no_argument, NULL, ARG_PRIVATE_NETWORK },
86 while ((c = getopt_long(argc, argv, "+hD:u:", options, NULL)) >= 0) {
96 if (!(arg_directory = strdup(optarg))) {
97 log_error("Failed to duplicate root directory.");
105 if (!(arg_user = strdup(optarg))) {
106 log_error("Failed to duplicate user name.");
112 case ARG_PRIVATE_NETWORK:
113 arg_private_network = true;
120 log_error("Unknown option code %c", c);
128 static int mount_all(const char *dest) {
130 typedef struct MountPoint {
139 static const MountPoint mount_table[] = {
140 { "proc", "/proc", "proc", NULL, MS_NOSUID|MS_NOEXEC|MS_NODEV, true },
141 { "/proc/sys", "/proc/sys", "bind", NULL, MS_BIND, true }, /* Bind mount first */
142 { "/proc/sys", "/proc/sys", "bind", NULL, MS_BIND|MS_RDONLY|MS_REMOUNT, true }, /* Then, make it r/o */
143 { "/sys", "/sys", "bind", NULL, MS_BIND, true }, /* Bind mount first */
144 { "/sys", "/sys", "bind", NULL, MS_BIND|MS_RDONLY|MS_REMOUNT, true }, /* Then, make it r/o */
145 { "tmpfs", "/dev", "tmpfs", "mode=755", MS_NOSUID, true },
146 { "/dev/pts", "/dev/pts", "bind", NULL, MS_BIND, true },
147 { "tmpfs", "/run", "tmpfs", "mode=755", MS_NOSUID|MS_NODEV, true },
149 { "/sys/fs/selinux", "/sys/fs/selinux", "bind", NULL, MS_BIND, false }, /* Bind mount first */
150 { "/sys/fs/selinux", "/sys/fs/selinux", "bind", NULL, MS_BIND|MS_RDONLY|MS_REMOUNT, false }, /* Then, make it r/o */
158 for (k = 0; k < ELEMENTSOF(mount_table); k++) {
161 if (asprintf(&where, "%s/%s", dest, mount_table[k].where) < 0) {
162 log_error("Out of memory");
170 if ((t = path_is_mount_point(where, false)) < 0) {
171 log_error("Failed to detect whether %s is a mount point: %s", where, strerror(-t));
180 mkdir_p(where, 0755);
182 if (mount(mount_table[k].what,
185 mount_table[k].flags,
186 mount_table[k].options) < 0 &&
187 mount_table[k].fatal) {
189 log_error("mount(%s) failed: %m", where);
198 /* Fix the timezone, if possible */
199 if (asprintf(&where, "%s/%s", dest, "/etc/localtime") >= 0) {
201 if (mount("/etc/localtime", where, "bind", MS_BIND, NULL) >= 0)
202 mount("/etc/localtime", where, "bind", MS_BIND|MS_REMOUNT|MS_RDONLY, NULL);
210 static int copy_devnodes(const char *dest, const char *console) {
212 static const char devnodes[] =
227 char *from = NULL, *to = NULL;
234 NULSTR_FOREACH(d, devnodes) {
237 asprintf(&from, "/dev/%s", d);
238 asprintf(&to, "%s/dev/%s", dest, d);
241 log_error("Failed to allocate devnode path");
254 if (stat(from, &st) < 0) {
256 if (errno != ENOENT) {
257 log_error("Failed to stat %s: %m", from);
262 } else if (!S_ISCHR(st.st_mode) && !S_ISBLK(st.st_mode)) {
264 log_error("%s is not a char or block device, cannot copy.", from);
268 } else if (mknod(to, st.st_mode, st.st_rdev) < 0) {
270 log_error("mknod(%s) failed: %m", dest);
279 if (stat(console, &st) < 0) {
281 log_error("Failed to stat %s: %m", console);
287 } else if (!S_ISCHR(st.st_mode)) {
289 log_error("/dev/console is not a char device.");
296 if (asprintf(&to, "%s/dev/console", dest) < 0) {
298 log_error("Out of memory");
305 /* We need to bind mount the right tty to /dev/console since
306 * ptys can only exist on pts file systems. To have something
307 * to bind mount things on we create a device node first, that
308 * has the right major/minor (note that the major minor
309 * doesn't actually matter here, since we mount it over
312 if (mknod(to, (st.st_mode & ~07777) | 0600, st.st_rdev) < 0)
313 log_error("mknod for /dev/console failed: %m");
315 if (mount(console, to, "bind", MS_BIND, NULL) < 0) {
316 log_error("bind mount for /dev/console failed: %m");
324 if ((k = chmod_and_chown(console, 0600, 0, 0)) < 0) {
325 log_error("Failed to correct access mode for TTY: %s", strerror(-k));
337 static int drop_capabilities(void) {
338 static const unsigned long retain[] = {
348 CAP_NET_BIND_SERVICE,
364 for (l = 0; l <= MAX(63LU, (unsigned long) CAP_LAST_CAP); l++) {
367 for (i = 0; i < ELEMENTSOF(retain); i++)
371 if (i < ELEMENTSOF(retain))
374 if (prctl(PR_CAPBSET_DROP, l) < 0) {
376 /* If this capability is not known, EINVAL
377 * will be returned, let's ignore this. */
381 log_error("PR_CAPBSET_DROP failed: %m");
389 static int is_os_tree(const char *path) {
392 /* We use /bin/sh as flag file if something is an OS */
394 if (asprintf(&p, "%s/bin/sh", path) < 0)
400 return r < 0 ? 0 : 1;
403 #define BUFFER_SIZE 1024
405 static int process_pty(int master, sigset_t *mask) {
407 char in_buffer[BUFFER_SIZE], out_buffer[BUFFER_SIZE];
408 size_t in_buffer_full = 0, out_buffer_full = 0;
409 struct epoll_event stdin_ev, stdout_ev, master_ev, signal_ev;
410 bool stdin_readable = false, stdout_writable = false, master_readable = false, master_writable = false;
411 int ep = -1, signal_fd = -1, r;
413 fd_nonblock(STDIN_FILENO, 1);
414 fd_nonblock(STDOUT_FILENO, 1);
415 fd_nonblock(master, 1);
417 if ((signal_fd = signalfd(-1, mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0) {
418 log_error("signalfd(): %m");
423 if ((ep = epoll_create1(EPOLL_CLOEXEC)) < 0) {
424 log_error("Failed to create epoll: %m");
430 stdin_ev.events = EPOLLIN|EPOLLET;
431 stdin_ev.data.fd = STDIN_FILENO;
434 stdout_ev.events = EPOLLOUT|EPOLLET;
435 stdout_ev.data.fd = STDOUT_FILENO;
438 master_ev.events = EPOLLIN|EPOLLOUT|EPOLLET;
439 master_ev.data.fd = master;
442 signal_ev.events = EPOLLIN;
443 signal_ev.data.fd = signal_fd;
445 if (epoll_ctl(ep, EPOLL_CTL_ADD, STDIN_FILENO, &stdin_ev) < 0 ||
446 epoll_ctl(ep, EPOLL_CTL_ADD, STDOUT_FILENO, &stdout_ev) < 0 ||
447 epoll_ctl(ep, EPOLL_CTL_ADD, master, &master_ev) < 0 ||
448 epoll_ctl(ep, EPOLL_CTL_ADD, signal_fd, &signal_ev) < 0) {
449 log_error("Failed to regiser fds in epoll: %m");
455 struct epoll_event ev[16];
459 if ((nfds = epoll_wait(ep, ev, ELEMENTSOF(ev), -1)) < 0) {
461 if (errno == EINTR || errno == EAGAIN)
464 log_error("epoll_wait(): %m");
471 for (i = 0; i < nfds; i++) {
472 if (ev[i].data.fd == STDIN_FILENO) {
474 if (ev[i].events & (EPOLLIN|EPOLLHUP))
475 stdin_readable = true;
477 } else if (ev[i].data.fd == STDOUT_FILENO) {
479 if (ev[i].events & (EPOLLOUT|EPOLLHUP))
480 stdout_writable = true;
482 } else if (ev[i].data.fd == master) {
484 if (ev[i].events & (EPOLLIN|EPOLLHUP))
485 master_readable = true;
487 if (ev[i].events & (EPOLLOUT|EPOLLHUP))
488 master_writable = true;
490 } else if (ev[i].data.fd == signal_fd) {
491 struct signalfd_siginfo sfsi;
494 if ((n = read(signal_fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
497 log_error("Failed to read from signalfd: invalid block size");
502 if (errno != EINTR && errno != EAGAIN) {
503 log_error("Failed to read from signalfd: %m");
509 if (sfsi.ssi_signo == SIGWINCH) {
512 /* The window size changed, let's forward that. */
513 if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) >= 0)
514 ioctl(master, TIOCSWINSZ, &ws);
523 while ((stdin_readable && in_buffer_full <= 0) ||
524 (master_writable && in_buffer_full > 0) ||
525 (master_readable && out_buffer_full <= 0) ||
526 (stdout_writable && out_buffer_full > 0)) {
528 if (stdin_readable && in_buffer_full < BUFFER_SIZE) {
530 if ((k = read(STDIN_FILENO, in_buffer + in_buffer_full, BUFFER_SIZE - in_buffer_full)) < 0) {
532 if (errno == EAGAIN || errno == EPIPE || errno == ECONNRESET || errno == EIO)
533 stdin_readable = false;
535 log_error("read(): %m");
540 in_buffer_full += (size_t) k;
543 if (master_writable && in_buffer_full > 0) {
545 if ((k = write(master, in_buffer, in_buffer_full)) < 0) {
547 if (errno == EAGAIN || errno == EPIPE || errno == ECONNRESET || errno == EIO)
548 master_writable = false;
550 log_error("write(): %m");
556 assert(in_buffer_full >= (size_t) k);
557 memmove(in_buffer, in_buffer + k, in_buffer_full - k);
562 if (master_readable && out_buffer_full < BUFFER_SIZE) {
564 if ((k = read(master, out_buffer + out_buffer_full, BUFFER_SIZE - out_buffer_full)) < 0) {
566 if (errno == EAGAIN || errno == EPIPE || errno == ECONNRESET || errno == EIO)
567 master_readable = false;
569 log_error("read(): %m");
574 out_buffer_full += (size_t) k;
577 if (stdout_writable && out_buffer_full > 0) {
579 if ((k = write(STDOUT_FILENO, out_buffer, out_buffer_full)) < 0) {
581 if (errno == EAGAIN || errno == EPIPE || errno == ECONNRESET || errno == EIO)
582 stdout_writable = false;
584 log_error("write(): %m");
590 assert(out_buffer_full >= (size_t) k);
591 memmove(out_buffer, out_buffer + k, out_buffer_full - k);
592 out_buffer_full -= k;
600 close_nointr_nofail(ep);
603 close_nointr_nofail(signal_fd);
608 int main(int argc, char *argv[]) {
610 int r = EXIT_FAILURE, k;
611 char *oldcg = NULL, *newcg = NULL;
613 const char *console = NULL;
614 struct termios saved_attr, raw_attr;
616 bool saved_attr_valid = false;
619 log_parse_environment();
622 if ((r = parse_argv(argc, argv)) <= 0)
628 p = path_make_absolute_cwd(arg_directory);
632 arg_directory = get_current_dir_name();
634 if (!arg_directory) {
635 log_error("Failed to determine path");
639 path_kill_slashes(arg_directory);
641 if (geteuid() != 0) {
642 log_error("Need to be root.");
646 if (sd_booted() <= 0) {
647 log_error("Not running on a systemd system.");
651 if (path_equal(arg_directory, "/")) {
652 log_error("Spawning container on root directory not supported.");
656 if (is_os_tree(arg_directory) <= 0) {
657 log_error("Directory %s doesn't look like an OS root directory. Refusing.", arg_directory);
661 if ((k = cg_get_by_pid(SYSTEMD_CGROUP_CONTROLLER, 0, &oldcg)) < 0) {
662 log_error("Failed to determine current cgroup: %s", strerror(-k));
666 if (asprintf(&newcg, "%s/nspawn-%lu", oldcg, (unsigned long) getpid()) < 0) {
667 log_error("Failed to allocate cgroup path.");
671 if ((k = cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER, newcg, 0)) < 0) {
672 log_error("Failed to create cgroup: %s", strerror(-k));
676 if ((master = posix_openpt(O_RDWR|O_NOCTTY|O_CLOEXEC|O_NDELAY)) < 0) {
677 log_error("Failed to acquire pseudo tty: %m");
681 if (!(console = ptsname(master))) {
682 log_error("Failed to determine tty name: %m");
686 log_info("Spawning namespace container on %s (console is %s).", arg_directory, console);
688 if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) >= 0)
689 ioctl(master, TIOCSWINSZ, &ws);
691 if (unlockpt(master) < 0) {
692 log_error("Failed to unlock tty: %m");
696 if (tcgetattr(STDIN_FILENO, &saved_attr) < 0) {
697 log_error("Failed to get terminal attributes: %m");
701 saved_attr_valid = true;
703 raw_attr = saved_attr;
704 cfmakeraw(&raw_attr);
705 raw_attr.c_lflag &= ~ECHO;
707 if (tcsetattr(STDIN_FILENO, TCSANOW, &raw_attr) < 0) {
708 log_error("Failed to set terminal attributes: %m");
712 assert_se(sigemptyset(&mask) == 0);
713 sigset_add_many(&mask, SIGCHLD, SIGWINCH, SIGTERM, SIGINT, -1);
714 assert_se(sigprocmask(SIG_BLOCK, &mask, NULL) == 0);
716 if ((pid = syscall(__NR_clone, SIGCHLD|CLONE_NEWIPC|CLONE_NEWNS|CLONE_NEWPID|CLONE_NEWUTS|(arg_private_network ? CLONE_NEWNET : 0), NULL)) < 0) {
717 log_error("clone() failed: %m");
725 const char *home = NULL;
726 uid_t uid = (uid_t) -1;
727 gid_t gid = (gid_t) -1;
728 const char *envp[] = {
729 "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
730 "container=systemd-nspawn", /* LXC sets container=lxc, so follow the scheme here */
738 envp[2] = strv_find_prefix(environ, "TERM=");
740 close_nointr_nofail(master);
742 close_nointr(STDIN_FILENO);
743 close_nointr(STDOUT_FILENO);
744 close_nointr(STDERR_FILENO);
746 close_all_fds(NULL, 0);
748 reset_all_signal_handlers();
750 assert_se(sigemptyset(&mask) == 0);
751 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
756 if (prctl(PR_SET_PDEATHSIG, SIGKILL) < 0)
759 /* Mark / as private, in case somebody marked it shared */
760 if (mount(NULL, "/", NULL, MS_PRIVATE|MS_REC, NULL) < 0)
763 if (mount_all(arg_directory) < 0)
766 if (copy_devnodes(arg_directory, console) < 0)
769 if (chdir(arg_directory) < 0) {
770 log_error("chdir(%s) failed: %m", arg_directory);
774 if (open_terminal("dev/console", O_RDWR) != STDIN_FILENO ||
775 dup2(STDIN_FILENO, STDOUT_FILENO) != STDOUT_FILENO ||
776 dup2(STDIN_FILENO, STDERR_FILENO) != STDERR_FILENO)
779 if (mount(arg_directory, "/", "bind", MS_BIND|MS_MOVE, NULL) < 0) {
780 log_error("mount(MS_MOVE) failed: %m");
784 if (chroot(".") < 0) {
785 log_error("chroot() failed: %m");
789 if (chdir("/") < 0) {
790 log_error("chdir() failed: %m");
798 if (drop_capabilities() < 0)
803 if (get_user_creds((const char**)&arg_user, &uid, &gid, &home) < 0) {
804 log_error("get_user_creds() failed: %m");
808 if (mkdir_parents(home, 0775) < 0) {
809 log_error("mkdir_parents() failed: %m");
813 if (safe_mkdir(home, 0775, uid, gid) < 0) {
814 log_error("safe_mkdir() failed: %m");
818 if (initgroups((const char*)arg_user, gid) < 0) {
819 log_error("initgroups() failed: %m");
823 if (setresgid(gid, gid, gid) < 0) {
824 log_error("setregid() failed: %m");
828 if (setresuid(uid, uid, uid) < 0) {
829 log_error("setreuid() failed: %m");
834 if ((asprintf((char**)(envp + 3), "HOME=%s", home? home: "/root") < 0) ||
835 (asprintf((char**)(envp + 4), "USER=%s", arg_user? arg_user : "root") < 0) ||
836 (asprintf((char**)(envp + 5), "LOGNAME=%s", arg_user? arg_user : "root") < 0)) {
837 log_error("Out of memory");
841 if ((hn = file_name_from_path(arg_directory)))
842 sethostname(hn, strlen(hn));
845 execvpe(argv[optind], argv + optind, (char**) envp);
847 chdir(home ? home : "/root");
848 execle("/bin/bash", "-bash", NULL, (char**) envp);
851 log_error("execv() failed: %m");
857 if (process_pty(master, &mask) < 0)
860 if (saved_attr_valid) {
861 tcsetattr(STDIN_FILENO, TCSANOW, &saved_attr);
862 saved_attr_valid = false;
865 r = wait_for_terminate_and_warn(argc > optind ? argv[optind] : "bash", pid);
871 if (saved_attr_valid)
872 tcsetattr(STDIN_FILENO, TCSANOW, &saved_attr);
875 close_nointr_nofail(master);
878 cg_attach(SYSTEMD_CGROUP_CONTROLLER, oldcg, 0);
881 cg_kill_recursive_and_wait(SYSTEMD_CGROUP_CONTROLLER, newcg, true);