2 This file is part of systemd.
4 Copyright 2010 Lennart Poettering
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
21 #include <blkid/blkid.h>
26 #include <linux/loop.h>
30 #include <selinux/selinux.h>
37 #include <sys/mount.h>
38 #include <sys/personality.h>
39 #include <sys/prctl.h>
40 #include <sys/types.h>
43 #include "sd-daemon.h"
46 #include "alloc-util.h"
48 #include "base-filesystem.h"
49 #include "blkid-util.h"
50 #include "btrfs-util.h"
52 #include "capability-util.h"
53 #include "cgroup-util.h"
55 #include "dev-setup.h"
56 #include "dissect-image.h"
61 #include "format-util.h"
64 #include "hexdecoct.h"
65 #include "hostname-util.h"
66 #include "id128-util.h"
68 #include "loop-util.h"
69 #include "loopback-setup.h"
70 #include "machine-image.h"
74 #include "mount-util.h"
75 #include "netlink-util.h"
76 #include "nspawn-cgroup.h"
77 #include "nspawn-expose-ports.h"
78 #include "nspawn-mount.h"
79 #include "nspawn-network.h"
80 #include "nspawn-patch-uid.h"
81 #include "nspawn-register.h"
82 #include "nspawn-seccomp.h"
83 #include "nspawn-settings.h"
84 #include "nspawn-setuid.h"
85 #include "nspawn-stub-pid1.h"
86 #include "parse-util.h"
87 #include "path-util.h"
88 #include "process-util.h"
90 #include "random-util.h"
91 #include "raw-clone.h"
93 #include "selinux-util.h"
94 #include "signal-util.h"
95 #include "socket-util.h"
96 #include "stat-util.h"
97 #include "stdio-util.h"
98 #include "string-util.h"
100 #include "terminal-util.h"
101 #include "udev-util.h"
102 #include "umask-util.h"
103 #include "user-util.h"
106 /* Note that devpts's gid= parameter parses GIDs as signed values, hence we stay away from the upper half of the 32bit
107 * UID range here. We leave a bit of room at the lower end and a lot of room at the upper end, so that other subsystems
108 * may have their own allocation ranges too. */
109 #define UID_SHIFT_PICK_MIN ((uid_t) UINT32_C(0x00080000))
110 #define UID_SHIFT_PICK_MAX ((uid_t) UINT32_C(0x6FFF0000))
112 /* nspawn is listening on the socket at the path in the constant nspawn_notify_socket_path
113 * nspawn_notify_socket_path is relative to the container
114 * the init process in the container pid can send messages to nspawn following the sd_notify(3) protocol */
115 #define NSPAWN_NOTIFY_SOCKET_PATH "/run/systemd/nspawn/notify"
117 #define EXIT_FORCE_RESTART 133
119 typedef enum ContainerStatus
{
120 CONTAINER_TERMINATED
,
124 typedef enum LinkJournal
{
131 static char *arg_directory
= NULL
;
132 static char *arg_template
= NULL
;
133 static char *arg_chdir
= NULL
;
134 static char *arg_user
= NULL
;
135 static sd_id128_t arg_uuid
= {};
136 static char *arg_machine
= NULL
;
137 static const char *arg_selinux_context
= NULL
;
138 static const char *arg_selinux_apifs_context
= NULL
;
139 static const char *arg_slice
= NULL
;
140 static bool arg_private_network
= false;
141 static bool arg_read_only
= false;
142 static StartMode arg_start_mode
= START_PID1
;
143 static bool arg_ephemeral
= false;
144 static LinkJournal arg_link_journal
= LINK_AUTO
;
145 static bool arg_link_journal_try
= false;
146 static uint64_t arg_caps_retain
=
147 (1ULL << CAP_AUDIT_CONTROL
) |
148 (1ULL << CAP_AUDIT_WRITE
) |
149 (1ULL << CAP_CHOWN
) |
150 (1ULL << CAP_DAC_OVERRIDE
) |
151 (1ULL << CAP_DAC_READ_SEARCH
) |
152 (1ULL << CAP_FOWNER
) |
153 (1ULL << CAP_FSETID
) |
154 (1ULL << CAP_IPC_OWNER
) |
156 (1ULL << CAP_LEASE
) |
157 (1ULL << CAP_LINUX_IMMUTABLE
) |
158 (1ULL << CAP_MKNOD
) |
159 (1ULL << CAP_NET_BIND_SERVICE
) |
160 (1ULL << CAP_NET_BROADCAST
) |
161 (1ULL << CAP_NET_RAW
) |
162 (1ULL << CAP_SETFCAP
) |
163 (1ULL << CAP_SETGID
) |
164 (1ULL << CAP_SETPCAP
) |
165 (1ULL << CAP_SETUID
) |
166 (1ULL << CAP_SYS_ADMIN
) |
167 (1ULL << CAP_SYS_BOOT
) |
168 (1ULL << CAP_SYS_CHROOT
) |
169 (1ULL << CAP_SYS_NICE
) |
170 (1ULL << CAP_SYS_PTRACE
) |
171 (1ULL << CAP_SYS_RESOURCE
) |
172 (1ULL << CAP_SYS_TTY_CONFIG
);
173 static CustomMount
*arg_custom_mounts
= NULL
;
174 static unsigned arg_n_custom_mounts
= 0;
175 static char **arg_setenv
= NULL
;
176 static bool arg_quiet
= false;
177 static bool arg_register
= true;
178 static bool arg_keep_unit
= false;
179 static char **arg_network_interfaces
= NULL
;
180 static char **arg_network_macvlan
= NULL
;
181 static char **arg_network_ipvlan
= NULL
;
182 static bool arg_network_veth
= false;
183 static char **arg_network_veth_extra
= NULL
;
184 static char *arg_network_bridge
= NULL
;
185 static char *arg_network_zone
= NULL
;
186 static unsigned long arg_personality
= PERSONALITY_INVALID
;
187 static char *arg_image
= NULL
;
188 static VolatileMode arg_volatile_mode
= VOLATILE_NO
;
189 static ExposePort
*arg_expose_ports
= NULL
;
190 static char **arg_property
= NULL
;
191 static UserNamespaceMode arg_userns_mode
= USER_NAMESPACE_NO
;
192 static uid_t arg_uid_shift
= UID_INVALID
, arg_uid_range
= 0x10000U
;
193 static bool arg_userns_chown
= false;
194 static int arg_kill_signal
= 0;
195 static CGroupUnified arg_unified_cgroup_hierarchy
= CGROUP_UNIFIED_UNKNOWN
;
196 static SettingsMask arg_settings_mask
= 0;
197 static int arg_settings_trusted
= -1;
198 static char **arg_parameters
= NULL
;
199 static const char *arg_container_service_name
= "systemd-nspawn";
200 static bool arg_notify_ready
= false;
201 static bool arg_use_cgns
= true;
202 static unsigned long arg_clone_ns_flags
= CLONE_NEWIPC
|CLONE_NEWPID
|CLONE_NEWUTS
;
203 static MountSettingsMask arg_mount_settings
= MOUNT_APPLY_APIVFS_RO
;
204 static void *arg_root_hash
= NULL
;
205 static size_t arg_root_hash_size
= 0;
207 static void help(void) {
208 printf("%s [OPTIONS...] [PATH] [ARGUMENTS...]\n\n"
209 "Spawn a minimal namespace container for debugging, testing and building.\n\n"
210 " -h --help Show this help\n"
211 " --version Print version string\n"
212 " -q --quiet Do not show status information\n"
213 " -D --directory=PATH Root directory for the container\n"
214 " --template=PATH Initialize root directory from template directory,\n"
216 " -x --ephemeral Run container with snapshot of root directory, and\n"
217 " remove it after exit\n"
218 " -i --image=PATH File system device or disk image for the container\n"
219 " --root-hash=HASH Specify verity root hash\n"
220 " -a --as-pid2 Maintain a stub init as PID1, invoke binary as PID2\n"
221 " -b --boot Boot up full system (i.e. invoke init)\n"
222 " --chdir=PATH Set working directory in the container\n"
223 " -u --user=USER Run the command under specified user or uid\n"
224 " -M --machine=NAME Set the machine name for the container\n"
225 " --uuid=UUID Set a specific machine UUID for the container\n"
226 " -S --slice=SLICE Place the container in the specified slice\n"
227 " --property=NAME=VALUE Set scope unit property\n"
228 " -U --private-users=pick Run within user namespace, autoselect UID/GID range\n"
229 " --private-users[=UIDBASE[:NUIDS]]\n"
230 " Similar, but with user configured UID/GID range\n"
231 " --private-users-chown Adjust OS tree ownership to private UID/GID range\n"
232 " --private-network Disable network in container\n"
233 " --network-interface=INTERFACE\n"
234 " Assign an existing network interface to the\n"
236 " --network-macvlan=INTERFACE\n"
237 " Create a macvlan network interface based on an\n"
238 " existing network interface to the container\n"
239 " --network-ipvlan=INTERFACE\n"
240 " Create a ipvlan network interface based on an\n"
241 " existing network interface to the container\n"
242 " -n --network-veth Add a virtual Ethernet connection between host\n"
244 " --network-veth-extra=HOSTIF[:CONTAINERIF]\n"
245 " Add an additional virtual Ethernet link between\n"
246 " host and container\n"
247 " --network-bridge=INTERFACE\n"
248 " Add a virtual Ethernet connection to the container\n"
249 " and attach it to an existing bridge on the host\n"
250 " --network-zone=NAME Similar, but attach the new interface to an\n"
251 " an automatically managed bridge interface\n"
252 " -p --port=[PROTOCOL:]HOSTPORT[:CONTAINERPORT]\n"
253 " Expose a container IP port on the host\n"
254 " -Z --selinux-context=SECLABEL\n"
255 " Set the SELinux security context to be used by\n"
256 " processes in the container\n"
257 " -L --selinux-apifs-context=SECLABEL\n"
258 " Set the SELinux security context to be used by\n"
259 " API/tmpfs file systems in the container\n"
260 " --capability=CAP In addition to the default, retain specified\n"
262 " --drop-capability=CAP Drop the specified capability from the default set\n"
263 " --kill-signal=SIGNAL Select signal to use for shutting down PID 1\n"
264 " --link-journal=MODE Link up guest journal, one of no, auto, guest, \n"
265 " host, try-guest, try-host\n"
266 " -j Equivalent to --link-journal=try-guest\n"
267 " --read-only Mount the root directory read-only\n"
268 " --bind=PATH[:PATH[:OPTIONS]]\n"
269 " Bind mount a file or directory from the host into\n"
271 " --bind-ro=PATH[:PATH[:OPTIONS]\n"
272 " Similar, but creates a read-only bind mount\n"
273 " --tmpfs=PATH:[OPTIONS] Mount an empty tmpfs to the specified directory\n"
274 " --overlay=PATH[:PATH...]:PATH\n"
275 " Create an overlay mount from the host to \n"
277 " --overlay-ro=PATH[:PATH...]:PATH\n"
278 " Similar, but creates a read-only overlay mount\n"
279 " -E --setenv=NAME=VALUE Pass an environment variable to PID 1\n"
280 " --register=BOOLEAN Register container as machine\n"
281 " --keep-unit Do not register a scope for the machine, reuse\n"
282 " the service unit nspawn is running in\n"
283 " --volatile[=MODE] Run the system in volatile mode\n"
284 " --settings=BOOLEAN Load additional settings from .nspawn file\n"
285 " --notify-ready=BOOLEAN Receive notifications from the child init process\n"
286 , program_invocation_short_name
);
289 static int custom_mount_check_all(void) {
292 for (i
= 0; i
< arg_n_custom_mounts
; i
++) {
293 CustomMount
*m
= &arg_custom_mounts
[i
];
295 if (path_equal(m
->destination
, "/") && arg_userns_mode
!= USER_NAMESPACE_NO
) {
297 if (arg_userns_chown
) {
298 log_error("--private-users-chown may not be combined with custom root mounts.");
300 } else if (arg_uid_shift
== UID_INVALID
) {
301 log_error("--private-users with automatic UID shift may not be combined with custom root mounts.");
310 static int detect_unified_cgroup_hierarchy(const char *directory
) {
312 int r
, all_unified
, systemd_unified
;
314 /* Allow the user to control whether the unified hierarchy is used */
315 e
= getenv("UNIFIED_CGROUP_HIERARCHY");
317 r
= parse_boolean(e
);
319 return log_error_errno(r
, "Failed to parse $UNIFIED_CGROUP_HIERARCHY.");
321 arg_unified_cgroup_hierarchy
= CGROUP_UNIFIED_ALL
;
323 arg_unified_cgroup_hierarchy
= CGROUP_UNIFIED_NONE
;
328 all_unified
= cg_all_unified();
329 systemd_unified
= cg_unified(SYSTEMD_CGROUP_CONTROLLER
);
331 if (all_unified
< 0 || systemd_unified
< 0)
332 return log_error_errno(all_unified
< 0 ? all_unified
: systemd_unified
,
333 "Failed to determine whether the unified cgroups hierarchy is used: %m");
335 /* Otherwise inherit the default from the host system */
336 if (all_unified
> 0) {
337 /* Unified cgroup hierarchy support was added in 230. Unfortunately the detection
338 * routine only detects 231, so we'll have a false negative here for 230. */
339 r
= systemd_installation_has_version(directory
, 230);
341 return log_error_errno(r
, "Failed to determine systemd version in container: %m");
343 arg_unified_cgroup_hierarchy
= CGROUP_UNIFIED_ALL
;
345 arg_unified_cgroup_hierarchy
= CGROUP_UNIFIED_NONE
;
346 } else if (systemd_unified
> 0) {
347 /* Mixed cgroup hierarchy support was added in 232 */
348 r
= systemd_installation_has_version(directory
, 232);
350 return log_error_errno(r
, "Failed to determine systemd version in container: %m");
352 arg_unified_cgroup_hierarchy
= CGROUP_UNIFIED_SYSTEMD
;
354 arg_unified_cgroup_hierarchy
= CGROUP_UNIFIED_NONE
;
356 arg_unified_cgroup_hierarchy
= CGROUP_UNIFIED_NONE
;
361 static void parse_share_ns_env(const char *name
, unsigned long ns_flag
) {
364 r
= getenv_bool(name
);
368 log_warning_errno(r
, "Failed to parse %s from environment, defaulting to false.", name
);
369 arg_clone_ns_flags
= (arg_clone_ns_flags
& ~ns_flag
) | (r
> 0 ? 0 : ns_flag
);
372 static void parse_mount_settings_env(void) {
376 e
= getenv("SYSTEMD_NSPAWN_API_VFS_WRITABLE");
380 if (streq(e
, "network")) {
381 arg_mount_settings
|= MOUNT_APPLY_APIVFS_RO
|MOUNT_APPLY_APIVFS_NETNS
;
385 r
= parse_boolean(e
);
387 log_warning_errno(r
, "Failed to parse SYSTEMD_NSPAWN_API_VFS_WRITABLE from environment, ignoring.");
390 arg_mount_settings
&= ~MOUNT_APPLY_APIVFS_RO
;
392 arg_mount_settings
|= MOUNT_APPLY_APIVFS_RO
;
394 arg_mount_settings
&= ~MOUNT_APPLY_APIVFS_NETNS
;
397 static int parse_argv(int argc
, char *argv
[]) {
415 ARG_NETWORK_INTERFACE
,
420 ARG_NETWORK_VETH_EXTRA
,
429 ARG_PRIVATE_USERS_CHOWN
,
434 static const struct option options
[] = {
435 { "help", no_argument
, NULL
, 'h' },
436 { "version", no_argument
, NULL
, ARG_VERSION
},
437 { "directory", required_argument
, NULL
, 'D' },
438 { "template", required_argument
, NULL
, ARG_TEMPLATE
},
439 { "ephemeral", no_argument
, NULL
, 'x' },
440 { "user", required_argument
, NULL
, 'u' },
441 { "private-network", no_argument
, NULL
, ARG_PRIVATE_NETWORK
},
442 { "as-pid2", no_argument
, NULL
, 'a' },
443 { "boot", no_argument
, NULL
, 'b' },
444 { "uuid", required_argument
, NULL
, ARG_UUID
},
445 { "read-only", no_argument
, NULL
, ARG_READ_ONLY
},
446 { "capability", required_argument
, NULL
, ARG_CAPABILITY
},
447 { "drop-capability", required_argument
, NULL
, ARG_DROP_CAPABILITY
},
448 { "link-journal", required_argument
, NULL
, ARG_LINK_JOURNAL
},
449 { "bind", required_argument
, NULL
, ARG_BIND
},
450 { "bind-ro", required_argument
, NULL
, ARG_BIND_RO
},
451 { "tmpfs", required_argument
, NULL
, ARG_TMPFS
},
452 { "overlay", required_argument
, NULL
, ARG_OVERLAY
},
453 { "overlay-ro", required_argument
, NULL
, ARG_OVERLAY_RO
},
454 { "machine", required_argument
, NULL
, 'M' },
455 { "slice", required_argument
, NULL
, 'S' },
456 { "setenv", required_argument
, NULL
, 'E' },
457 { "selinux-context", required_argument
, NULL
, 'Z' },
458 { "selinux-apifs-context", required_argument
, NULL
, 'L' },
459 { "quiet", no_argument
, NULL
, 'q' },
460 { "share-system", no_argument
, NULL
, ARG_SHARE_SYSTEM
}, /* not documented */
461 { "register", required_argument
, NULL
, ARG_REGISTER
},
462 { "keep-unit", no_argument
, NULL
, ARG_KEEP_UNIT
},
463 { "network-interface", required_argument
, NULL
, ARG_NETWORK_INTERFACE
},
464 { "network-macvlan", required_argument
, NULL
, ARG_NETWORK_MACVLAN
},
465 { "network-ipvlan", required_argument
, NULL
, ARG_NETWORK_IPVLAN
},
466 { "network-veth", no_argument
, NULL
, 'n' },
467 { "network-veth-extra", required_argument
, NULL
, ARG_NETWORK_VETH_EXTRA
},
468 { "network-bridge", required_argument
, NULL
, ARG_NETWORK_BRIDGE
},
469 { "network-zone", required_argument
, NULL
, ARG_NETWORK_ZONE
},
470 { "personality", required_argument
, NULL
, ARG_PERSONALITY
},
471 { "image", required_argument
, NULL
, 'i' },
472 { "volatile", optional_argument
, NULL
, ARG_VOLATILE
},
473 { "port", required_argument
, NULL
, 'p' },
474 { "property", required_argument
, NULL
, ARG_PROPERTY
},
475 { "private-users", optional_argument
, NULL
, ARG_PRIVATE_USERS
},
476 { "private-users-chown", optional_argument
, NULL
, ARG_PRIVATE_USERS_CHOWN
},
477 { "kill-signal", required_argument
, NULL
, ARG_KILL_SIGNAL
},
478 { "settings", required_argument
, NULL
, ARG_SETTINGS
},
479 { "chdir", required_argument
, NULL
, ARG_CHDIR
},
480 { "notify-ready", required_argument
, NULL
, ARG_NOTIFY_READY
},
481 { "root-hash", required_argument
, NULL
, ARG_ROOT_HASH
},
487 uint64_t plus
= 0, minus
= 0;
488 bool mask_all_settings
= false, mask_no_settings
= false;
493 while ((c
= getopt_long(argc
, argv
, "+hD:u:abL:M:jS:Z:qi:xp:nUE:", options
, NULL
)) >= 0)
505 r
= parse_path_argument_and_warn(optarg
, false, &arg_directory
);
511 r
= parse_path_argument_and_warn(optarg
, false, &arg_template
);
517 r
= parse_path_argument_and_warn(optarg
, false, &arg_image
);
523 arg_ephemeral
= true;
527 r
= free_and_strdup(&arg_user
, optarg
);
531 arg_settings_mask
|= SETTING_USER
;
534 case ARG_NETWORK_ZONE
: {
537 j
= strappend("vz-", optarg
);
541 if (!ifname_valid(j
)) {
542 log_error("Network zone name not valid: %s", j
);
547 free(arg_network_zone
);
548 arg_network_zone
= j
;
550 arg_network_veth
= true;
551 arg_private_network
= true;
552 arg_settings_mask
|= SETTING_NETWORK
;
556 case ARG_NETWORK_BRIDGE
:
558 if (!ifname_valid(optarg
)) {
559 log_error("Bridge interface name not valid: %s", optarg
);
563 r
= free_and_strdup(&arg_network_bridge
, optarg
);
570 arg_network_veth
= true;
571 arg_private_network
= true;
572 arg_settings_mask
|= SETTING_NETWORK
;
575 case ARG_NETWORK_VETH_EXTRA
:
576 r
= veth_extra_parse(&arg_network_veth_extra
, optarg
);
578 return log_error_errno(r
, "Failed to parse --network-veth-extra= parameter: %s", optarg
);
580 arg_private_network
= true;
581 arg_settings_mask
|= SETTING_NETWORK
;
584 case ARG_NETWORK_INTERFACE
:
586 if (!ifname_valid(optarg
)) {
587 log_error("Network interface name not valid: %s", optarg
);
591 if (strv_extend(&arg_network_interfaces
, optarg
) < 0)
594 arg_private_network
= true;
595 arg_settings_mask
|= SETTING_NETWORK
;
598 case ARG_NETWORK_MACVLAN
:
600 if (!ifname_valid(optarg
)) {
601 log_error("MACVLAN network interface name not valid: %s", optarg
);
605 if (strv_extend(&arg_network_macvlan
, optarg
) < 0)
608 arg_private_network
= true;
609 arg_settings_mask
|= SETTING_NETWORK
;
612 case ARG_NETWORK_IPVLAN
:
614 if (!ifname_valid(optarg
)) {
615 log_error("IPVLAN network interface name not valid: %s", optarg
);
619 if (strv_extend(&arg_network_ipvlan
, optarg
) < 0)
624 case ARG_PRIVATE_NETWORK
:
625 arg_private_network
= true;
626 arg_settings_mask
|= SETTING_NETWORK
;
630 if (arg_start_mode
== START_PID2
) {
631 log_error("--boot and --as-pid2 may not be combined.");
635 arg_start_mode
= START_BOOT
;
636 arg_settings_mask
|= SETTING_START_MODE
;
640 if (arg_start_mode
== START_BOOT
) {
641 log_error("--boot and --as-pid2 may not be combined.");
645 arg_start_mode
= START_PID2
;
646 arg_settings_mask
|= SETTING_START_MODE
;
650 r
= sd_id128_from_string(optarg
, &arg_uuid
);
652 return log_error_errno(r
, "Invalid UUID: %s", optarg
);
654 if (sd_id128_is_null(arg_uuid
)) {
655 log_error("Machine UUID may not be all zeroes.");
659 arg_settings_mask
|= SETTING_MACHINE_ID
;
668 arg_machine
= mfree(arg_machine
);
670 if (!machine_name_is_valid(optarg
)) {
671 log_error("Invalid machine name: %s", optarg
);
675 r
= free_and_strdup(&arg_machine
, optarg
);
683 arg_selinux_context
= optarg
;
687 arg_selinux_apifs_context
= optarg
;
691 arg_read_only
= true;
692 arg_settings_mask
|= SETTING_READ_ONLY
;
696 case ARG_DROP_CAPABILITY
: {
699 _cleanup_free_
char *t
= NULL
;
701 r
= extract_first_word(&p
, &t
, ",", 0);
703 return log_error_errno(r
, "Failed to parse capability %s.", t
);
708 if (streq(t
, "all")) {
709 if (c
== ARG_CAPABILITY
)
710 plus
= (uint64_t) -1;
712 minus
= (uint64_t) -1;
716 cap
= capability_from_name(t
);
718 log_error("Failed to parse capability %s.", t
);
722 if (c
== ARG_CAPABILITY
)
723 plus
|= 1ULL << (uint64_t) cap
;
725 minus
|= 1ULL << (uint64_t) cap
;
729 arg_settings_mask
|= SETTING_CAPABILITY
;
734 arg_link_journal
= LINK_GUEST
;
735 arg_link_journal_try
= true;
738 case ARG_LINK_JOURNAL
:
739 if (streq(optarg
, "auto")) {
740 arg_link_journal
= LINK_AUTO
;
741 arg_link_journal_try
= false;
742 } else if (streq(optarg
, "no")) {
743 arg_link_journal
= LINK_NO
;
744 arg_link_journal_try
= false;
745 } else if (streq(optarg
, "guest")) {
746 arg_link_journal
= LINK_GUEST
;
747 arg_link_journal_try
= false;
748 } else if (streq(optarg
, "host")) {
749 arg_link_journal
= LINK_HOST
;
750 arg_link_journal_try
= false;
751 } else if (streq(optarg
, "try-guest")) {
752 arg_link_journal
= LINK_GUEST
;
753 arg_link_journal_try
= true;
754 } else if (streq(optarg
, "try-host")) {
755 arg_link_journal
= LINK_HOST
;
756 arg_link_journal_try
= true;
758 log_error("Failed to parse link journal mode %s", optarg
);
766 r
= bind_mount_parse(&arg_custom_mounts
, &arg_n_custom_mounts
, optarg
, c
== ARG_BIND_RO
);
768 return log_error_errno(r
, "Failed to parse --bind(-ro)= argument %s: %m", optarg
);
770 arg_settings_mask
|= SETTING_CUSTOM_MOUNTS
;
774 r
= tmpfs_mount_parse(&arg_custom_mounts
, &arg_n_custom_mounts
, optarg
);
776 return log_error_errno(r
, "Failed to parse --tmpfs= argument %s: %m", optarg
);
778 arg_settings_mask
|= SETTING_CUSTOM_MOUNTS
;
783 r
= overlay_mount_parse(&arg_custom_mounts
, &arg_n_custom_mounts
, optarg
, c
== ARG_OVERLAY_RO
);
784 if (r
== -EADDRNOTAVAIL
)
785 return log_error_errno(r
, "--overlay(-ro)= needs at least two colon-separated directories specified.");
787 return log_error_errno(r
, "Failed to parse --overlay(-ro)= argument %s: %m", optarg
);
789 arg_settings_mask
|= SETTING_CUSTOM_MOUNTS
;
795 if (!env_assignment_is_valid(optarg
)) {
796 log_error("Environment variable assignment '%s' is not valid.", optarg
);
800 n
= strv_env_set(arg_setenv
, optarg
);
804 strv_free(arg_setenv
);
807 arg_settings_mask
|= SETTING_ENVIRONMENT
;
815 case ARG_SHARE_SYSTEM
:
816 /* We don't officially support this anymore, except for compat reasons. People should use the
817 * $SYSTEMD_NSPAWN_SHARE_* environment variables instead. */
818 arg_clone_ns_flags
= 0;
822 r
= parse_boolean(optarg
);
824 log_error("Failed to parse --register= argument: %s", optarg
);
832 arg_keep_unit
= true;
835 case ARG_PERSONALITY
:
837 arg_personality
= personality_from_string(optarg
);
838 if (arg_personality
== PERSONALITY_INVALID
) {
839 log_error("Unknown or unsupported personality '%s'.", optarg
);
843 arg_settings_mask
|= SETTING_PERSONALITY
;
849 arg_volatile_mode
= VOLATILE_YES
;
853 m
= volatile_mode_from_string(optarg
);
855 log_error("Failed to parse --volatile= argument: %s", optarg
);
858 arg_volatile_mode
= m
;
861 arg_settings_mask
|= SETTING_VOLATILE_MODE
;
865 r
= expose_port_parse(&arg_expose_ports
, optarg
);
867 return log_error_errno(r
, "Duplicate port specification: %s", optarg
);
869 return log_error_errno(r
, "Failed to parse host port %s: %m", optarg
);
871 arg_settings_mask
|= SETTING_EXPOSE_PORTS
;
875 if (strv_extend(&arg_property
, optarg
) < 0)
880 case ARG_PRIVATE_USERS
: {
885 else if (!in_charset(optarg
, DIGITS
))
886 /* do *not* parse numbers as booleans */
887 boolean
= parse_boolean(optarg
);
889 if (boolean
== false) {
890 /* no: User namespacing off */
891 arg_userns_mode
= USER_NAMESPACE_NO
;
892 arg_uid_shift
= UID_INVALID
;
893 arg_uid_range
= UINT32_C(0x10000);
894 } else if (boolean
== true) {
895 /* yes: User namespacing on, UID range is read from root dir */
896 arg_userns_mode
= USER_NAMESPACE_FIXED
;
897 arg_uid_shift
= UID_INVALID
;
898 arg_uid_range
= UINT32_C(0x10000);
899 } else if (streq(optarg
, "pick")) {
900 /* pick: User namespacing on, UID range is picked randomly */
901 arg_userns_mode
= USER_NAMESPACE_PICK
;
902 arg_uid_shift
= UID_INVALID
;
903 arg_uid_range
= UINT32_C(0x10000);
905 _cleanup_free_
char *buffer
= NULL
;
906 const char *range
, *shift
;
908 /* anything else: User namespacing on, UID range is explicitly configured */
910 range
= strchr(optarg
, ':');
912 buffer
= strndup(optarg
, range
- optarg
);
918 r
= safe_atou32(range
, &arg_uid_range
);
920 return log_error_errno(r
, "Failed to parse UID range \"%s\": %m", range
);
924 r
= parse_uid(shift
, &arg_uid_shift
);
926 return log_error_errno(r
, "Failed to parse UID \"%s\": %m", optarg
);
928 arg_userns_mode
= USER_NAMESPACE_FIXED
;
931 if (arg_uid_range
<= 0) {
932 log_error("UID range cannot be 0.");
936 arg_settings_mask
|= SETTING_USERNS
;
941 if (userns_supported()) {
942 arg_userns_mode
= USER_NAMESPACE_PICK
;
943 arg_uid_shift
= UID_INVALID
;
944 arg_uid_range
= UINT32_C(0x10000);
946 arg_settings_mask
|= SETTING_USERNS
;
951 case ARG_PRIVATE_USERS_CHOWN
:
952 arg_userns_chown
= true;
954 arg_settings_mask
|= SETTING_USERNS
;
957 case ARG_KILL_SIGNAL
:
958 arg_kill_signal
= signal_from_string_try_harder(optarg
);
959 if (arg_kill_signal
< 0) {
960 log_error("Cannot parse signal: %s", optarg
);
964 arg_settings_mask
|= SETTING_KILL_SIGNAL
;
969 /* no → do not read files
970 * yes → read files, do not override cmdline, trust only subset
971 * override → read files, override cmdline, trust only subset
972 * trusted → read files, do not override cmdline, trust all
975 r
= parse_boolean(optarg
);
977 if (streq(optarg
, "trusted")) {
978 mask_all_settings
= false;
979 mask_no_settings
= false;
980 arg_settings_trusted
= true;
982 } else if (streq(optarg
, "override")) {
983 mask_all_settings
= false;
984 mask_no_settings
= true;
985 arg_settings_trusted
= -1;
987 return log_error_errno(r
, "Failed to parse --settings= argument: %s", optarg
);
990 mask_all_settings
= false;
991 mask_no_settings
= false;
992 arg_settings_trusted
= -1;
995 mask_all_settings
= true;
996 mask_no_settings
= false;
997 arg_settings_trusted
= false;
1003 if (!path_is_absolute(optarg
)) {
1004 log_error("Working directory %s is not an absolute path.", optarg
);
1008 r
= free_and_strdup(&arg_chdir
, optarg
);
1012 arg_settings_mask
|= SETTING_WORKING_DIRECTORY
;
1015 case ARG_NOTIFY_READY
:
1016 r
= parse_boolean(optarg
);
1018 log_error("%s is not a valid notify mode. Valid modes are: yes, no, and ready.", optarg
);
1021 arg_notify_ready
= r
;
1022 arg_settings_mask
|= SETTING_NOTIFY_READY
;
1025 case ARG_ROOT_HASH
: {
1029 r
= unhexmem(optarg
, strlen(optarg
), &k
, &l
);
1031 return log_error_errno(r
, "Failed to parse root hash: %s", optarg
);
1032 if (l
< sizeof(sd_id128_t
)) {
1033 log_error("Root hash must be at least 128bit long: %s", optarg
);
1038 free(arg_root_hash
);
1040 arg_root_hash_size
= l
;
1048 assert_not_reached("Unhandled option");
1051 parse_share_ns_env("SYSTEMD_NSPAWN_SHARE_NS_IPC", CLONE_NEWIPC
);
1052 parse_share_ns_env("SYSTEMD_NSPAWN_SHARE_NS_PID", CLONE_NEWPID
);
1053 parse_share_ns_env("SYSTEMD_NSPAWN_SHARE_NS_UTS", CLONE_NEWUTS
);
1054 parse_share_ns_env("SYSTEMD_NSPAWN_SHARE_SYSTEM", CLONE_NEWIPC
|CLONE_NEWPID
|CLONE_NEWUTS
);
1056 if (arg_userns_mode
!= USER_NAMESPACE_NO
)
1057 arg_mount_settings
|= MOUNT_USE_USERNS
;
1059 if (arg_private_network
)
1060 arg_mount_settings
|= MOUNT_APPLY_APIVFS_NETNS
;
1062 parse_mount_settings_env();
1064 if (!(arg_clone_ns_flags
& CLONE_NEWPID
) ||
1065 !(arg_clone_ns_flags
& CLONE_NEWUTS
)) {
1066 arg_register
= false;
1067 if (arg_start_mode
!= START_PID1
) {
1068 log_error("--boot cannot be used without namespacing.");
1073 if (arg_userns_mode
== USER_NAMESPACE_PICK
)
1074 arg_userns_chown
= true;
1076 if (arg_keep_unit
&& cg_pid_get_owner_uid(0, NULL
) >= 0) {
1077 log_error("--keep-unit may not be used when invoked from a user session.");
1081 if (arg_directory
&& arg_image
) {
1082 log_error("--directory= and --image= may not be combined.");
1086 if (arg_template
&& arg_image
) {
1087 log_error("--template= and --image= may not be combined.");
1091 if (arg_ephemeral
&& arg_template
&& !arg_directory
) {
1092 /* User asked for ephemeral execution but specified --template= instead of --directory=. Semantically
1093 * such an invocation makes some sense, see https://github.com/systemd/systemd/issues/3667. Let's
1094 * accept this here, and silently make "--ephemeral --template=" equivalent to "--ephemeral
1097 arg_directory
= arg_template
;
1098 arg_template
= NULL
;
1101 if (arg_template
&& !(arg_directory
|| arg_machine
)) {
1102 log_error("--template= needs --directory= or --machine=.");
1106 if (arg_ephemeral
&& arg_template
) {
1107 log_error("--ephemeral and --template= may not be combined.");
1111 if (arg_ephemeral
&& !IN_SET(arg_link_journal
, LINK_NO
, LINK_AUTO
)) {
1112 log_error("--ephemeral and --link-journal= may not be combined.");
1116 if (arg_userns_mode
!= USER_NAMESPACE_NO
&& !userns_supported()) {
1117 log_error("--private-users= is not supported, kernel compiled without user namespace support.");
1121 if (arg_userns_chown
&& arg_read_only
) {
1122 log_error("--read-only and --private-users-chown may not be combined.");
1126 if (arg_network_bridge
&& arg_network_zone
) {
1127 log_error("--network-bridge= and --network-zone= may not be combined.");
1131 if (argc
> optind
) {
1132 arg_parameters
= strv_copy(argv
+ optind
);
1133 if (!arg_parameters
)
1136 arg_settings_mask
|= SETTING_START_MODE
;
1139 /* Load all settings from .nspawn files */
1140 if (mask_no_settings
)
1141 arg_settings_mask
= 0;
1143 /* Don't load any settings from .nspawn files */
1144 if (mask_all_settings
)
1145 arg_settings_mask
= _SETTINGS_MASK_ALL
;
1147 arg_caps_retain
= (arg_caps_retain
| plus
| (arg_private_network
? 1ULL << CAP_NET_ADMIN
: 0)) & ~minus
;
1149 e
= getenv("SYSTEMD_NSPAWN_CONTAINER_SERVICE");
1151 arg_container_service_name
= e
;
1153 r
= getenv_bool("SYSTEMD_NSPAWN_USE_CGNS");
1155 arg_use_cgns
= cg_ns_supported();
1159 r
= custom_mount_check_all();
1166 static int verify_arguments(void) {
1167 if (arg_userns_mode
!= USER_NAMESPACE_NO
&& (arg_mount_settings
& MOUNT_APPLY_APIVFS_NETNS
) && !arg_private_network
) {
1168 log_error("Invalid namespacing settings. Mounting sysfs with --private-users requires --private-network.");
1172 if (arg_userns_mode
!= USER_NAMESPACE_NO
&& !(arg_mount_settings
& MOUNT_APPLY_APIVFS_RO
)) {
1173 log_error("Cannot combine --private-users with read-write mounts.");
1177 if (arg_volatile_mode
!= VOLATILE_NO
&& arg_read_only
) {
1178 log_error("Cannot combine --read-only with --volatile. Note that --volatile already implies a read-only base hierarchy.");
1182 if (arg_expose_ports
&& !arg_private_network
) {
1183 log_error("Cannot use --port= without private networking.");
1187 #ifndef HAVE_LIBIPTC
1188 if (arg_expose_ports
) {
1189 log_error("--port= is not supported, compiled without libiptc support.");
1194 if (arg_start_mode
== START_BOOT
&& arg_kill_signal
<= 0)
1195 arg_kill_signal
= SIGRTMIN
+3;
1200 static int userns_lchown(const char *p
, uid_t uid
, gid_t gid
) {
1203 if (arg_userns_mode
== USER_NAMESPACE_NO
)
1206 if (uid
== UID_INVALID
&& gid
== GID_INVALID
)
1209 if (uid
!= UID_INVALID
) {
1210 uid
+= arg_uid_shift
;
1212 if (uid
< arg_uid_shift
|| uid
>= arg_uid_shift
+ arg_uid_range
)
1216 if (gid
!= GID_INVALID
) {
1217 gid
+= (gid_t
) arg_uid_shift
;
1219 if (gid
< (gid_t
) arg_uid_shift
|| gid
>= (gid_t
) (arg_uid_shift
+ arg_uid_range
))
1223 if (lchown(p
, uid
, gid
) < 0)
1229 static int userns_mkdir(const char *root
, const char *path
, mode_t mode
, uid_t uid
, gid_t gid
) {
1232 q
= prefix_roota(root
, path
);
1233 if (mkdir(q
, mode
) < 0) {
1234 if (errno
== EEXIST
)
1239 return userns_lchown(q
, uid
, gid
);
1242 static int setup_timezone(const char *dest
) {
1243 _cleanup_free_
char *p
= NULL
, *q
= NULL
;
1244 const char *where
, *check
, *what
;
1250 /* Fix the timezone, if possible */
1251 r
= readlink_malloc("/etc/localtime", &p
);
1253 log_warning("host's /etc/localtime is not a symlink, not updating container timezone.");
1254 /* to handle warning, delete /etc/localtime and replace it
1255 * with a symbolic link to a time zone data file.
1258 * ln -s /usr/share/zoneinfo/UTC /etc/localtime
1263 z
= path_startswith(p
, "../usr/share/zoneinfo/");
1265 z
= path_startswith(p
, "/usr/share/zoneinfo/");
1267 log_warning("/etc/localtime does not point into /usr/share/zoneinfo/, not updating container timezone.");
1271 where
= prefix_roota(dest
, "/etc/localtime");
1272 r
= readlink_malloc(where
, &q
);
1274 y
= path_startswith(q
, "../usr/share/zoneinfo/");
1276 y
= path_startswith(q
, "/usr/share/zoneinfo/");
1278 /* Already pointing to the right place? Then do nothing .. */
1279 if (y
&& streq(y
, z
))
1283 check
= strjoina("/usr/share/zoneinfo/", z
);
1284 check
= prefix_roota(dest
, check
);
1285 if (laccess(check
, F_OK
) < 0) {
1286 log_warning("Timezone %s does not exist in container, not updating container timezone.", z
);
1291 if (r
< 0 && errno
!= ENOENT
) {
1292 log_error_errno(errno
, "Failed to remove existing timezone info %s in container: %m", where
);
1296 what
= strjoina("../usr/share/zoneinfo/", z
);
1297 if (symlink(what
, where
) < 0) {
1298 log_error_errno(errno
, "Failed to correct timezone of container: %m");
1302 r
= userns_lchown(where
, 0, 0);
1304 return log_warning_errno(r
, "Failed to chown /etc/localtime: %m");
1309 static int setup_resolv_conf(const char *dest
) {
1310 const char *where
= NULL
;
1315 if (arg_private_network
)
1318 /* Fix resolv.conf, if possible */
1319 where
= prefix_roota(dest
, "/etc/resolv.conf");
1321 if (access("/run/systemd/resolve/resolv.conf", F_OK
) >= 0 &&
1322 access("/usr/lib/systemd/resolv.conf", F_OK
) >= 0) {
1323 /* resolved is enabled on the host. In this, case bind mount its static resolv.conf file into the
1324 * container, so that the container can use the host's resolver. Given that network namespacing is
1325 * disabled it's only natural of the container also uses the host's resolver. It also has the big
1326 * advantage that the container will be able to follow the host's DNS server configuration changes
1329 (void) touch(where
);
1331 r
= mount_verbose(LOG_WARNING
, "/usr/lib/systemd/resolv.conf", where
, NULL
, MS_BIND
, NULL
);
1333 return mount_verbose(LOG_ERR
, NULL
, where
, NULL
,
1334 MS_BIND
|MS_REMOUNT
|MS_RDONLY
|MS_NOSUID
|MS_NODEV
, NULL
);
1337 /* If that didn't work, let's copy the file */
1338 r
= copy_file("/etc/resolv.conf", where
, O_TRUNC
|O_NOFOLLOW
, 0644, 0);
1340 /* If the file already exists as symlink, let's suppress the warning, under the assumption that
1341 * resolved or something similar runs inside and the symlink points there.
1343 * If the disk image is read-only, there's also no point in complaining.
1345 log_full_errno(IN_SET(r
, -ELOOP
, -EROFS
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1346 "Failed to copy /etc/resolv.conf to %s, ignoring: %m", where
);
1350 r
= userns_lchown(where
, 0, 0);
1352 log_warning_errno(r
, "Failed to chown /etc/resolv.conf, ignoring: %m");
1357 static int setup_boot_id(const char *dest
) {
1358 sd_id128_t rnd
= SD_ID128_NULL
;
1359 const char *from
, *to
;
1362 /* Generate a new randomized boot ID, so that each boot-up of
1363 * the container gets a new one */
1365 from
= prefix_roota(dest
, "/run/proc-sys-kernel-random-boot-id");
1366 to
= prefix_roota(dest
, "/proc/sys/kernel/random/boot_id");
1368 r
= sd_id128_randomize(&rnd
);
1370 return log_error_errno(r
, "Failed to generate random boot id: %m");
1372 r
= id128_write(from
, ID128_UUID
, rnd
, false);
1374 return log_error_errno(r
, "Failed to write boot id: %m");
1376 r
= mount_verbose(LOG_ERR
, from
, to
, NULL
, MS_BIND
, NULL
);
1378 r
= mount_verbose(LOG_ERR
, NULL
, to
, NULL
,
1379 MS_BIND
|MS_REMOUNT
|MS_RDONLY
|MS_NOSUID
|MS_NODEV
, NULL
);
1381 (void) unlink(from
);
1385 static int copy_devnodes(const char *dest
) {
1387 static const char devnodes
[] =
1398 _cleanup_umask_ mode_t u
;
1404 /* Create /dev/net, so that we can create /dev/net/tun in it */
1405 if (userns_mkdir(dest
, "/dev/net", 0755, 0, 0) < 0)
1406 return log_error_errno(r
, "Failed to create /dev/net directory: %m");
1408 NULSTR_FOREACH(d
, devnodes
) {
1409 _cleanup_free_
char *from
= NULL
, *to
= NULL
;
1412 from
= strappend("/dev/", d
);
1413 to
= prefix_root(dest
, from
);
1415 if (stat(from
, &st
) < 0) {
1417 if (errno
!= ENOENT
)
1418 return log_error_errno(errno
, "Failed to stat %s: %m", from
);
1420 } else if (!S_ISCHR(st
.st_mode
) && !S_ISBLK(st
.st_mode
)) {
1422 log_error("%s is not a char or block device, cannot copy.", from
);
1426 if (mknod(to
, st
.st_mode
, st
.st_rdev
) < 0) {
1428 * This is some sort of protection too against
1429 * recursive userns chown on shared /dev/
1431 if (errno
== EEXIST
)
1432 log_notice("%s/dev/ should be an empty directory", dest
);
1434 return log_error_errno(errno
, "mknod(%s) failed: %m", to
);
1436 /* Some systems abusively restrict mknod but
1437 * allow bind mounts. */
1440 return log_error_errno(r
, "touch (%s) failed: %m", to
);
1441 r
= mount_verbose(LOG_DEBUG
, from
, to
, NULL
, MS_BIND
, NULL
);
1443 return log_error_errno(r
, "Both mknod and bind mount (%s) failed: %m", to
);
1446 r
= userns_lchown(to
, 0, 0);
1448 return log_error_errno(r
, "chown() of device node %s failed: %m", to
);
1455 static int setup_pts(const char *dest
) {
1456 _cleanup_free_
char *options
= NULL
;
1461 if (arg_selinux_apifs_context
)
1462 (void) asprintf(&options
,
1463 "newinstance,ptmxmode=0666,mode=620,gid=" GID_FMT
",context=\"%s\"",
1464 arg_uid_shift
+ TTY_GID
,
1465 arg_selinux_apifs_context
);
1468 (void) asprintf(&options
,
1469 "newinstance,ptmxmode=0666,mode=620,gid=" GID_FMT
,
1470 arg_uid_shift
+ TTY_GID
);
1475 /* Mount /dev/pts itself */
1476 p
= prefix_roota(dest
, "/dev/pts");
1477 if (mkdir(p
, 0755) < 0)
1478 return log_error_errno(errno
, "Failed to create /dev/pts: %m");
1479 r
= mount_verbose(LOG_ERR
, "devpts", p
, "devpts", MS_NOSUID
|MS_NOEXEC
, options
);
1482 r
= userns_lchown(p
, 0, 0);
1484 return log_error_errno(r
, "Failed to chown /dev/pts: %m");
1486 /* Create /dev/ptmx symlink */
1487 p
= prefix_roota(dest
, "/dev/ptmx");
1488 if (symlink("pts/ptmx", p
) < 0)
1489 return log_error_errno(errno
, "Failed to create /dev/ptmx symlink: %m");
1490 r
= userns_lchown(p
, 0, 0);
1492 return log_error_errno(r
, "Failed to chown /dev/ptmx: %m");
1494 /* And fix /dev/pts/ptmx ownership */
1495 p
= prefix_roota(dest
, "/dev/pts/ptmx");
1496 r
= userns_lchown(p
, 0, 0);
1498 return log_error_errno(r
, "Failed to chown /dev/pts/ptmx: %m");
1503 static int setup_dev_console(const char *dest
, const char *console
) {
1504 _cleanup_umask_ mode_t u
;
1513 r
= chmod_and_chown(console
, 0600, arg_uid_shift
, arg_uid_shift
);
1515 return log_error_errno(r
, "Failed to correct access mode for TTY: %m");
1517 /* We need to bind mount the right tty to /dev/console since
1518 * ptys can only exist on pts file systems. To have something
1519 * to bind mount things on we create a empty regular file. */
1521 to
= prefix_roota(dest
, "/dev/console");
1524 return log_error_errno(r
, "touch() for /dev/console failed: %m");
1526 return mount_verbose(LOG_ERR
, console
, to
, NULL
, MS_BIND
, NULL
);
1529 static int setup_kmsg(const char *dest
, int kmsg_socket
) {
1530 const char *from
, *to
;
1531 _cleanup_umask_ mode_t u
;
1534 assert(kmsg_socket
>= 0);
1538 /* We create the kmsg FIFO as /run/kmsg, but immediately
1539 * delete it after bind mounting it to /proc/kmsg. While FIFOs
1540 * on the reading side behave very similar to /proc/kmsg,
1541 * their writing side behaves differently from /dev/kmsg in
1542 * that writing blocks when nothing is reading. In order to
1543 * avoid any problems with containers deadlocking due to this
1544 * we simply make /dev/kmsg unavailable to the container. */
1545 from
= prefix_roota(dest
, "/run/kmsg");
1546 to
= prefix_roota(dest
, "/proc/kmsg");
1548 if (mkfifo(from
, 0600) < 0)
1549 return log_error_errno(errno
, "mkfifo() for /run/kmsg failed: %m");
1550 r
= mount_verbose(LOG_ERR
, from
, to
, NULL
, MS_BIND
, NULL
);
1554 fd
= open(from
, O_RDWR
|O_NDELAY
|O_CLOEXEC
);
1556 return log_error_errno(errno
, "Failed to open fifo: %m");
1558 /* Store away the fd in the socket, so that it stays open as
1559 * long as we run the child */
1560 r
= send_one_fd(kmsg_socket
, fd
, 0);
1564 return log_error_errno(r
, "Failed to send FIFO fd: %m");
1566 /* And now make the FIFO unavailable as /run/kmsg... */
1567 (void) unlink(from
);
1572 static int on_address_change(sd_netlink
*rtnl
, sd_netlink_message
*m
, void *userdata
) {
1573 union in_addr_union
*exposed
= userdata
;
1579 expose_port_execute(rtnl
, arg_expose_ports
, exposed
);
1583 static int setup_hostname(void) {
1585 if ((arg_clone_ns_flags
& CLONE_NEWUTS
) == 0)
1588 if (sethostname_idempotent(arg_machine
) < 0)
1594 static int setup_journal(const char *directory
) {
1596 _cleanup_free_
char *d
= NULL
;
1602 /* Don't link journals in ephemeral mode */
1606 if (arg_link_journal
== LINK_NO
)
1609 try = arg_link_journal_try
|| arg_link_journal
== LINK_AUTO
;
1611 r
= sd_id128_get_machine(&this_id
);
1613 return log_error_errno(r
, "Failed to retrieve machine ID: %m");
1615 if (sd_id128_equal(arg_uuid
, this_id
)) {
1616 log_full(try ? LOG_WARNING
: LOG_ERR
,
1617 "Host and machine ids are equal (%s): refusing to link journals", sd_id128_to_string(arg_uuid
, id
));
1623 r
= userns_mkdir(directory
, "/var", 0755, 0, 0);
1625 return log_error_errno(r
, "Failed to create /var: %m");
1627 r
= userns_mkdir(directory
, "/var/log", 0755, 0, 0);
1629 return log_error_errno(r
, "Failed to create /var/log: %m");
1631 r
= userns_mkdir(directory
, "/var/log/journal", 0755, 0, 0);
1633 return log_error_errno(r
, "Failed to create /var/log/journal: %m");
1635 (void) sd_id128_to_string(arg_uuid
, id
);
1637 p
= strjoina("/var/log/journal/", id
);
1638 q
= prefix_roota(directory
, p
);
1640 if (path_is_mount_point(p
, NULL
, 0) > 0) {
1644 log_error("%s: already a mount point, refusing to use for journal", p
);
1648 if (path_is_mount_point(q
, NULL
, 0) > 0) {
1652 log_error("%s: already a mount point, refusing to use for journal", q
);
1656 r
= readlink_and_make_absolute(p
, &d
);
1658 if ((arg_link_journal
== LINK_GUEST
||
1659 arg_link_journal
== LINK_AUTO
) &&
1662 r
= userns_mkdir(directory
, p
, 0755, 0, 0);
1664 log_warning_errno(r
, "Failed to create directory %s: %m", q
);
1669 return log_error_errno(errno
, "Failed to remove symlink %s: %m", p
);
1670 } else if (r
== -EINVAL
) {
1672 if (arg_link_journal
== LINK_GUEST
&&
1675 if (errno
== ENOTDIR
) {
1676 log_error("%s already exists and is neither a symlink nor a directory", p
);
1679 return log_error_errno(errno
, "Failed to remove %s: %m", p
);
1681 } else if (r
!= -ENOENT
)
1682 return log_error_errno(r
, "readlink(%s) failed: %m", p
);
1684 if (arg_link_journal
== LINK_GUEST
) {
1686 if (symlink(q
, p
) < 0) {
1688 log_debug_errno(errno
, "Failed to symlink %s to %s, skipping journal setup: %m", q
, p
);
1691 return log_error_errno(errno
, "Failed to symlink %s to %s: %m", q
, p
);
1694 r
= userns_mkdir(directory
, p
, 0755, 0, 0);
1696 log_warning_errno(r
, "Failed to create directory %s: %m", q
);
1700 if (arg_link_journal
== LINK_HOST
) {
1701 /* don't create parents here — if the host doesn't have
1702 * permanent journal set up, don't force it here */
1704 if (mkdir(p
, 0755) < 0 && errno
!= EEXIST
) {
1706 log_debug_errno(errno
, "Failed to create %s, skipping journal setup: %m", p
);
1709 return log_error_errno(errno
, "Failed to create %s: %m", p
);
1712 } else if (access(p
, F_OK
) < 0)
1715 if (dir_is_empty(q
) == 0)
1716 log_warning("%s is not empty, proceeding anyway.", q
);
1718 r
= userns_mkdir(directory
, p
, 0755, 0, 0);
1720 return log_error_errno(r
, "Failed to create %s: %m", q
);
1722 r
= mount_verbose(LOG_DEBUG
, p
, q
, NULL
, MS_BIND
, NULL
);
1724 return log_error_errno(errno
, "Failed to bind mount journal from host into guest: %m");
1729 static int drop_capabilities(void) {
1730 return capability_bounding_set_drop(arg_caps_retain
, false);
1733 static int reset_audit_loginuid(void) {
1734 _cleanup_free_
char *p
= NULL
;
1737 if ((arg_clone_ns_flags
& CLONE_NEWPID
) == 0)
1740 r
= read_one_line_file("/proc/self/loginuid", &p
);
1744 return log_error_errno(r
, "Failed to read /proc/self/loginuid: %m");
1746 /* Already reset? */
1747 if (streq(p
, "4294967295"))
1750 r
= write_string_file("/proc/self/loginuid", "4294967295", 0);
1753 "Failed to reset audit login UID. This probably means that your kernel is too\n"
1754 "old and you have audit enabled. Note that the auditing subsystem is known to\n"
1755 "be incompatible with containers on old kernels. Please make sure to upgrade\n"
1756 "your kernel or to off auditing with 'audit=0' on the kernel command line before\n"
1757 "using systemd-nspawn. Sleeping for 5s... (%m)");
1766 static int setup_propagate(const char *root
) {
1770 (void) mkdir_p("/run/systemd/nspawn/", 0755);
1771 (void) mkdir_p("/run/systemd/nspawn/propagate", 0600);
1772 p
= strjoina("/run/systemd/nspawn/propagate/", arg_machine
);
1773 (void) mkdir_p(p
, 0600);
1775 r
= userns_mkdir(root
, "/run/systemd", 0755, 0, 0);
1777 return log_error_errno(r
, "Failed to create /run/systemd: %m");
1779 r
= userns_mkdir(root
, "/run/systemd/nspawn", 0755, 0, 0);
1781 return log_error_errno(r
, "Failed to create /run/systemd/nspawn: %m");
1783 r
= userns_mkdir(root
, "/run/systemd/nspawn/incoming", 0600, 0, 0);
1785 return log_error_errno(r
, "Failed to create /run/systemd/nspawn/incoming: %m");
1787 q
= prefix_roota(root
, "/run/systemd/nspawn/incoming");
1788 r
= mount_verbose(LOG_ERR
, p
, q
, NULL
, MS_BIND
, NULL
);
1792 r
= mount_verbose(LOG_ERR
, NULL
, q
, NULL
, MS_BIND
|MS_REMOUNT
|MS_RDONLY
, NULL
);
1796 /* machined will MS_MOVE into that directory, and that's only
1797 * supported for non-shared mounts. */
1798 return mount_verbose(LOG_ERR
, NULL
, q
, NULL
, MS_SLAVE
, NULL
);
1801 static int setup_machine_id(const char *directory
) {
1802 const char *etc_machine_id
;
1806 /* If the UUID in the container is already set, then that's what counts, and we use. If it isn't set, and the
1807 * caller passed --uuid=, then we'll pass it in the $container_uuid env var to PID 1 of the container. The
1808 * assumption is that PID 1 will then write it to /etc/machine-id to make it persistent. If --uuid= is not
1809 * passed we generate a random UUID, and pass it via $container_uuid. In effect this means that /etc/machine-id
1810 * in the container and our idea of the container UUID will always be in sync (at least if PID 1 in the
1811 * container behaves nicely). */
1813 etc_machine_id
= prefix_roota(directory
, "/etc/machine-id");
1815 r
= id128_read(etc_machine_id
, ID128_PLAIN
, &id
);
1817 if (!IN_SET(r
, -ENOENT
, -ENOMEDIUM
)) /* If the file is missing or empty, we don't mind */
1818 return log_error_errno(r
, "Failed to read machine ID from container image: %m");
1820 if (sd_id128_is_null(arg_uuid
)) {
1821 r
= sd_id128_randomize(&arg_uuid
);
1823 return log_error_errno(r
, "Failed to acquire randomized machine UUID: %m");
1826 if (sd_id128_is_null(id
)) {
1827 log_error("Machine ID in container image is zero, refusing.");
1837 static int recursive_chown(const char *directory
, uid_t shift
, uid_t range
) {
1842 if (arg_userns_mode
== USER_NAMESPACE_NO
|| !arg_userns_chown
)
1845 r
= path_patch_uid(directory
, arg_uid_shift
, arg_uid_range
);
1846 if (r
== -EOPNOTSUPP
)
1847 return log_error_errno(r
, "Automatic UID/GID adjusting is only supported for UID/GID ranges starting at multiples of 2^16 with a range of 2^16.");
1849 return log_error_errno(r
, "Upper 16 bits of root directory UID and GID do not match.");
1851 return log_error_errno(r
, "Failed to adjust UID/GID shift of OS tree: %m");
1853 log_debug("Root directory of image is already owned by the right UID/GID range, skipping recursive chown operation.");
1855 log_debug("Patched directory tree to match UID/GID range.");
1862 * < 0 : wait_for_terminate() failed to get the state of the
1863 * container, the container was terminated by a signal, or
1864 * failed for an unknown reason. No change is made to the
1865 * container argument.
1866 * > 0 : The program executed in the container terminated with an
1867 * error. The exit code of the program executed in the
1868 * container is returned. The container argument has been set
1869 * to CONTAINER_TERMINATED.
1870 * 0 : The container is being rebooted, has been shut down or exited
1871 * successfully. The container argument has been set to either
1872 * CONTAINER_TERMINATED or CONTAINER_REBOOTED.
1874 * That is, success is indicated by a return value of zero, and an
1875 * error is indicated by a non-zero value.
1877 static int wait_for_container(pid_t pid
, ContainerStatus
*container
) {
1881 r
= wait_for_terminate(pid
, &status
);
1883 return log_warning_errno(r
, "Failed to wait for container: %m");
1885 switch (status
.si_code
) {
1888 if (status
.si_status
== 0)
1889 log_full(arg_quiet
? LOG_DEBUG
: LOG_INFO
, "Container %s exited successfully.", arg_machine
);
1891 log_full(arg_quiet
? LOG_DEBUG
: LOG_INFO
, "Container %s failed with error code %i.", arg_machine
, status
.si_status
);
1893 *container
= CONTAINER_TERMINATED
;
1894 return status
.si_status
;
1897 if (status
.si_status
== SIGINT
) {
1898 log_full(arg_quiet
? LOG_DEBUG
: LOG_INFO
, "Container %s has been shut down.", arg_machine
);
1899 *container
= CONTAINER_TERMINATED
;
1902 } else if (status
.si_status
== SIGHUP
) {
1903 log_full(arg_quiet
? LOG_DEBUG
: LOG_INFO
, "Container %s is being rebooted.", arg_machine
);
1904 *container
= CONTAINER_REBOOTED
;
1908 /* CLD_KILLED fallthrough */
1911 log_error("Container %s terminated by signal %s.", arg_machine
, signal_to_string(status
.si_status
));
1915 log_error("Container %s failed due to unknown reason.", arg_machine
);
1920 static int on_orderly_shutdown(sd_event_source
*s
, const struct signalfd_siginfo
*si
, void *userdata
) {
1923 pid
= PTR_TO_PID(userdata
);
1925 if (kill(pid
, arg_kill_signal
) >= 0) {
1926 log_info("Trying to halt container. Send SIGTERM again to trigger immediate termination.");
1927 sd_event_source_set_userdata(s
, NULL
);
1932 sd_event_exit(sd_event_source_get_event(s
), 0);
1936 static int determine_names(void) {
1939 if (arg_template
&& !arg_directory
&& arg_machine
) {
1941 /* If --template= was specified then we should not
1942 * search for a machine, but instead create a new one
1943 * in /var/lib/machine. */
1945 arg_directory
= strjoin("/var/lib/machines/", arg_machine
);
1950 if (!arg_image
&& !arg_directory
) {
1952 _cleanup_(image_unrefp
) Image
*i
= NULL
;
1954 r
= image_find(arg_machine
, &i
);
1956 return log_error_errno(r
, "Failed to find image for machine '%s': %m", arg_machine
);
1958 log_error("No image for machine '%s': %m", arg_machine
);
1962 if (i
->type
== IMAGE_RAW
)
1963 r
= free_and_strdup(&arg_image
, i
->path
);
1965 r
= free_and_strdup(&arg_directory
, i
->path
);
1970 arg_read_only
= arg_read_only
|| i
->read_only
;
1972 arg_directory
= get_current_dir_name();
1974 if (!arg_directory
&& !arg_image
) {
1975 log_error("Failed to determine path, please use -D or -i.");
1982 if (arg_directory
&& path_equal(arg_directory
, "/"))
1983 arg_machine
= gethostname_malloc();
1988 arg_machine
= strdup(basename(arg_image
));
1990 /* Truncate suffix if there is one */
1991 e
= endswith(arg_machine
, ".raw");
1995 arg_machine
= strdup(basename(arg_directory
));
2000 hostname_cleanup(arg_machine
);
2001 if (!machine_name_is_valid(arg_machine
)) {
2002 log_error("Failed to determine machine name automatically, please use -M.");
2006 if (arg_ephemeral
) {
2009 /* Add a random suffix when this is an
2010 * ephemeral machine, so that we can run many
2011 * instances at once without manually having
2012 * to specify -M each time. */
2014 if (asprintf(&b
, "%s-%016" PRIx64
, arg_machine
, random_u64()) < 0)
2025 static int chase_symlinks_and_update(char **p
, unsigned flags
) {
2034 r
= chase_symlinks(*p
, NULL
, flags
, &chased
);
2036 return log_error_errno(r
, "Failed to resolve path %s: %m", *p
);
2044 static int determine_uid_shift(const char *directory
) {
2047 if (arg_userns_mode
== USER_NAMESPACE_NO
) {
2052 if (arg_uid_shift
== UID_INVALID
) {
2055 r
= stat(directory
, &st
);
2057 return log_error_errno(errno
, "Failed to determine UID base of %s: %m", directory
);
2059 arg_uid_shift
= st
.st_uid
& UINT32_C(0xffff0000);
2061 if (arg_uid_shift
!= (st
.st_gid
& UINT32_C(0xffff0000))) {
2062 log_error("UID and GID base of %s don't match.", directory
);
2066 arg_uid_range
= UINT32_C(0x10000);
2069 if (arg_uid_shift
> (uid_t
) -1 - arg_uid_range
) {
2070 log_error("UID base too high for UID range.");
2077 static int inner_child(
2079 const char *directory
,
2085 _cleanup_free_
char *home
= NULL
;
2088 const char *envp
[] = {
2089 "PATH=" DEFAULT_PATH_SPLIT_USR
,
2090 NULL
, /* container */
2095 NULL
, /* container_uuid */
2096 NULL
, /* LISTEN_FDS */
2097 NULL
, /* LISTEN_PID */
2098 NULL
, /* NOTIFY_SOCKET */
2102 _cleanup_strv_free_
char **env_use
= NULL
;
2107 assert(kmsg_socket
>= 0);
2111 if (arg_userns_mode
!= USER_NAMESPACE_NO
) {
2112 /* Tell the parent, that it now can write the UID map. */
2113 (void) barrier_place(barrier
); /* #1 */
2115 /* Wait until the parent wrote the UID map */
2116 if (!barrier_place_and_sync(barrier
)) { /* #2 */
2117 log_error("Parent died too early");
2122 r
= reset_uid_gid();
2124 return log_error_errno(r
, "Couldn't become new root: %m");
2127 arg_mount_settings
| MOUNT_IN_USERNS
,
2130 arg_selinux_apifs_context
);
2135 r
= mount_sysfs(NULL
, arg_mount_settings
);
2139 /* Wait until we are cgroup-ified, so that we
2140 * can mount the right cgroup path writable */
2141 if (!barrier_place_and_sync(barrier
)) { /* #3 */
2142 log_error("Parent died too early");
2146 if (arg_use_cgns
&& cg_ns_supported()) {
2147 r
= unshare(CLONE_NEWCGROUP
);
2149 return log_error_errno(errno
, "Failed to unshare cgroup namespace");
2152 arg_unified_cgroup_hierarchy
,
2153 arg_userns_mode
!= USER_NAMESPACE_NO
,
2156 arg_selinux_apifs_context
,
2161 r
= mount_systemd_cgroup_writable("", arg_unified_cgroup_hierarchy
);
2166 r
= setup_boot_id(NULL
);
2170 r
= setup_kmsg(NULL
, kmsg_socket
);
2173 kmsg_socket
= safe_close(kmsg_socket
);
2178 return log_error_errno(errno
, "setsid() failed: %m");
2180 if (arg_private_network
)
2183 if (arg_expose_ports
) {
2184 r
= expose_port_send_rtnl(rtnl_socket
);
2187 rtnl_socket
= safe_close(rtnl_socket
);
2190 r
= drop_capabilities();
2192 return log_error_errno(r
, "drop_capabilities() failed: %m");
2196 if (arg_personality
!= PERSONALITY_INVALID
) {
2197 if (personality(arg_personality
) < 0)
2198 return log_error_errno(errno
, "personality() failed: %m");
2199 } else if (secondary
) {
2200 if (personality(PER_LINUX32
) < 0)
2201 return log_error_errno(errno
, "personality() failed: %m");
2205 if (arg_selinux_context
)
2206 if (setexeccon(arg_selinux_context
) < 0)
2207 return log_error_errno(errno
, "setexeccon(\"%s\") failed: %m", arg_selinux_context
);
2210 r
= change_uid_gid(arg_user
, &home
);
2214 /* LXC sets container=lxc, so follow the scheme here */
2215 envp
[n_env
++] = strjoina("container=", arg_container_service_name
);
2217 envp
[n_env
] = strv_find_prefix(environ
, "TERM=");
2221 if ((asprintf((char**)(envp
+ n_env
++), "HOME=%s", home
? home
: "/root") < 0) ||
2222 (asprintf((char**)(envp
+ n_env
++), "USER=%s", arg_user
? arg_user
: "root") < 0) ||
2223 (asprintf((char**)(envp
+ n_env
++), "LOGNAME=%s", arg_user
? arg_user
: "root") < 0))
2226 assert(!sd_id128_is_null(arg_uuid
));
2228 if (asprintf((char**)(envp
+ n_env
++), "container_uuid=%s", id128_to_uuid_string(arg_uuid
, as_uuid
)) < 0)
2231 if (fdset_size(fds
) > 0) {
2232 r
= fdset_cloexec(fds
, false);
2234 return log_error_errno(r
, "Failed to unset O_CLOEXEC for file descriptors.");
2236 if ((asprintf((char **)(envp
+ n_env
++), "LISTEN_FDS=%u", fdset_size(fds
)) < 0) ||
2237 (asprintf((char **)(envp
+ n_env
++), "LISTEN_PID=1") < 0))
2240 if (asprintf((char **)(envp
+ n_env
++), "NOTIFY_SOCKET=%s", NSPAWN_NOTIFY_SOCKET_PATH
) < 0)
2243 env_use
= strv_env_merge(2, envp
, arg_setenv
);
2247 /* Let the parent know that we are ready and
2248 * wait until the parent is ready with the
2250 if (!barrier_place_and_sync(barrier
)) { /* #4 */
2251 log_error("Parent died too early");
2256 if (chdir(arg_chdir
) < 0)
2257 return log_error_errno(errno
, "Failed to change to specified working directory %s: %m", arg_chdir
);
2259 if (arg_start_mode
== START_PID2
) {
2265 /* Now, explicitly close the log, so that we
2266 * then can close all remaining fds. Closing
2267 * the log explicitly first has the benefit
2268 * that the logging subsystem knows about it,
2269 * and is thus ready to be reopened should we
2270 * need it again. Note that the other fds
2271 * closed here are at least the locking and
2274 (void) fdset_close_others(fds
);
2276 if (arg_start_mode
== START_BOOT
) {
2280 /* Automatically search for the init system */
2282 m
= strv_length(arg_parameters
);
2283 a
= newa(char*, m
+ 2);
2284 memcpy_safe(a
+ 1, arg_parameters
, m
* sizeof(char*));
2287 a
[0] = (char*) "/usr/lib/systemd/systemd";
2288 execve(a
[0], a
, env_use
);
2290 a
[0] = (char*) "/lib/systemd/systemd";
2291 execve(a
[0], a
, env_use
);
2293 a
[0] = (char*) "/sbin/init";
2294 execve(a
[0], a
, env_use
);
2295 } else if (!strv_isempty(arg_parameters
))
2296 execvpe(arg_parameters
[0], arg_parameters
, env_use
);
2299 /* If we cannot change the directory, we'll end up in /, that is expected. */
2300 (void) chdir(home
?: "/root");
2302 execle("/bin/bash", "-bash", NULL
, env_use
);
2303 execle("/bin/sh", "-sh", NULL
, env_use
);
2308 return log_error_errno(r
, "execv() failed: %m");
2311 static int setup_sd_notify_child(void) {
2312 static const int one
= 1;
2314 union sockaddr_union sa
= {
2315 .sa
.sa_family
= AF_UNIX
,
2319 fd
= socket(AF_UNIX
, SOCK_DGRAM
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
2321 return log_error_errno(errno
, "Failed to allocate notification socket: %m");
2323 (void) mkdir_parents(NSPAWN_NOTIFY_SOCKET_PATH
, 0755);
2324 (void) unlink(NSPAWN_NOTIFY_SOCKET_PATH
);
2326 strncpy(sa
.un
.sun_path
, NSPAWN_NOTIFY_SOCKET_PATH
, sizeof(sa
.un
.sun_path
)-1);
2327 r
= bind(fd
, &sa
.sa
, SOCKADDR_UN_LEN(sa
.un
));
2330 return log_error_errno(errno
, "bind(%s) failed: %m", sa
.un
.sun_path
);
2333 r
= setsockopt(fd
, SOL_SOCKET
, SO_PASSCRED
, &one
, sizeof(one
));
2336 return log_error_errno(errno
, "SO_PASSCRED failed: %m");
2342 static int outer_child(
2344 const char *directory
,
2345 const char *console
,
2346 DissectedImage
*dissected_image
,
2354 int uid_shift_socket
,
2360 _cleanup_close_
int fd
= -1;
2365 assert(pid_socket
>= 0);
2366 assert(uuid_socket
>= 0);
2367 assert(notify_socket
>= 0);
2368 assert(kmsg_socket
>= 0);
2372 if (prctl(PR_SET_PDEATHSIG
, SIGKILL
) < 0)
2373 return log_error_errno(errno
, "PR_SET_PDEATHSIG failed: %m");
2376 close_nointr(STDIN_FILENO
);
2377 close_nointr(STDOUT_FILENO
);
2378 close_nointr(STDERR_FILENO
);
2380 r
= open_terminal(console
, O_RDWR
);
2381 if (r
!= STDIN_FILENO
) {
2387 return log_error_errno(r
, "Failed to open console: %m");
2390 if (dup2(STDIN_FILENO
, STDOUT_FILENO
) != STDOUT_FILENO
||
2391 dup2(STDIN_FILENO
, STDERR_FILENO
) != STDERR_FILENO
)
2392 return log_error_errno(errno
, "Failed to duplicate console: %m");
2395 r
= reset_audit_loginuid();
2399 /* Mark everything as slave, so that we still
2400 * receive mounts from the real root, but don't
2401 * propagate mounts to the real root. */
2402 r
= mount_verbose(LOG_ERR
, NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
);
2406 if (dissected_image
) {
2407 r
= dissected_image_mount(dissected_image
, directory
, DISSECT_IMAGE_DISCARD_ON_LOOP
|(arg_read_only
? DISSECT_IMAGE_READ_ONLY
: 0));
2412 r
= determine_uid_shift(directory
);
2416 r
= detect_unified_cgroup_hierarchy(directory
);
2420 if (arg_userns_mode
!= USER_NAMESPACE_NO
) {
2421 /* Let the parent know which UID shift we read from the image */
2422 l
= send(uid_shift_socket
, &arg_uid_shift
, sizeof(arg_uid_shift
), MSG_NOSIGNAL
);
2424 return log_error_errno(errno
, "Failed to send UID shift: %m");
2425 if (l
!= sizeof(arg_uid_shift
)) {
2426 log_error("Short write while sending UID shift.");
2430 if (arg_userns_mode
== USER_NAMESPACE_PICK
) {
2431 /* When we are supposed to pick the UID shift, the parent will check now whether the UID shift
2432 * we just read from the image is available. If yes, it will send the UID shift back to us, if
2433 * not it will pick a different one, and send it back to us. */
2435 l
= recv(uid_shift_socket
, &arg_uid_shift
, sizeof(arg_uid_shift
), 0);
2437 return log_error_errno(errno
, "Failed to recv UID shift: %m");
2438 if (l
!= sizeof(arg_uid_shift
)) {
2439 log_error("Short read while receiving UID shift.");
2444 log_info("Selected user namespace base " UID_FMT
" and range " UID_FMT
".", arg_uid_shift
, arg_uid_range
);
2447 /* Turn directory into bind mount */
2448 r
= mount_verbose(LOG_ERR
, directory
, directory
, NULL
, MS_BIND
|MS_REC
, NULL
);
2452 /* Mark everything as shared so our mounts get propagated down. This is
2453 * required to make new bind mounts available in systemd services
2454 * inside the containter that create a new mount namespace.
2455 * See https://github.com/systemd/systemd/issues/3860
2456 * Further submounts (such as /dev) done after this will inherit the
2457 * shared propagation mode.*/
2458 r
= mount_verbose(LOG_ERR
, NULL
, directory
, NULL
, MS_SHARED
|MS_REC
, NULL
);
2462 r
= recursive_chown(directory
, arg_uid_shift
, arg_uid_range
);
2469 arg_userns_mode
!= USER_NAMESPACE_NO
,
2472 arg_selinux_context
);
2476 r
= setup_volatile_state(
2479 arg_userns_mode
!= USER_NAMESPACE_NO
,
2482 arg_selinux_context
);
2486 r
= base_filesystem_create(directory
, arg_uid_shift
, (gid_t
) arg_uid_shift
);
2490 if (arg_read_only
) {
2491 r
= bind_remount_recursive(directory
, true, NULL
);
2493 return log_error_errno(r
, "Failed to make tree read-only: %m");
2496 r
= mount_all(directory
,
2500 arg_selinux_apifs_context
);
2504 r
= copy_devnodes(directory
);
2508 dev_setup(directory
, arg_uid_shift
, arg_uid_shift
);
2510 r
= setup_pts(directory
);
2514 r
= setup_propagate(directory
);
2518 r
= setup_dev_console(directory
, console
);
2522 r
= setup_seccomp(arg_caps_retain
);
2526 r
= setup_timezone(directory
);
2530 r
= setup_resolv_conf(directory
);
2534 r
= setup_machine_id(directory
);
2538 r
= setup_journal(directory
);
2545 arg_n_custom_mounts
,
2546 arg_userns_mode
!= USER_NAMESPACE_NO
,
2549 arg_selinux_apifs_context
);
2553 if (!arg_use_cgns
|| !cg_ns_supported()) {
2556 arg_unified_cgroup_hierarchy
,
2557 arg_userns_mode
!= USER_NAMESPACE_NO
,
2560 arg_selinux_apifs_context
,
2566 r
= mount_move_root(directory
);
2568 return log_error_errno(r
, "Failed to move root directory: %m");
2570 fd
= setup_sd_notify_child();
2574 pid
= raw_clone(SIGCHLD
|CLONE_NEWNS
|
2575 arg_clone_ns_flags
|
2576 (arg_private_network
? CLONE_NEWNET
: 0) |
2577 (arg_userns_mode
!= USER_NAMESPACE_NO
? CLONE_NEWUSER
: 0));
2579 return log_error_errno(errno
, "Failed to fork inner child: %m");
2581 pid_socket
= safe_close(pid_socket
);
2582 uuid_socket
= safe_close(uuid_socket
);
2583 notify_socket
= safe_close(notify_socket
);
2584 uid_shift_socket
= safe_close(uid_shift_socket
);
2586 /* The inner child has all namespaces that are
2587 * requested, so that we all are owned by the user if
2588 * user namespaces are turned on. */
2590 r
= inner_child(barrier
, directory
, secondary
, kmsg_socket
, rtnl_socket
, fds
);
2592 _exit(EXIT_FAILURE
);
2594 _exit(EXIT_SUCCESS
);
2597 l
= send(pid_socket
, &pid
, sizeof(pid
), MSG_NOSIGNAL
);
2599 return log_error_errno(errno
, "Failed to send PID: %m");
2600 if (l
!= sizeof(pid
)) {
2601 log_error("Short write while sending PID.");
2605 l
= send(uuid_socket
, &arg_uuid
, sizeof(arg_uuid
), MSG_NOSIGNAL
);
2607 return log_error_errno(errno
, "Failed to send machine ID: %m");
2608 if (l
!= sizeof(arg_uuid
)) {
2609 log_error("Short write while sending machine ID.");
2613 l
= send_one_fd(notify_socket
, fd
, 0);
2615 return log_error_errno(errno
, "Failed to send notify fd: %m");
2617 pid_socket
= safe_close(pid_socket
);
2618 uuid_socket
= safe_close(uuid_socket
);
2619 notify_socket
= safe_close(notify_socket
);
2620 kmsg_socket
= safe_close(kmsg_socket
);
2621 rtnl_socket
= safe_close(rtnl_socket
);
2626 static int uid_shift_pick(uid_t
*shift
, LockFile
*ret_lock_file
) {
2627 unsigned n_tries
= 100;
2632 assert(ret_lock_file
);
2633 assert(arg_userns_mode
== USER_NAMESPACE_PICK
);
2634 assert(arg_uid_range
== 0x10000U
);
2638 (void) mkdir("/run/systemd/nspawn-uid", 0755);
2641 char lock_path
[strlen("/run/systemd/nspawn-uid/") + DECIMAL_STR_MAX(uid_t
) + 1];
2642 _cleanup_release_lock_file_ LockFile lf
= LOCK_FILE_INIT
;
2647 if (candidate
< UID_SHIFT_PICK_MIN
|| candidate
> UID_SHIFT_PICK_MAX
)
2649 if ((candidate
& UINT32_C(0xFFFF)) != 0)
2652 xsprintf(lock_path
, "/run/systemd/nspawn-uid/" UID_FMT
, candidate
);
2653 r
= make_lock_file(lock_path
, LOCK_EX
|LOCK_NB
, &lf
);
2654 if (r
== -EBUSY
) /* Range already taken by another nspawn instance */
2659 /* Make some superficial checks whether the range is currently known in the user database */
2660 if (getpwuid(candidate
))
2662 if (getpwuid(candidate
+ UINT32_C(0xFFFE)))
2664 if (getgrgid(candidate
))
2666 if (getgrgid(candidate
+ UINT32_C(0xFFFE)))
2669 *ret_lock_file
= lf
;
2670 lf
= (struct LockFile
) LOCK_FILE_INIT
;
2675 random_bytes(&candidate
, sizeof(candidate
));
2676 candidate
= (candidate
% (UID_SHIFT_PICK_MAX
- UID_SHIFT_PICK_MIN
)) + UID_SHIFT_PICK_MIN
;
2677 candidate
&= (uid_t
) UINT32_C(0xFFFF0000);
2681 static int setup_uid_map(pid_t pid
) {
2682 char uid_map
[strlen("/proc//uid_map") + DECIMAL_STR_MAX(uid_t
) + 1], line
[DECIMAL_STR_MAX(uid_t
)*3+3+1];
2687 xsprintf(uid_map
, "/proc/" PID_FMT
"/uid_map", pid
);
2688 xsprintf(line
, UID_FMT
" " UID_FMT
" " UID_FMT
"\n", 0, arg_uid_shift
, arg_uid_range
);
2689 r
= write_string_file(uid_map
, line
, 0);
2691 return log_error_errno(r
, "Failed to write UID map: %m");
2693 /* We always assign the same UID and GID ranges */
2694 xsprintf(uid_map
, "/proc/" PID_FMT
"/gid_map", pid
);
2695 r
= write_string_file(uid_map
, line
, 0);
2697 return log_error_errno(r
, "Failed to write GID map: %m");
2702 static int nspawn_dispatch_notify_fd(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
2703 char buf
[NOTIFY_BUFFER_MAX
+1];
2705 struct iovec iovec
= {
2707 .iov_len
= sizeof(buf
)-1,
2710 struct cmsghdr cmsghdr
;
2711 uint8_t buf
[CMSG_SPACE(sizeof(struct ucred
)) +
2712 CMSG_SPACE(sizeof(int) * NOTIFY_FD_MAX
)];
2714 struct msghdr msghdr
= {
2717 .msg_control
= &control
,
2718 .msg_controllen
= sizeof(control
),
2720 struct cmsghdr
*cmsg
;
2721 struct ucred
*ucred
= NULL
;
2723 pid_t inner_child_pid
;
2724 _cleanup_strv_free_
char **tags
= NULL
;
2728 inner_child_pid
= PTR_TO_PID(userdata
);
2730 if (revents
!= EPOLLIN
) {
2731 log_warning("Got unexpected poll event for notify fd.");
2735 n
= recvmsg(fd
, &msghdr
, MSG_DONTWAIT
|MSG_CMSG_CLOEXEC
);
2737 if (errno
== EAGAIN
|| errno
== EINTR
)
2740 return log_warning_errno(errno
, "Couldn't read notification socket: %m");
2742 cmsg_close_all(&msghdr
);
2744 CMSG_FOREACH(cmsg
, &msghdr
) {
2745 if (cmsg
->cmsg_level
== SOL_SOCKET
&&
2746 cmsg
->cmsg_type
== SCM_CREDENTIALS
&&
2747 cmsg
->cmsg_len
== CMSG_LEN(sizeof(struct ucred
))) {
2749 ucred
= (struct ucred
*) CMSG_DATA(cmsg
);
2753 if (!ucred
|| ucred
->pid
!= inner_child_pid
) {
2754 log_warning("Received notify message without valid credentials. Ignoring.");
2758 if ((size_t) n
>= sizeof(buf
)) {
2759 log_warning("Received notify message exceeded maximum size. Ignoring.");
2764 tags
= strv_split(buf
, "\n\r");
2768 if (strv_find(tags
, "READY=1"))
2769 sd_notifyf(false, "READY=1\n");
2771 p
= strv_find_startswith(tags
, "STATUS=");
2773 sd_notifyf(false, "STATUS=Container running: %s", p
);
2778 static int setup_sd_notify_parent(sd_event
*event
, int fd
, pid_t
*inner_child_pid
) {
2780 sd_event_source
*notify_event_source
;
2782 r
= sd_event_add_io(event
, ¬ify_event_source
, fd
, EPOLLIN
, nspawn_dispatch_notify_fd
, inner_child_pid
);
2784 return log_error_errno(r
, "Failed to allocate notify event source: %m");
2786 (void) sd_event_source_set_description(notify_event_source
, "nspawn-notify");
2791 static int load_settings(void) {
2792 _cleanup_(settings_freep
) Settings
*settings
= NULL
;
2793 _cleanup_fclose_
FILE *f
= NULL
;
2794 _cleanup_free_
char *p
= NULL
;
2798 /* If all settings are masked, there's no point in looking for
2799 * the settings file */
2800 if ((arg_settings_mask
& _SETTINGS_MASK_ALL
) == _SETTINGS_MASK_ALL
)
2803 fn
= strjoina(arg_machine
, ".nspawn");
2805 /* We first look in the admin's directories in /etc and /run */
2806 FOREACH_STRING(i
, "/etc/systemd/nspawn", "/run/systemd/nspawn") {
2807 _cleanup_free_
char *j
= NULL
;
2809 j
= strjoin(i
, "/", fn
);
2818 /* By default, we trust configuration from /etc and /run */
2819 if (arg_settings_trusted
< 0)
2820 arg_settings_trusted
= true;
2825 if (errno
!= ENOENT
)
2826 return log_error_errno(errno
, "Failed to open %s: %m", j
);
2830 /* After that, let's look for a file next to the
2831 * actual image we shall boot. */
2834 p
= file_in_same_dir(arg_image
, fn
);
2837 } else if (arg_directory
) {
2838 p
= file_in_same_dir(arg_directory
, fn
);
2845 if (!f
&& errno
!= ENOENT
)
2846 return log_error_errno(errno
, "Failed to open %s: %m", p
);
2848 /* By default, we do not trust configuration from /var/lib/machines */
2849 if (arg_settings_trusted
< 0)
2850 arg_settings_trusted
= false;
2857 log_debug("Settings are trusted: %s", yes_no(arg_settings_trusted
));
2859 r
= settings_load(f
, p
, &settings
);
2863 /* Copy over bits from the settings, unless they have been
2864 * explicitly masked by command line switches. */
2866 if ((arg_settings_mask
& SETTING_START_MODE
) == 0 &&
2867 settings
->start_mode
>= 0) {
2868 arg_start_mode
= settings
->start_mode
;
2870 strv_free(arg_parameters
);
2871 arg_parameters
= settings
->parameters
;
2872 settings
->parameters
= NULL
;
2875 if ((arg_settings_mask
& SETTING_WORKING_DIRECTORY
) == 0 &&
2876 settings
->working_directory
) {
2878 arg_chdir
= settings
->working_directory
;
2879 settings
->working_directory
= NULL
;
2882 if ((arg_settings_mask
& SETTING_ENVIRONMENT
) == 0 &&
2883 settings
->environment
) {
2884 strv_free(arg_setenv
);
2885 arg_setenv
= settings
->environment
;
2886 settings
->environment
= NULL
;
2889 if ((arg_settings_mask
& SETTING_USER
) == 0 &&
2892 arg_user
= settings
->user
;
2893 settings
->user
= NULL
;
2896 if ((arg_settings_mask
& SETTING_CAPABILITY
) == 0) {
2899 plus
= settings
->capability
;
2900 if (settings_private_network(settings
))
2901 plus
|= (1ULL << CAP_NET_ADMIN
);
2903 if (!arg_settings_trusted
&& plus
!= 0) {
2904 if (settings
->capability
!= 0)
2905 log_warning("Ignoring Capability= setting, file %s is not trusted.", p
);
2907 arg_caps_retain
|= plus
;
2909 arg_caps_retain
&= ~settings
->drop_capability
;
2912 if ((arg_settings_mask
& SETTING_KILL_SIGNAL
) == 0 &&
2913 settings
->kill_signal
> 0)
2914 arg_kill_signal
= settings
->kill_signal
;
2916 if ((arg_settings_mask
& SETTING_PERSONALITY
) == 0 &&
2917 settings
->personality
!= PERSONALITY_INVALID
)
2918 arg_personality
= settings
->personality
;
2920 if ((arg_settings_mask
& SETTING_MACHINE_ID
) == 0 &&
2921 !sd_id128_is_null(settings
->machine_id
)) {
2923 if (!arg_settings_trusted
)
2924 log_warning("Ignoring MachineID= setting, file %s is not trusted.", p
);
2926 arg_uuid
= settings
->machine_id
;
2929 if ((arg_settings_mask
& SETTING_READ_ONLY
) == 0 &&
2930 settings
->read_only
>= 0)
2931 arg_read_only
= settings
->read_only
;
2933 if ((arg_settings_mask
& SETTING_VOLATILE_MODE
) == 0 &&
2934 settings
->volatile_mode
!= _VOLATILE_MODE_INVALID
)
2935 arg_volatile_mode
= settings
->volatile_mode
;
2937 if ((arg_settings_mask
& SETTING_CUSTOM_MOUNTS
) == 0 &&
2938 settings
->n_custom_mounts
> 0) {
2940 if (!arg_settings_trusted
)
2941 log_warning("Ignoring TemporaryFileSystem=, Bind= and BindReadOnly= settings, file %s is not trusted.", p
);
2943 custom_mount_free_all(arg_custom_mounts
, arg_n_custom_mounts
);
2944 arg_custom_mounts
= settings
->custom_mounts
;
2945 arg_n_custom_mounts
= settings
->n_custom_mounts
;
2947 settings
->custom_mounts
= NULL
;
2948 settings
->n_custom_mounts
= 0;
2952 if ((arg_settings_mask
& SETTING_NETWORK
) == 0 &&
2953 (settings
->private_network
>= 0 ||
2954 settings
->network_veth
>= 0 ||
2955 settings
->network_bridge
||
2956 settings
->network_zone
||
2957 settings
->network_interfaces
||
2958 settings
->network_macvlan
||
2959 settings
->network_ipvlan
||
2960 settings
->network_veth_extra
)) {
2962 if (!arg_settings_trusted
)
2963 log_warning("Ignoring network settings, file %s is not trusted.", p
);
2965 arg_network_veth
= settings_network_veth(settings
);
2966 arg_private_network
= settings_private_network(settings
);
2968 strv_free(arg_network_interfaces
);
2969 arg_network_interfaces
= settings
->network_interfaces
;
2970 settings
->network_interfaces
= NULL
;
2972 strv_free(arg_network_macvlan
);
2973 arg_network_macvlan
= settings
->network_macvlan
;
2974 settings
->network_macvlan
= NULL
;
2976 strv_free(arg_network_ipvlan
);
2977 arg_network_ipvlan
= settings
->network_ipvlan
;
2978 settings
->network_ipvlan
= NULL
;
2980 strv_free(arg_network_veth_extra
);
2981 arg_network_veth_extra
= settings
->network_veth_extra
;
2982 settings
->network_veth_extra
= NULL
;
2984 free(arg_network_bridge
);
2985 arg_network_bridge
= settings
->network_bridge
;
2986 settings
->network_bridge
= NULL
;
2988 free(arg_network_zone
);
2989 arg_network_zone
= settings
->network_zone
;
2990 settings
->network_zone
= NULL
;
2994 if ((arg_settings_mask
& SETTING_EXPOSE_PORTS
) == 0 &&
2995 settings
->expose_ports
) {
2997 if (!arg_settings_trusted
)
2998 log_warning("Ignoring Port= setting, file %s is not trusted.", p
);
3000 expose_port_free_all(arg_expose_ports
);
3001 arg_expose_ports
= settings
->expose_ports
;
3002 settings
->expose_ports
= NULL
;
3006 if ((arg_settings_mask
& SETTING_USERNS
) == 0 &&
3007 settings
->userns_mode
!= _USER_NAMESPACE_MODE_INVALID
) {
3009 if (!arg_settings_trusted
)
3010 log_warning("Ignoring PrivateUsers= and PrivateUsersChown= settings, file %s is not trusted.", p
);
3012 arg_userns_mode
= settings
->userns_mode
;
3013 arg_uid_shift
= settings
->uid_shift
;
3014 arg_uid_range
= settings
->uid_range
;
3015 arg_userns_chown
= settings
->userns_chown
;
3019 if ((arg_settings_mask
& SETTING_NOTIFY_READY
) == 0)
3020 arg_notify_ready
= settings
->notify_ready
;
3025 static int run(int master
,
3026 const char* console
,
3027 DissectedImage
*dissected_image
,
3031 char veth_name
[IFNAMSIZ
], bool *veth_created
,
3032 union in_addr_union
*exposed
,
3033 pid_t
*pid
, int *ret
) {
3035 static const struct sigaction sa
= {
3036 .sa_handler
= nop_signal_handler
,
3037 .sa_flags
= SA_NOCLDSTOP
|SA_RESTART
,
3040 _cleanup_release_lock_file_ LockFile uid_shift_lock
= LOCK_FILE_INIT
;
3041 _cleanup_close_
int etc_passwd_lock
= -1;
3042 _cleanup_close_pair_
int
3043 kmsg_socket_pair
[2] = { -1, -1 },
3044 rtnl_socket_pair
[2] = { -1, -1 },
3045 pid_socket_pair
[2] = { -1, -1 },
3046 uuid_socket_pair
[2] = { -1, -1 },
3047 notify_socket_pair
[2] = { -1, -1 },
3048 uid_shift_socket_pair
[2] = { -1, -1 };
3049 _cleanup_close_
int notify_socket
= -1;
3050 _cleanup_(barrier_destroy
) Barrier barrier
= BARRIER_NULL
;
3051 _cleanup_(sd_event_unrefp
) sd_event
*event
= NULL
;
3052 _cleanup_(pty_forward_freep
) PTYForward
*forward
= NULL
;
3053 _cleanup_(sd_netlink_unrefp
) sd_netlink
*rtnl
= NULL
;
3054 ContainerStatus container_status
= 0;
3060 assert_se(sigemptyset(&mask_chld
) == 0);
3061 assert_se(sigaddset(&mask_chld
, SIGCHLD
) == 0);
3063 if (arg_userns_mode
== USER_NAMESPACE_PICK
) {
3064 /* When we shall pick the UID/GID range, let's first lock /etc/passwd, so that we can safely
3065 * check with getpwuid() if the specific user already exists. Note that /etc might be
3066 * read-only, in which case this will fail with EROFS. But that's really OK, as in that case we
3067 * can be reasonably sure that no users are going to be added. Note that getpwuid() checks are
3068 * really just an extra safety net. We kinda assume that the UID range we allocate from is
3071 etc_passwd_lock
= take_etc_passwd_lock(NULL
);
3072 if (etc_passwd_lock
< 0 && etc_passwd_lock
!= -EROFS
)
3073 return log_error_errno(etc_passwd_lock
, "Failed to take /etc/passwd lock: %m");
3076 r
= barrier_create(&barrier
);
3078 return log_error_errno(r
, "Cannot initialize IPC barrier: %m");
3080 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, kmsg_socket_pair
) < 0)
3081 return log_error_errno(errno
, "Failed to create kmsg socket pair: %m");
3083 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, rtnl_socket_pair
) < 0)
3084 return log_error_errno(errno
, "Failed to create rtnl socket pair: %m");
3086 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, pid_socket_pair
) < 0)
3087 return log_error_errno(errno
, "Failed to create pid socket pair: %m");
3089 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, uuid_socket_pair
) < 0)
3090 return log_error_errno(errno
, "Failed to create id socket pair: %m");
3092 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, notify_socket_pair
) < 0)
3093 return log_error_errno(errno
, "Failed to create notify socket pair: %m");
3095 if (arg_userns_mode
!= USER_NAMESPACE_NO
)
3096 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, uid_shift_socket_pair
) < 0)
3097 return log_error_errno(errno
, "Failed to create uid shift socket pair: %m");
3099 /* Child can be killed before execv(), so handle SIGCHLD in order to interrupt
3100 * parent's blocking calls and give it a chance to call wait() and terminate. */
3101 r
= sigprocmask(SIG_UNBLOCK
, &mask_chld
, NULL
);
3103 return log_error_errno(errno
, "Failed to change the signal mask: %m");
3105 r
= sigaction(SIGCHLD
, &sa
, NULL
);
3107 return log_error_errno(errno
, "Failed to install SIGCHLD handler: %m");
3109 *pid
= raw_clone(SIGCHLD
|CLONE_NEWNS
);
3111 return log_error_errno(errno
, "clone() failed%s: %m",
3113 ", do you have namespace support enabled in your kernel? (You need UTS, IPC, PID and NET namespacing built in)" : "");
3116 /* The outer child only has a file system namespace. */
3117 barrier_set_role(&barrier
, BARRIER_CHILD
);
3119 master
= safe_close(master
);
3121 kmsg_socket_pair
[0] = safe_close(kmsg_socket_pair
[0]);
3122 rtnl_socket_pair
[0] = safe_close(rtnl_socket_pair
[0]);
3123 pid_socket_pair
[0] = safe_close(pid_socket_pair
[0]);
3124 uuid_socket_pair
[0] = safe_close(uuid_socket_pair
[0]);
3125 notify_socket_pair
[0] = safe_close(notify_socket_pair
[0]);
3126 uid_shift_socket_pair
[0] = safe_close(uid_shift_socket_pair
[0]);
3128 (void) reset_all_signal_handlers();
3129 (void) reset_signal_mask();
3131 r
= outer_child(&barrier
,
3138 uuid_socket_pair
[1],
3139 notify_socket_pair
[1],
3140 kmsg_socket_pair
[1],
3141 rtnl_socket_pair
[1],
3142 uid_shift_socket_pair
[1],
3145 _exit(EXIT_FAILURE
);
3147 _exit(EXIT_SUCCESS
);
3150 barrier_set_role(&barrier
, BARRIER_PARENT
);
3152 fds
= fdset_free(fds
);
3154 kmsg_socket_pair
[1] = safe_close(kmsg_socket_pair
[1]);
3155 rtnl_socket_pair
[1] = safe_close(rtnl_socket_pair
[1]);
3156 pid_socket_pair
[1] = safe_close(pid_socket_pair
[1]);
3157 uuid_socket_pair
[1] = safe_close(uuid_socket_pair
[1]);
3158 notify_socket_pair
[1] = safe_close(notify_socket_pair
[1]);
3159 uid_shift_socket_pair
[1] = safe_close(uid_shift_socket_pair
[1]);
3161 if (arg_userns_mode
!= USER_NAMESPACE_NO
) {
3162 /* The child just let us know the UID shift it might have read from the image. */
3163 l
= recv(uid_shift_socket_pair
[0], &arg_uid_shift
, sizeof arg_uid_shift
, 0);
3165 return log_error_errno(errno
, "Failed to read UID shift: %m");
3166 if (l
!= sizeof arg_uid_shift
) {
3167 log_error("Short read while reading UID shift.");
3171 if (arg_userns_mode
== USER_NAMESPACE_PICK
) {
3172 /* If we are supposed to pick the UID shift, let's try to use the shift read from the
3173 * image, but if that's already in use, pick a new one, and report back to the child,
3174 * which one we now picked. */
3176 r
= uid_shift_pick(&arg_uid_shift
, &uid_shift_lock
);
3178 return log_error_errno(r
, "Failed to pick suitable UID/GID range: %m");
3180 l
= send(uid_shift_socket_pair
[0], &arg_uid_shift
, sizeof arg_uid_shift
, MSG_NOSIGNAL
);
3182 return log_error_errno(errno
, "Failed to send UID shift: %m");
3183 if (l
!= sizeof arg_uid_shift
) {
3184 log_error("Short write while writing UID shift.");
3190 /* Wait for the outer child. */
3191 r
= wait_for_terminate_and_warn("namespace helper", *pid
, NULL
);
3193 return r
< 0 ? r
: -EIO
;
3195 /* And now retrieve the PID of the inner child. */
3196 l
= recv(pid_socket_pair
[0], pid
, sizeof *pid
, 0);
3198 return log_error_errno(errno
, "Failed to read inner child PID: %m");
3199 if (l
!= sizeof *pid
) {
3200 log_error("Short read while reading inner child PID.");
3204 /* We also retrieve container UUID in case it was generated by outer child */
3205 l
= recv(uuid_socket_pair
[0], &arg_uuid
, sizeof arg_uuid
, 0);
3207 return log_error_errno(errno
, "Failed to read container machine ID: %m");
3208 if (l
!= sizeof(arg_uuid
)) {
3209 log_error("Short read while reading container machined ID.");
3213 /* We also retrieve the socket used for notifications generated by outer child */
3214 notify_socket
= receive_one_fd(notify_socket_pair
[0], 0);
3215 if (notify_socket
< 0)
3216 return log_error_errno(notify_socket
,
3217 "Failed to receive notification socket from the outer child: %m");
3219 log_debug("Init process invoked as PID "PID_FMT
, *pid
);
3221 if (arg_userns_mode
!= USER_NAMESPACE_NO
) {
3222 if (!barrier_place_and_sync(&barrier
)) { /* #1 */
3223 log_error("Child died too early.");
3227 r
= setup_uid_map(*pid
);
3231 (void) barrier_place(&barrier
); /* #2 */
3234 if (arg_private_network
) {
3236 r
= move_network_interfaces(*pid
, arg_network_interfaces
);
3240 if (arg_network_veth
) {
3241 r
= setup_veth(arg_machine
, *pid
, veth_name
,
3242 arg_network_bridge
|| arg_network_zone
);
3248 if (arg_network_bridge
) {
3249 /* Add the interface to a bridge */
3250 r
= setup_bridge(veth_name
, arg_network_bridge
, false);
3255 } else if (arg_network_zone
) {
3256 /* Add the interface to a bridge, possibly creating it */
3257 r
= setup_bridge(veth_name
, arg_network_zone
, true);
3265 r
= setup_veth_extra(arg_machine
, *pid
, arg_network_veth_extra
);
3269 /* We created the primary and extra veth links now; let's remember this, so that we know to
3270 remove them later on. Note that we don't bother with removing veth links that were created
3271 here when their setup failed half-way, because in that case the kernel should be able to
3272 remove them on its own, since they cannot be referenced by anything yet. */
3273 *veth_created
= true;
3275 r
= setup_macvlan(arg_machine
, *pid
, arg_network_macvlan
);
3279 r
= setup_ipvlan(arg_machine
, *pid
, arg_network_ipvlan
);
3285 r
= register_machine(
3292 arg_custom_mounts
, arg_n_custom_mounts
,
3296 arg_container_service_name
);
3301 r
= sync_cgroup(*pid
, arg_unified_cgroup_hierarchy
, arg_uid_shift
);
3305 if (arg_keep_unit
) {
3306 r
= create_subcgroup(*pid
, arg_unified_cgroup_hierarchy
);
3311 r
= chown_cgroup(*pid
, arg_uid_shift
);
3315 /* Notify the child that the parent is ready with all
3316 * its setup (including cgroup-ification), and that
3317 * the child can now hand over control to the code to
3318 * run inside the container. */
3319 (void) barrier_place(&barrier
); /* #3 */
3321 /* Block SIGCHLD here, before notifying child.
3322 * process_pty() will handle it with the other signals. */
3323 assert_se(sigprocmask(SIG_BLOCK
, &mask_chld
, NULL
) >= 0);
3325 /* Reset signal to default */
3326 r
= default_signals(SIGCHLD
, -1);
3328 return log_error_errno(r
, "Failed to reset SIGCHLD: %m");
3330 r
= sd_event_new(&event
);
3332 return log_error_errno(r
, "Failed to get default event source: %m");
3334 r
= setup_sd_notify_parent(event
, notify_socket
, PID_TO_PTR(*pid
));
3338 /* Let the child know that we are ready and wait that the child is completely ready now. */
3339 if (!barrier_place_and_sync(&barrier
)) { /* #4 */
3340 log_error("Child died too early.");
3344 /* At this point we have made use of the UID we picked, and thus nss-mymachines
3345 * will make them appear in getpwuid(), thus we can release the /etc/passwd lock. */
3346 etc_passwd_lock
= safe_close(etc_passwd_lock
);
3349 "STATUS=Container running.\n"
3350 "X_NSPAWN_LEADER_PID=" PID_FMT
, *pid
);
3351 if (!arg_notify_ready
)
3352 sd_notify(false, "READY=1\n");
3354 if (arg_kill_signal
> 0) {
3355 /* Try to kill the init system on SIGINT or SIGTERM */
3356 sd_event_add_signal(event
, NULL
, SIGINT
, on_orderly_shutdown
, PID_TO_PTR(*pid
));
3357 sd_event_add_signal(event
, NULL
, SIGTERM
, on_orderly_shutdown
, PID_TO_PTR(*pid
));
3359 /* Immediately exit */
3360 sd_event_add_signal(event
, NULL
, SIGINT
, NULL
, NULL
);
3361 sd_event_add_signal(event
, NULL
, SIGTERM
, NULL
, NULL
);
3364 /* simply exit on sigchld */
3365 sd_event_add_signal(event
, NULL
, SIGCHLD
, NULL
, NULL
);
3367 if (arg_expose_ports
) {
3368 r
= expose_port_watch_rtnl(event
, rtnl_socket_pair
[0], on_address_change
, exposed
, &rtnl
);
3372 (void) expose_port_execute(rtnl
, arg_expose_ports
, exposed
);
3375 rtnl_socket_pair
[0] = safe_close(rtnl_socket_pair
[0]);
3377 r
= pty_forward_new(event
, master
,
3378 PTY_FORWARD_IGNORE_VHANGUP
| (interactive
? 0 : PTY_FORWARD_READ_ONLY
),
3381 return log_error_errno(r
, "Failed to create PTY forwarder: %m");
3383 r
= sd_event_loop(event
);
3385 return log_error_errno(r
, "Failed to run event loop: %m");
3387 pty_forward_get_last_char(forward
, &last_char
);
3389 forward
= pty_forward_free(forward
);
3391 if (!arg_quiet
&& last_char
!= '\n')
3394 /* Kill if it is not dead yet anyway */
3395 if (arg_register
&& !arg_keep_unit
)
3396 terminate_machine(*pid
);
3398 /* Normally redundant, but better safe than sorry */
3399 (void) kill(*pid
, SIGKILL
);
3401 r
= wait_for_container(*pid
, &container_status
);
3405 /* We failed to wait for the container, or the container exited abnormally. */
3407 if (r
> 0 || container_status
== CONTAINER_TERMINATED
) {
3408 /* r > 0 → The container exited with a non-zero status.
3409 * As a special case, we need to replace 133 with a different value,
3410 * because 133 is special-cased in the service file to reboot the container.
3411 * otherwise → The container exited with zero status and a reboot was not requested.
3413 if (r
== EXIT_FORCE_RESTART
)
3414 r
= EXIT_FAILURE
; /* replace 133 with the general failure code */
3416 return 0; /* finito */
3419 /* CONTAINER_REBOOTED, loop again */
3421 if (arg_keep_unit
) {
3422 /* Special handling if we are running as a service: instead of simply
3423 * restarting the machine we want to restart the entire service, so let's
3424 * inform systemd about this with the special exit code 133. The service
3425 * file uses RestartForceExitStatus=133 so that this results in a full
3426 * nspawn restart. This is necessary since we might have cgroup parameters
3427 * set we want to have flushed out. */
3428 *ret
= EXIT_FORCE_RESTART
;
3429 return 0; /* finito */
3432 expose_port_flush(arg_expose_ports
, exposed
);
3434 (void) remove_veth_links(veth_name
, arg_network_veth_extra
);
3435 *veth_created
= false;
3436 return 1; /* loop again */
3439 static int load_root_hash(const char *image
) {
3440 _cleanup_free_
char *text
= NULL
;
3448 /* Try to load the root hash from a file next to the image file if it exists. */
3453 fn
= new(char, strlen(image
) + strlen(".roothash") + 1);
3457 n
= stpcpy(fn
, image
);
3458 e
= endswith(fn
, ".raw");
3462 strcpy(n
, ".roothash");
3464 r
= read_one_line_file(fn
, &text
);
3468 log_warning_errno(r
, "Failed to read %s, ignoring: %m", fn
);
3472 r
= unhexmem(text
, strlen(text
), &k
, &l
);
3474 return log_error_errno(r
, "Invalid root hash: %s", text
);
3475 if (l
< sizeof(sd_id128_t
)) {
3477 return log_error_errno(r
, "Root hash too short: %s", text
);
3481 arg_root_hash_size
= l
;
3486 int main(int argc
, char *argv
[]) {
3488 _cleanup_free_
char *console
= NULL
;
3489 _cleanup_close_
int master
= -1;
3490 _cleanup_fdset_free_ FDSet
*fds
= NULL
;
3491 int r
, n_fd_passed
, ret
= EXIT_SUCCESS
;
3492 char veth_name
[IFNAMSIZ
] = "";
3493 bool secondary
= false, remove_directory
= false, remove_image
= false;
3495 union in_addr_union exposed
= {};
3496 _cleanup_release_lock_file_ LockFile tree_global_lock
= LOCK_FILE_INIT
, tree_local_lock
= LOCK_FILE_INIT
;
3497 bool interactive
, veth_created
= false, remove_tmprootdir
= false;
3498 char tmprootdir
[] = "/tmp/nspawn-root-XXXXXX";
3499 _cleanup_(loop_device_unrefp
) LoopDevice
*loop
= NULL
;
3500 _cleanup_(decrypted_image_unrefp
) DecryptedImage
*decrypted_image
= NULL
;
3501 _cleanup_(dissected_image_unrefp
) DissectedImage
*dissected_image
= NULL
;
3503 log_parse_environment();
3506 /* Make sure rename_process() in the stub init process can work */
3510 r
= parse_argv(argc
, argv
);
3514 if (geteuid() != 0) {
3515 log_error("Need to be root.");
3519 r
= determine_names();
3523 r
= load_settings();
3527 r
= verify_arguments();
3531 n_fd_passed
= sd_listen_fds(false);
3532 if (n_fd_passed
> 0) {
3533 r
= fdset_new_listen_fds(&fds
, false);
3535 log_error_errno(r
, "Failed to collect file descriptors: %m");
3540 if (arg_directory
) {
3543 if (path_equal(arg_directory
, "/") && !arg_ephemeral
) {
3544 log_error("Spawning container on root directory is not supported. Consider using --ephemeral.");
3549 if (arg_ephemeral
) {
3550 _cleanup_free_
char *np
= NULL
;
3552 r
= chase_symlinks_and_update(&arg_directory
, 0);
3556 /* If the specified path is a mount point we
3557 * generate the new snapshot immediately
3558 * inside it under a random name. However if
3559 * the specified is not a mount point we
3560 * create the new snapshot in the parent
3561 * directory, just next to it. */
3562 r
= path_is_mount_point(arg_directory
, NULL
, 0);
3564 log_error_errno(r
, "Failed to determine whether directory %s is mount point: %m", arg_directory
);
3568 r
= tempfn_random_child(arg_directory
, "machine.", &np
);
3570 r
= tempfn_random(arg_directory
, "machine.", &np
);
3572 log_error_errno(r
, "Failed to generate name for directory snapshot: %m");
3576 r
= image_path_lock(np
, (arg_read_only
? LOCK_SH
: LOCK_EX
) | LOCK_NB
, &tree_global_lock
, &tree_local_lock
);
3578 log_error_errno(r
, "Failed to lock %s: %m", np
);
3582 r
= btrfs_subvol_snapshot(arg_directory
, np
,
3583 (arg_read_only
? BTRFS_SNAPSHOT_READ_ONLY
: 0) |
3584 BTRFS_SNAPSHOT_FALLBACK_COPY
|
3585 BTRFS_SNAPSHOT_FALLBACK_DIRECTORY
|
3586 BTRFS_SNAPSHOT_RECURSIVE
|
3587 BTRFS_SNAPSHOT_QUOTA
);
3589 log_error_errno(r
, "Failed to create snapshot %s from %s: %m", np
, arg_directory
);
3593 free(arg_directory
);
3597 remove_directory
= true;
3600 r
= chase_symlinks_and_update(&arg_directory
, arg_template
? CHASE_NONEXISTENT
: 0);
3604 r
= image_path_lock(arg_directory
, (arg_read_only
? LOCK_SH
: LOCK_EX
) | LOCK_NB
, &tree_global_lock
, &tree_local_lock
);
3606 log_error_errno(r
, "Directory tree %s is currently busy.", arg_directory
);
3610 log_error_errno(r
, "Failed to lock %s: %m", arg_directory
);
3615 r
= chase_symlinks_and_update(&arg_template
, 0);
3619 r
= btrfs_subvol_snapshot(arg_template
, arg_directory
,
3620 (arg_read_only
? BTRFS_SNAPSHOT_READ_ONLY
: 0) |
3621 BTRFS_SNAPSHOT_FALLBACK_COPY
|
3622 BTRFS_SNAPSHOT_FALLBACK_DIRECTORY
|
3623 BTRFS_SNAPSHOT_FALLBACK_IMMUTABLE
|
3624 BTRFS_SNAPSHOT_RECURSIVE
|
3625 BTRFS_SNAPSHOT_QUOTA
);
3628 log_info("Directory %s already exists, not populating from template %s.", arg_directory
, arg_template
);
3630 log_error_errno(r
, "Couldn't create snapshot %s from %s: %m", arg_directory
, arg_template
);
3634 log_info("Populated %s from template %s.", arg_directory
, arg_template
);
3639 if (arg_start_mode
== START_BOOT
) {
3640 if (path_is_os_tree(arg_directory
) <= 0) {
3641 log_error("Directory %s doesn't look like an OS root directory (os-release file is missing). Refusing.", arg_directory
);
3648 p
= strjoina(arg_directory
, "/usr/");
3649 if (laccess(p
, F_OK
) < 0) {
3650 log_error("Directory %s doesn't look like it has an OS tree. Refusing.", arg_directory
);
3658 assert(!arg_template
);
3660 r
= chase_symlinks_and_update(&arg_image
, 0);
3664 if (arg_ephemeral
) {
3665 _cleanup_free_
char *np
= NULL
;
3667 r
= tempfn_random(arg_image
, "machine.", &np
);
3669 log_error_errno(r
, "Failed to generate name for image snapshot: %m");
3673 r
= image_path_lock(np
, (arg_read_only
? LOCK_SH
: LOCK_EX
) | LOCK_NB
, &tree_global_lock
, &tree_local_lock
);
3675 r
= log_error_errno(r
, "Failed to create image lock: %m");
3679 r
= copy_file(arg_image
, np
, O_EXCL
, arg_read_only
? 0400 : 0600, FS_NOCOW_FL
);
3681 r
= log_error_errno(r
, "Failed to copy image file: %m");
3689 remove_image
= true;
3691 r
= image_path_lock(arg_image
, (arg_read_only
? LOCK_SH
: LOCK_EX
) | LOCK_NB
, &tree_global_lock
, &tree_local_lock
);
3693 r
= log_error_errno(r
, "Disk image %s is currently busy.", arg_image
);
3697 r
= log_error_errno(r
, "Failed to create image lock: %m");
3701 r
= load_root_hash(arg_image
);
3706 if (!mkdtemp(tmprootdir
)) {
3707 r
= log_error_errno(errno
, "Failed to create temporary directory: %m");
3711 remove_tmprootdir
= true;
3713 arg_directory
= strdup(tmprootdir
);
3714 if (!arg_directory
) {
3719 r
= loop_device_make_by_path(arg_image
, arg_read_only
? O_RDONLY
: O_RDWR
, &loop
);
3721 log_error_errno(r
, "Failed to set up loopback block device: %m");
3725 r
= dissect_image(loop
->fd
, arg_root_hash
, arg_root_hash_size
, &dissected_image
);
3727 log_error_errno(r
, "Could not find a suitable file system or partition table in image: %s", arg_image
);
3729 log_notice("Note that the disk image needs to\n"
3730 " a) either contain only a single MBR partition of type 0x83 that is marked bootable\n"
3731 " b) or contain a single GPT partition of type 0FC63DAF-8483-4772-8E79-3D69D8477DE4\n"
3732 " c) or follow http://www.freedesktop.org/wiki/Specifications/DiscoverablePartitionsSpec/\n"
3733 " d) or contain a file system without a partition table\n"
3734 "in order to be bootable with systemd-nspawn.");
3737 if (r
== -EADDRNOTAVAIL
) {
3738 log_error_errno(r
, "No root partition for specified root hash found.");
3741 if (r
== -EOPNOTSUPP
) {
3742 log_error_errno(r
, "--image= is not supported, compiled without blkid support.");
3746 log_error_errno(r
, "Failed to dissect image: %m");
3750 if (!arg_root_hash
&& dissected_image
->can_verity
)
3751 log_notice("Note: image %s contains verity information, but no root hash specified! Proceeding without integrity checking.", arg_image
);
3753 r
= dissected_image_decrypt_interactively(dissected_image
, NULL
, arg_root_hash
, arg_root_hash_size
, 0, &decrypted_image
);
3757 /* Now that we mounted the image, let's try to remove it again, if it is ephemeral */
3758 if (remove_image
&& unlink(arg_image
) >= 0)
3759 remove_image
= false;
3762 r
= custom_mount_prepare_all(arg_directory
, arg_custom_mounts
, arg_n_custom_mounts
);
3767 isatty(STDIN_FILENO
) > 0 &&
3768 isatty(STDOUT_FILENO
) > 0;
3770 master
= posix_openpt(O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NDELAY
);
3772 r
= log_error_errno(errno
, "Failed to acquire pseudo tty: %m");
3776 r
= ptsname_malloc(master
, &console
);
3778 r
= log_error_errno(r
, "Failed to determine tty name: %m");
3782 if (arg_selinux_apifs_context
) {
3783 r
= mac_selinux_apply(console
, arg_selinux_apifs_context
);
3788 if (unlockpt(master
) < 0) {
3789 r
= log_error_errno(errno
, "Failed to unlock tty: %m");
3794 log_info("Spawning container %s on %s.\nPress ^] three times within 1s to kill container.",
3795 arg_machine
, arg_image
?: arg_directory
);
3797 assert_se(sigprocmask_many(SIG_BLOCK
, NULL
, SIGCHLD
, SIGWINCH
, SIGTERM
, SIGINT
, -1) >= 0);
3799 if (prctl(PR_SET_CHILD_SUBREAPER
, 1) < 0) {
3800 r
= log_error_errno(errno
, "Failed to become subreaper: %m");
3808 interactive
, secondary
,
3810 veth_name
, &veth_created
,
3819 r
== 0 && ret
== EXIT_FORCE_RESTART
? "STOPPING=1\nSTATUS=Restarting..." :
3820 "STOPPING=1\nSTATUS=Terminating...");
3823 (void) kill(pid
, SIGKILL
);
3825 /* Try to flush whatever is still queued in the pty */
3827 (void) copy_bytes(master
, STDOUT_FILENO
, (uint64_t) -1, false);
3828 master
= safe_close(master
);
3832 (void) wait_for_terminate(pid
, NULL
);
3834 if (remove_directory
&& arg_directory
) {
3837 k
= rm_rf(arg_directory
, REMOVE_ROOT
|REMOVE_PHYSICAL
|REMOVE_SUBVOLUME
);
3839 log_warning_errno(k
, "Cannot remove '%s', ignoring: %m", arg_directory
);
3842 if (remove_image
&& arg_image
) {
3843 if (unlink(arg_image
) < 0)
3844 log_warning_errno(errno
, "Can't remove image file '%s', ignoring: %m", arg_image
);
3847 if (remove_tmprootdir
) {
3848 if (rmdir(tmprootdir
) < 0)
3849 log_debug_errno(errno
, "Can't remove temporary root directory '%s', ignoring: %m", tmprootdir
);
3855 p
= strjoina("/run/systemd/nspawn/propagate/", arg_machine
);
3856 (void) rm_rf(p
, REMOVE_ROOT
);
3859 expose_port_flush(arg_expose_ports
, &exposed
);
3862 (void) remove_veth_links(veth_name
, arg_network_veth_extra
);
3863 (void) remove_bridge(arg_network_zone
);
3865 free(arg_directory
);
3871 strv_free(arg_setenv
);
3872 free(arg_network_bridge
);
3873 strv_free(arg_network_interfaces
);
3874 strv_free(arg_network_macvlan
);
3875 strv_free(arg_network_ipvlan
);
3876 strv_free(arg_network_veth_extra
);
3877 strv_free(arg_parameters
);
3878 custom_mount_free_all(arg_custom_mounts
, arg_n_custom_mounts
);
3879 expose_port_free_all(arg_expose_ports
);
3880 free(arg_root_hash
);
3882 return r
< 0 ? EXIT_FAILURE
: ret
;