nspawn.c revision efdb02375beb0a940c3320865572913780b4d7de
/*-*- 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 <getopt.h>
#include <grp.h>
#include <sys/personality.h>
#ifdef HAVE_SELINUX
#endif
#ifdef HAVE_SECCOMP
#include <seccomp.h>
#endif
#ifdef HAVE_BLKID
#endif
#include "sd-daemon.h"
#include "sd-bus.h"
#include "sd-id128.h"
#include "sd-netlink.h"
#include "random-util.h"
#include "log.h"
#include "util.h"
#include "mkdir.h"
#include "rm-rf.h"
#include "macro.h"
#include "missing.h"
#include "cgroup-util.h"
#include "strv.h"
#include "path-util.h"
#include "loopback-setup.h"
#include "dev-setup.h"
#include "fdset.h"
#include "build.h"
#include "fileio.h"
#include "bus-util.h"
#include "bus-error.h"
#include "ptyfwd.h"
#include "env-util.h"
#include "netlink-util.h"
#include "udev-util.h"
#include "blkid-util.h"
#include "gpt.h"
#include "siphash24.h"
#include "copy.h"
#include "base-filesystem.h"
#include "barrier.h"
#include "event-util.h"
#include "capability.h"
#include "cap-list.h"
#include "btrfs-util.h"
#include "machine-image.h"
#include "list.h"
#include "in-addr-util.h"
#include "firewall-util.h"
#include "local-addresses.h"
#include "formats-util.h"
#include "process-util.h"
#include "terminal-util.h"
#include "hostname-util.h"
#include "signal-util.h"
#ifdef HAVE_SECCOMP
#include "seccomp-util.h"
#endif
typedef struct ExposePort {
int protocol;
} ExposePort;
typedef enum ContainerStatus {
typedef enum LinkJournal {
} LinkJournal;
typedef enum Volatile {
} Volatile;
typedef enum CustomMountType {
typedef struct CustomMount {
bool read_only;
char *source; /* for overlayfs this is the upper directory */
char *destination;
char *options;
char *work_dir;
char **lower;
} CustomMount;
static char *arg_directory = NULL;
static char *arg_template = NULL;
static sd_id128_t arg_uuid = {};
static char *arg_machine = NULL;
static const char *arg_selinux_context = NULL;
static const char *arg_selinux_apifs_context = NULL;
static bool arg_private_network = false;
static bool arg_read_only = false;
static bool arg_boot = false;
static bool arg_ephemeral = false;
static bool arg_link_journal_try = 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) |
(1ULL << CAP_MKNOD);
static unsigned arg_n_custom_mounts = 0;
static char **arg_setenv = NULL;
static bool arg_quiet = false;
static bool arg_share_system = false;
static bool arg_register = true;
static bool arg_keep_unit = false;
static char **arg_network_interfaces = NULL;
static char **arg_network_macvlan = NULL;
static char **arg_network_ipvlan = NULL;
static bool arg_network_veth = false;
static const char *arg_network_bridge = NULL;
static unsigned long arg_personality = PERSONALITY_INVALID;
static char **arg_property = NULL;
static bool arg_userns = false;
static int arg_kill_signal = 0;
static bool arg_unified_cgroup_hierarchy = false;
static void 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"
" -q --quiet Do not show status information\n"
" -D --directory=PATH Root directory for the container\n"
" --template=PATH Initialize root directory from template directory,\n"
" if missing\n"
" -x --ephemeral Run container with snapshot of root directory, and\n"
" remove it after exit\n"
" -i --image=PATH File system device or disk image 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"
" -M --machine=NAME Set the machine name for the container\n"
" --uuid=UUID Set a specific machine UUID for the container\n"
" -S --slice=SLICE Place the container in the specified slice\n"
" --property=NAME=VALUE Set scope unit property\n"
" --private-users[=UIDBASE[:NUIDS]]\n"
" Run within user namespace\n"
" --private-network Disable network in container\n"
" --network-interface=INTERFACE\n"
" Assign an existing network interface to the\n"
" container\n"
" --network-macvlan=INTERFACE\n"
" Create a macvlan network interface based on an\n"
" existing network interface to the container\n"
" --network-ipvlan=INTERFACE\n"
" Create a ipvlan network interface based on an\n"
" existing network interface to the container\n"
" -n --network-veth Add a virtual ethernet connection between host\n"
" and container\n"
" --network-bridge=INTERFACE\n"
" Add a virtual ethernet connection between host\n"
" and container and add it to an existing bridge on\n"
" the host\n"
" -p --port=[PROTOCOL:]HOSTPORT[:CONTAINERPORT]\n"
" Expose a container IP port on the host\n"
" -Z --selinux-context=SECLABEL\n"
" Set the SELinux security context to be used by\n"
" processes in the container\n"
" -L --selinux-apifs-context=SECLABEL\n"
" Set the SELinux security context to be used by\n"
" --capability=CAP In addition to the default, retain specified\n"
" capability\n"
" --drop-capability=CAP Drop the specified capability from the default set\n"
" --kill-signal=SIGNAL Select signal to use for shutting down PID 1\n"
" --link-journal=MODE Link up guest journal, one of no, auto, guest, host,\n"
" try-guest, try-host\n"
" -j Equivalent to --link-journal=try-guest\n"
" --read-only Mount the root directory read-only\n"
" --bind=PATH[:PATH[:OPTIONS]]\n"
" Bind mount a file or directory from the host into\n"
" the container\n"
" --bind-ro=PATH[:PATH[:OPTIONS]\n"
" Similar, but creates a read-only bind mount\n"
" --tmpfs=PATH:[OPTIONS] Mount an empty tmpfs to the specified directory\n"
" --overlay=PATH[:PATH...]:PATH\n"
" Create an overlay mount from the host to \n"
" the container\n"
" --overlay-ro=PATH[:PATH...]:PATH\n"
" Similar, but creates a read-only overlay mount\n"
" --setenv=NAME=VALUE Pass an environment variable to PID 1\n"
" --share-system Share system namespaces with host\n"
" --register=BOOLEAN Register container as machine\n"
" --keep-unit Do not register a scope for the machine, reuse\n"
" the service unit nspawn is running in\n"
" --volatile[=MODE] Run the system in volatile mode\n"
}
CustomMount *c, *ret;
if (!c)
return NULL;
arg_custom_mounts = c;
return ret;
}
static void custom_mount_free_all(void) {
unsigned i;
for (i = 0; i < arg_n_custom_mounts; i++) {
CustomMount *m = &arg_custom_mounts[i];
free(m->destination);
if (m->work_dir) {
}
}
arg_n_custom_mounts = 0;
}
static int custom_mount_compare(const void *a, const void *b) {
const CustomMount *x = a, *y = b;
int r;
if (r != 0)
return r;
return -1;
return 1;
return 0;
}
static int custom_mounts_prepare(void) {
unsigned i;
int r;
/* Ensure the mounts are applied prefix first. */
/* Allocate working directories for the overlay file systems that need it */
for (i = 0; i < arg_n_custom_mounts; i++) {
CustomMount *m = &arg_custom_mounts[i];
log_error("--private-users with automatic UID shift may not be combined with custom root mounts.");
return -EINVAL;
}
if (m->type != CUSTOM_MOUNT_OVERLAY)
continue;
if (m->work_dir)
continue;
if (m->read_only)
continue;
if (r < 0)
}
return 0;
}
static int set_sanitized_path(char **b, const char *path) {
char *p;
assert(b);
p = canonicalize_file_name(path);
if (!p) {
return -errno;
p = path_make_absolute_cwd(path);
if (!p)
return -ENOMEM;
}
free(*b);
*b = path_kill_slashes(p);
return 0;
}
static int detect_unified_cgroup_hierarchy(void) {
const char *e;
int r;
/* Allow the user to control whether the unified hierarchy is used */
e = getenv("UNIFIED_CGROUP_HIERARCHY");
if (e) {
r = parse_boolean(e);
if (r < 0)
return log_error_errno(r, "Failed to parse $UNIFIED_CGROUP_HIERARCHY.");
return 0;
}
/* Otherwise inherit the default from the host system */
r = cg_unified();
if (r < 0)
return log_error_errno(r, "Failed to determine whether the unified cgroups hierarchy is used: %m");
return 0;
}
enum {
ARG_VERSION = 0x100,
};
{}
};
int c, r;
switch (c) {
case 'h':
help();
return 0;
case ARG_VERSION:
return 0;
case 'D':
if (r < 0)
return log_error_errno(r, "Invalid root directory: %m");
break;
case ARG_TEMPLATE:
if (r < 0)
return log_error_errno(r, "Invalid template directory: %m");
break;
case 'i':
if (r < 0)
return log_error_errno(r, "Invalid image path: %m");
break;
case 'x':
arg_ephemeral = true;
break;
case 'u':
if (r < 0)
return log_oom();
break;
case ARG_NETWORK_BRIDGE:
/* fall through */
case 'n':
arg_network_veth = true;
arg_private_network = true;
break;
case ARG_NETWORK_INTERFACE:
return log_oom();
arg_private_network = true;
break;
case ARG_NETWORK_MACVLAN:
return log_oom();
arg_private_network = true;
break;
case ARG_NETWORK_IPVLAN:
return log_oom();
/* fall through */
case ARG_PRIVATE_NETWORK:
arg_private_network = true;
break;
case 'b':
arg_boot = true;
break;
case ARG_UUID:
if (r < 0) {
return r;
}
break;
case 'S':
break;
case 'M':
else {
if (!machine_name_is_valid(optarg)) {
return -EINVAL;
}
if (r < 0)
return log_oom();
break;
}
case 'Z':
break;
case 'L':
break;
case ARG_READ_ONLY:
arg_read_only = true;
break;
case ARG_CAPABILITY:
case ARG_DROP_CAPABILITY: {
_cleanup_free_ char *t;
if (!t)
return log_oom();
if (streq(t, "all")) {
if (c == ARG_CAPABILITY)
else
} else {
int cap;
cap = capability_from_name(t);
if (cap < 0) {
log_error("Failed to parse capability %s.", t);
return -EINVAL;
}
if (c == ARG_CAPABILITY)
else
}
}
break;
}
case 'j':
arg_link_journal_try = true;
break;
case ARG_LINK_JOURNAL:
arg_link_journal_try = false;
arg_link_journal_try = false;
arg_link_journal_try = false;
arg_link_journal_try = false;
arg_link_journal_try = true;
arg_link_journal_try = true;
} else {
return -EINVAL;
}
break;
case ARG_BIND:
case ARG_BIND_RO: {
CustomMount *m;
r = extract_many_words(¤t, ":", EXTRACT_DONT_COALESCE_SEPARATORS, &source, &destination, &opts, NULL);
switch (r) {
case 1:
case 2:
case 3:
break;
case -ENOMEM:
return log_oom();
default:
return -EINVAL;
}
if (!source || !destination)
return log_oom();
return -EINVAL;
}
if (!m)
return log_oom();
m->destination = destination;
m->read_only = c == ARG_BIND_RO;
break;
}
case ARG_TMPFS: {
CustomMount *m;
if (r == -ENOMEM)
return log_oom();
else if (r < 0) {
return r;
}
if (r)
else
return log_oom();
if (!path_is_absolute(path)) {
return -EINVAL;
}
if (!m)
return log_oom();
m->destination = path;
break;
}
case ARG_OVERLAY:
case ARG_OVERLAY_RO: {
CustomMount *m;
unsigned n = 0;
char **i;
if (r == -ENOMEM)
return log_oom();
else if (r < 0) {
return r;
}
STRV_FOREACH(i, lower) {
if (!path_is_absolute(*i)) {
log_error("Overlay path %s is not absolute.", *i);
return -EINVAL;
}
n++;
}
if (n < 2) {
log_error("--overlay= needs at least two colon-separated directories specified.");
return -EINVAL;
}
if (n == 2) {
/* If two parameters are specified,
* the first one is the lower, the
* second one the upper directory. And
* we'll also define the destination
* mount point the same as the upper. */
if (!destination)
return log_oom();
} else {
}
if (!m)
return log_oom();
m->destination = destination;
m->read_only = c == ARG_OVERLAY_RO;
break;
}
case ARG_SETENV: {
char **n;
if (!env_assignment_is_valid(optarg)) {
return -EINVAL;
}
if (!n)
return log_oom();
arg_setenv = n;
break;
}
case 'q':
arg_quiet = true;
break;
case ARG_SHARE_SYSTEM:
arg_share_system = true;
break;
case ARG_REGISTER:
r = parse_boolean(optarg);
if (r < 0) {
return r;
}
arg_register = r;
break;
case ARG_KEEP_UNIT:
arg_keep_unit = true;
break;
case ARG_PERSONALITY:
if (arg_personality == PERSONALITY_INVALID) {
return -EINVAL;
}
break;
case ARG_VOLATILE:
if (!optarg)
else {
r = parse_boolean(optarg);
if (r < 0) {
else {
return r;
}
} else
}
break;
case 'p': {
const char *split, *e;
int protocol;
ExposePort *p;
else {
e = optarg;
}
if (split) {
char v[split - e + 1];
v[split - e] = 0;
r = safe_atou16(v, &host_port);
if (r < 0 || host_port <= 0) {
return -EINVAL;
}
} else {
r = safe_atou16(e, &container_port);
}
if (r < 0 || container_port <= 0) {
return -EINVAL;
}
return -EINVAL;
}
}
if (!p)
return log_oom();
p->container_port = container_port;
break;
}
case ARG_PROPERTY:
return log_oom();
break;
case ARG_PRIVATE_USERS:
if (optarg) {
if (range) {
if (!buffer)
return log_oom();
range++;
return -EINVAL;
}
} else
return -EINVAL;
}
}
arg_userns = true;
break;
case ARG_KILL_SIGNAL:
if (arg_kill_signal < 0) {
return -EINVAL;
}
break;
case '?':
return -EINVAL;
default:
assert_not_reached("Unhandled option");
}
if (arg_share_system)
arg_register = false;
if (arg_boot && arg_share_system) {
log_error("--boot and --share-system may not be combined.");
return -EINVAL;
}
log_error("--keep-unit may not be used when invoked from a user session.");
return -EINVAL;
}
if (arg_directory && arg_image) {
log_error("--directory= and --image= may not be combined.");
return -EINVAL;
}
if (arg_template && arg_image) {
log_error("--template= and --image= may not be combined.");
return -EINVAL;
}
log_error("--template= needs --directory= or --machine=.");
return -EINVAL;
}
if (arg_ephemeral && arg_template) {
log_error("--ephemeral and --template= may not be combined.");
return -EINVAL;
}
if (arg_ephemeral && arg_image) {
log_error("--ephemeral and --image= may not be combined.");
return -EINVAL;
}
log_error("--ephemeral and --link-journal= may not be combined.");
return -EINVAL;
}
log_error("Cannot combine --read-only with --volatile. Note that --volatile already implies a read-only base hierarchy.");
return -EINVAL;
}
if (arg_expose_ports && !arg_private_network) {
log_error("Cannot use --port= without private networking.");
return -EINVAL;
}
return log_error_errno(EOPNOTSUPP, "--private-users= is not supported, kernel compiled without user namespace support.");
if (arg_boot && arg_kill_signal <= 0)
if (r < 0)
return r;
return 1;
}
if (arg_userns && arg_uid_shift != 0) {
if (options)
else
if (!buf)
return -ENOMEM;
}
#ifdef HAVE_SELINUX
if (arg_selinux_apifs_context) {
char *t;
if (options)
else
if (!t) {
return -ENOMEM;
}
buf = t;
}
#endif
return !!buf;
}
typedef struct MountPoint {
const char *what;
const char *where;
const char *type;
const char *options;
unsigned long flags;
bool fatal;
bool userns;
} MountPoint;
static const MountPoint mount_table[] = {
{ NULL, "/proc/sys", NULL, NULL, MS_BIND|MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_REMOUNT, true, true }, /* Then, make it r/o */
#ifdef HAVE_SELINUX
{ NULL, "/sys/fs/selinux", NULL, NULL, MS_BIND|MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_REMOUNT, false, false }, /* Then, make it r/o */
#endif
};
unsigned k;
int r;
for (k = 0; k < ELEMENTSOF(mount_table); k++) {
const char *o;
continue;
if (!where)
return log_oom();
if (r < 0 && r != -ENOENT)
/* Skip this entry if it is not a remount. */
if (mount_table[k].what && r > 0)
continue;
if (r < 0) {
if (mount_table[k].fatal)
continue;
}
o = mount_table[k].options;
r = tmpfs_patch_options(o, &options);
if (r < 0)
return log_oom();
if (r > 0)
o = options;
}
mount_table[k].type,
mount_table[k].flags,
o) < 0) {
if (mount_table[k].fatal)
}
}
return 0;
}
static int parse_mount_bind_options(const char *options, unsigned long *mount_flags, char **mount_opts) {
const char *p = options;
unsigned long flags = *mount_flags;
for (;;) {
if (r < 0)
return log_error_errno(r, "Failed to extract mount option: %m");
if (r == 0)
break;
else {
return -EINVAL;
}
}
*mount_flags = flags;
/* in the future mount_opts will hold string options for mount(2) */
*mount_opts = opts;
return 0;
}
const char *where;
int r;
assert(m);
if (m->options) {
if (r < 0)
return r;
}
return -EINVAL;
}
return -EINVAL;
}
if (r < 0)
} else {
return -errno;
}
/* Create the mount point. Any non-directory file can be
* mounted on any non-directory file (regular, fifo, socket,
* char, block).
*/
else
if (r < 0 && r != -EEXIST)
if (m->read_only) {
r = bind_remount_recursive(where, true);
if (r < 0)
return log_error_errno(r, "Read-only bind mount failed: %m");
}
return 0;
}
int r;
assert(m);
if (r < 0 && r != -EEXIST)
if (r < 0)
return log_oom();
return 0;
}
static char *joined_and_escaped_lower_dirs(char * const *lower) {
if (!sv)
return NULL;
return NULL;
}
int r;
assert(m);
if (r < 0 && r != -EEXIST)
if (!lower)
return log_oom();
if (m->read_only) {
if (!escaped_source)
return log_oom();
} else {
if (!escaped_source)
return log_oom();
if (!escaped_work_dir)
return log_oom();
options = strjoina("lowerdir=", lower, ",upperdir=", escaped_source, ",workdir=", escaped_work_dir);
}
return 0;
}
static int mount_custom(const char *dest) {
unsigned i;
int r;
for (i = 0; i < arg_n_custom_mounts; i++) {
CustomMount *m = &arg_custom_mounts[i];
switch (m->type) {
case CUSTOM_MOUNT_BIND:
r = mount_bind(dest, m);
break;
case CUSTOM_MOUNT_TMPFS:
r = mount_tmpfs(dest, m);
break;
case CUSTOM_MOUNT_OVERLAY:
r = mount_overlay(dest, m);
break;
default:
assert_not_reached("Unknown custom mount type");
}
if (r < 0)
return r;
}
return 0;
}
static int mount_legacy_cgroup_hierarchy(const char *dest, const char *controller, const char *hierarchy, bool read_only) {
char *to;
int r;
r = path_is_mount_point(to, 0);
if (r < 0 && r != -ENOENT)
if (r > 0)
return 0;
/* The superblock mount options of the mount point need to be
* identical to the hosts', and hence writable... */
/* ... hence let's only make the bind mount read-only, not the
* superblock. */
if (read_only) {
}
return 1;
}
static int mount_legacy_cgroups(const char *dest) {
const char *cgroup_root;
int r;
if (r < 0)
return log_error_errno(r, "Failed to determine if /sys/fs/cgroup is already mounted: %m");
if (r == 0) {
if (r < 0)
return log_oom();
}
if (cg_unified() > 0)
goto skip_controllers;
if (!controllers)
return log_oom();
if (r < 0)
return log_error_errno(r, "Failed to determine cgroup controllers: %m");
for (;;) {
if (!controller)
break;
if (!origin)
return log_oom();
if (r == -EINVAL) {
/* Not a symbolic link, but directly a single cgroup hierarchy */
if (r < 0)
return r;
} else if (r < 0)
else {
if (!target)
return log_oom();
/* A symbolic link, a combination of controllers in one hierarchy */
if (!filename_is_valid(combined)) {
continue;
}
if (r < 0)
return r;
if (r == -EINVAL) {
log_error("Invalid existing symlink for combined hierarchy");
return r;
}
if (r < 0)
return log_error_errno(r, "Failed to create symlink for combined hierarchy: %m");
}
}
if (r < 0)
return r;
if (mount(NULL, cgroup_root, NULL, MS_REMOUNT|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_STRICTATIME|MS_RDONLY, "mode=755") < 0)
return 0;
}
static int mount_unified_cgroups(const char *dest) {
const char *p;
int r;
r = path_is_mount_point(p, AT_SYMLINK_FOLLOW);
if (r < 0)
return log_error_errno(r, "Failed to determine if %s is mounted already: %m", p);
if (r > 0) {
return 0;
return log_error_errno(errno, "Failed to determine if mount point %s contains the unified cgroup hierarchy: %m", p);
log_error("%s is already mounted but not a unified cgroup hierarchy. Refusing.", p);
return -EINVAL;
}
return 0;
}
static int mount_cgroups(const char *dest) {
return mount_unified_cgroups(dest);
else
return mount_legacy_cgroups(dest);
}
static int mount_systemd_cgroup_writable(const char *dest) {
const char *systemd_root, *systemd_own;
int r;
if (r < 0)
return log_error_errno(r, "Failed to determine our own cgroup path: %m");
/* If we are living in the top-level, then there's nothing to do... */
return 0;
if (arg_unified_cgroup_hierarchy) {
} else {
}
/* Make our own cgroup a (writable) bind mount */
/* And then remount the systemd cgroup root read-only */
if (mount(NULL, systemd_root, NULL, MS_BIND|MS_REMOUNT|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_RDONLY, NULL) < 0)
return 0;
}
assert(p);
if (!arg_userns)
return 0;
return 0;
if (uid != UID_INVALID) {
uid += arg_uid_shift;
return -EOVERFLOW;
}
if (gid != GID_INVALID) {
return -EOVERFLOW;
}
return -errno;
return 0;
}
const char *q;
return 0;
return -errno;
}
}
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;
}
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;
}
log_warning("Timezone %s does not exist in container, not updating container timezone.", z);
return 0;
}
return 0;
}
return 0;
}
r = userns_lchown(where, 0, 0);
if (r < 0)
return log_warning_errno(r, "Failed to chown /etc/localtime: %m");
return 0;
}
static int setup_resolv_conf(const char *dest) {
int r;
if (arg_private_network)
return 0;
/* Fix resolv.conf, if possible */
if (r < 0) {
/* If the file already exists as symlink, let's
* suppress the warning, under the assumption that
* resolved or something similar runs inside and the
* symlink points there.
*
* If the disk image is read-only, there's also no
* point in complaining.
*/
"Failed to copy /etc/resolv.conf to %s: %m", where);
return 0;
}
r = userns_lchown(where, 0, 0);
if (r < 0)
log_warning_errno(r, "Failed to chown /etc/resolv.conf: %m");
return 0;
}
static int setup_volatile_state(const char *directory) {
const char *p, *options;
int r;
if (arg_volatile != VOLATILE_STATE)
return 0;
/* --volatile=state means we simply overmount /var
with a tmpfs, and the rest read-only. */
r = bind_remount_recursive(directory, true);
if (r < 0)
r = mkdir(p, 0755);
options = "mode=755";
if (r < 0)
return log_oom();
if (r > 0)
return 0;
}
static int setup_volatile(const char *directory) {
bool tmpfs_mounted = false, bind_mounted = false;
char template[] = "/tmp/nspawn-volatile-XXXXXX";
const char *f, *t, *options;
int r;
if (arg_volatile != VOLATILE_YES)
return 0;
/* --volatile=yes means we mount a tmpfs to the root dir, and
the original /usr to use inside it, and that read-only. */
options = "mode=755";
if (r < 0)
return log_oom();
if (r > 0)
goto fail;
}
tmpfs_mounted = true;
r = mkdir(t, 0755);
goto fail;
}
goto fail;
}
bind_mounted = true;
r = bind_remount_recursive(t, true);
if (r < 0) {
log_error_errno(r, "Failed to remount %s read-only: %m", t);
goto fail;
}
goto fail;
}
return 0;
fail:
if (bind_mounted)
(void) umount(t);
if (tmpfs_mounted)
return r;
}
assert(s);
snprintf(s, 37,
"%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
return s;
}
static int setup_boot_id(const char *dest) {
sd_id128_t rnd = {};
char as_uuid[37];
int r;
if (arg_share_system)
return 0;
/* Generate a new randomized boot ID, so that each boot-up of
* the container gets a new one */
r = sd_id128_randomize(&rnd);
if (r < 0)
return log_error_errno(r, "Failed to generate random boot id: %m");
if (r < 0)
return log_error_errno(r, "Failed to write boot id: %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);
return log_error_errno(r, "Failed to create /dev/net directory: %m");
NULSTR_FOREACH(d, devnodes) {
return -EIO;
} else {
/* Some systems abusively restrict mknod but
* allow bind mounts. */
if (r < 0)
}
r = userns_lchown(to, 0, 0);
if (r < 0)
}
}
return r;
}
const char *p;
#ifdef HAVE_SELINUX
else
#endif
"newinstance,ptmxmode=0666,mode=620,gid=" GID_FMT,
arg_uid_shift + TTY_GID);
if (!options)
return log_oom();
if (mkdir(p, 0755) < 0)
if (userns_lchown(p, 0, 0) < 0)
if (userns_lchown(p, 0, 0) < 0)
if (userns_lchown(p, 0, 0) < 0)
return 0;
}
const char *to;
int r;
u = umask(0000);
if (r < 0)
return log_error_errno(r, "Failed to correct access mode for TTY: %m");
* ptys can only exist on pts file systems. To have something
* to bind mount things on we create a empty regular file. */
if (r < 0)
return log_error_errno(r, "touch() for /dev/console failed: %m");
return 0;
}
int 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
if (fd < 0)
/* Store away the fd in the socket, so that it stays open as
* long as we run the child */
safe_close(fd);
if (k < 0)
return 0;
}
union {
} control = {};
.msg_control = &control,
.msg_controllen = sizeof(control),
};
ssize_t k;
if (!arg_expose_ports)
return 0;
if (fd < 0)
/* Store away the fd in the socket, so that it stays open as
* long as we run the child */
if (k < 0)
return 0;
}
ExposePort *p;
if (!arg_expose_ports)
return 0;
return 0;
log_debug("Lost IP address.");
r = fw_add_local_dnat(false,
af,
p->protocol,
NULL,
NULL, 0,
NULL, 0,
p->host_port,
p->container_port,
NULL);
if (r < 0)
log_warning_errno(r, "Failed to modify firewall: %m");
}
*exposed = IN_ADDR_NULL;
return 0;
}
union in_addr_union new_exposed;
ExposePort *p;
bool add;
/* Invoked each time an address is added or removed inside the
* container */
if (!arg_expose_ports)
return 0;
if (r < 0)
return log_error_errno(r, "Failed to enumerate local addresses: %m");
add = r > 0 &&
if (!add)
return flush_ports(exposed);
return 0;
r = fw_add_local_dnat(true,
af,
p->protocol,
NULL,
NULL, 0,
NULL, 0,
p->host_port,
p->container_port,
if (r < 0)
log_warning_errno(r, "Failed to modify firewall: %m");
}
*exposed = new_exposed;
return 0;
}
assert(m);
return 0;
}
static int watch_rtnl(sd_event *event, int recv_fd, union in_addr_union *exposed, sd_netlink **ret) {
union {
} control = {};
.msg_control = &control,
.msg_controllen = sizeof(control),
};
int fd, r;
ssize_t k;
if (!arg_expose_ports)
return 0;
if (k < 0)
if (r < 0) {
safe_close(fd);
return log_error_errno(r, "Failed to create rtnl object: %m");
}
if (r < 0)
return log_error_errno(r, "Failed to subscribe to RTM_NEWADDR messages: %m");
if (r < 0)
return log_error_errno(r, "Failed to subscribe to RTM_DELADDR messages: %m");
if (r < 0)
return log_error_errno(r, "Failed to add to even loop: %m");
return 0;
}
static int setup_hostname(void) {
if (arg_share_system)
return 0;
if (sethostname_idempotent(arg_machine) < 0)
return -errno;
return 0;
}
static int setup_journal(const char *directory) {
const char *etc_machine_id, *p, *q;
char *id;
int r;
/* Don't link journals in ephemeral mode */
if (arg_ephemeral)
return 0;
r = read_one_line_file(etc_machine_id, &b);
return 0;
else if (r < 0)
return 0;
/* Verify validity */
if (r < 0)
r = sd_id128_get_machine(&this_id);
if (r < 0)
return log_error_errno(r, "Failed to retrieve machine ID: %m");
"Host and machine ids are equal (%s): refusing to link journals", id);
if (arg_link_journal == LINK_AUTO)
return 0;
return -EEXIST;
}
if (arg_link_journal == LINK_NO)
return 0;
if (r < 0)
return log_error_errno(r, "Failed to create /var: %m");
if (r < 0)
return log_error_errno(r, "Failed to create /var/log: %m");
if (r < 0)
return log_error_errno(r, "Failed to create /var/log/journal: %m");
q = prefix_roota(directory, p);
if (path_is_mount_point(p, 0) > 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, 0) > 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)) {
if (r < 0)
return 0;
}
if (unlink(p) < 0)
} 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 {
return -errno;
}
}
} else if (r != -ENOENT) {
return r;
}
if (arg_link_journal == LINK_GUEST) {
if (symlink(q, p) < 0) {
if (arg_link_journal_try) {
return 0;
} else {
return -errno;
}
}
if (r < 0)
return 0;
}
if (arg_link_journal == LINK_HOST) {
/* don't create parents here -- if the host doesn't have
* permanent journal set up, don't force it here */
r = mkdir(p, 0755);
if (r < 0) {
if (arg_link_journal_try) {
return 0;
} else {
return r;
}
}
return 0;
if (dir_is_empty(q) == 0)
log_warning("%s is not empty, proceeding anyway.", q);
if (r < 0) {
return r;
}
return 0;
}
static int drop_capabilities(void) {
return capability_bounding_set_drop(~arg_retain, false);
}
int r;
if (!arg_register)
return 0;
r = sd_bus_default_system(&bus);
if (r < 0)
return log_error_errno(r, "Failed to open system bus: %m");
if (arg_keep_unit) {
r = sd_bus_call_method(
bus,
"org.freedesktop.machine1",
"/org/freedesktop/machine1",
"org.freedesktop.machine1.Manager",
"RegisterMachineWithNetwork",
&error,
NULL,
"sayssusai",
"nspawn",
"container",
} else {
char **i;
unsigned j;
bus,
&m,
"org.freedesktop.machine1",
"/org/freedesktop/machine1",
"org.freedesktop.machine1.Manager",
"CreateMachineWithNetwork");
if (r < 0)
return bus_log_create_error(r);
m,
"sayssusai",
"nspawn",
"container",
if (r < 0)
return bus_log_create_error(r);
if (r < 0)
return bus_log_create_error(r);
if (r < 0)
return bus_log_create_error(r);
}
if (r < 0)
return bus_log_create_error(r);
/* If you make changes here, also make sure to update
* systemd-nspawn@.service, to keep the device
* policies in sync regardless if we are run with or
* without the --keep-unit switch. */
/* Allow the container to
* access and create the API
* device nodes, so that
* PrivateDevices= in the
* container can work
* fine */
/* Allow the container
* access to ptys. However,
* do not permit the
* container to ever create
* these device nodes. */
"char-pts", "rw");
if (r < 0)
return bus_log_create_error(r);
for (j = 0; j < arg_n_custom_mounts; j++) {
continue;
if (r < 0)
if (r) {
if (r < 0)
return log_error_errno(r, "Failed to append message arguments: %m");
}
}
if (arg_kill_signal != 0) {
if (r < 0)
return bus_log_create_error(r);
if (r < 0)
return bus_log_create_error(r);
}
STRV_FOREACH(i, arg_property) {
if (r < 0)
return bus_log_create_error(r);
r = bus_append_unit_property_assignment(m, *i);
if (r < 0)
return r;
r = sd_bus_message_close_container(m);
if (r < 0)
return bus_log_create_error(r);
}
r = sd_bus_message_close_container(m);
if (r < 0)
return bus_log_create_error(r);
}
if (r < 0) {
return r;
}
return 0;
}
const char *path;
int r;
if (!arg_register)
return 0;
/* If we are reusing the unit, then just exit, systemd will do
* the right thing when we exit. */
if (arg_keep_unit)
return 0;
r = sd_bus_default_system(&bus);
if (r < 0)
return log_error_errno(r, "Failed to open system bus: %m");
r = sd_bus_call_method(
bus,
"org.freedesktop.machine1",
"/org/freedesktop/machine1",
"org.freedesktop.machine1.Manager",
"GetMachineByPID",
&error,
&reply,
"u",
if (r < 0) {
/* Note that the machine might already have been
* cleaned up automatically, hence don't consider it a
* failure if we cannot get the machine object. */
return 0;
}
if (r < 0)
return bus_log_parse_error(r);
r = sd_bus_call_method(
bus,
"org.freedesktop.machine1",
path,
"org.freedesktop.machine1.Machine",
"Terminate",
&error,
NULL,
NULL);
if (r < 0) {
return 0;
}
return 0;
}
static int reset_audit_loginuid(void) {
_cleanup_free_ char *p = NULL;
int r;
if (arg_share_system)
return 0;
r = read_one_line_file("/proc/self/loginuid", &p);
if (r == -ENOENT)
return 0;
if (r < 0)
return log_error_errno(r, "Failed to read /proc/self/loginuid: %m");
/* Already reset? */
if (streq(p, "4294967295"))
return 0;
if (r < 0) {
"Failed to reset audit login UID. This probably means that your kernel is too\n"
"old and you have audit enabled. Note that the auditing subsystem is known to\n"
"be incompatible with containers on old kernels. Please make sure to upgrade\n"
"your kernel or to off auditing with 'audit=0' on the kernel command line before\n"
"using systemd-nspawn. Sleeping for 5s... (%m)");
sleep(5);
}
return 0;
}
uint8_t *v, *i;
int r;
l = strlen(arg_machine);
sz = sizeof(sd_id128_t) + l;
if (idx > 0)
/* fetch some persistent data unique to the host */
r = sd_id128_get_machine((sd_id128_t*) v);
if (r < 0)
return r;
/* combine with some data unique (on this host) to this
* container instance */
if (idx > 0) {
}
/* Let's hash the host machine ID plus the container name. We
* use a fixed, but originally randomly created hash key here. */
/* see eth_random_addr in the kernel */
return 0;
}
int r, i;
if (!arg_private_network)
return 0;
if (!arg_network_veth)
return 0;
/* Use two different interface name prefixes depending whether
* we are in bridge mode or not. */
if (r < 0)
return log_error_errno(r, "Failed to generate predictable MAC address for container side: %m");
if (r < 0)
return log_error_errno(r, "Failed to generate predictable MAC address for host side: %m");
r = sd_netlink_open(&rtnl);
if (r < 0)
return log_error_errno(r, "Failed to connect to netlink: %m");
if (r < 0)
return log_error_errno(r, "Failed to allocate netlink message: %m");
if (r < 0)
return log_error_errno(r, "Failed to add netlink interface name: %m");
if (r < 0)
return log_error_errno(r, "Failed to add netlink MAC address: %m");
if (r < 0)
return log_error_errno(r, "Failed to open netlink container: %m");
if (r < 0)
return log_error_errno(r, "Failed to open netlink container: %m");
if (r < 0)
return log_error_errno(r, "Failed to open netlink container: %m");
if (r < 0)
return log_error_errno(r, "Failed to add netlink interface name: %m");
if (r < 0)
return log_error_errno(r, "Failed to add netlink MAC address: %m");
if (r < 0)
return log_error_errno(r, "Failed to add netlink namespace field: %m");
if (r < 0)
return log_error_errno(r, "Failed to close netlink container: %m");
if (r < 0)
return log_error_errno(r, "Failed to close netlink container: %m");
if (r < 0)
return log_error_errno(r, "Failed to close netlink container: %m");
if (r < 0)
i = (int) if_nametoindex(iface_name);
if (i <= 0)
*ifi = i;
return 0;
}
int r, bridge;
if (!arg_private_network)
return 0;
if (!arg_network_veth)
return 0;
if (!arg_network_bridge)
return 0;
if (bridge <= 0)
r = sd_netlink_open(&rtnl);
if (r < 0)
return log_error_errno(r, "Failed to connect to netlink: %m");
if (r < 0)
return log_error_errno(r, "Failed to allocate netlink message: %m");
if (r < 0)
return log_error_errno(r, "Failed to set IFF_UP flag: %m");
if (r < 0)
return log_error_errno(r, "Failed to add netlink interface name field: %m");
if (r < 0)
return log_error_errno(r, "Failed to add netlink master field: %m");
if (r < 0)
return log_error_errno(r, "Failed to add veth interface to bridge: %m");
return 0;
}
int ifi;
if (ifi <= 0)
if (!d)
if (udev_device_get_is_initialized(d) <= 0) {
return -EBUSY;
}
return ifi;
}
char **i;
int r;
if (!arg_private_network)
return 0;
return 0;
r = sd_netlink_open(&rtnl);
if (r < 0)
return log_error_errno(r, "Failed to connect to netlink: %m");
if (!udev) {
log_error("Failed to connect to udev.");
return -ENOMEM;
}
int ifi;
if (ifi < 0)
return ifi;
if (r < 0)
return log_error_errno(r, "Failed to allocate netlink message: %m");
if (r < 0)
return log_error_errno(r, "Failed to append namespace PID to netlink message: %m");
if (r < 0)
return log_error_errno(r, "Failed to move interface %s to namespace: %m", *i);
}
return 0;
}
unsigned idx = 0;
char **i;
int r;
if (!arg_private_network)
return 0;
return 0;
r = sd_netlink_open(&rtnl);
if (r < 0)
return log_error_errno(r, "Failed to connect to netlink: %m");
if (!udev) {
log_error("Failed to connect to udev.");
return -ENOMEM;
}
_cleanup_free_ char *n = NULL;
struct ether_addr mac;
int ifi;
if (ifi < 0)
return ifi;
if (r < 0)
return log_error_errno(r, "Failed to create MACVLAN MAC address: %m");
if (r < 0)
return log_error_errno(r, "Failed to allocate netlink message: %m");
if (r < 0)
return log_error_errno(r, "Failed to add netlink interface index: %m");
n = strappend("mv-", *i);
if (!n)
return log_oom();
r = sd_netlink_message_append_string(m, IFLA_IFNAME, n);
if (r < 0)
return log_error_errno(r, "Failed to add netlink interface name: %m");
if (r < 0)
return log_error_errno(r, "Failed to add netlink MAC address: %m");
if (r < 0)
return log_error_errno(r, "Failed to add netlink namespace field: %m");
if (r < 0)
return log_error_errno(r, "Failed to open netlink container: %m");
if (r < 0)
return log_error_errno(r, "Failed to open netlink container: %m");
if (r < 0)
return log_error_errno(r, "Failed to append macvlan mode: %m");
if (r < 0)
return log_error_errno(r, "Failed to close netlink container: %m");
if (r < 0)
return log_error_errno(r, "Failed to close netlink container: %m");
if (r < 0)
return log_error_errno(r, "Failed to add new macvlan interfaces: %m");
}
return 0;
}
char **i;
int r;
if (!arg_private_network)
return 0;
return 0;
r = sd_netlink_open(&rtnl);
if (r < 0)
return log_error_errno(r, "Failed to connect to netlink: %m");
if (!udev) {
log_error("Failed to connect to udev.");
return -ENOMEM;
}
_cleanup_free_ char *n = NULL;
int ifi;
if (ifi < 0)
return ifi;
if (r < 0)
return log_error_errno(r, "Failed to allocate netlink message: %m");
if (r < 0)
return log_error_errno(r, "Failed to add netlink interface index: %m");
n = strappend("iv-", *i);
if (!n)
return log_oom();
r = sd_netlink_message_append_string(m, IFLA_IFNAME, n);
if (r < 0)
return log_error_errno(r, "Failed to add netlink interface name: %m");
if (r < 0)
return log_error_errno(r, "Failed to add netlink namespace field: %m");
if (r < 0)
return log_error_errno(r, "Failed to open netlink container: %m");
if (r < 0)
return log_error_errno(r, "Failed to open netlink container: %m");
if (r < 0)
return log_error_errno(r, "Failed to add ipvlan mode: %m");
if (r < 0)
return log_error_errno(r, "Failed to close netlink container: %m");
if (r < 0)
return log_error_errno(r, "Failed to close netlink container: %m");
if (r < 0)
return log_error_errno(r, "Failed to add new ipvlan interfaces: %m");
}
return 0;
}
static int setup_seccomp(void) {
#ifdef HAVE_SECCOMP
static const struct {
int syscall_num;
} blacklist[] = {
};
unsigned i;
int r;
if (!seccomp)
return log_oom();
if (r < 0) {
log_error_errno(r, "Failed to add secondary archs to seccomp filter: %m");
goto finish;
}
for (i = 0; i < ELEMENTSOF(blacklist); i++) {
continue;
if (r == -EFAULT)
continue; /* unknown syscall */
if (r < 0) {
log_error_errno(r, "Failed to block syscall: %m");
goto finish;
}
}
/*
Audit is broken in containers, much of the userspace audit
hookup will fail if running inside a container. We don't
care and just turn off creation of audit sockets.
This will make socket(AF_NETLINK, *, NETLINK_AUDIT) fail
with EAFNOSUPPORT which audit userspace uses as indication
that audit is disabled in the kernel.
*/
r = seccomp_rule_add(
2,
if (r < 0) {
log_error_errno(r, "Failed to add audit seccomp rule: %m");
goto finish;
}
if (r < 0) {
log_error_errno(r, "Failed to unset NO_NEW_PRIVS: %m");
goto finish;
}
r = seccomp_load(seccomp);
if (r == -EINVAL) {
log_debug_errno(r, "Kernel is probably not configured with CONFIG_SECCOMP. Disabling seccomp audit filter: %m");
r = 0;
goto finish;
}
if (r < 0) {
log_error_errno(r, "Failed to install seccomp audit filter: %m");
goto finish;
}
return r;
#else
return 0;
#endif
}
static int setup_propagate(const char *root) {
const char *p, *q;
(void) mkdir_p(p, 0600);
return 0;
}
struct loop_info64 info = {
};
int r, nr;
if (fd < 0)
char *p;
if (!p)
return log_oom();
*device_path = p;
*loop_nr = -1;
r = fd;
fd = -1;
return r;
}
return -EINVAL;
}
if (control < 0)
if (nr < 0)
return log_oom();
if (loop < 0)
if (arg_read_only)
*device_path = loopdev;
r = loop;
loop = -1;
return r;
}
#define PARTITION_TABLE_BLURB \
"Note that the disk image needs to either contain only a single MBR partition of\n" \
"type 0x83 that is marked bootable, or a single GPT partition of type " \
"0FC63DAF-8483-4772-8E79-3D69D8477DE4 or follow\n" \
"to be bootable with systemd-nspawn."
static int dissect_image(
int fd,
char **root_device, bool *root_device_rw,
char **home_device, bool *home_device_rw,
char **srv_device, bool *srv_device_rw,
bool *secondary) {
#ifdef HAVE_BLKID
#ifdef GPT_ROOT_NATIVE
int root_nr = -1;
#endif
#ifdef GPT_ROOT_SECONDARY
int secondary_root_nr = -1;
#endif
_cleanup_free_ char *home = NULL, *root = NULL, *secondary_root = NULL, *srv = NULL, *generic = NULL;
unsigned i;
int r;
b = blkid_new_probe();
if (!b)
return log_oom();
errno = 0;
r = blkid_probe_set_device(b, fd, 0, 0);
if (r != 0) {
if (errno == 0)
return log_oom();
return -errno;
}
errno = 0;
r = blkid_do_safeprobe(b);
if (r == -2 || r == 1) {
log_error("Failed to identify any partition table on\n"
" %s\n"
return -EINVAL;
} else if (r != 0) {
if (errno == 0)
return -errno;
}
log_error("No GPT or MBR partition table discovered on\n"
" %s\n"
return -EINVAL;
}
errno = 0;
pl = blkid_probe_get_partitions(b);
if (!pl) {
if (errno == 0)
return log_oom();
return -errno;
}
if (!udev)
return log_oom();
if (!d)
return log_oom();
for (i = 0;; i++) {
int n, m;
if (i >= 10) {
log_error("Kernel partitions never appeared.");
return -ENXIO;
}
e = udev_enumerate_new(udev);
if (!e)
return log_oom();
r = udev_enumerate_add_match_parent(e, d);
if (r < 0)
return log_oom();
r = udev_enumerate_scan_devices(e);
if (r < 0)
/* Count the partitions enumerated by the kernel */
n = 0;
n++;
/* Count the partitions enumerated by blkid */
if (n == m + 1)
break;
if (n > m + 1) {
log_error("blkid and kernel partition list do not match.");
return -EIO;
}
if (n < m + 1) {
unsigned j;
/* The kernel has probed fewer partitions than
* blkid? Maybe the kernel prober is still
* running or it got EBUSY because udev
* already opened the device. Let's reprobe
* the device, which is a synchronous call
* that waits until probing is complete. */
for (j = 0; j < 20; j++) {
if (r < 0)
r = -errno;
if (r >= 0 || r != -EBUSY)
break;
/* If something else has the device
* open, such as an udev rule, the
* ioctl will return EBUSY. Since
* there's no way to wait until it
* isn't busy anymore, let's just wait
* a bit, and try again.
*
* This is really something they
* should fix in the kernel! */
}
if (r < 0)
return log_error_errno(r, "Failed to reread partition table: %m");
}
e = udev_enumerate_unref(e);
}
_cleanup_udev_device_unref_ struct udev_device *q;
const char *node;
unsigned long long flags;
int nr;
errno = 0;
if (!q) {
if (!errno)
return -errno;
}
qn = udev_device_get_devnum(q);
continue;
continue;
node = udev_device_get_devnode(q);
if (!node)
continue;
if (!pp)
continue;
if (nr < 0)
continue;
if (is_gpt) {
const char *stype;
if (flags & GPT_FLAG_NO_AUTO)
continue;
if (!stype)
continue;
continue;
continue;
if (r < 0)
return log_oom();
continue;
if (r < 0)
return log_oom();
}
#ifdef GPT_ROOT_NATIVE
continue;
if (r < 0)
return log_oom();
}
#endif
#ifdef GPT_ROOT_SECONDARY
continue;
if (r < 0)
return log_oom();
}
#endif
if (generic)
multiple_generic = true;
else {
if (r < 0)
return log_oom();
}
}
} else if (is_mbr) {
int type;
continue;
continue;
if (generic)
multiple_generic = true;
else {
generic_rw = true;
if (r < 0)
return log_oom();
}
}
}
if (root) {
*root_device = root;
*secondary = false;
} else if (secondary_root) {
*secondary = true;
} else if (generic) {
/* There were no partitions with precise meanings
* around, but we found generic partitions. In this
* case, if there's only one, we can go ahead and boot
* it, otherwise we bail out, because we really cannot
* make any sense of it. */
if (multiple_generic) {
log_error("Identified multiple bootable Linux partitions on\n"
" %s\n"
return -EINVAL;
}
*root_device = generic;
*secondary = false;
} else {
log_error("Failed to identify root partition in disk image\n"
" %s\n"
return -EINVAL;
}
if (home) {
*home_device = home;
}
if (srv) {
*srv_device = srv;
*srv_device_rw = srv_rw;
}
return 0;
#else
log_error("--image= is not supported, compiled without blkid support.");
return -EOPNOTSUPP;
#endif
}
#ifdef HAVE_BLKID
const char *fstype, *p;
int r;
if (arg_read_only)
rw = false;
if (directory)
else
p = where;
errno = 0;
if (!b) {
if (errno == 0)
return log_oom();
return -errno;
}
errno = 0;
r = blkid_do_safeprobe(b);
if (r == -1 || r == 1) {
return -EINVAL;
} else if (r != 0) {
if (errno == 0)
return -errno;
}
errno = 0;
if (errno == 0)
return -errno;
}
log_error("nspawn currently does not support LUKS disk images.");
return -EOPNOTSUPP;
}
return 0;
#else
log_error("--image= is not supported, compiled without blkid support.");
return -EOPNOTSUPP;
#endif
}
static int mount_devices(
const char *where,
const char *root_device, bool root_device_rw,
const char *home_device, bool home_device_rw,
const char *srv_device, bool srv_device_rw) {
int r;
if (root_device) {
if (r < 0)
return log_error_errno(r, "Failed to mount root directory: %m");
}
if (home_device) {
if (r < 0)
return log_error_errno(r, "Failed to mount home directory: %m");
}
if (srv_device) {
if (r < 0)
return log_error_errno(r, "Failed to mount server data directory: %m");
}
return 0;
}
int r;
if (nr < 0)
return;
if (r < 0)
}
if (control < 0) {
return;
}
if (r < 0)
}
int pipe_fds[2];
if (pid < 0)
else if (pid == 0) {
int nullfd;
if (pipe_fds[0] > 2)
safe_close(pipe_fds[0]);
if (nullfd < 0)
if (nullfd > 2)
(void) reset_all_signal_handlers();
(void) reset_signal_mask();
close_all_fds(NULL, 0);
}
return pipe_fds[0];
}
static int change_uid_gid(char **_home) {
unsigned n_uids = 0;
int r;
/* Reset everything fully to 0, just in case */
r = reset_uid_gid();
if (r < 0)
return log_error_errno(r, "Failed to become root: %m");
return 0;
}
/* First, get user credentials */
if (fd < 0)
return fd;
if (!f)
return log_oom();
fd = -1;
if (!ferror(f)) {
return -ESRCH;
}
return -errno;
}
if (!x) {
return -EIO;
}
if (!u) {
return -EIO;
}
u++;
g = strchr(u, ':');
if (!g) {
return -EIO;
}
*g = 0;
g++;
x = strchr(g, ':');
if (!x) {
return -EIO;
}
*x = 0;
if (!h) {
return -EIO;
}
h++;
x = strchr(h, ':');
if (!x) {
return -EIO;
}
*x = 0;
if (r < 0) {
log_error("Failed to parse UID of user.");
return -EIO;
}
if (r < 0) {
log_error("Failed to parse GID of user.");
return -EIO;
}
if (!home)
return log_oom();
/* Second, get group memberships */
if (fd < 0)
return fd;
fclose(f);
if (!f)
return log_oom();
fd = -1;
if (!ferror(f)) {
return -ESRCH;
}
return -errno;
}
/* Skip over the username and subsequent separator whitespace */
x = line;
x += strcspn(x, WHITESPACE);
x += strspn(x, WHITESPACE);
char c[l+1];
c[l] = 0;
return log_oom();
if (r < 0) {
log_error("Failed to parse group data from getent.");
return -EIO;
}
}
if (r < 0)
return log_error_errno(r, "Failed to make home root directory: %m");
if (r < 0 && r != -EEXIST)
return log_error_errno(r, "Failed to make home directory: %m");
if (_home) {
}
return 0;
}
/*
* Return values:
* < 0 : wait_for_terminate() failed to get the state of the
* container, the container was terminated by a signal, or
* failed for an unknown reason. No change is made to the
* container argument.
* > 0 : The program executed in the container terminated with an
* error. The exit code of the program executed in the
* container is returned. The container argument has been set
* to CONTAINER_TERMINATED.
* 0 : The container is being rebooted, has been shut down or exited
* successfully. The container argument has been set to either
* CONTAINER_TERMINATED or CONTAINER_REBOOTED.
*
* That is, success is indicated by a return value of zero, and an
* error is indicated by a non-zero value.
*/
int r;
if (r < 0)
return log_warning_errno(r, "Failed to wait for container: %m");
case CLD_EXITED:
} else
log_full(arg_quiet ? LOG_DEBUG : LOG_INFO, "Container %s failed with error code %i.", arg_machine, status.si_status);
case CLD_KILLED:
return 0;
return 0;
}
/* CLD_KILLED fallthrough */
case CLD_DUMPED:
log_error("Container %s terminated by signal %s.", arg_machine, signal_to_string(status.si_status));
return -EIO;
default:
return -EIO;
}
return r;
}
static void nop_handler(int sig) {}
static int on_orderly_shutdown(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
if (pid > 0) {
log_info("Trying to halt container. Send SIGTERM again to trigger immediate termination.");
return 0;
}
}
return 0;
}
static int determine_names(void) {
int r;
/* If --template= was specified then we should not
* search for a machine, but instead create a new one
if (!arg_directory)
return log_oom();
}
if (!arg_image && !arg_directory) {
if (arg_machine) {
r = image_find(arg_machine, &i);
if (r < 0)
else if (r == 0) {
return -ENOENT;
}
else
if (r < 0)
return log_error_errno(r, "Invalid image directory: %m");
if (!arg_ephemeral)
} else
if (!arg_directory && !arg_machine) {
log_error("Failed to determine path, please use -D or -i.");
return -EINVAL;
}
}
if (!arg_machine) {
else
if (!arg_machine)
return log_oom();
if (!machine_name_is_valid(arg_machine)) {
log_error("Failed to determine machine name automatically, please use -M.");
return -EINVAL;
}
if (arg_ephemeral) {
char *b;
/* Add a random suffix when this is an
* ephemeral machine, so that we can run many
* instances at once without manually having
* to specify -M each time. */
return log_oom();
arg_machine = b;
}
}
return 0;
}
static int determine_uid_shift(const char *directory) {
int r;
if (!arg_userns) {
arg_uid_shift = 0;
return 0;
}
if (arg_uid_shift == UID_INVALID) {
if (r < 0)
return -EINVAL;
}
}
log_error("UID base too high for UID range.");
return -EINVAL;
}
log_info("Using user namespaces with base " UID_FMT " and range " UID_FMT ".", arg_uid_shift, arg_uid_range);
return 0;
}
static int inner_child(
const char *directory,
bool secondary,
int kmsg_socket,
int rtnl_socket,
int argc,
char *argv[]) {
unsigned n_env = 2;
const char *envp[] = {
"PATH=" DEFAULT_PATH_SPLIT_USR,
"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 */
};
int r;
assert(kmsg_socket >= 0);
if (arg_userns) {
/* Tell the parent, that it now can write the UID map. */
/* Wait until the parent wrote the UID map */
log_error("Parent died too early");
return -ESRCH;
}
}
if (r < 0)
return r;
/* Wait until we are cgroup-ified, so that we
* can mount the right cgroup path writable */
log_error("Parent died too early");
return -ESRCH;
}
r = mount_systemd_cgroup_writable("");
if (r < 0)
return r;
r = reset_uid_gid();
if (r < 0)
return log_error_errno(r, "Couldn't become new root: %m");
r = setup_boot_id(NULL);
if (r < 0)
return r;
if (r < 0)
return r;
umask(0022);
if (setsid() < 0)
if (arg_private_network)
r = send_rtnl(rtnl_socket);
if (r < 0)
return r;
if (drop_capabilities() < 0)
if (arg_personality != PERSONALITY_INVALID) {
if (personality(arg_personality) < 0)
} else if (secondary) {
if (personality(PER_LINUX32) < 0)
}
#ifdef HAVE_SELINUX
if (arg_selinux_context)
#endif
r = change_uid_gid(&home);
if (r < 0)
return r;
n_env ++;
return log_oom();
char as_uuid[37];
if (asprintf((char**)(envp + n_env++), "container_uuid=%s", id128_format_as_uuid(arg_uuid, as_uuid)) < 0)
return log_oom();
}
if (fdset_size(fds) > 0) {
r = fdset_cloexec(fds, false);
if (r < 0)
return log_error_errno(r, "Failed to unset O_CLOEXEC for file descriptors.");
return log_oom();
}
if (!env_use)
return log_oom();
/* Let the parent know that we are ready and
* wait until the parent is ready with the
* setup, too... */
log_error("Parent died too early");
return -ESRCH;
}
/* Now, explicitly close the log, so that we
* then can close all remaining fds. Closing
* the log explicitly first has the benefit
* that the logging subsystem knows about it,
* and is thus ready to be reopened should we
* need it again. Note that the other fds
* closed here are at least the locking and
* barrier fds. */
log_close();
(void) fdset_close_others(fds);
if (arg_boot) {
char **a;
size_t m;
/* Automatically search for the init system */
a = newa(char*, m + 1);
else {
}
(void) log_open();
}
static int outer_child(
const char *directory,
const char *console,
const char *root_device, bool root_device_rw,
const char *home_device, bool home_device_rw,
const char *srv_device, bool srv_device_rw,
bool interactive,
bool secondary,
int pid_socket,
int kmsg_socket,
int rtnl_socket,
int uid_shift_socket,
int argc,
char *argv[]) {
ssize_t l;
int r;
assert(pid_socket >= 0);
assert(kmsg_socket >= 0);
if (interactive) {
if (r != STDIN_FILENO) {
if (r >= 0) {
safe_close(r);
r = -EINVAL;
}
return log_error_errno(r, "Failed to open console: %m");
}
}
r = reset_audit_loginuid();
if (r < 0)
return r;
/* Mark everything as slave, so that we still
* receive mounts from the real root, but don't
* propagate mounts to the real root. */
r = mount_devices(directory,
if (r < 0)
return r;
r = determine_uid_shift(directory);
if (r < 0)
return r;
if (arg_userns) {
if (l < 0)
if (l != sizeof(arg_uid_shift)) {
log_error("Short write while sending UID shift.");
return -EIO;
}
}
/* Turn directory into bind mount */
r = setup_volatile(directory);
if (r < 0)
return r;
if (r < 0)
return r;
if (r < 0)
return r;
if (arg_read_only) {
r = bind_remount_recursive(directory, true);
if (r < 0)
return log_error_errno(r, "Failed to make tree read-only: %m");
}
if (r < 0)
return r;
if (copy_devnodes(directory) < 0)
return r;
return r;
r = setup_propagate(directory);
if (r < 0)
return r;
if (r < 0)
return r;
r = setup_seccomp();
if (r < 0)
return r;
r = setup_timezone(directory);
if (r < 0)
return r;
r = setup_resolv_conf(directory);
if (r < 0)
return r;
r = setup_journal(directory);
if (r < 0)
return r;
r = mount_custom(directory);
if (r < 0)
return r;
r = mount_cgroups(directory);
if (r < 0)
return r;
r = mount_move_root(directory);
if (r < 0)
return log_error_errno(r, "Failed to move root directory: %m");
(arg_private_network ? CLONE_NEWNET : 0) |
(arg_userns ? CLONE_NEWUSER : 0),
NULL);
if (pid < 0)
if (pid == 0) {
/* The inner child has all namespaces that are
* requested, so that we all are owned by the user if
* user namespaces are turned on. */
if (r < 0)
}
if (l < 0)
if (l != sizeof(pid)) {
log_error("Short write while sending PID.");
return -EIO;
}
return 0;
}
char uid_map[strlen("/proc//uid_map") + DECIMAL_STR_MAX(uid_t) + 1], line[DECIMAL_STR_MAX(uid_t)*3+3+1];
int r;
if (r < 0)
return log_error_errno(r, "Failed to write UID map: %m");
/* We always assign the same UID and GID ranges */
if (r < 0)
return log_error_errno(r, "Failed to write GID map: %m");
return 0;
}
const char *fn;
int r;
if (r < 0)
return log_error_errno(r, "Failed to get container cgroup path: %m");
if (r < 0)
return log_error_errno(r, "Failed to get file system path for container cgroup: %m");
if (fd < 0)
".",
"tasks",
"notify_on_release",
"cgroup.procs",
"cgroup.clone_children",
"cgroup.controllers",
"cgroup.subtree_control",
"cgroup.populated")
"Failed to chown() cgroup file %s, ignoring: %m", fn);
return 0;
}
bool undo_mount = false;
const char *fn;
int unified, r;
unified = cg_unified();
if (unified < 0)
if ((unified > 0) == arg_unified_cgroup_hierarchy)
return 0;
/* When the host uses the legacy cgroup setup, but the
* container shall use the unified hierarchy, let's make sure
* we copy the path from the name=systemd hierarchy into the
* unified hierarchy. Similar for the reverse situation. */
if (r < 0)
/* In order to access the unified hierarchy we need to mount it */
return log_error_errno(errno, "Failed to generate temporary mount point for unified hierarchy: %m");
if (unified)
else
if (r < 0) {
goto finish;
}
undo_mount = true;
if (r < 0)
log_error_errno(r, "Failed to move process: %m");
if (undo_mount)
return r;
}
const char *child;
int unified, r;
/* In the unified hierarchy inner nodes may only only contain
* subgroups, but not processes. Hence, if we running in the
* unified hierarchy and the container does the same, and we
* did not create a scope unit for the container move us and
* the container into two separate subcgroups. */
if (!arg_keep_unit)
return 0;
return 0;
unified = cg_unified();
if (unified < 0)
if (unified == 0)
return 0;
if (r < 0)
return log_error_errno(r, "Failed to get our control group: %m");
if (r < 0)
if (r < 0)
return 0;
}
_cleanup_free_ char *device_path = NULL, *root_device = NULL, *home_device = NULL, *srv_device = NULL, *console = NULL;
bool secondary = false, remove_subvol = false;
int ret = EXIT_SUCCESS;
union in_addr_union exposed = {};
_cleanup_release_lock_file_ LockFile tree_global_lock = LOCK_FILE_INIT, tree_local_lock = LOCK_FILE_INIT;
bool interactive;
log_open();
if (r <= 0)
goto finish;
r = determine_names();
if (r < 0)
goto finish;
if (geteuid() != 0) {
log_error("Need to be root.");
r = -EPERM;
goto finish;
}
n_fd_passed = sd_listen_fds(false);
if (n_fd_passed > 0) {
r = fdset_new_listen_fds(&fds, false);
if (r < 0) {
log_error_errno(r, "Failed to collect file descriptors: %m");
goto finish;
}
}
if (arg_directory) {
log_error("Spawning container on root directory is not supported. Consider using --ephemeral.");
r = -EINVAL;
goto finish;
}
if (arg_ephemeral) {
/* If the specified path is a mount point we
* generate the new snapshot immediately
* inside it under a random name. However if
* the specified is not a mount point we
* create the new snapshot in the parent
* directory, just next to it. */
r = path_is_mount_point(arg_directory, 0);
if (r < 0) {
goto finish;
}
if (r > 0)
else
if (r < 0) {
log_error_errno(r, "Failed to generate name for snapshot: %m");
goto finish;
}
r = image_path_lock(np, (arg_read_only ? LOCK_SH : LOCK_EX) | LOCK_NB, &tree_global_lock, &tree_local_lock);
if (r < 0) {
goto finish;
}
r = btrfs_subvol_snapshot(arg_directory, np, (arg_read_only ? BTRFS_SNAPSHOT_READ_ONLY : 0) | BTRFS_SNAPSHOT_FALLBACK_COPY | BTRFS_SNAPSHOT_RECURSIVE);
if (r < 0) {
goto finish;
}
arg_directory = np;
remove_subvol = true;
} else {
r = image_path_lock(arg_directory, (arg_read_only ? LOCK_SH : LOCK_EX) | LOCK_NB, &tree_global_lock, &tree_local_lock);
if (r == -EBUSY) {
goto finish;
}
if (r < 0) {
return r;
}
if (arg_template) {
r = btrfs_subvol_snapshot(arg_template, arg_directory, (arg_read_only ? BTRFS_SNAPSHOT_READ_ONLY : 0) | BTRFS_SNAPSHOT_FALLBACK_COPY | BTRFS_SNAPSHOT_RECURSIVE);
if (r == -EEXIST) {
if (!arg_quiet)
log_info("Directory %s already exists, not populating from template %s.", arg_directory, arg_template);
} else if (r < 0) {
goto finish;
} else {
if (!arg_quiet)
}
}
}
if (arg_boot) {
if (path_is_os_tree(arg_directory) <= 0) {
log_error("Directory %s doesn't look like an OS root directory (os-release file is missing). Refusing.", arg_directory);
r = -EINVAL;
goto finish;
}
} else {
const char *p;
p = strjoina(arg_directory,
log_error("Directory %s lacks the binary to execute or doesn't look like a binary tree. Refusing.", arg_directory);
r = -EINVAL;
goto finish;
}
}
} else {
char template[] = "/tmp/nspawn-root-XXXXXX";
r = image_path_lock(arg_image, (arg_read_only ? LOCK_SH : LOCK_EX) | LOCK_NB, &tree_global_lock, &tree_local_lock);
if (r == -EBUSY) {
goto finish;
}
if (r < 0) {
r = log_error_errno(r, "Failed to create image lock: %m");
goto finish;
}
r = -errno;
goto finish;
}
if (!arg_directory) {
r = log_oom();
goto finish;
}
if (image_fd < 0) {
r = image_fd;
goto finish;
}
r = dissect_image(image_fd,
&secondary);
if (r < 0)
goto finish;
}
r = custom_mounts_prepare();
if (r < 0)
goto finish;
isatty(STDIN_FILENO) > 0 &&
isatty(STDOUT_FILENO) > 0;
if (master < 0) {
goto finish;
}
if (r < 0) {
r = log_error_errno(r, "Failed to determine tty name: %m");
goto finish;
}
goto finish;
}
if (!arg_quiet)
log_info("Spawning container %s on %s.\nPress ^] three times within 1s to kill container.",
goto finish;
}
for (;;) {
_cleanup_close_pair_ int kmsg_socket_pair[2] = { -1, -1 }, rtnl_socket_pair[2] = { -1, -1 }, pid_socket_pair[2] = { -1, -1 },
.sa_flags = SA_NOCLDSTOP,
};
int ifi = 0;
ssize_t l;
char last_char = 0;
r = barrier_create(&barrier);
if (r < 0) {
log_error_errno(r, "Cannot initialize IPC barrier: %m");
goto finish;
}
goto finish;
}
goto finish;
}
goto finish;
}
if (arg_userns)
goto finish;
}
/* Child can be killed before execv(), so handle SIGCHLD
* in order to interrupt parent's blocking calls and
* give it a chance to call wait() and terminate. */
if (r < 0) {
goto finish;
}
if (r < 0) {
goto finish;
}
if (pid < 0) {
r = log_error_errno(errno, "clone() failed, do you have namespace support enabled in your kernel? (You need UTS, IPC, PID and NET namespacing built in): %m");
else
goto finish;
}
if (pid == 0) {
/* The outer child only has a file system namespace. */
(void) reset_all_signal_handlers();
(void) reset_signal_mask();
r = outer_child(&barrier,
pid_socket_pair[1],
kmsg_socket_pair[1],
rtnl_socket_pair[1],
fds,
if (r < 0)
}
/* Wait for the outer child. */
if (r < 0)
goto finish;
if (r != 0) {
r = -EIO;
goto finish;
}
pid = 0;
/* And now retrieve the PID of the inner child. */
if (l < 0) {
goto finish;
}
if (l != sizeof(pid)) {
log_error("Short read while reading inner child PID: %m");
r = EIO;
goto finish;
}
if (arg_userns) {
log_error("Child died too early.");
r = -ESRCH;
goto finish;
}
if (l < 0) {
goto finish;
}
if (l != sizeof(arg_uid_shift)) {
log_error("Short read while reading UID shift: %m");
r = EIO;
goto finish;
}
r = setup_uid_map(pid);
if (r < 0)
goto finish;
}
r = move_network_interfaces(pid);
if (r < 0)
goto finish;
if (r < 0)
goto finish;
if (r < 0)
goto finish;
r = setup_macvlan(pid);
if (r < 0)
goto finish;
r = setup_ipvlan(pid);
if (r < 0)
goto finish;
if (r < 0)
goto finish;
r = sync_cgroup(pid);
if (r < 0)
goto finish;
r = create_subcgroup(pid);
if (r < 0)
goto finish;
r = chown_cgroup(pid);
if (r < 0)
goto finish;
/* Notify the child that the parent is ready with all
* its setup (including cgroup-ification), and that
* the child can now hand over control to the code to
* run inside the container. */
/* Block SIGCHLD here, before notifying child.
* process_pty() will handle it with the other signals. */
/* Reset signal to default */
if (r < 0) {
log_error_errno(r, "Failed to reset SIGCHLD: %m");
goto finish;
}
/* Let the child know that we are ready and wait that the child is completely ready now. */
log_error("Client died too early.");
r = -ESRCH;
goto finish;
}
sd_notifyf(false,
"READY=1\n"
"STATUS=Container running.\n"
r = sd_event_new(&event);
if (r < 0) {
log_error_errno(r, "Failed to get default event source: %m");
goto finish;
}
if (arg_kill_signal > 0) {
/* Try to kill the init system on SIGINT or SIGTERM */
} else {
/* Immediately exit */
}
/* simply exit on sigchld */
if (arg_expose_ports) {
if (r < 0)
goto finish;
}
if (r < 0) {
log_error_errno(r, "Failed to create PTY forwarder: %m");
goto finish;
}
r = sd_event_loop(event);
if (r < 0) {
log_error_errno(r, "Failed to run event loop: %m");
goto finish;
}
/* Kill if it is not dead yet anyway */
/* Normally redundant, but better safe than sorry */
pid = 0;
if (r < 0)
/* We failed to wait for the container, or the
* container exited abnormally */
goto finish;
else if (r > 0 || container_status == CONTAINER_TERMINATED){
/* The container exited with a non-zero
* status, or with zero status and no reboot
* was requested. */
ret = r;
break;
}
/* CONTAINER_REBOOTED, loop again */
if (arg_keep_unit) {
/* Special handling if we are running as a
* service: instead of simply restarting the
* machine we want to restart the entire
* service, so let's inform systemd about this
* with the special exit code 133. The service
* file uses RestartForceExitStatus=133 so
* that this results in a full nspawn
* restart. This is necessary since we might
* have cgroup parameters set we want to have
* flushed out. */
ret = 133;
r = 0;
break;
}
}
sd_notify(false,
"STOPPING=1\n"
"STATUS=Terminating...");
if (pid > 0)
/* Try to flush whatever is still queued in the pty */
if (master >= 0)
if (remove_subvol && arg_directory) {
int k;
k = btrfs_subvol_remove(arg_directory, true);
if (k < 0)
}
if (arg_machine) {
const char *p;
(void) rm_rf(p, REMOVE_ROOT);
}
while (arg_expose_ports) {
ExposePort *p = arg_expose_ports;
free(p);
}
return r < 0 ? EXIT_FAILURE : ret;
}