nspawn.c revision 2e996f4d4b642c5682c608c9692ad2ffae398ab2
/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
/***
This file is part of systemd.
Copyright 2010 Lennart Poettering
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
systemd is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with systemd; If not, see <http://www.gnu.org/licenses/>.
***/
#include <signal.h>
#include <sched.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <sys/capability.h>
#include <getopt.h>
#include <termios.h>
#include <sys/signalfd.h>
#include <grp.h>
#ifdef HAVE_XATTR
#endif
#include <systemd/sd-daemon.h>
#include "log.h"
#include "util.h"
#include "mkdir.h"
#include "macro.h"
#include "audit.h"
#include "missing.h"
#include "cgroup-util.h"
#include "strv.h"
#include "path-util.h"
#include "loopback-setup.h"
#include "sd-id128.h"
#include "dev-setup.h"
#include "fdset.h"
#include "build.h"
#include "fileio.h"
#ifndef TTY_GID
#define TTY_GID 5
#endif
typedef enum LinkJournal {
} LinkJournal;
static char *arg_directory = NULL;
static char **arg_controllers = NULL;
static char *arg_machine = NULL;
static bool arg_private_network = false;
static bool arg_read_only = false;
static bool arg_boot = false;
static uint64_t arg_retain =
(1ULL << CAP_CHOWN) |
(1ULL << CAP_DAC_OVERRIDE) |
(1ULL << CAP_DAC_READ_SEARCH) |
(1ULL << CAP_FOWNER) |
(1ULL << CAP_FSETID) |
(1ULL << CAP_IPC_OWNER) |
(1ULL << CAP_KILL) |
(1ULL << CAP_LEASE) |
(1ULL << CAP_LINUX_IMMUTABLE) |
(1ULL << CAP_NET_BIND_SERVICE) |
(1ULL << CAP_NET_BROADCAST) |
(1ULL << CAP_NET_RAW) |
(1ULL << CAP_SETGID) |
(1ULL << CAP_SETFCAP) |
(1ULL << CAP_SETPCAP) |
(1ULL << CAP_SETUID) |
(1ULL << CAP_SYS_ADMIN) |
(1ULL << CAP_SYS_CHROOT) |
(1ULL << CAP_SYS_NICE) |
(1ULL << CAP_SYS_PTRACE) |
(1ULL << CAP_SYS_TTY_CONFIG) |
(1ULL << CAP_SYS_RESOURCE) |
(1ULL << CAP_SYS_BOOT) |
(1ULL << CAP_AUDIT_WRITE) |
(1ULL << CAP_AUDIT_CONTROL);
static char **arg_bind_ro = NULL;
static int help(void) {
printf("%s [OPTIONS...] [PATH] [ARGUMENTS...]\n\n"
"Spawn a minimal namespace container for debugging, testing and building.\n\n"
" -h --help Show this help\n"
" --version Print version string\n"
" -D --directory=NAME Root directory for the container\n"
" -b --boot Boot up full system (i.e. invoke init)\n"
" -u --user=USER Run the command under specified user or uid\n"
" -C --controllers=LIST Put the container in specified comma-separated\n"
" cgroup hierarchies\n"
" --uuid=UUID Set a specific machine UUID for the container\n"
" -M --machine=NAME Set the machine name for the container\n"
" --private-network Disable network in container\n"
" --read-only Mount the root directory read-only\n"
" --capability=CAP In addition to the default, retain specified\n"
" capability\n"
" --link-journal=MODE Link up guest journal, one of no, auto, guest, host\n"
" -j Equivalent to --link-journal=host\n"
" --bind=PATH[:PATH] Bind mount a file or directory from the host into\n"
" the container\n"
" --bind-ro=PATH[:PATH] Similar, but creates a read-only bind mount\n",
return 0;
}
enum {
ARG_VERSION = 0x100,
};
};
int c;
switch (c) {
case 'h':
help();
return 0;
case ARG_VERSION:
return 0;
case 'D':
if (!arg_directory) {
log_error("Failed to canonicalize root directory.");
return -ENOMEM;
}
break;
case 'u':
if (!arg_user)
return log_oom();
break;
case 'C':
if (!arg_controllers)
return log_oom();
break;
case ARG_PRIVATE_NETWORK:
arg_private_network = true;
break;
case 'b':
arg_boot = true;
break;
case ARG_UUID:
if (!id128_is_valid(optarg)) {
return -EINVAL;
}
break;
case 'M':
if (!hostname_is_valid(optarg)) {
return -EINVAL;
}
if (!arg_machine)
return log_oom();
break;
case ARG_READ_ONLY:
arg_read_only = true;
break;
case ARG_CAPABILITY: {
char *t;
if (!t)
return log_oom();
if (cap_from_name(t, &cap) < 0) {
log_error("Failed to parse capability %s.", t);
free(t);
return -EINVAL;
}
free(t);
}
break;
}
case 'j':
break;
case ARG_LINK_JOURNAL:
else {
return -EINVAL;
}
break;
case ARG_BIND:
case ARG_BIND_RO: {
char *e;
char ***x;
int r;
if (e) {
b = strdup(e + 1);
} else {
}
if (!a || !b)
return log_oom();
if (!path_is_absolute(a) || !path_is_absolute(b)) {
return -EINVAL;
}
r = strv_extend(x, a);
if (r < 0)
return r;
r = strv_extend(x, b);
if (r < 0)
return r;
break;
}
case '?':
return -EINVAL;
default:
log_error("Unknown option code %c", c);
return -EINVAL;
}
}
return 1;
}
typedef struct MountPoint {
const char *what;
const char *where;
const char *type;
const char *options;
unsigned long flags;
bool fatal;
} MountPoint;
static const MountPoint mount_table[] = {
{ "devpts", "/dev/pts", "devpts","newinstance,ptmxmode=0666,mode=620,gid=" STRINGIFY(TTY_GID), MS_NOSUID|MS_NOEXEC, true },
#ifdef HAVE_SELINUX
{ NULL, "/sys/fs/selinux", NULL, NULL, MS_BIND|MS_RDONLY|MS_REMOUNT, false }, /* Then, make it r/o */
#endif
};
unsigned k;
int r = 0;
for (k = 0; k < ELEMENTSOF(mount_table); k++) {
int t;
if (!where)
return log_oom();
t = path_is_mount_point(where, true);
if (t < 0) {
if (r == 0)
r = t;
continue;
}
/* Skip this entry if it is not a remount. */
if (mount_table[k].what && t > 0)
continue;
mount_table[k].type,
mount_table[k].flags,
mount_table[k].options) < 0 &&
mount_table[k].fatal) {
if (r == 0)
r = -errno;
}
}
return r;
}
char **x, **y;
STRV_FOREACH_PAIR(x, y, l) {
if (!where)
return log_oom();
return -errno;
}
return -errno;
}
}
return 0;
}
static int setup_timezone(const char *dest) {
char *z, *y;
int r;
/* Fix the timezone, if possible */
r = readlink_malloc("/etc/localtime", &p);
if (r < 0) {
log_warning("/etc/localtime is not a symlink, not updating container timezone.");
return 0;
}
z = path_startswith(p, "../usr/share/zoneinfo/");
if (!z)
z = path_startswith(p, "/usr/share/zoneinfo/");
if (!z) {
log_warning("/etc/localtime does not point into /usr/share/zoneinfo/, not updating container timezone.");
return 0;
}
if (!where)
return log_oom();
r = readlink_malloc(where, &q);
if (r >= 0) {
y = path_startswith(q, "../usr/share/zoneinfo/");
if (!y)
y = path_startswith(q, "/usr/share/zoneinfo/");
/* Already pointing to the right place? Then do nothing .. */
if (y && streq(y, z))
return 0;
}
if (!check)
return log_oom();
log_warning("Timezone %s does not exist in container, not updating container timezone.", z);
return 0;
}
if (!what)
return log_oom();
log_error("Failed to correct timezone of container: %m");
return 0;
}
return 0;
}
static int setup_resolv_conf(const char *dest) {
if (arg_private_network)
return 0;
/* Fix resolv.conf, if possible */
if (!where)
return log_oom();
/* We don't really care for the results of this really. If it
* fails, it fails, but meh... */
log_warning("Failed to bind mount /etc/resolv.conf: %m");
else
log_error("Failed to remount /etc/resolv.conf readonly: %m");
return -errno;
}
return 0;
}
static int setup_boot_id(const char *dest) {
char as_uuid[37];
int r;
/* Generate a new randomized boot ID, so that each boot-up of
* the container gets a new one */
return log_oom();
r = sd_id128_randomize(&rnd);
if (r < 0) {
return r;
}
"%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
if (r < 0) {
return r;
}
log_error("Failed to bind mount boot id: %m");
r = -errno;
log_warning("Failed to make boot id read-only: %m");
return r;
}
static int copy_devnodes(const char *dest) {
static const char devnodes[] =
"null\0"
"zero\0"
"full\0"
"random\0"
"urandom\0"
"tty\0";
const char *d;
int r = 0;
u = umask(0000);
NULSTR_FOREACH(d, devnodes) {
log_oom();
if (r == 0)
r = -ENOMEM;
break;
}
if (r == 0)
r = -errno;
}
if (r == 0)
r = -EIO;
if (r == 0)
r = -errno;
}
}
return r;
}
static int setup_ptmx(const char *dest) {
_cleanup_free_ char *p = NULL;
if (!p)
return log_oom();
return -errno;
}
return 0;
}
int r;
u = umask(0000);
return -errno;
return -EIO;
}
if (r < 0) {
return r;
}
return log_oom();
* ptys can only exist on pts file systems. To have something
* to bind mount things on we create a device node first, that
* doesn't actually matter here, since we mount it over
* anyway). */
return -errno;
}
return -errno;
}
return 0;
}
int r, fd, k;
union {
} control = {};
.msg_control = &control,
.msg_controllen = sizeof(control),
};
assert(kmsg_socket >= 0);
u = umask(0000);
* that writing blocks when nothing is reading. In order to
* avoid any problems with containers deadlocking due to this
return log_oom();
return -errno;
}
if (r < 0) {
return r;
}
return -errno;
}
if (fd < 0) {
log_error("Failed to open fifo: %m");
return -errno;
}
/* Store away the fd in the socket, so that it stays open as
* long as we run the child */
if (k < 0) {
log_error("Failed to send FIFO fd: %m");
return -errno;
}
return 0;
}
static int setup_hostname(void) {
return -errno;
return 0;
}
static int setup_journal(const char *directory) {
char *id;
int r;
if (arg_link_journal == LINK_NO)
return 0;
if (!p)
return log_oom();
r = read_one_line_file(p, &b);
return 0;
else if (r < 0) {
return r;
}
return 0;
/* Verify validity */
if (r < 0) {
return r;
}
free(p);
if (!p || !q)
return log_oom();
if (path_is_mount_point(p, false) > 0) {
if (arg_link_journal != LINK_AUTO) {
log_error("%s: already a mount point, refusing to use for journal", p);
return -EEXIST;
}
return 0;
}
if (path_is_mount_point(q, false) > 0) {
if (arg_link_journal != LINK_AUTO) {
log_error("%s: already a mount point, refusing to use for journal", q);
return -EEXIST;
}
return 0;
}
r = readlink_and_make_absolute(p, &d);
if (r >= 0) {
if ((arg_link_journal == LINK_GUEST ||
arg_link_journal == LINK_AUTO) &&
path_equal(d, q)) {
r = mkdir_p(q, 0755);
if (r < 0)
log_warning("failed to create directory %s: %m", q);
return 0;
}
if (unlink(p) < 0) {
log_error("Failed to remove symlink %s: %m", p);
return -errno;
}
} else if (r == -EINVAL) {
if (arg_link_journal == LINK_GUEST &&
rmdir(p) < 0) {
log_error("%s already exists and is neither a symlink nor a directory", p);
return r;
} else {
log_error("Failed to remove %s: %m", p);
return -errno;
}
}
} else if (r != -ENOENT) {
log_error("readlink(%s) failed: %m", p);
return r;
}
if (arg_link_journal == LINK_GUEST) {
if (symlink(q, p) < 0) {
log_error("Failed to symlink %s to %s: %m", q, p);
return -errno;
}
r = mkdir_p(q, 0755);
if (r < 0)
log_warning("failed to create directory %s: %m", q);
return 0;
}
if (arg_link_journal == LINK_HOST) {
r = mkdir_p(p, 0755);
if (r < 0) {
log_error("Failed to create %s: %m", p);
return r;
}
return 0;
if (dir_is_empty(q) == 0) {
log_error("%s not empty.", q);
return -ENOTEMPTY;
}
r = mkdir_p(q, 0755);
if (r < 0) {
log_error("Failed to create %s: %m", q);
return r;
}
log_error("Failed to bind mount journal from host into guest: %m");
return -errno;
}
return 0;
}
static int setup_cgroup(const char *path) {
char **c;
int r;
if (r < 0) {
return r;
}
STRV_FOREACH(c, arg_controllers) {
if (r < 0)
}
return 0;
}
static int save_attributes(const char *cgroup, pid_t pid, const char *uuid, const char *directory) {
#ifdef HAVE_XATTR
int r = 0, k;
if (r < 0) {
return r;
}
if (r < 0)
if (uuid) {
if (k < 0) {
if (r == 0)
r = k;
}
}
if (k < 0) {
if (r == 0)
r = k;
}
return r;
#else
return 0;
#endif
}
static int drop_capabilities(void) {
return capability_bounding_set_drop(~arg_retain, false);
}
bool stdin_readable = false, stdout_writable = false, master_readable = false, master_writable = false;
bool tried_orderly_shutdown = false;
if (signal_fd < 0) {
log_error("signalfd(): %m");
r = -errno;
goto finish;
}
if (ep < 0) {
log_error("Failed to create epoll: %m");
r = -errno;
goto finish;
}
/* We read from STDIN only if this is actually a TTY,
* otherwise we assume non-interactivity. */
if (isatty(STDIN_FILENO)) {
log_error("Failed to register STDIN in epoll: %m");
r = -errno;
goto finish;
}
}
log_error("Failed to register stdout in epoll: %m");
r = -errno;
goto finish;
}
/* stdout without epoll support. Likely redirected to regular file. */
stdout_writable = true;
}
log_error("Failed to register fds in epoll: %m");
r = -errno;
goto finish;
}
for (;;) {
ssize_t k;
int i, nfds;
if (nfds < 0) {
continue;
log_error("epoll_wait(): %m");
r = -errno;
goto finish;
}
for (i = 0; i < nfds; i++) {
stdin_readable = true;
stdout_writable = true;
master_readable = true;
master_writable = true;
struct signalfd_siginfo sfsi;
ssize_t n;
if (n != sizeof(sfsi)) {
if (n >= 0) {
log_error("Failed to read from signalfd: invalid block size");
r = -EIO;
goto finish;
}
log_error("Failed to read from signalfd: %m");
r = -errno;
goto finish;
}
} else {
/* The window size changed, let's forward that. */
log_info("Trying to halt container. Send SIGTERM again to trigger immediate termination.");
/* This only works for systemd... */
tried_orderly_shutdown = true;
} else {
r = 0;
goto finish;
}
}
}
}
while ((stdin_readable && in_buffer_full <= 0) ||
(master_writable && in_buffer_full > 0) ||
(master_readable && out_buffer_full <= 0) ||
(stdout_writable && out_buffer_full > 0)) {
if (k < 0) {
stdin_readable = false;
else {
log_error("read(): %m");
r = -errno;
goto finish;
}
} else
in_buffer_full += (size_t) k;
}
if (master_writable && in_buffer_full > 0) {
if (k < 0) {
master_writable = false;
else {
log_error("write(): %m");
r = -errno;
goto finish;
}
} else {
in_buffer_full -= k;
}
}
if (k < 0) {
master_readable = false;
else {
log_error("read(): %m");
r = -errno;
goto finish;
}
} else
out_buffer_full += (size_t) k;
}
if (stdout_writable && out_buffer_full > 0) {
if (k < 0) {
stdout_writable = false;
else {
log_error("write(): %m");
r = -errno;
goto finish;
}
} else {
out_buffer_full -= k;
}
}
}
}
if (ep >= 0)
if (signal_fd >= 0)
return r;
}
static bool audit_enabled(void) {
int fd;
if (fd >= 0) {
return true;
}
return false;
}
int r = EXIT_FAILURE, k;
int n_fd_passed;
bool saved_attr_valid = false;
log_open();
if (k < 0)
goto finish;
else if (k == 0) {
r = EXIT_SUCCESS;
goto finish;
}
if (arg_directory) {
char *p;
arg_directory = p;
} else
if (!arg_directory) {
log_error("Failed to determine path, please use -D.");
goto finish;
}
if (!arg_machine) {
if (!arg_machine) {
log_oom();
goto finish;
}
hostname_cleanup(arg_machine, false);
if (isempty(arg_machine)) {
log_error("Failed to determine machine name automatically, please use -M.");
goto finish;
}
}
if (geteuid() != 0) {
log_error("Need to be root.");
goto finish;
}
if (sd_booted() <= 0) {
log_error("Not running on a systemd system.");
goto finish;
}
if (audit_enabled()) {
log_warning("The kernel auditing subsystem is known to be incompatible with containers.\n"
"Please make sure to turn off auditing with 'audit=0' on the kernel command\n"
"line before using systemd-nspawn. Sleeping for 5s...\n");
sleep(5);
}
log_error("Spawning container on root directory not supported.");
goto finish;
}
if (path_is_os_tree(arg_directory) <= 0) {
log_error("Directory %s doesn't look like an OS root directory (/etc/os-release is missing). Refusing.", arg_directory);
goto finish;
}
log_close();
n_fd_passed = sd_listen_fds(false);
if (n_fd_passed > 0) {
k = fdset_new_listen_fds(&fds, false);
if (k < 0) {
goto finish;
}
}
log_open();
if (k < 0) {
goto finish;
}
if (k <= 0 && k != -ENOENT) {
log_error("Container already running.");
goto finish;
}
if (master < 0) {
log_error("Failed to acquire pseudo tty: %m");
goto finish;
}
if (!console) {
log_error("Failed to determine tty name: %m");
goto finish;
}
log_error("Failed to unlock tty: %m");
goto finish;
}
saved_attr_valid = true;
}
log_error("Failed to create kmsg socket pair.");
goto finish;
}
sd_notify(0, "READY=1");
for (;;) {
log_error("pipe2(): %m");
goto finish;
}
log_error("pipe2(): %m");
goto finish;
}
pid = syscall(__NR_clone, SIGCHLD|CLONE_NEWIPC|CLONE_NEWNS|CLONE_NEWPID|CLONE_NEWUTS|(arg_private_network ? CLONE_NEWNET : 0), NULL);
if (pid < 0) {
log_error("clone() failed, do you have namespace support enabled in your kernel? (You need UTS, IPC, PID and NET namespacing built in): %m");
else
log_error("clone() failed: %m");
goto finish;
}
if (pid == 0) {
/* child */
unsigned n_env = 2;
const char *envp[] = {
"container=systemd-nspawn", /* LXC sets container=lxc, so follow the scheme here */
NULL, /* TERM */
NULL, /* HOME */
NULL, /* USER */
NULL, /* LOGNAME */
NULL, /* container_uuid */
NULL, /* LISTEN_FDS */
NULL, /* LISTEN_PID */
};
n_env ++;
/* Wait for the parent process to log our PID */
master = -1;
if (saved_attr_valid) {
log_error("Failed to set terminal attributes: %m");
goto child_fail;
}
}
kmsg_socket_pair[0] = -1;
if (k != STDIN_FILENO) {
if (k >= 0) {
k = -EINVAL;
}
goto child_fail;
}
log_error("Failed to duplicate console: %m");
goto child_fail;
}
if (setsid() < 0) {
log_error("setsid() failed: %m");
goto child_fail;
}
log_error("PR_SET_PDEATHSIG failed: %m");
goto child_fail;
}
if (setup_cgroup(newcg) < 0)
goto child_fail;
/* Mark everything as slave, so that we still
* receive mounts from the real root, but don't
* propagate mounts to the real root. */
log_error("MS_SLAVE|MS_REC failed: %m");
goto child_fail;
}
/* Turn directory into bind mount */
log_error("Failed to make bind mount.");
goto child_fail;
}
if (arg_read_only)
log_error("Failed to make read-only.");
goto child_fail;
}
if (mount_all(arg_directory) < 0)
goto child_fail;
if (copy_devnodes(arg_directory) < 0)
goto child_fail;
if (setup_ptmx(arg_directory) < 0)
goto child_fail;
goto child_fail;
goto child_fail;
if (setup_boot_id(arg_directory) < 0)
goto child_fail;
if (setup_timezone(arg_directory) < 0)
goto child_fail;
if (setup_resolv_conf(arg_directory) < 0)
goto child_fail;
if (setup_journal(arg_directory) < 0)
goto child_fail;
goto child_fail;
goto child_fail;
if (chdir(arg_directory) < 0) {
goto child_fail;
}
log_error("mount(MS_MOVE) failed: %m");
goto child_fail;
}
if (chroot(".") < 0) {
log_error("chroot() failed: %m");
goto child_fail;
}
if (chdir("/") < 0) {
log_error("chdir() failed: %m");
goto child_fail;
}
umask(0022);
if (drop_capabilities() < 0) {
log_error("drop_capabilities() failed: %m");
goto child_fail;
}
if (arg_user) {
/* Note that this resolves user names
* inside the container, and hence
* accesses the NSS modules from the
* container and not the host. This is
* a bit weird... */
log_error("get_user_creds() failed: %m");
goto child_fail;
}
log_error("mkdir_parents_label() failed: %m");
goto child_fail;
}
log_error("mkdir_safe_label() failed: %m");
goto child_fail;
}
log_error("initgroups() failed: %m");
goto child_fail;
}
log_error("setregid() failed: %m");
goto child_fail;
}
log_error("setreuid() failed: %m");
goto child_fail;
}
} else {
/* Reset everything fully to 0, just in case */
log_error("setgroups() failed: %m");
goto child_fail;
}
if (setresgid(0, 0, 0) < 0) {
log_error("setregid() failed: %m");
goto child_fail;
}
if (setresuid(0, 0, 0) < 0) {
log_error("setreuid() failed: %m");
goto child_fail;
}
}
log_oom();
goto child_fail;
}
if (arg_uuid) {
log_oom();
goto child_fail;
}
}
if (fdset_size(fds) > 0) {
k = fdset_cloexec(fds, false);
if (k < 0) {
log_error("Failed to unset O_CLOEXEC for file descriptors.");
goto child_fail;
}
log_oom();
goto child_fail;
}
}
if (arg_boot) {
char **a;
size_t l;
/* Automatically search for the init system */
a = newa(char*, l + 1);
else {
}
log_error("execv() failed: %m");
}
/* Wait for the child process to establish cgroup hierarchy */
goto finish;
if (saved_attr_valid)
if (k < 0) {
r = EXIT_FAILURE;
break;
}
break;
}
log_debug("Container exited successfully.");
break;
log_info("Container has been shut down.");
r = 0;
break;
log_info("Container is being rebooted.");
continue;
r = EXIT_FAILURE;
break;
} else {
log_error("Container failed due to unknown reason.");
r = EXIT_FAILURE;
break;
}
}
if (saved_attr_valid)
if (newcg)
return r;
}