]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/nspawn/nspawn.c
util-lib: split out all temporary file related calls into tmpfiles-util.c
[thirdparty/systemd.git] / src / nspawn / nspawn.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #if HAVE_BLKID
4 #include <blkid.h>
5 #endif
6 #include <errno.h>
7 #include <getopt.h>
8 #include <grp.h>
9 #include <linux/loop.h>
10 #include <pwd.h>
11 #include <sched.h>
12 #if HAVE_SELINUX
13 #include <selinux/selinux.h>
14 #endif
15 #include <signal.h>
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <string.h>
19 #include <sys/file.h>
20 #include <sys/mount.h>
21 #include <sys/personality.h>
22 #include <sys/prctl.h>
23 #include <sys/types.h>
24 #include <sys/wait.h>
25 #include <unistd.h>
26
27 #include "sd-bus.h"
28 #include "sd-daemon.h"
29 #include "sd-id128.h"
30
31 #include "alloc-util.h"
32 #include "barrier.h"
33 #include "base-filesystem.h"
34 #include "blkid-util.h"
35 #include "btrfs-util.h"
36 #include "bus-error.h"
37 #include "bus-util.h"
38 #include "cap-list.h"
39 #include "capability-util.h"
40 #include "cgroup-util.h"
41 #include "copy.h"
42 #include "cpu-set-util.h"
43 #include "dev-setup.h"
44 #include "dissect-image.h"
45 #include "env-util.h"
46 #include "fd-util.h"
47 #include "fdset.h"
48 #include "fileio.h"
49 #include "format-util.h"
50 #include "fs-util.h"
51 #include "gpt.h"
52 #include "hexdecoct.h"
53 #include "hostname-util.h"
54 #include "id128-util.h"
55 #include "log.h"
56 #include "loop-util.h"
57 #include "loopback-setup.h"
58 #include "machine-image.h"
59 #include "macro.h"
60 #include "missing.h"
61 #include "mkdir.h"
62 #include "mount-util.h"
63 #include "mountpoint-util.h"
64 #include "netlink-util.h"
65 #include "nspawn-cgroup.h"
66 #include "nspawn-def.h"
67 #include "nspawn-expose-ports.h"
68 #include "nspawn-mount.h"
69 #include "nspawn-network.h"
70 #include "nspawn-patch-uid.h"
71 #include "nspawn-register.h"
72 #include "nspawn-seccomp.h"
73 #include "nspawn-settings.h"
74 #include "nspawn-setuid.h"
75 #include "nspawn-stub-pid1.h"
76 #include "os-util.h"
77 #include "pager.h"
78 #include "parse-util.h"
79 #include "path-util.h"
80 #include "pretty-print.h"
81 #include "process-util.h"
82 #include "ptyfwd.h"
83 #include "random-util.h"
84 #include "raw-clone.h"
85 #include "rlimit-util.h"
86 #include "rm-rf.h"
87 #include "selinux-util.h"
88 #include "signal-util.h"
89 #include "socket-util.h"
90 #include "stat-util.h"
91 #include "stdio-util.h"
92 #include "string-table.h"
93 #include "string-util.h"
94 #include "strv.h"
95 #include "terminal-util.h"
96 #include "tmpfile-util.h"
97 #include "umask-util.h"
98 #include "user-util.h"
99 #include "util.h"
100
101 #if HAVE_SPLIT_USR
102 #define STATIC_RESOLV_CONF "/lib/systemd/resolv.conf"
103 #else
104 #define STATIC_RESOLV_CONF "/usr/lib/systemd/resolv.conf"
105 #endif
106
107 /* nspawn is listening on the socket at the path in the constant nspawn_notify_socket_path
108 * nspawn_notify_socket_path is relative to the container
109 * the init process in the container pid can send messages to nspawn following the sd_notify(3) protocol */
110 #define NSPAWN_NOTIFY_SOCKET_PATH "/run/systemd/nspawn/notify"
111
112 #define EXIT_FORCE_RESTART 133
113
114 typedef enum ContainerStatus {
115 CONTAINER_TERMINATED,
116 CONTAINER_REBOOTED
117 } ContainerStatus;
118
119 static char *arg_directory = NULL;
120 static char *arg_template = NULL;
121 static char *arg_chdir = NULL;
122 static char *arg_pivot_root_new = NULL;
123 static char *arg_pivot_root_old = NULL;
124 static char *arg_user = NULL;
125 static sd_id128_t arg_uuid = {};
126 static char *arg_machine = NULL; /* The name used by the host to refer to this */
127 static char *arg_hostname = NULL; /* The name the payload sees by default */
128 static const char *arg_selinux_context = NULL;
129 static const char *arg_selinux_apifs_context = NULL;
130 static const char *arg_slice = NULL;
131 static bool arg_private_network = false;
132 static bool arg_read_only = false;
133 static StartMode arg_start_mode = START_PID1;
134 static bool arg_ephemeral = false;
135 static LinkJournal arg_link_journal = LINK_AUTO;
136 static bool arg_link_journal_try = false;
137 static uint64_t arg_caps_retain =
138 (1ULL << CAP_AUDIT_CONTROL) |
139 (1ULL << CAP_AUDIT_WRITE) |
140 (1ULL << CAP_CHOWN) |
141 (1ULL << CAP_DAC_OVERRIDE) |
142 (1ULL << CAP_DAC_READ_SEARCH) |
143 (1ULL << CAP_FOWNER) |
144 (1ULL << CAP_FSETID) |
145 (1ULL << CAP_IPC_OWNER) |
146 (1ULL << CAP_KILL) |
147 (1ULL << CAP_LEASE) |
148 (1ULL << CAP_LINUX_IMMUTABLE) |
149 (1ULL << CAP_MKNOD) |
150 (1ULL << CAP_NET_BIND_SERVICE) |
151 (1ULL << CAP_NET_BROADCAST) |
152 (1ULL << CAP_NET_RAW) |
153 (1ULL << CAP_SETFCAP) |
154 (1ULL << CAP_SETGID) |
155 (1ULL << CAP_SETPCAP) |
156 (1ULL << CAP_SETUID) |
157 (1ULL << CAP_SYS_ADMIN) |
158 (1ULL << CAP_SYS_BOOT) |
159 (1ULL << CAP_SYS_CHROOT) |
160 (1ULL << CAP_SYS_NICE) |
161 (1ULL << CAP_SYS_PTRACE) |
162 (1ULL << CAP_SYS_RESOURCE) |
163 (1ULL << CAP_SYS_TTY_CONFIG);
164 static CustomMount *arg_custom_mounts = NULL;
165 static size_t arg_n_custom_mounts = 0;
166 static char **arg_setenv = NULL;
167 static bool arg_quiet = false;
168 static bool arg_register = true;
169 static bool arg_keep_unit = false;
170 static char **arg_network_interfaces = NULL;
171 static char **arg_network_macvlan = NULL;
172 static char **arg_network_ipvlan = NULL;
173 static bool arg_network_veth = false;
174 static char **arg_network_veth_extra = NULL;
175 static char *arg_network_bridge = NULL;
176 static char *arg_network_zone = NULL;
177 static char *arg_network_namespace_path = NULL;
178 static unsigned long arg_personality = PERSONALITY_INVALID;
179 static char *arg_image = NULL;
180 static VolatileMode arg_volatile_mode = VOLATILE_NO;
181 static ExposePort *arg_expose_ports = NULL;
182 static char **arg_property = NULL;
183 static UserNamespaceMode arg_userns_mode = USER_NAMESPACE_NO;
184 static uid_t arg_uid_shift = UID_INVALID, arg_uid_range = 0x10000U;
185 static bool arg_userns_chown = false;
186 static int arg_kill_signal = 0;
187 static CGroupUnified arg_unified_cgroup_hierarchy = CGROUP_UNIFIED_UNKNOWN;
188 static SettingsMask arg_settings_mask = 0;
189 static int arg_settings_trusted = -1;
190 static char **arg_parameters = NULL;
191 static const char *arg_container_service_name = "systemd-nspawn";
192 static bool arg_notify_ready = false;
193 static bool arg_use_cgns = true;
194 static unsigned long arg_clone_ns_flags = CLONE_NEWIPC|CLONE_NEWPID|CLONE_NEWUTS;
195 static MountSettingsMask arg_mount_settings = MOUNT_APPLY_APIVFS_RO|MOUNT_APPLY_TMPFS_TMP;
196 static void *arg_root_hash = NULL;
197 static size_t arg_root_hash_size = 0;
198 static char **arg_syscall_whitelist = NULL;
199 static char **arg_syscall_blacklist = NULL;
200 static struct rlimit *arg_rlimit[_RLIMIT_MAX] = {};
201 static bool arg_no_new_privileges = false;
202 static int arg_oom_score_adjust = 0;
203 static bool arg_oom_score_adjust_set = false;
204 static cpu_set_t *arg_cpuset = NULL;
205 static unsigned arg_cpuset_ncpus = 0;
206 static ResolvConfMode arg_resolv_conf = RESOLV_CONF_AUTO;
207 static TimezoneMode arg_timezone = TIMEZONE_AUTO;
208
209 static int help(void) {
210 _cleanup_free_ char *link = NULL;
211 int r;
212
213 (void) pager_open(false);
214
215 r = terminal_urlify_man("systemd-nspawn", "1", &link);
216 if (r < 0)
217 return log_oom();
218
219 printf("%s [OPTIONS...] [PATH] [ARGUMENTS...]\n\n"
220 "Spawn a command or OS in a light-weight container.\n\n"
221 " -h --help Show this help\n"
222 " --version Print version string\n"
223 " -q --quiet Do not show status information\n"
224 " -D --directory=PATH Root directory for the container\n"
225 " --template=PATH Initialize root directory from template directory,\n"
226 " if missing\n"
227 " -x --ephemeral Run container with snapshot of root directory, and\n"
228 " remove it after exit\n"
229 " -i --image=PATH File system device or disk image for the container\n"
230 " --root-hash=HASH Specify verity root hash\n"
231 " -a --as-pid2 Maintain a stub init as PID1, invoke binary as PID2\n"
232 " -b --boot Boot up full system (i.e. invoke init)\n"
233 " --chdir=PATH Set working directory in the container\n"
234 " --pivot-root=PATH[:PATH]\n"
235 " Pivot root to given directory in the container\n"
236 " -u --user=USER Run the command under specified user or uid\n"
237 " -M --machine=NAME Set the machine name for the container\n"
238 " --hostname=NAME Override the hostname for the container\n"
239 " --uuid=UUID Set a specific machine UUID for the container\n"
240 " -S --slice=SLICE Place the container in the specified slice\n"
241 " --property=NAME=VALUE Set scope unit property\n"
242 " -U --private-users=pick Run within user namespace, autoselect UID/GID range\n"
243 " --private-users[=UIDBASE[:NUIDS]]\n"
244 " Similar, but with user configured UID/GID range\n"
245 " --private-users-chown Adjust OS tree ownership to private UID/GID range\n"
246 " --private-network Disable network in container\n"
247 " --network-interface=INTERFACE\n"
248 " Assign an existing network interface to the\n"
249 " container\n"
250 " --network-macvlan=INTERFACE\n"
251 " Create a macvlan network interface based on an\n"
252 " existing network interface to the container\n"
253 " --network-ipvlan=INTERFACE\n"
254 " Create a ipvlan network interface based on an\n"
255 " existing network interface to the container\n"
256 " -n --network-veth Add a virtual Ethernet connection between host\n"
257 " and container\n"
258 " --network-veth-extra=HOSTIF[:CONTAINERIF]\n"
259 " Add an additional virtual Ethernet link between\n"
260 " host and container\n"
261 " --network-bridge=INTERFACE\n"
262 " Add a virtual Ethernet connection to the container\n"
263 " and attach it to an existing bridge on the host\n"
264 " --network-zone=NAME Similar, but attach the new interface to an\n"
265 " an automatically managed bridge interface\n"
266 " --network-namespace-path=PATH\n"
267 " Set network namespace to the one represented by\n"
268 " the specified kernel namespace file node\n"
269 " -p --port=[PROTOCOL:]HOSTPORT[:CONTAINERPORT]\n"
270 " Expose a container IP port on the host\n"
271 " -Z --selinux-context=SECLABEL\n"
272 " Set the SELinux security context to be used by\n"
273 " processes in the container\n"
274 " -L --selinux-apifs-context=SECLABEL\n"
275 " Set the SELinux security context to be used by\n"
276 " API/tmpfs file systems in the container\n"
277 " --capability=CAP In addition to the default, retain specified\n"
278 " capability\n"
279 " --drop-capability=CAP Drop the specified capability from the default set\n"
280 " --system-call-filter=LIST|~LIST\n"
281 " Permit/prohibit specific system calls\n"
282 " --rlimit=NAME=LIMIT Set a resource limit for the payload\n"
283 " --oom-score-adjust=VALUE\n"
284 " Adjust the OOM score value for the payload\n"
285 " --cpu-affinity=CPUS Adjust the CPU affinity of the container\n"
286 " --kill-signal=SIGNAL Select signal to use for shutting down PID 1\n"
287 " --link-journal=MODE Link up guest journal, one of no, auto, guest, \n"
288 " host, try-guest, try-host\n"
289 " -j Equivalent to --link-journal=try-guest\n"
290 " --resolv-conf=MODE Select mode of /etc/resolv.conf initialization\n"
291 " --timezone=MODE Select mode of /etc/localtime initialization\n"
292 " --read-only Mount the root directory read-only\n"
293 " --bind=PATH[:PATH[:OPTIONS]]\n"
294 " Bind mount a file or directory from the host into\n"
295 " the container\n"
296 " --bind-ro=PATH[:PATH[:OPTIONS]\n"
297 " Similar, but creates a read-only bind mount\n"
298 " --tmpfs=PATH:[OPTIONS] Mount an empty tmpfs to the specified directory\n"
299 " --overlay=PATH[:PATH...]:PATH\n"
300 " Create an overlay mount from the host to \n"
301 " the container\n"
302 " --overlay-ro=PATH[:PATH...]:PATH\n"
303 " Similar, but creates a read-only overlay mount\n"
304 " -E --setenv=NAME=VALUE Pass an environment variable to PID 1\n"
305 " --register=BOOLEAN Register container as machine\n"
306 " --keep-unit Do not register a scope for the machine, reuse\n"
307 " the service unit nspawn is running in\n"
308 " --volatile[=MODE] Run the system in volatile mode\n"
309 " --settings=BOOLEAN Load additional settings from .nspawn file\n"
310 " --notify-ready=BOOLEAN Receive notifications from the child init process\n"
311 "\nSee the %s for details.\n"
312 , program_invocation_short_name
313 , link
314 );
315
316 return 0;
317 }
318
319 static int custom_mount_check_all(void) {
320 size_t i;
321
322 for (i = 0; i < arg_n_custom_mounts; i++) {
323 CustomMount *m = &arg_custom_mounts[i];
324
325 if (path_equal(m->destination, "/") && arg_userns_mode != USER_NAMESPACE_NO) {
326 if (arg_userns_chown)
327 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
328 "--private-users-chown may not be combined with custom root mounts.");
329 else if (arg_uid_shift == UID_INVALID)
330 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
331 "--private-users with automatic UID shift may not be combined with custom root mounts.");
332 }
333 }
334
335 return 0;
336 }
337
338 static int detect_unified_cgroup_hierarchy_from_environment(void) {
339 const char *e;
340 int r;
341
342 /* Allow the user to control whether the unified hierarchy is used */
343 e = getenv("UNIFIED_CGROUP_HIERARCHY");
344 if (e) {
345 r = parse_boolean(e);
346 if (r < 0)
347 return log_error_errno(r, "Failed to parse $UNIFIED_CGROUP_HIERARCHY.");
348 if (r > 0)
349 arg_unified_cgroup_hierarchy = CGROUP_UNIFIED_ALL;
350 else
351 arg_unified_cgroup_hierarchy = CGROUP_UNIFIED_NONE;
352 }
353
354 return 0;
355 }
356
357 static int detect_unified_cgroup_hierarchy_from_image(const char *directory) {
358 int r;
359
360 /* Let's inherit the mode to use from the host system, but let's take into consideration what systemd in the
361 * image actually supports. */
362 r = cg_all_unified();
363 if (r < 0)
364 return log_error_errno(r, "Failed to determine whether we are in all unified mode.");
365 if (r > 0) {
366 /* Unified cgroup hierarchy support was added in 230. Unfortunately the detection
367 * routine only detects 231, so we'll have a false negative here for 230. */
368 r = systemd_installation_has_version(directory, 230);
369 if (r < 0)
370 return log_error_errno(r, "Failed to determine systemd version in container: %m");
371 if (r > 0)
372 arg_unified_cgroup_hierarchy = CGROUP_UNIFIED_ALL;
373 else
374 arg_unified_cgroup_hierarchy = CGROUP_UNIFIED_NONE;
375 } else if (cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER) > 0) {
376 /* Mixed cgroup hierarchy support was added in 233 */
377 r = systemd_installation_has_version(directory, 233);
378 if (r < 0)
379 return log_error_errno(r, "Failed to determine systemd version in container: %m");
380 if (r > 0)
381 arg_unified_cgroup_hierarchy = CGROUP_UNIFIED_SYSTEMD;
382 else
383 arg_unified_cgroup_hierarchy = CGROUP_UNIFIED_NONE;
384 } else
385 arg_unified_cgroup_hierarchy = CGROUP_UNIFIED_NONE;
386
387 log_debug("Using %s hierarchy for container.",
388 arg_unified_cgroup_hierarchy == CGROUP_UNIFIED_NONE ? "legacy" :
389 arg_unified_cgroup_hierarchy == CGROUP_UNIFIED_SYSTEMD ? "hybrid" : "unified");
390
391 return 0;
392 }
393
394 static void parse_share_ns_env(const char *name, unsigned long ns_flag) {
395 int r;
396
397 r = getenv_bool(name);
398 if (r == -ENXIO)
399 return;
400 if (r < 0)
401 log_warning_errno(r, "Failed to parse %s from environment, defaulting to false.", name);
402 arg_clone_ns_flags = (arg_clone_ns_flags & ~ns_flag) | (r > 0 ? 0 : ns_flag);
403 }
404
405 static void parse_mount_settings_env(void) {
406 const char *e;
407 int r;
408
409 r = getenv_bool("SYSTEMD_NSPAWN_TMPFS_TMP");
410 if (r >= 0)
411 SET_FLAG(arg_mount_settings, MOUNT_APPLY_TMPFS_TMP, r > 0);
412 else if (r != -ENXIO)
413 log_warning_errno(r, "Failed to parse $SYSTEMD_NSPAWN_TMPFS_TMP, ignoring: %m");
414
415 e = getenv("SYSTEMD_NSPAWN_API_VFS_WRITABLE");
416 if (!e)
417 return;
418
419 if (streq(e, "network")) {
420 arg_mount_settings |= MOUNT_APPLY_APIVFS_RO|MOUNT_APPLY_APIVFS_NETNS;
421 return;
422 }
423
424 r = parse_boolean(e);
425 if (r < 0) {
426 log_warning_errno(r, "Failed to parse SYSTEMD_NSPAWN_API_VFS_WRITABLE from environment, ignoring.");
427 return;
428 }
429
430 SET_FLAG(arg_mount_settings, MOUNT_APPLY_APIVFS_RO, r == 0);
431 SET_FLAG(arg_mount_settings, MOUNT_APPLY_APIVFS_NETNS, false);
432 }
433
434 static int parse_argv(int argc, char *argv[]) {
435 enum {
436 ARG_VERSION = 0x100,
437 ARG_PRIVATE_NETWORK,
438 ARG_UUID,
439 ARG_READ_ONLY,
440 ARG_CAPABILITY,
441 ARG_DROP_CAPABILITY,
442 ARG_LINK_JOURNAL,
443 ARG_BIND,
444 ARG_BIND_RO,
445 ARG_TMPFS,
446 ARG_OVERLAY,
447 ARG_OVERLAY_RO,
448 ARG_SHARE_SYSTEM,
449 ARG_REGISTER,
450 ARG_KEEP_UNIT,
451 ARG_NETWORK_INTERFACE,
452 ARG_NETWORK_MACVLAN,
453 ARG_NETWORK_IPVLAN,
454 ARG_NETWORK_BRIDGE,
455 ARG_NETWORK_ZONE,
456 ARG_NETWORK_VETH_EXTRA,
457 ARG_NETWORK_NAMESPACE_PATH,
458 ARG_PERSONALITY,
459 ARG_VOLATILE,
460 ARG_TEMPLATE,
461 ARG_PROPERTY,
462 ARG_PRIVATE_USERS,
463 ARG_KILL_SIGNAL,
464 ARG_SETTINGS,
465 ARG_CHDIR,
466 ARG_PIVOT_ROOT,
467 ARG_PRIVATE_USERS_CHOWN,
468 ARG_NOTIFY_READY,
469 ARG_ROOT_HASH,
470 ARG_SYSTEM_CALL_FILTER,
471 ARG_RLIMIT,
472 ARG_HOSTNAME,
473 ARG_NO_NEW_PRIVILEGES,
474 ARG_OOM_SCORE_ADJUST,
475 ARG_CPU_AFFINITY,
476 ARG_RESOLV_CONF,
477 ARG_TIMEZONE,
478 };
479
480 static const struct option options[] = {
481 { "help", no_argument, NULL, 'h' },
482 { "version", no_argument, NULL, ARG_VERSION },
483 { "directory", required_argument, NULL, 'D' },
484 { "template", required_argument, NULL, ARG_TEMPLATE },
485 { "ephemeral", no_argument, NULL, 'x' },
486 { "user", required_argument, NULL, 'u' },
487 { "private-network", no_argument, NULL, ARG_PRIVATE_NETWORK },
488 { "as-pid2", no_argument, NULL, 'a' },
489 { "boot", no_argument, NULL, 'b' },
490 { "uuid", required_argument, NULL, ARG_UUID },
491 { "read-only", no_argument, NULL, ARG_READ_ONLY },
492 { "capability", required_argument, NULL, ARG_CAPABILITY },
493 { "drop-capability", required_argument, NULL, ARG_DROP_CAPABILITY },
494 { "no-new-privileges", required_argument, NULL, ARG_NO_NEW_PRIVILEGES },
495 { "link-journal", required_argument, NULL, ARG_LINK_JOURNAL },
496 { "bind", required_argument, NULL, ARG_BIND },
497 { "bind-ro", required_argument, NULL, ARG_BIND_RO },
498 { "tmpfs", required_argument, NULL, ARG_TMPFS },
499 { "overlay", required_argument, NULL, ARG_OVERLAY },
500 { "overlay-ro", required_argument, NULL, ARG_OVERLAY_RO },
501 { "machine", required_argument, NULL, 'M' },
502 { "hostname", required_argument, NULL, ARG_HOSTNAME },
503 { "slice", required_argument, NULL, 'S' },
504 { "setenv", required_argument, NULL, 'E' },
505 { "selinux-context", required_argument, NULL, 'Z' },
506 { "selinux-apifs-context", required_argument, NULL, 'L' },
507 { "quiet", no_argument, NULL, 'q' },
508 { "share-system", no_argument, NULL, ARG_SHARE_SYSTEM }, /* not documented */
509 { "register", required_argument, NULL, ARG_REGISTER },
510 { "keep-unit", no_argument, NULL, ARG_KEEP_UNIT },
511 { "network-interface", required_argument, NULL, ARG_NETWORK_INTERFACE },
512 { "network-macvlan", required_argument, NULL, ARG_NETWORK_MACVLAN },
513 { "network-ipvlan", required_argument, NULL, ARG_NETWORK_IPVLAN },
514 { "network-veth", no_argument, NULL, 'n' },
515 { "network-veth-extra", required_argument, NULL, ARG_NETWORK_VETH_EXTRA },
516 { "network-bridge", required_argument, NULL, ARG_NETWORK_BRIDGE },
517 { "network-zone", required_argument, NULL, ARG_NETWORK_ZONE },
518 { "network-namespace-path", required_argument, NULL, ARG_NETWORK_NAMESPACE_PATH },
519 { "personality", required_argument, NULL, ARG_PERSONALITY },
520 { "image", required_argument, NULL, 'i' },
521 { "volatile", optional_argument, NULL, ARG_VOLATILE },
522 { "port", required_argument, NULL, 'p' },
523 { "property", required_argument, NULL, ARG_PROPERTY },
524 { "private-users", optional_argument, NULL, ARG_PRIVATE_USERS },
525 { "private-users-chown", optional_argument, NULL, ARG_PRIVATE_USERS_CHOWN },
526 { "kill-signal", required_argument, NULL, ARG_KILL_SIGNAL },
527 { "settings", required_argument, NULL, ARG_SETTINGS },
528 { "chdir", required_argument, NULL, ARG_CHDIR },
529 { "pivot-root", required_argument, NULL, ARG_PIVOT_ROOT },
530 { "notify-ready", required_argument, NULL, ARG_NOTIFY_READY },
531 { "root-hash", required_argument, NULL, ARG_ROOT_HASH },
532 { "system-call-filter", required_argument, NULL, ARG_SYSTEM_CALL_FILTER },
533 { "rlimit", required_argument, NULL, ARG_RLIMIT },
534 { "oom-score-adjust", required_argument, NULL, ARG_OOM_SCORE_ADJUST },
535 { "cpu-affinity", required_argument, NULL, ARG_CPU_AFFINITY },
536 { "resolv-conf", required_argument, NULL, ARG_RESOLV_CONF },
537 { "timezone", required_argument, NULL, ARG_TIMEZONE },
538 {}
539 };
540
541 int c, r;
542 const char *p, *e;
543 uint64_t plus = 0, minus = 0;
544 bool mask_all_settings = false, mask_no_settings = false;
545
546 assert(argc >= 0);
547 assert(argv);
548
549 while ((c = getopt_long(argc, argv, "+hD:u:abL:M:jS:Z:qi:xp:nUE:", options, NULL)) >= 0)
550 switch (c) {
551
552 case 'h':
553 return help();
554
555 case ARG_VERSION:
556 return version();
557
558 case 'D':
559 r = parse_path_argument_and_warn(optarg, false, &arg_directory);
560 if (r < 0)
561 return r;
562 break;
563
564 case ARG_TEMPLATE:
565 r = parse_path_argument_and_warn(optarg, false, &arg_template);
566 if (r < 0)
567 return r;
568 break;
569
570 case 'i':
571 r = parse_path_argument_and_warn(optarg, false, &arg_image);
572 if (r < 0)
573 return r;
574 break;
575
576 case 'x':
577 arg_ephemeral = true;
578 arg_settings_mask |= SETTING_EPHEMERAL;
579 break;
580
581 case 'u':
582 r = free_and_strdup(&arg_user, optarg);
583 if (r < 0)
584 return log_oom();
585
586 arg_settings_mask |= SETTING_USER;
587 break;
588
589 case ARG_NETWORK_ZONE: {
590 char *j;
591
592 j = strappend("vz-", optarg);
593 if (!j)
594 return log_oom();
595
596 if (!ifname_valid(j)) {
597 log_error("Network zone name not valid: %s", j);
598 free(j);
599 return -EINVAL;
600 }
601
602 free_and_replace(arg_network_zone, j);
603
604 arg_network_veth = true;
605 arg_private_network = true;
606 arg_settings_mask |= SETTING_NETWORK;
607 break;
608 }
609
610 case ARG_NETWORK_BRIDGE:
611
612 if (!ifname_valid(optarg))
613 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
614 "Bridge interface name not valid: %s", optarg);
615
616 r = free_and_strdup(&arg_network_bridge, optarg);
617 if (r < 0)
618 return log_oom();
619
620 _fallthrough_;
621 case 'n':
622 arg_network_veth = true;
623 arg_private_network = true;
624 arg_settings_mask |= SETTING_NETWORK;
625 break;
626
627 case ARG_NETWORK_VETH_EXTRA:
628 r = veth_extra_parse(&arg_network_veth_extra, optarg);
629 if (r < 0)
630 return log_error_errno(r, "Failed to parse --network-veth-extra= parameter: %s", optarg);
631
632 arg_private_network = true;
633 arg_settings_mask |= SETTING_NETWORK;
634 break;
635
636 case ARG_NETWORK_INTERFACE:
637 if (!ifname_valid(optarg))
638 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
639 "Network interface name not valid: %s", optarg);
640
641 if (strv_extend(&arg_network_interfaces, optarg) < 0)
642 return log_oom();
643
644 arg_private_network = true;
645 arg_settings_mask |= SETTING_NETWORK;
646 break;
647
648 case ARG_NETWORK_MACVLAN:
649
650 if (!ifname_valid(optarg))
651 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
652 "MACVLAN network interface name not valid: %s", optarg);
653
654 if (strv_extend(&arg_network_macvlan, optarg) < 0)
655 return log_oom();
656
657 arg_private_network = true;
658 arg_settings_mask |= SETTING_NETWORK;
659 break;
660
661 case ARG_NETWORK_IPVLAN:
662
663 if (!ifname_valid(optarg))
664 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
665 "IPVLAN network interface name not valid: %s", optarg);
666
667 if (strv_extend(&arg_network_ipvlan, optarg) < 0)
668 return log_oom();
669
670 _fallthrough_;
671 case ARG_PRIVATE_NETWORK:
672 arg_private_network = true;
673 arg_settings_mask |= SETTING_NETWORK;
674 break;
675
676 case ARG_NETWORK_NAMESPACE_PATH:
677 r = parse_path_argument_and_warn(optarg, false, &arg_network_namespace_path);
678 if (r < 0)
679 return r;
680
681 break;
682
683 case 'b':
684 if (arg_start_mode == START_PID2)
685 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
686 "--boot and --as-pid2 may not be combined.");
687
688 arg_start_mode = START_BOOT;
689 arg_settings_mask |= SETTING_START_MODE;
690 break;
691
692 case 'a':
693 if (arg_start_mode == START_BOOT)
694 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
695 "--boot and --as-pid2 may not be combined.");
696
697 arg_start_mode = START_PID2;
698 arg_settings_mask |= SETTING_START_MODE;
699 break;
700
701 case ARG_UUID:
702 r = sd_id128_from_string(optarg, &arg_uuid);
703 if (r < 0)
704 return log_error_errno(r, "Invalid UUID: %s", optarg);
705
706 if (sd_id128_is_null(arg_uuid))
707 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
708 "Machine UUID may not be all zeroes.");
709
710 arg_settings_mask |= SETTING_MACHINE_ID;
711 break;
712
713 case 'S':
714 arg_slice = optarg;
715 break;
716
717 case 'M':
718 if (isempty(optarg))
719 arg_machine = mfree(arg_machine);
720 else {
721 if (!machine_name_is_valid(optarg))
722 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
723 "Invalid machine name: %s", optarg);
724
725 r = free_and_strdup(&arg_machine, optarg);
726 if (r < 0)
727 return log_oom();
728 }
729 break;
730
731 case ARG_HOSTNAME:
732 if (isempty(optarg))
733 arg_hostname = mfree(arg_hostname);
734 else {
735 if (!hostname_is_valid(optarg, false))
736 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
737 "Invalid hostname: %s", optarg);
738
739 r = free_and_strdup(&arg_hostname, optarg);
740 if (r < 0)
741 return log_oom();
742 }
743
744 arg_settings_mask |= SETTING_HOSTNAME;
745 break;
746
747 case 'Z':
748 arg_selinux_context = optarg;
749 break;
750
751 case 'L':
752 arg_selinux_apifs_context = optarg;
753 break;
754
755 case ARG_READ_ONLY:
756 arg_read_only = true;
757 arg_settings_mask |= SETTING_READ_ONLY;
758 break;
759
760 case ARG_CAPABILITY:
761 case ARG_DROP_CAPABILITY: {
762 p = optarg;
763 for (;;) {
764 _cleanup_free_ char *t = NULL;
765
766 r = extract_first_word(&p, &t, ",", 0);
767 if (r < 0)
768 return log_error_errno(r, "Failed to parse capability %s.", t);
769
770 if (r == 0)
771 break;
772
773 if (streq(t, "all")) {
774 if (c == ARG_CAPABILITY)
775 plus = (uint64_t) -1;
776 else
777 minus = (uint64_t) -1;
778 } else {
779 r = capability_from_name(t);
780 if (r < 0)
781 return log_error_errno(r, "Failed to parse capability %s.", t);
782
783 if (c == ARG_CAPABILITY)
784 plus |= 1ULL << r;
785 else
786 minus |= 1ULL << r;
787 }
788 }
789
790 arg_settings_mask |= SETTING_CAPABILITY;
791 break;
792 }
793
794 case ARG_NO_NEW_PRIVILEGES:
795 r = parse_boolean(optarg);
796 if (r < 0)
797 return log_error_errno(r, "Failed to parse --no-new-privileges= argument: %s", optarg);
798
799 arg_no_new_privileges = r;
800 arg_settings_mask |= SETTING_NO_NEW_PRIVILEGES;
801 break;
802
803 case 'j':
804 arg_link_journal = LINK_GUEST;
805 arg_link_journal_try = true;
806 arg_settings_mask |= SETTING_LINK_JOURNAL;
807 break;
808
809 case ARG_LINK_JOURNAL:
810 r = parse_link_journal(optarg, &arg_link_journal, &arg_link_journal_try);
811 if (r < 0) {
812 log_error_errno(r, "Failed to parse link journal mode %s", optarg);
813 return -EINVAL;
814 }
815
816 arg_settings_mask |= SETTING_LINK_JOURNAL;
817 break;
818
819 case ARG_BIND:
820 case ARG_BIND_RO:
821 r = bind_mount_parse(&arg_custom_mounts, &arg_n_custom_mounts, optarg, c == ARG_BIND_RO);
822 if (r < 0)
823 return log_error_errno(r, "Failed to parse --bind(-ro)= argument %s: %m", optarg);
824
825 arg_settings_mask |= SETTING_CUSTOM_MOUNTS;
826 break;
827
828 case ARG_TMPFS:
829 r = tmpfs_mount_parse(&arg_custom_mounts, &arg_n_custom_mounts, optarg);
830 if (r < 0)
831 return log_error_errno(r, "Failed to parse --tmpfs= argument %s: %m", optarg);
832
833 arg_settings_mask |= SETTING_CUSTOM_MOUNTS;
834 break;
835
836 case ARG_OVERLAY:
837 case ARG_OVERLAY_RO:
838 r = overlay_mount_parse(&arg_custom_mounts, &arg_n_custom_mounts, optarg, c == ARG_OVERLAY_RO);
839 if (r == -EADDRNOTAVAIL)
840 return log_error_errno(r, "--overlay(-ro)= needs at least two colon-separated directories specified.");
841 if (r < 0)
842 return log_error_errno(r, "Failed to parse --overlay(-ro)= argument %s: %m", optarg);
843
844 arg_settings_mask |= SETTING_CUSTOM_MOUNTS;
845 break;
846
847 case 'E': {
848 char **n;
849
850 if (!env_assignment_is_valid(optarg))
851 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
852 "Environment variable assignment '%s' is not valid.", optarg);
853
854 n = strv_env_set(arg_setenv, optarg);
855 if (!n)
856 return log_oom();
857
858 strv_free_and_replace(arg_setenv, n);
859 arg_settings_mask |= SETTING_ENVIRONMENT;
860 break;
861 }
862
863 case 'q':
864 arg_quiet = true;
865 break;
866
867 case ARG_SHARE_SYSTEM:
868 /* We don't officially support this anymore, except for compat reasons. People should use the
869 * $SYSTEMD_NSPAWN_SHARE_* environment variables instead. */
870 log_warning("Please do not use --share-system anymore, use $SYSTEMD_NSPAWN_SHARE_* instead.");
871 arg_clone_ns_flags = 0;
872 break;
873
874 case ARG_REGISTER:
875 r = parse_boolean(optarg);
876 if (r < 0) {
877 log_error("Failed to parse --register= argument: %s", optarg);
878 return r;
879 }
880
881 arg_register = r;
882 break;
883
884 case ARG_KEEP_UNIT:
885 arg_keep_unit = true;
886 break;
887
888 case ARG_PERSONALITY:
889
890 arg_personality = personality_from_string(optarg);
891 if (arg_personality == PERSONALITY_INVALID)
892 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
893 "Unknown or unsupported personality '%s'.", optarg);
894
895 arg_settings_mask |= SETTING_PERSONALITY;
896 break;
897
898 case ARG_VOLATILE:
899
900 if (!optarg)
901 arg_volatile_mode = VOLATILE_YES;
902 else if (streq(optarg, "help")) {
903 DUMP_STRING_TABLE(volatile_mode, VolatileMode, _VOLATILE_MODE_MAX);
904 return 0;
905 } else {
906 VolatileMode m;
907
908 m = volatile_mode_from_string(optarg);
909 if (m < 0)
910 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
911 "Failed to parse --volatile= argument: %s", optarg);
912 else
913 arg_volatile_mode = m;
914 }
915
916 arg_settings_mask |= SETTING_VOLATILE_MODE;
917 break;
918
919 case 'p':
920 r = expose_port_parse(&arg_expose_ports, optarg);
921 if (r == -EEXIST)
922 return log_error_errno(r, "Duplicate port specification: %s", optarg);
923 if (r < 0)
924 return log_error_errno(r, "Failed to parse host port %s: %m", optarg);
925
926 arg_settings_mask |= SETTING_EXPOSE_PORTS;
927 break;
928
929 case ARG_PROPERTY:
930 if (strv_extend(&arg_property, optarg) < 0)
931 return log_oom();
932
933 break;
934
935 case ARG_PRIVATE_USERS: {
936 int boolean = -1;
937
938 if (!optarg)
939 boolean = true;
940 else if (!in_charset(optarg, DIGITS))
941 /* do *not* parse numbers as booleans */
942 boolean = parse_boolean(optarg);
943
944 if (boolean == false) {
945 /* no: User namespacing off */
946 arg_userns_mode = USER_NAMESPACE_NO;
947 arg_uid_shift = UID_INVALID;
948 arg_uid_range = UINT32_C(0x10000);
949 } else if (boolean == true) {
950 /* yes: User namespacing on, UID range is read from root dir */
951 arg_userns_mode = USER_NAMESPACE_FIXED;
952 arg_uid_shift = UID_INVALID;
953 arg_uid_range = UINT32_C(0x10000);
954 } else if (streq(optarg, "pick")) {
955 /* pick: User namespacing on, UID range is picked randomly */
956 arg_userns_mode = USER_NAMESPACE_PICK;
957 arg_uid_shift = UID_INVALID;
958 arg_uid_range = UINT32_C(0x10000);
959 } else {
960 _cleanup_free_ char *buffer = NULL;
961 const char *range, *shift;
962
963 /* anything else: User namespacing on, UID range is explicitly configured */
964
965 range = strchr(optarg, ':');
966 if (range) {
967 buffer = strndup(optarg, range - optarg);
968 if (!buffer)
969 return log_oom();
970 shift = buffer;
971
972 range++;
973 r = safe_atou32(range, &arg_uid_range);
974 if (r < 0)
975 return log_error_errno(r, "Failed to parse UID range \"%s\": %m", range);
976 } else
977 shift = optarg;
978
979 r = parse_uid(shift, &arg_uid_shift);
980 if (r < 0)
981 return log_error_errno(r, "Failed to parse UID \"%s\": %m", optarg);
982
983 arg_userns_mode = USER_NAMESPACE_FIXED;
984 }
985
986 if (arg_uid_range <= 0)
987 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
988 "UID range cannot be 0.");
989
990 arg_settings_mask |= SETTING_USERNS;
991 break;
992 }
993
994 case 'U':
995 if (userns_supported()) {
996 arg_userns_mode = USER_NAMESPACE_PICK;
997 arg_uid_shift = UID_INVALID;
998 arg_uid_range = UINT32_C(0x10000);
999
1000 arg_settings_mask |= SETTING_USERNS;
1001 }
1002
1003 break;
1004
1005 case ARG_PRIVATE_USERS_CHOWN:
1006 arg_userns_chown = true;
1007
1008 arg_settings_mask |= SETTING_USERNS;
1009 break;
1010
1011 case ARG_KILL_SIGNAL:
1012 if (streq(optarg, "help")) {
1013 DUMP_STRING_TABLE(signal, int, _NSIG);
1014 return 0;
1015 }
1016
1017 arg_kill_signal = signal_from_string(optarg);
1018 if (arg_kill_signal < 0)
1019 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1020 "Cannot parse signal: %s", optarg);
1021
1022 arg_settings_mask |= SETTING_KILL_SIGNAL;
1023 break;
1024
1025 case ARG_SETTINGS:
1026
1027 /* no → do not read files
1028 * yes → read files, do not override cmdline, trust only subset
1029 * override → read files, override cmdline, trust only subset
1030 * trusted → read files, do not override cmdline, trust all
1031 */
1032
1033 r = parse_boolean(optarg);
1034 if (r < 0) {
1035 if (streq(optarg, "trusted")) {
1036 mask_all_settings = false;
1037 mask_no_settings = false;
1038 arg_settings_trusted = true;
1039
1040 } else if (streq(optarg, "override")) {
1041 mask_all_settings = false;
1042 mask_no_settings = true;
1043 arg_settings_trusted = -1;
1044 } else
1045 return log_error_errno(r, "Failed to parse --settings= argument: %s", optarg);
1046 } else if (r > 0) {
1047 /* yes */
1048 mask_all_settings = false;
1049 mask_no_settings = false;
1050 arg_settings_trusted = -1;
1051 } else {
1052 /* no */
1053 mask_all_settings = true;
1054 mask_no_settings = false;
1055 arg_settings_trusted = false;
1056 }
1057
1058 break;
1059
1060 case ARG_CHDIR:
1061 if (!path_is_absolute(optarg))
1062 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1063 "Working directory %s is not an absolute path.", optarg);
1064
1065 r = free_and_strdup(&arg_chdir, optarg);
1066 if (r < 0)
1067 return log_oom();
1068
1069 arg_settings_mask |= SETTING_WORKING_DIRECTORY;
1070 break;
1071
1072 case ARG_PIVOT_ROOT:
1073 r = pivot_root_parse(&arg_pivot_root_new, &arg_pivot_root_old, optarg);
1074 if (r < 0)
1075 return log_error_errno(r, "Failed to parse --pivot-root= argument %s: %m", optarg);
1076
1077 arg_settings_mask |= SETTING_PIVOT_ROOT;
1078 break;
1079
1080 case ARG_NOTIFY_READY:
1081 r = parse_boolean(optarg);
1082 if (r < 0)
1083 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1084 "%s is not a valid notify mode. Valid modes are: yes, no, and ready.", optarg);
1085 arg_notify_ready = r;
1086 arg_settings_mask |= SETTING_NOTIFY_READY;
1087 break;
1088
1089 case ARG_ROOT_HASH: {
1090 void *k;
1091 size_t l;
1092
1093 r = unhexmem(optarg, strlen(optarg), &k, &l);
1094 if (r < 0)
1095 return log_error_errno(r, "Failed to parse root hash: %s", optarg);
1096 if (l < sizeof(sd_id128_t)) {
1097 log_error("Root hash must be at least 128bit long: %s", optarg);
1098 free(k);
1099 return -EINVAL;
1100 }
1101
1102 free(arg_root_hash);
1103 arg_root_hash = k;
1104 arg_root_hash_size = l;
1105 break;
1106 }
1107
1108 case ARG_SYSTEM_CALL_FILTER: {
1109 bool negative;
1110 const char *items;
1111
1112 negative = optarg[0] == '~';
1113 items = negative ? optarg + 1 : optarg;
1114
1115 for (;;) {
1116 _cleanup_free_ char *word = NULL;
1117
1118 r = extract_first_word(&items, &word, NULL, 0);
1119 if (r == 0)
1120 break;
1121 if (r == -ENOMEM)
1122 return log_oom();
1123 if (r < 0)
1124 return log_error_errno(r, "Failed to parse system call filter: %m");
1125
1126 if (negative)
1127 r = strv_extend(&arg_syscall_blacklist, word);
1128 else
1129 r = strv_extend(&arg_syscall_whitelist, word);
1130 if (r < 0)
1131 return log_oom();
1132 }
1133
1134 arg_settings_mask |= SETTING_SYSCALL_FILTER;
1135 break;
1136 }
1137
1138 case ARG_RLIMIT: {
1139 const char *eq;
1140 char *name;
1141 int rl;
1142
1143 if (streq(optarg, "help")) {
1144 DUMP_STRING_TABLE(rlimit, int, _RLIMIT_MAX);
1145 return 0;
1146 }
1147
1148 eq = strchr(optarg, '=');
1149 if (!eq)
1150 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1151 "--rlimit= expects an '=' assignment.");
1152
1153 name = strndup(optarg, eq - optarg);
1154 if (!name)
1155 return log_oom();
1156
1157 rl = rlimit_from_string_harder(name);
1158 if (rl < 0)
1159 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1160 "Unknown resource limit: %s", name);
1161
1162 if (!arg_rlimit[rl]) {
1163 arg_rlimit[rl] = new0(struct rlimit, 1);
1164 if (!arg_rlimit[rl])
1165 return log_oom();
1166 }
1167
1168 r = rlimit_parse(rl, eq + 1, arg_rlimit[rl]);
1169 if (r < 0)
1170 return log_error_errno(r, "Failed to parse resource limit: %s", eq + 1);
1171
1172 arg_settings_mask |= SETTING_RLIMIT_FIRST << rl;
1173 break;
1174 }
1175
1176 case ARG_OOM_SCORE_ADJUST:
1177 r = parse_oom_score_adjust(optarg, &arg_oom_score_adjust);
1178 if (r < 0)
1179 return log_error_errno(r, "Failed to parse --oom-score-adjust= parameter: %s", optarg);
1180
1181 arg_oom_score_adjust_set = true;
1182 arg_settings_mask |= SETTING_OOM_SCORE_ADJUST;
1183 break;
1184
1185 case ARG_CPU_AFFINITY: {
1186 _cleanup_cpu_free_ cpu_set_t *cpuset = NULL;
1187
1188 r = parse_cpu_set(optarg, &cpuset);
1189 if (r < 0)
1190 return log_error_errno(r, "Failed to parse CPU affinity mask: %s", optarg);
1191
1192 if (arg_cpuset)
1193 CPU_FREE(arg_cpuset);
1194
1195 arg_cpuset = TAKE_PTR(cpuset);
1196 arg_cpuset_ncpus = r;
1197 arg_settings_mask |= SETTING_CPU_AFFINITY;
1198 break;
1199 }
1200
1201 case ARG_RESOLV_CONF:
1202 if (streq(optarg, "help")) {
1203 DUMP_STRING_TABLE(resolv_conf_mode, ResolvConfMode, _RESOLV_CONF_MODE_MAX);
1204 return 0;
1205 }
1206
1207 arg_resolv_conf = resolv_conf_mode_from_string(optarg);
1208 if (arg_resolv_conf < 0)
1209 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1210 "Failed to parse /etc/resolv.conf mode: %s", optarg);
1211
1212 arg_settings_mask |= SETTING_RESOLV_CONF;
1213 break;
1214
1215 case ARG_TIMEZONE:
1216 if (streq(optarg, "help")) {
1217 DUMP_STRING_TABLE(timezone_mode, TimezoneMode, _TIMEZONE_MODE_MAX);
1218 return 0;
1219 }
1220
1221 arg_timezone = timezone_mode_from_string(optarg);
1222 if (arg_timezone < 0)
1223 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1224 "Failed to parse /etc/localtime mode: %s", optarg);
1225
1226 arg_settings_mask |= SETTING_TIMEZONE;
1227 break;
1228
1229 case '?':
1230 return -EINVAL;
1231
1232 default:
1233 assert_not_reached("Unhandled option");
1234 }
1235
1236 /* If --network-namespace-path is given with any other network-related option,
1237 * we need to error out, to avoid conflicts between different network options. */
1238 if (arg_network_namespace_path &&
1239 (arg_network_interfaces || arg_network_macvlan ||
1240 arg_network_ipvlan || arg_network_veth_extra ||
1241 arg_network_bridge || arg_network_zone ||
1242 arg_network_veth || arg_private_network))
1243 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1244 "--network-namespace-path cannot be combined with other network options.");
1245
1246 parse_share_ns_env("SYSTEMD_NSPAWN_SHARE_NS_IPC", CLONE_NEWIPC);
1247 parse_share_ns_env("SYSTEMD_NSPAWN_SHARE_NS_PID", CLONE_NEWPID);
1248 parse_share_ns_env("SYSTEMD_NSPAWN_SHARE_NS_UTS", CLONE_NEWUTS);
1249 parse_share_ns_env("SYSTEMD_NSPAWN_SHARE_SYSTEM", CLONE_NEWIPC|CLONE_NEWPID|CLONE_NEWUTS);
1250
1251 if (arg_userns_mode != USER_NAMESPACE_NO)
1252 arg_mount_settings |= MOUNT_USE_USERNS;
1253
1254 if (arg_private_network)
1255 arg_mount_settings |= MOUNT_APPLY_APIVFS_NETNS;
1256
1257 parse_mount_settings_env();
1258
1259 if (!(arg_clone_ns_flags & CLONE_NEWPID) ||
1260 !(arg_clone_ns_flags & CLONE_NEWUTS)) {
1261 arg_register = false;
1262 if (arg_start_mode != START_PID1)
1263 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1264 "--boot cannot be used without namespacing.");
1265 }
1266
1267 if (arg_userns_mode == USER_NAMESPACE_PICK)
1268 arg_userns_chown = true;
1269
1270 if (arg_keep_unit && arg_register && cg_pid_get_owner_uid(0, NULL) >= 0)
1271 /* Save the user from accidentally registering either user-$SESSION.scope or user@.service.
1272 * The latter is not technically a user session, but we don't need to labour the point. */
1273 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1274 "--keep-unit --register=yes may not be used when invoked from a user session.");
1275
1276 if (arg_directory && arg_image)
1277 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1278 "--directory= and --image= may not be combined.");
1279
1280 if (arg_template && arg_image)
1281 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1282 "--template= and --image= may not be combined.");
1283
1284 if (arg_ephemeral && arg_template && !arg_directory) {
1285 /* User asked for ephemeral execution but specified --template= instead of --directory=. Semantically
1286 * such an invocation makes some sense, see https://github.com/systemd/systemd/issues/3667. Let's
1287 * accept this here, and silently make "--ephemeral --template=" equivalent to "--ephemeral
1288 * --directory=". */
1289
1290 arg_directory = TAKE_PTR(arg_template);
1291 }
1292
1293 if (arg_template && !(arg_directory || arg_machine))
1294 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1295 "--template= needs --directory= or --machine=.");
1296
1297 if (arg_ephemeral && arg_template)
1298 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1299 "--ephemeral and --template= may not be combined.");
1300
1301 if (arg_ephemeral && !IN_SET(arg_link_journal, LINK_NO, LINK_AUTO))
1302 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1303 "--ephemeral and --link-journal= may not be combined.");
1304
1305 if (arg_userns_mode != USER_NAMESPACE_NO && !userns_supported())
1306 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1307 "--private-users= is not supported, kernel compiled without user namespace support.");
1308
1309 if (arg_userns_chown && arg_read_only)
1310 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1311 "--read-only and --private-users-chown may not be combined.");
1312
1313 if (arg_network_bridge && arg_network_zone)
1314 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1315 "--network-bridge= and --network-zone= may not be combined.");
1316
1317 if (argc > optind) {
1318 arg_parameters = strv_copy(argv + optind);
1319 if (!arg_parameters)
1320 return log_oom();
1321
1322 arg_settings_mask |= SETTING_START_MODE;
1323 }
1324
1325 /* Load all settings from .nspawn files */
1326 if (mask_no_settings)
1327 arg_settings_mask = 0;
1328
1329 /* Don't load any settings from .nspawn files */
1330 if (mask_all_settings)
1331 arg_settings_mask = _SETTINGS_MASK_ALL;
1332
1333 arg_caps_retain = (arg_caps_retain | plus | (arg_private_network ? 1ULL << CAP_NET_ADMIN : 0)) & ~minus;
1334
1335 r = cg_unified_flush();
1336 if (r < 0)
1337 return log_error_errno(r, "Failed to determine whether the unified cgroups hierarchy is used: %m");
1338
1339 e = getenv("SYSTEMD_NSPAWN_CONTAINER_SERVICE");
1340 if (e)
1341 arg_container_service_name = e;
1342
1343 r = getenv_bool("SYSTEMD_NSPAWN_USE_CGNS");
1344 if (r < 0)
1345 arg_use_cgns = cg_ns_supported();
1346 else
1347 arg_use_cgns = r;
1348
1349 r = custom_mount_check_all();
1350 if (r < 0)
1351 return r;
1352
1353 return 1;
1354 }
1355
1356 static int verify_arguments(void) {
1357 if (arg_userns_mode != USER_NAMESPACE_NO && (arg_mount_settings & MOUNT_APPLY_APIVFS_NETNS) && !arg_private_network)
1358 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1359 "Invalid namespacing settings. Mounting sysfs with --private-users requires --private-network.");
1360
1361 if (arg_userns_mode != USER_NAMESPACE_NO && !(arg_mount_settings & MOUNT_APPLY_APIVFS_RO))
1362 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1363 "Cannot combine --private-users with read-write mounts.");
1364
1365 if (arg_volatile_mode != VOLATILE_NO && arg_read_only)
1366 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1367 "Cannot combine --read-only with --volatile. Note that --volatile already implies a read-only base hierarchy.");
1368
1369 if (arg_expose_ports && !arg_private_network)
1370 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1371 "Cannot use --port= without private networking.");
1372
1373 #if ! HAVE_LIBIPTC
1374 if (arg_expose_ports)
1375 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1376 "--port= is not supported, compiled without libiptc support.");
1377 #endif
1378
1379 if (arg_start_mode == START_BOOT && arg_kill_signal <= 0)
1380 arg_kill_signal = SIGRTMIN+3;
1381
1382 return 0;
1383 }
1384
1385 static int userns_lchown(const char *p, uid_t uid, gid_t gid) {
1386 assert(p);
1387
1388 if (arg_userns_mode == USER_NAMESPACE_NO)
1389 return 0;
1390
1391 if (uid == UID_INVALID && gid == GID_INVALID)
1392 return 0;
1393
1394 if (uid != UID_INVALID) {
1395 uid += arg_uid_shift;
1396
1397 if (uid < arg_uid_shift || uid >= arg_uid_shift + arg_uid_range)
1398 return -EOVERFLOW;
1399 }
1400
1401 if (gid != GID_INVALID) {
1402 gid += (gid_t) arg_uid_shift;
1403
1404 if (gid < (gid_t) arg_uid_shift || gid >= (gid_t) (arg_uid_shift + arg_uid_range))
1405 return -EOVERFLOW;
1406 }
1407
1408 if (lchown(p, uid, gid) < 0)
1409 return -errno;
1410
1411 return 0;
1412 }
1413
1414 static int userns_mkdir(const char *root, const char *path, mode_t mode, uid_t uid, gid_t gid) {
1415 const char *q;
1416 int r;
1417
1418 q = prefix_roota(root, path);
1419 r = mkdir_errno_wrapper(q, mode);
1420 if (r == -EEXIST)
1421 return 0;
1422 if (r < 0)
1423 return r;
1424
1425 return userns_lchown(q, uid, gid);
1426 }
1427
1428 static const char *timezone_from_path(const char *path) {
1429 return PATH_STARTSWITH_SET(
1430 path,
1431 "../usr/share/zoneinfo/",
1432 "/usr/share/zoneinfo/");
1433 }
1434
1435 static int setup_timezone(const char *dest) {
1436 _cleanup_free_ char *p = NULL, *etc = NULL;
1437 const char *where, *check;
1438 TimezoneMode m;
1439 int r;
1440
1441 assert(dest);
1442
1443 if (IN_SET(arg_timezone, TIMEZONE_AUTO, TIMEZONE_SYMLINK)) {
1444 r = readlink_malloc("/etc/localtime", &p);
1445 if (r == -ENOENT && arg_timezone == TIMEZONE_AUTO)
1446 m = arg_read_only && arg_volatile_mode != VOLATILE_YES ? TIMEZONE_OFF : TIMEZONE_DELETE;
1447 else if (r == -EINVAL && arg_timezone == TIMEZONE_AUTO) /* regular file? */
1448 m = arg_read_only && arg_volatile_mode != VOLATILE_YES ? TIMEZONE_BIND : TIMEZONE_COPY;
1449 else if (r < 0) {
1450 log_warning_errno(r, "Failed to read host's /etc/localtime symlink, not updating container timezone: %m");
1451 /* To handle warning, delete /etc/localtime and replace it with a symbolic link to a time zone data
1452 * file.
1453 *
1454 * Example:
1455 * ln -s /usr/share/zoneinfo/UTC /etc/localtime
1456 */
1457 return 0;
1458 } else if (arg_timezone == TIMEZONE_AUTO)
1459 m = arg_read_only && arg_volatile_mode != VOLATILE_YES ? TIMEZONE_BIND : TIMEZONE_SYMLINK;
1460 else
1461 m = arg_timezone;
1462 } else
1463 m = arg_timezone;
1464
1465 if (m == TIMEZONE_OFF)
1466 return 0;
1467
1468 r = chase_symlinks("/etc", dest, CHASE_PREFIX_ROOT, &etc);
1469 if (r < 0) {
1470 log_warning_errno(r, "Failed to resolve /etc path in container, ignoring: %m");
1471 return 0;
1472 }
1473
1474 where = strjoina(etc, "/localtime");
1475
1476 switch (m) {
1477
1478 case TIMEZONE_DELETE:
1479 if (unlink(where) < 0)
1480 log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_WARNING, errno, "Failed to remove '%s', ignoring: %m", where);
1481
1482 return 0;
1483
1484 case TIMEZONE_SYMLINK: {
1485 _cleanup_free_ char *q = NULL;
1486 const char *z, *what;
1487
1488 z = timezone_from_path(p);
1489 if (!z) {
1490 log_warning("/etc/localtime does not point into /usr/share/zoneinfo/, not updating container timezone.");
1491 return 0;
1492 }
1493
1494 r = readlink_malloc(where, &q);
1495 if (r >= 0 && streq_ptr(timezone_from_path(q), z))
1496 return 0; /* Already pointing to the right place? Then do nothing .. */
1497
1498 check = strjoina(dest, "/usr/share/zoneinfo/", z);
1499 r = chase_symlinks(check, dest, 0, NULL);
1500 if (r < 0)
1501 log_debug_errno(r, "Timezone %s does not exist (or is not accessible) in container, not creating symlink: %m", z);
1502 else {
1503 if (unlink(where) < 0 && errno != ENOENT) {
1504 log_full_errno(IN_SET(errno, EROFS, EACCES, EPERM) ? LOG_DEBUG : LOG_WARNING, /* Don't complain on read-only images */
1505 errno, "Failed to remove existing timezone info %s in container, ignoring: %m", where);
1506 return 0;
1507 }
1508
1509 what = strjoina("../usr/share/zoneinfo/", z);
1510 if (symlink(what, where) < 0) {
1511 log_full_errno(IN_SET(errno, EROFS, EACCES, EPERM) ? LOG_DEBUG : LOG_WARNING,
1512 errno, "Failed to correct timezone of container, ignoring: %m");
1513 return 0;
1514 }
1515
1516 break;
1517 }
1518
1519 _fallthrough_;
1520 }
1521
1522 case TIMEZONE_BIND: {
1523 _cleanup_free_ char *resolved = NULL;
1524 int found;
1525
1526 found = chase_symlinks(where, dest, CHASE_NONEXISTENT, &resolved);
1527 if (found < 0) {
1528 log_warning_errno(found, "Failed to resolve /etc/localtime path in container, ignoring: %m");
1529 return 0;
1530 }
1531
1532 if (found == 0) /* missing? */
1533 (void) touch(resolved);
1534
1535 r = mount_verbose(LOG_WARNING, "/etc/localtime", resolved, NULL, MS_BIND, NULL);
1536 if (r >= 0)
1537 return mount_verbose(LOG_ERR, NULL, resolved, NULL, MS_BIND|MS_REMOUNT|MS_RDONLY|MS_NOSUID|MS_NODEV, NULL);
1538
1539 _fallthrough_;
1540 }
1541
1542 case TIMEZONE_COPY:
1543 /* If mounting failed, try to copy */
1544 r = copy_file_atomic("/etc/localtime", where, 0644, 0, COPY_REFLINK|COPY_REPLACE);
1545 if (r < 0) {
1546 log_full_errno(IN_SET(r, -EROFS, -EACCES, -EPERM) ? LOG_DEBUG : LOG_WARNING, r,
1547 "Failed to copy /etc/localtime to %s, ignoring: %m", where);
1548 return 0;
1549 }
1550
1551 break;
1552
1553 default:
1554 assert_not_reached("unexpected mode");
1555 }
1556
1557 /* Fix permissions of the symlink or file copy we just created */
1558 r = userns_lchown(where, 0, 0);
1559 if (r < 0)
1560 log_warning_errno(r, "Failed to chown /etc/localtime, ignoring: %m");
1561
1562 return 0;
1563 }
1564
1565 static int have_resolv_conf(const char *path) {
1566 assert(path);
1567
1568 if (access(path, F_OK) < 0) {
1569 if (errno == ENOENT)
1570 return 0;
1571
1572 return log_debug_errno(errno, "Failed to determine whether '%s' is available: %m", path);
1573 }
1574
1575 return 1;
1576 }
1577
1578 static int resolved_listening(void) {
1579 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1580 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1581 _cleanup_free_ char *dns_stub_listener_mode = NULL;
1582 int r;
1583
1584 /* Check if resolved is listening */
1585
1586 r = sd_bus_open_system(&bus);
1587 if (r < 0)
1588 return log_debug_errno(r, "Failed to open system bus: %m");
1589
1590 r = bus_name_has_owner(bus, "org.freedesktop.resolve1", NULL);
1591 if (r < 0)
1592 return log_debug_errno(r, "Failed to check whether the 'org.freedesktop.resolve1' bus name is taken: %m");
1593 if (r == 0)
1594 return 0;
1595
1596 r = sd_bus_get_property_string(bus,
1597 "org.freedesktop.resolve1",
1598 "/org/freedesktop/resolve1",
1599 "org.freedesktop.resolve1.Manager",
1600 "DNSStubListener",
1601 &error,
1602 &dns_stub_listener_mode);
1603 if (r < 0)
1604 return log_debug_errno(r, "Failed to query DNSStubListener property: %s", bus_error_message(&error, r));
1605
1606 return STR_IN_SET(dns_stub_listener_mode, "udp", "yes");
1607 }
1608
1609 static int setup_resolv_conf(const char *dest) {
1610 _cleanup_free_ char *etc = NULL;
1611 const char *where, *what;
1612 ResolvConfMode m;
1613 int r;
1614
1615 assert(dest);
1616
1617 if (arg_resolv_conf == RESOLV_CONF_AUTO) {
1618 if (arg_private_network)
1619 m = RESOLV_CONF_OFF;
1620 else if (have_resolv_conf(STATIC_RESOLV_CONF) > 0 && resolved_listening() > 0)
1621 m = arg_read_only && arg_volatile_mode != VOLATILE_YES ? RESOLV_CONF_BIND_STATIC : RESOLV_CONF_COPY_STATIC;
1622 else if (have_resolv_conf("/etc/resolv.conf") > 0)
1623 m = arg_read_only && arg_volatile_mode != VOLATILE_YES ? RESOLV_CONF_BIND_HOST : RESOLV_CONF_COPY_HOST;
1624 else
1625 m = arg_read_only && arg_volatile_mode != VOLATILE_YES ? RESOLV_CONF_OFF : RESOLV_CONF_DELETE;
1626 } else
1627 m = arg_resolv_conf;
1628
1629 if (m == RESOLV_CONF_OFF)
1630 return 0;
1631
1632 r = chase_symlinks("/etc", dest, CHASE_PREFIX_ROOT, &etc);
1633 if (r < 0) {
1634 log_warning_errno(r, "Failed to resolve /etc path in container, ignoring: %m");
1635 return 0;
1636 }
1637
1638 where = strjoina(etc, "/resolv.conf");
1639
1640 if (m == RESOLV_CONF_DELETE) {
1641 if (unlink(where) < 0)
1642 log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_WARNING, errno, "Failed to remove '%s', ignoring: %m", where);
1643
1644 return 0;
1645 }
1646
1647 if (IN_SET(m, RESOLV_CONF_BIND_STATIC, RESOLV_CONF_COPY_STATIC))
1648 what = STATIC_RESOLV_CONF;
1649 else
1650 what = "/etc/resolv.conf";
1651
1652 if (IN_SET(m, RESOLV_CONF_BIND_HOST, RESOLV_CONF_BIND_STATIC)) {
1653 _cleanup_free_ char *resolved = NULL;
1654 int found;
1655
1656 found = chase_symlinks(where, dest, CHASE_NONEXISTENT, &resolved);
1657 if (found < 0) {
1658 log_warning_errno(found, "Failed to resolve /etc/resolv.conf path in container, ignoring: %m");
1659 return 0;
1660 }
1661
1662 if (found == 0) /* missing? */
1663 (void) touch(resolved);
1664
1665 r = mount_verbose(LOG_WARNING, what, resolved, NULL, MS_BIND, NULL);
1666 if (r >= 0)
1667 return mount_verbose(LOG_ERR, NULL, resolved, NULL, MS_BIND|MS_REMOUNT|MS_RDONLY|MS_NOSUID|MS_NODEV, NULL);
1668 }
1669
1670 /* If that didn't work, let's copy the file */
1671 r = copy_file(what, where, O_TRUNC|O_NOFOLLOW, 0644, 0, COPY_REFLINK);
1672 if (r < 0) {
1673 /* If the file already exists as symlink, let's suppress the warning, under the assumption that
1674 * resolved or something similar runs inside and the symlink points there.
1675 *
1676 * If the disk image is read-only, there's also no point in complaining.
1677 */
1678 log_full_errno(!IN_SET(RESOLV_CONF_COPY_HOST, RESOLV_CONF_COPY_STATIC) && IN_SET(r, -ELOOP, -EROFS, -EACCES, -EPERM) ? LOG_DEBUG : LOG_WARNING, r,
1679 "Failed to copy /etc/resolv.conf to %s, ignoring: %m", where);
1680 return 0;
1681 }
1682
1683 r = userns_lchown(where, 0, 0);
1684 if (r < 0)
1685 log_warning_errno(r, "Failed to chown /etc/resolv.conf, ignoring: %m");
1686
1687 return 0;
1688 }
1689
1690 static int setup_boot_id(void) {
1691 _cleanup_(unlink_and_freep) char *from = NULL;
1692 _cleanup_free_ char *path = NULL;
1693 sd_id128_t rnd = SD_ID128_NULL;
1694 const char *to;
1695 int r;
1696
1697 /* Generate a new randomized boot ID, so that each boot-up of
1698 * the container gets a new one */
1699
1700 r = tempfn_random_child(NULL, "proc-sys-kernel-random-boot-id", &path);
1701 if (r < 0)
1702 return log_error_errno(r, "Failed to generate random boot ID path: %m");
1703
1704 r = sd_id128_randomize(&rnd);
1705 if (r < 0)
1706 return log_error_errno(r, "Failed to generate random boot id: %m");
1707
1708 r = id128_write(path, ID128_UUID, rnd, false);
1709 if (r < 0)
1710 return log_error_errno(r, "Failed to write boot id: %m");
1711
1712 from = TAKE_PTR(path);
1713 to = "/proc/sys/kernel/random/boot_id";
1714
1715 r = mount_verbose(LOG_ERR, from, to, NULL, MS_BIND, NULL);
1716 if (r < 0)
1717 return r;
1718
1719 return mount_verbose(LOG_ERR, NULL, to, NULL, MS_BIND|MS_REMOUNT|MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV, NULL);
1720 }
1721
1722 static int copy_devnodes(const char *dest) {
1723 static const char devnodes[] =
1724 "null\0"
1725 "zero\0"
1726 "full\0"
1727 "random\0"
1728 "urandom\0"
1729 "tty\0"
1730 "net/tun\0";
1731
1732 const char *d;
1733 int r = 0;
1734 _cleanup_umask_ mode_t u;
1735
1736 assert(dest);
1737
1738 u = umask(0000);
1739
1740 /* Create /dev/net, so that we can create /dev/net/tun in it */
1741 if (userns_mkdir(dest, "/dev/net", 0755, 0, 0) < 0)
1742 return log_error_errno(r, "Failed to create /dev/net directory: %m");
1743
1744 NULSTR_FOREACH(d, devnodes) {
1745 _cleanup_free_ char *from = NULL, *to = NULL;
1746 struct stat st;
1747
1748 from = strappend("/dev/", d);
1749 if (!from)
1750 return log_oom();
1751
1752 to = prefix_root(dest, from);
1753 if (!to)
1754 return log_oom();
1755
1756 if (stat(from, &st) < 0) {
1757
1758 if (errno != ENOENT)
1759 return log_error_errno(errno, "Failed to stat %s: %m", from);
1760
1761 } else if (!S_ISCHR(st.st_mode) && !S_ISBLK(st.st_mode))
1762 return log_error_errno(SYNTHETIC_ERRNO(EIO),
1763 "%s is not a char or block device, cannot copy.", from);
1764 else {
1765 _cleanup_free_ char *sl = NULL, *prefixed = NULL, *dn = NULL, *t = NULL;
1766
1767 if (mknod(to, st.st_mode, st.st_rdev) < 0) {
1768 /* Explicitly warn the user when /dev is already populated. */
1769 if (errno == EEXIST)
1770 log_notice("%s/dev is pre-mounted and pre-populated. If a pre-mounted /dev is provided it needs to be an unpopulated file system.", dest);
1771 if (errno != EPERM)
1772 return log_error_errno(errno, "mknod(%s) failed: %m", to);
1773
1774 /* Some systems abusively restrict mknod but allow bind mounts. */
1775 r = touch(to);
1776 if (r < 0)
1777 return log_error_errno(r, "touch (%s) failed: %m", to);
1778 r = mount_verbose(LOG_DEBUG, from, to, NULL, MS_BIND, NULL);
1779 if (r < 0)
1780 return log_error_errno(r, "Both mknod and bind mount (%s) failed: %m", to);
1781 }
1782
1783 r = userns_lchown(to, 0, 0);
1784 if (r < 0)
1785 return log_error_errno(r, "chown() of device node %s failed: %m", to);
1786
1787 dn = strjoin("/dev/", S_ISCHR(st.st_mode) ? "char" : "block");
1788 if (!dn)
1789 return log_oom();
1790
1791 r = userns_mkdir(dest, dn, 0755, 0, 0);
1792 if (r < 0)
1793 return log_error_errno(r, "Failed to create '%s': %m", dn);
1794
1795 if (asprintf(&sl, "%s/%u:%u", dn, major(st.st_rdev), minor(st.st_rdev)) < 0)
1796 return log_oom();
1797
1798 prefixed = prefix_root(dest, sl);
1799 if (!prefixed)
1800 return log_oom();
1801
1802 t = strjoin("../", d);
1803 if (!t)
1804 return log_oom();
1805
1806 if (symlink(t, prefixed) < 0)
1807 log_debug_errno(errno, "Failed to symlink '%s' to '%s': %m", t, prefixed);
1808 }
1809 }
1810
1811 return r;
1812 }
1813
1814 static int setup_pts(const char *dest) {
1815 _cleanup_free_ char *options = NULL;
1816 const char *p;
1817 int r;
1818
1819 #if HAVE_SELINUX
1820 if (arg_selinux_apifs_context)
1821 (void) asprintf(&options,
1822 "newinstance,ptmxmode=0666,mode=620,gid=" GID_FMT ",context=\"%s\"",
1823 arg_uid_shift + TTY_GID,
1824 arg_selinux_apifs_context);
1825 else
1826 #endif
1827 (void) asprintf(&options,
1828 "newinstance,ptmxmode=0666,mode=620,gid=" GID_FMT,
1829 arg_uid_shift + TTY_GID);
1830
1831 if (!options)
1832 return log_oom();
1833
1834 /* Mount /dev/pts itself */
1835 p = prefix_roota(dest, "/dev/pts");
1836 r = mkdir_errno_wrapper(p, 0755);
1837 if (r < 0)
1838 return log_error_errno(r, "Failed to create /dev/pts: %m");
1839
1840 r = mount_verbose(LOG_ERR, "devpts", p, "devpts", MS_NOSUID|MS_NOEXEC, options);
1841 if (r < 0)
1842 return r;
1843 r = userns_lchown(p, 0, 0);
1844 if (r < 0)
1845 return log_error_errno(r, "Failed to chown /dev/pts: %m");
1846
1847 /* Create /dev/ptmx symlink */
1848 p = prefix_roota(dest, "/dev/ptmx");
1849 if (symlink("pts/ptmx", p) < 0)
1850 return log_error_errno(errno, "Failed to create /dev/ptmx symlink: %m");
1851 r = userns_lchown(p, 0, 0);
1852 if (r < 0)
1853 return log_error_errno(r, "Failed to chown /dev/ptmx: %m");
1854
1855 /* And fix /dev/pts/ptmx ownership */
1856 p = prefix_roota(dest, "/dev/pts/ptmx");
1857 r = userns_lchown(p, 0, 0);
1858 if (r < 0)
1859 return log_error_errno(r, "Failed to chown /dev/pts/ptmx: %m");
1860
1861 return 0;
1862 }
1863
1864 static int setup_dev_console(const char *dest, const char *console) {
1865 _cleanup_umask_ mode_t u;
1866 const char *to;
1867 int r;
1868
1869 assert(dest);
1870 assert(console);
1871
1872 u = umask(0000);
1873
1874 r = chmod_and_chown(console, 0600, arg_uid_shift, arg_uid_shift);
1875 if (r < 0)
1876 return log_error_errno(r, "Failed to correct access mode for TTY: %m");
1877
1878 /* We need to bind mount the right tty to /dev/console since
1879 * ptys can only exist on pts file systems. To have something
1880 * to bind mount things on we create a empty regular file. */
1881
1882 to = prefix_roota(dest, "/dev/console");
1883 r = touch(to);
1884 if (r < 0)
1885 return log_error_errno(r, "touch() for /dev/console failed: %m");
1886
1887 return mount_verbose(LOG_ERR, console, to, NULL, MS_BIND, NULL);
1888 }
1889
1890 static int setup_keyring(void) {
1891 key_serial_t keyring;
1892
1893 /* Allocate a new session keyring for the container. This makes sure the keyring of the session systemd-nspawn
1894 * was invoked from doesn't leak into the container. Note that by default we block keyctl() and request_key()
1895 * anyway via seccomp so doing this operation isn't strictly necessary, but in case people explicitly whitelist
1896 * these system calls let's make sure we don't leak anything into the container. */
1897
1898 keyring = keyctl(KEYCTL_JOIN_SESSION_KEYRING, 0, 0, 0, 0);
1899 if (keyring == -1) {
1900 if (errno == ENOSYS)
1901 log_debug_errno(errno, "Kernel keyring not supported, ignoring.");
1902 else if (IN_SET(errno, EACCES, EPERM))
1903 log_debug_errno(errno, "Kernel keyring access prohibited, ignoring.");
1904 else
1905 return log_error_errno(errno, "Setting up kernel keyring failed: %m");
1906 }
1907
1908 return 0;
1909 }
1910
1911 static int setup_kmsg(int kmsg_socket) {
1912 _cleanup_(unlink_and_freep) char *from = NULL;
1913 _cleanup_free_ char *fifo = NULL;
1914 _cleanup_close_ int fd = -1;
1915 _cleanup_umask_ mode_t u;
1916 const char *to;
1917 int r;
1918
1919 assert(kmsg_socket >= 0);
1920
1921 u = umask(0000);
1922
1923 /* We create the kmsg FIFO as as temporary file in /tmp, but immediately delete it after bind mounting it to
1924 * /proc/kmsg. While FIFOs on the reading side behave very similar to /proc/kmsg, their writing side behaves
1925 * differently from /dev/kmsg in that writing blocks when nothing is reading. In order to avoid any problems
1926 * with containers deadlocking due to this we simply make /dev/kmsg unavailable to the container. */
1927
1928 r = tempfn_random_child(NULL, "proc-kmsg", &fifo);
1929 if (r < 0)
1930 return log_error_errno(r, "Failed to generate kmsg path: %m");
1931
1932 if (mkfifo(fifo, 0600) < 0)
1933 return log_error_errno(errno, "mkfifo() for /run/kmsg failed: %m");
1934
1935 from = TAKE_PTR(fifo);
1936 to = "/proc/kmsg";
1937
1938 r = mount_verbose(LOG_ERR, from, to, NULL, MS_BIND, NULL);
1939 if (r < 0)
1940 return r;
1941
1942 fd = open(from, O_RDWR|O_NONBLOCK|O_CLOEXEC);
1943 if (fd < 0)
1944 return log_error_errno(errno, "Failed to open fifo: %m");
1945
1946 /* Store away the fd in the socket, so that it stays open as long as we run the child */
1947 r = send_one_fd(kmsg_socket, fd, 0);
1948 if (r < 0)
1949 return log_error_errno(r, "Failed to send FIFO fd: %m");
1950
1951 return 0;
1952 }
1953
1954 static int on_address_change(sd_netlink *rtnl, sd_netlink_message *m, void *userdata) {
1955 union in_addr_union *exposed = userdata;
1956
1957 assert(rtnl);
1958 assert(m);
1959 assert(exposed);
1960
1961 expose_port_execute(rtnl, arg_expose_ports, exposed);
1962 return 0;
1963 }
1964
1965 static int setup_hostname(void) {
1966 int r;
1967
1968 if ((arg_clone_ns_flags & CLONE_NEWUTS) == 0)
1969 return 0;
1970
1971 r = sethostname_idempotent(arg_hostname ?: arg_machine);
1972 if (r < 0)
1973 return log_error_errno(r, "Failed to set hostname: %m");
1974
1975 return 0;
1976 }
1977
1978 static int setup_journal(const char *directory) {
1979 sd_id128_t this_id;
1980 _cleanup_free_ char *d = NULL;
1981 const char *p, *q;
1982 bool try;
1983 char id[33], *dirname;
1984 int r;
1985
1986 /* Don't link journals in ephemeral mode */
1987 if (arg_ephemeral)
1988 return 0;
1989
1990 if (arg_link_journal == LINK_NO)
1991 return 0;
1992
1993 try = arg_link_journal_try || arg_link_journal == LINK_AUTO;
1994
1995 r = sd_id128_get_machine(&this_id);
1996 if (r < 0)
1997 return log_error_errno(r, "Failed to retrieve machine ID: %m");
1998
1999 if (sd_id128_equal(arg_uuid, this_id)) {
2000 log_full(try ? LOG_WARNING : LOG_ERR,
2001 "Host and machine ids are equal (%s): refusing to link journals", sd_id128_to_string(arg_uuid, id));
2002 if (try)
2003 return 0;
2004 return -EEXIST;
2005 }
2006
2007 FOREACH_STRING(dirname, "/var", "/var/log", "/var/log/journal") {
2008 r = userns_mkdir(directory, dirname, 0755, 0, 0);
2009 if (r < 0) {
2010 bool ignore = r == -EROFS && try;
2011 log_full_errno(ignore ? LOG_DEBUG : LOG_ERR, r,
2012 "Failed to create %s%s: %m", dirname, ignore ? ", ignoring" : "");
2013 return ignore ? 0 : r;
2014 }
2015 }
2016
2017 (void) sd_id128_to_string(arg_uuid, id);
2018
2019 p = strjoina("/var/log/journal/", id);
2020 q = prefix_roota(directory, p);
2021
2022 if (path_is_mount_point(p, NULL, 0) > 0) {
2023 if (try)
2024 return 0;
2025
2026 return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
2027 "%s: already a mount point, refusing to use for journal", p);
2028 }
2029
2030 if (path_is_mount_point(q, NULL, 0) > 0) {
2031 if (try)
2032 return 0;
2033
2034 return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
2035 "%s: already a mount point, refusing to use for journal", q);
2036 }
2037
2038 r = readlink_and_make_absolute(p, &d);
2039 if (r >= 0) {
2040 if (IN_SET(arg_link_journal, LINK_GUEST, LINK_AUTO) &&
2041 path_equal(d, q)) {
2042
2043 r = userns_mkdir(directory, p, 0755, 0, 0);
2044 if (r < 0)
2045 log_warning_errno(r, "Failed to create directory %s: %m", q);
2046 return 0;
2047 }
2048
2049 if (unlink(p) < 0)
2050 return log_error_errno(errno, "Failed to remove symlink %s: %m", p);
2051 } else if (r == -EINVAL) {
2052
2053 if (arg_link_journal == LINK_GUEST &&
2054 rmdir(p) < 0) {
2055
2056 if (errno == ENOTDIR) {
2057 log_error("%s already exists and is neither a symlink nor a directory", p);
2058 return r;
2059 } else
2060 return log_error_errno(errno, "Failed to remove %s: %m", p);
2061 }
2062 } else if (r != -ENOENT)
2063 return log_error_errno(r, "readlink(%s) failed: %m", p);
2064
2065 if (arg_link_journal == LINK_GUEST) {
2066
2067 if (symlink(q, p) < 0) {
2068 if (try) {
2069 log_debug_errno(errno, "Failed to symlink %s to %s, skipping journal setup: %m", q, p);
2070 return 0;
2071 } else
2072 return log_error_errno(errno, "Failed to symlink %s to %s: %m", q, p);
2073 }
2074
2075 r = userns_mkdir(directory, p, 0755, 0, 0);
2076 if (r < 0)
2077 log_warning_errno(r, "Failed to create directory %s: %m", q);
2078 return 0;
2079 }
2080
2081 if (arg_link_journal == LINK_HOST) {
2082 /* don't create parents here — if the host doesn't have
2083 * permanent journal set up, don't force it here */
2084
2085 r = mkdir_errno_wrapper(p, 0755);
2086 if (r < 0 && r != -EEXIST) {
2087 if (try) {
2088 log_debug_errno(r, "Failed to create %s, skipping journal setup: %m", p);
2089 return 0;
2090 } else
2091 return log_error_errno(r, "Failed to create %s: %m", p);
2092 }
2093
2094 } else if (access(p, F_OK) < 0)
2095 return 0;
2096
2097 if (dir_is_empty(q) == 0)
2098 log_warning("%s is not empty, proceeding anyway.", q);
2099
2100 r = userns_mkdir(directory, p, 0755, 0, 0);
2101 if (r < 0)
2102 return log_error_errno(r, "Failed to create %s: %m", q);
2103
2104 r = mount_verbose(LOG_DEBUG, p, q, NULL, MS_BIND, NULL);
2105 if (r < 0)
2106 return log_error_errno(errno, "Failed to bind mount journal from host into guest: %m");
2107
2108 return 0;
2109 }
2110
2111 static int drop_capabilities(void) {
2112 return capability_bounding_set_drop(arg_caps_retain, false);
2113 }
2114
2115 static int reset_audit_loginuid(void) {
2116 _cleanup_free_ char *p = NULL;
2117 int r;
2118
2119 if ((arg_clone_ns_flags & CLONE_NEWPID) == 0)
2120 return 0;
2121
2122 r = read_one_line_file("/proc/self/loginuid", &p);
2123 if (r == -ENOENT)
2124 return 0;
2125 if (r < 0)
2126 return log_error_errno(r, "Failed to read /proc/self/loginuid: %m");
2127
2128 /* Already reset? */
2129 if (streq(p, "4294967295"))
2130 return 0;
2131
2132 r = write_string_file("/proc/self/loginuid", "4294967295", WRITE_STRING_FILE_DISABLE_BUFFER);
2133 if (r < 0) {
2134 log_error_errno(r,
2135 "Failed to reset audit login UID. This probably means that your kernel is too\n"
2136 "old and you have audit enabled. Note that the auditing subsystem is known to\n"
2137 "be incompatible with containers on old kernels. Please make sure to upgrade\n"
2138 "your kernel or to off auditing with 'audit=0' on the kernel command line before\n"
2139 "using systemd-nspawn. Sleeping for 5s... (%m)");
2140
2141 sleep(5);
2142 }
2143
2144 return 0;
2145 }
2146
2147 static int setup_propagate(const char *root) {
2148 const char *p, *q;
2149 int r;
2150
2151 (void) mkdir_p("/run/systemd/nspawn/", 0755);
2152 (void) mkdir_p("/run/systemd/nspawn/propagate", 0600);
2153 p = strjoina("/run/systemd/nspawn/propagate/", arg_machine);
2154 (void) mkdir_p(p, 0600);
2155
2156 r = userns_mkdir(root, "/run/systemd", 0755, 0, 0);
2157 if (r < 0)
2158 return log_error_errno(r, "Failed to create /run/systemd: %m");
2159
2160 r = userns_mkdir(root, "/run/systemd/nspawn", 0755, 0, 0);
2161 if (r < 0)
2162 return log_error_errno(r, "Failed to create /run/systemd/nspawn: %m");
2163
2164 r = userns_mkdir(root, "/run/systemd/nspawn/incoming", 0600, 0, 0);
2165 if (r < 0)
2166 return log_error_errno(r, "Failed to create /run/systemd/nspawn/incoming: %m");
2167
2168 q = prefix_roota(root, "/run/systemd/nspawn/incoming");
2169 r = mount_verbose(LOG_ERR, p, q, NULL, MS_BIND, NULL);
2170 if (r < 0)
2171 return r;
2172
2173 r = mount_verbose(LOG_ERR, NULL, q, NULL, MS_BIND|MS_REMOUNT|MS_RDONLY, NULL);
2174 if (r < 0)
2175 return r;
2176
2177 /* machined will MS_MOVE into that directory, and that's only
2178 * supported for non-shared mounts. */
2179 return mount_verbose(LOG_ERR, NULL, q, NULL, MS_SLAVE, NULL);
2180 }
2181
2182 static int setup_machine_id(const char *directory) {
2183 const char *etc_machine_id;
2184 sd_id128_t id;
2185 int r;
2186
2187 /* If the UUID in the container is already set, then that's what counts, and we use. If it isn't set, and the
2188 * caller passed --uuid=, then we'll pass it in the $container_uuid env var to PID 1 of the container. The
2189 * assumption is that PID 1 will then write it to /etc/machine-id to make it persistent. If --uuid= is not
2190 * passed we generate a random UUID, and pass it via $container_uuid. In effect this means that /etc/machine-id
2191 * in the container and our idea of the container UUID will always be in sync (at least if PID 1 in the
2192 * container behaves nicely). */
2193
2194 etc_machine_id = prefix_roota(directory, "/etc/machine-id");
2195
2196 r = id128_read(etc_machine_id, ID128_PLAIN, &id);
2197 if (r < 0) {
2198 if (!IN_SET(r, -ENOENT, -ENOMEDIUM)) /* If the file is missing or empty, we don't mind */
2199 return log_error_errno(r, "Failed to read machine ID from container image: %m");
2200
2201 if (sd_id128_is_null(arg_uuid)) {
2202 r = sd_id128_randomize(&arg_uuid);
2203 if (r < 0)
2204 return log_error_errno(r, "Failed to acquire randomized machine UUID: %m");
2205 }
2206 } else {
2207 if (sd_id128_is_null(id))
2208 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2209 "Machine ID in container image is zero, refusing.");
2210
2211 arg_uuid = id;
2212 }
2213
2214 return 0;
2215 }
2216
2217 static int recursive_chown(const char *directory, uid_t shift, uid_t range) {
2218 int r;
2219
2220 assert(directory);
2221
2222 if (arg_userns_mode == USER_NAMESPACE_NO || !arg_userns_chown)
2223 return 0;
2224
2225 r = path_patch_uid(directory, arg_uid_shift, arg_uid_range);
2226 if (r == -EOPNOTSUPP)
2227 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.");
2228 if (r == -EBADE)
2229 return log_error_errno(r, "Upper 16 bits of root directory UID and GID do not match.");
2230 if (r < 0)
2231 return log_error_errno(r, "Failed to adjust UID/GID shift of OS tree: %m");
2232 if (r == 0)
2233 log_debug("Root directory of image is already owned by the right UID/GID range, skipping recursive chown operation.");
2234 else
2235 log_debug("Patched directory tree to match UID/GID range.");
2236
2237 return r;
2238 }
2239
2240 /*
2241 * Return values:
2242 * < 0 : wait_for_terminate() failed to get the state of the
2243 * container, the container was terminated by a signal, or
2244 * failed for an unknown reason. No change is made to the
2245 * container argument.
2246 * > 0 : The program executed in the container terminated with an
2247 * error. The exit code of the program executed in the
2248 * container is returned. The container argument has been set
2249 * to CONTAINER_TERMINATED.
2250 * 0 : The container is being rebooted, has been shut down or exited
2251 * successfully. The container argument has been set to either
2252 * CONTAINER_TERMINATED or CONTAINER_REBOOTED.
2253 *
2254 * That is, success is indicated by a return value of zero, and an
2255 * error is indicated by a non-zero value.
2256 */
2257 static int wait_for_container(pid_t pid, ContainerStatus *container) {
2258 siginfo_t status;
2259 int r;
2260
2261 r = wait_for_terminate(pid, &status);
2262 if (r < 0)
2263 return log_warning_errno(r, "Failed to wait for container: %m");
2264
2265 switch (status.si_code) {
2266
2267 case CLD_EXITED:
2268 if (status.si_status == 0)
2269 log_full(arg_quiet ? LOG_DEBUG : LOG_INFO, "Container %s exited successfully.", arg_machine);
2270 else
2271 log_full(arg_quiet ? LOG_DEBUG : LOG_INFO, "Container %s failed with error code %i.", arg_machine, status.si_status);
2272
2273 *container = CONTAINER_TERMINATED;
2274 return status.si_status;
2275
2276 case CLD_KILLED:
2277 if (status.si_status == SIGINT) {
2278 log_full(arg_quiet ? LOG_DEBUG : LOG_INFO, "Container %s has been shut down.", arg_machine);
2279 *container = CONTAINER_TERMINATED;
2280 return 0;
2281
2282 } else if (status.si_status == SIGHUP) {
2283 log_full(arg_quiet ? LOG_DEBUG : LOG_INFO, "Container %s is being rebooted.", arg_machine);
2284 *container = CONTAINER_REBOOTED;
2285 return 0;
2286 }
2287
2288 _fallthrough_;
2289 case CLD_DUMPED:
2290 return log_error_errno(SYNTHETIC_ERRNO(EIO),
2291 "Container %s terminated by signal %s.", arg_machine, signal_to_string(status.si_status));
2292
2293 default:
2294 return log_error_errno(SYNTHETIC_ERRNO(EIO),
2295 "Container %s failed due to unknown reason.", arg_machine);
2296 }
2297 }
2298
2299 static int on_orderly_shutdown(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
2300 pid_t pid;
2301
2302 pid = PTR_TO_PID(userdata);
2303 if (pid > 0) {
2304 if (kill(pid, arg_kill_signal) >= 0) {
2305 log_info("Trying to halt container. Send SIGTERM again to trigger immediate termination.");
2306 sd_event_source_set_userdata(s, NULL);
2307 return 0;
2308 }
2309 }
2310
2311 sd_event_exit(sd_event_source_get_event(s), 0);
2312 return 0;
2313 }
2314
2315 static int on_sigchld(sd_event_source *s, const struct signalfd_siginfo *ssi, void *userdata) {
2316 pid_t pid;
2317
2318 assert(s);
2319 assert(ssi);
2320
2321 pid = PTR_TO_PID(userdata);
2322
2323 for (;;) {
2324 siginfo_t si = {};
2325
2326 if (waitid(P_ALL, 0, &si, WNOHANG|WNOWAIT|WEXITED) < 0)
2327 return log_error_errno(errno, "Failed to waitid(): %m");
2328 if (si.si_pid == 0) /* No pending children. */
2329 break;
2330 if (si.si_pid == pid) {
2331 /* The main process we care for has exited. Return from
2332 * signal handler but leave the zombie. */
2333 sd_event_exit(sd_event_source_get_event(s), 0);
2334 break;
2335 }
2336
2337 /* Reap all other children. */
2338 (void) waitid(P_PID, si.si_pid, &si, WNOHANG|WEXITED);
2339 }
2340
2341 return 0;
2342 }
2343
2344 static int on_request_stop(sd_bus_message *m, void *userdata, sd_bus_error *error) {
2345 pid_t pid;
2346
2347 assert(m);
2348
2349 pid = PTR_TO_PID(userdata);
2350
2351 if (arg_kill_signal > 0) {
2352 log_info("Container termination requested. Attempting to halt container.");
2353 (void) kill(pid, arg_kill_signal);
2354 } else {
2355 log_info("Container termination requested. Exiting.");
2356 sd_event_exit(sd_bus_get_event(sd_bus_message_get_bus(m)), 0);
2357 }
2358
2359 return 0;
2360 }
2361
2362 static int determine_names(void) {
2363 int r;
2364
2365 if (arg_template && !arg_directory && arg_machine) {
2366
2367 /* If --template= was specified then we should not
2368 * search for a machine, but instead create a new one
2369 * in /var/lib/machine. */
2370
2371 arg_directory = strjoin("/var/lib/machines/", arg_machine);
2372 if (!arg_directory)
2373 return log_oom();
2374 }
2375
2376 if (!arg_image && !arg_directory) {
2377 if (arg_machine) {
2378 _cleanup_(image_unrefp) Image *i = NULL;
2379
2380 r = image_find(IMAGE_MACHINE, arg_machine, &i);
2381 if (r == -ENOENT)
2382 return log_error_errno(r, "No image for machine '%s'.", arg_machine);
2383 if (r < 0)
2384 return log_error_errno(r, "Failed to find image for machine '%s': %m", arg_machine);
2385
2386 if (IN_SET(i->type, IMAGE_RAW, IMAGE_BLOCK))
2387 r = free_and_strdup(&arg_image, i->path);
2388 else
2389 r = free_and_strdup(&arg_directory, i->path);
2390 if (r < 0)
2391 return log_oom();
2392
2393 if (!arg_ephemeral)
2394 arg_read_only = arg_read_only || i->read_only;
2395 } else {
2396 r = safe_getcwd(&arg_directory);
2397 if (r < 0)
2398 return log_error_errno(r, "Failed to determine current directory: %m");
2399 }
2400
2401 if (!arg_directory && !arg_image) {
2402 log_error("Failed to determine path, please use -D or -i.");
2403 return -EINVAL;
2404 }
2405 }
2406
2407 if (!arg_machine) {
2408 if (arg_directory && path_equal(arg_directory, "/"))
2409 arg_machine = gethostname_malloc();
2410 else {
2411 if (arg_image) {
2412 char *e;
2413
2414 arg_machine = strdup(basename(arg_image));
2415
2416 /* Truncate suffix if there is one */
2417 e = endswith(arg_machine, ".raw");
2418 if (e)
2419 *e = 0;
2420 } else
2421 arg_machine = strdup(basename(arg_directory));
2422 }
2423 if (!arg_machine)
2424 return log_oom();
2425
2426 hostname_cleanup(arg_machine);
2427 if (!machine_name_is_valid(arg_machine)) {
2428 log_error("Failed to determine machine name automatically, please use -M.");
2429 return -EINVAL;
2430 }
2431
2432 if (arg_ephemeral) {
2433 char *b;
2434
2435 /* Add a random suffix when this is an
2436 * ephemeral machine, so that we can run many
2437 * instances at once without manually having
2438 * to specify -M each time. */
2439
2440 if (asprintf(&b, "%s-%016" PRIx64, arg_machine, random_u64()) < 0)
2441 return log_oom();
2442
2443 free(arg_machine);
2444 arg_machine = b;
2445 }
2446 }
2447
2448 return 0;
2449 }
2450
2451 static int chase_symlinks_and_update(char **p, unsigned flags) {
2452 char *chased;
2453 int r;
2454
2455 assert(p);
2456
2457 if (!*p)
2458 return 0;
2459
2460 r = chase_symlinks(*p, NULL, flags, &chased);
2461 if (r < 0)
2462 return log_error_errno(r, "Failed to resolve path %s: %m", *p);
2463
2464 free_and_replace(*p, chased);
2465 return r; /* r might be an fd here in case we ever use CHASE_OPEN in flags */
2466 }
2467
2468 static int determine_uid_shift(const char *directory) {
2469 int r;
2470
2471 if (arg_userns_mode == USER_NAMESPACE_NO) {
2472 arg_uid_shift = 0;
2473 return 0;
2474 }
2475
2476 if (arg_uid_shift == UID_INVALID) {
2477 struct stat st;
2478
2479 r = stat(directory, &st);
2480 if (r < 0)
2481 return log_error_errno(errno, "Failed to determine UID base of %s: %m", directory);
2482
2483 arg_uid_shift = st.st_uid & UINT32_C(0xffff0000);
2484
2485 if (arg_uid_shift != (st.st_gid & UINT32_C(0xffff0000)))
2486 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2487 "UID and GID base of %s don't match.", directory);
2488
2489 arg_uid_range = UINT32_C(0x10000);
2490 }
2491
2492 if (arg_uid_shift > (uid_t) -1 - arg_uid_range)
2493 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2494 "UID base too high for UID range.");
2495
2496 return 0;
2497 }
2498
2499 static int inner_child(
2500 Barrier *barrier,
2501 const char *directory,
2502 bool secondary,
2503 int kmsg_socket,
2504 int rtnl_socket,
2505 FDSet *fds) {
2506
2507 _cleanup_free_ char *home = NULL;
2508 char as_uuid[37];
2509 size_t n_env = 1;
2510 const char *envp[] = {
2511 "PATH=" DEFAULT_PATH_COMPAT,
2512 NULL, /* container */
2513 NULL, /* TERM */
2514 NULL, /* HOME */
2515 NULL, /* USER */
2516 NULL, /* LOGNAME */
2517 NULL, /* container_uuid */
2518 NULL, /* LISTEN_FDS */
2519 NULL, /* LISTEN_PID */
2520 NULL, /* NOTIFY_SOCKET */
2521 NULL
2522 };
2523 const char *exec_target;
2524 _cleanup_strv_free_ char **env_use = NULL;
2525 int r;
2526
2527 /* This is the "inner" child process, i.e. the one forked off by the "outer" child process, which is the one
2528 * the container manager itself forked off. At the time of clone() it gained its own CLONE_NEWNS, CLONE_NEWPID,
2529 * CLONE_NEWUTS, CLONE_NEWIPC, CLONE_NEWUSER namespaces. Note that it has its own CLONE_NEWNS namespace,
2530 * separate from the CLONE_NEWNS created for the "outer" child, and also separate from the host's CLONE_NEWNS
2531 * namespace. The reason for having two levels of CLONE_NEWNS namespaces is that the "inner" one is owned by
2532 * the CLONE_NEWUSER namespace of the container, while the "outer" one is owned by the host's CLONE_NEWUSER
2533 * namespace.
2534 *
2535 * Note at this point we have no CLONE_NEWNET namespace yet. We'll acquire that one later through
2536 * unshare(). See below. */
2537
2538 assert(barrier);
2539 assert(directory);
2540 assert(kmsg_socket >= 0);
2541
2542 if (arg_userns_mode != USER_NAMESPACE_NO) {
2543 /* Tell the parent, that it now can write the UID map. */
2544 (void) barrier_place(barrier); /* #1 */
2545
2546 /* Wait until the parent wrote the UID map */
2547 if (!barrier_place_and_sync(barrier)) /* #2 */
2548 return log_error_errno(SYNTHETIC_ERRNO(ESRCH),
2549 "Parent died too early");
2550 }
2551
2552 r = reset_uid_gid();
2553 if (r < 0)
2554 return log_error_errno(r, "Couldn't become new root: %m");
2555
2556 r = mount_all(NULL,
2557 arg_mount_settings | MOUNT_IN_USERNS,
2558 arg_uid_shift,
2559 arg_selinux_apifs_context);
2560 if (r < 0)
2561 return r;
2562
2563 if (!arg_network_namespace_path && arg_private_network) {
2564 r = unshare(CLONE_NEWNET);
2565 if (r < 0)
2566 return log_error_errno(errno, "Failed to unshare network namespace: %m");
2567
2568 /* Tell the parent that it can setup network interfaces. */
2569 (void) barrier_place(barrier); /* #3 */
2570 }
2571
2572 r = mount_sysfs(NULL, arg_mount_settings);
2573 if (r < 0)
2574 return r;
2575
2576 /* Wait until we are cgroup-ified, so that we
2577 * can mount the right cgroup path writable */
2578 if (!barrier_place_and_sync(barrier)) /* #4 */
2579 return log_error_errno(SYNTHETIC_ERRNO(ESRCH),
2580 "Parent died too early");
2581
2582 if (arg_use_cgns && cg_ns_supported()) {
2583 r = unshare(CLONE_NEWCGROUP);
2584 if (r < 0)
2585 return log_error_errno(errno, "Failed to unshare cgroup namespace: %m");
2586 r = mount_cgroups(
2587 "",
2588 arg_unified_cgroup_hierarchy,
2589 arg_userns_mode != USER_NAMESPACE_NO,
2590 arg_uid_shift,
2591 arg_uid_range,
2592 arg_selinux_apifs_context,
2593 true);
2594 if (r < 0)
2595 return r;
2596 } else {
2597 r = mount_systemd_cgroup_writable("", arg_unified_cgroup_hierarchy);
2598 if (r < 0)
2599 return r;
2600 }
2601
2602 r = setup_boot_id();
2603 if (r < 0)
2604 return r;
2605
2606 r = setup_kmsg(kmsg_socket);
2607 if (r < 0)
2608 return r;
2609 kmsg_socket = safe_close(kmsg_socket);
2610
2611 if (setsid() < 0)
2612 return log_error_errno(errno, "setsid() failed: %m");
2613
2614 if (arg_private_network)
2615 loopback_setup();
2616
2617 if (arg_expose_ports) {
2618 r = expose_port_send_rtnl(rtnl_socket);
2619 if (r < 0)
2620 return r;
2621 rtnl_socket = safe_close(rtnl_socket);
2622 }
2623
2624 if (arg_oom_score_adjust_set) {
2625 r = set_oom_score_adjust(arg_oom_score_adjust);
2626 if (r < 0)
2627 return log_error_errno(r, "Failed to adjust OOM score: %m");
2628 }
2629
2630 if (arg_cpuset)
2631 if (sched_setaffinity(0, CPU_ALLOC_SIZE(arg_cpuset_ncpus), arg_cpuset) < 0)
2632 return log_error_errno(errno, "Failed to set CPU affinity: %m");
2633
2634 r = drop_capabilities();
2635 if (r < 0)
2636 return log_error_errno(r, "drop_capabilities() failed: %m");
2637
2638 (void) setup_hostname();
2639
2640 if (arg_personality != PERSONALITY_INVALID) {
2641 r = safe_personality(arg_personality);
2642 if (r < 0)
2643 return log_error_errno(r, "personality() failed: %m");
2644 } else if (secondary) {
2645 r = safe_personality(PER_LINUX32);
2646 if (r < 0)
2647 return log_error_errno(r, "personality() failed: %m");
2648 }
2649
2650 #if HAVE_SELINUX
2651 if (arg_selinux_context)
2652 if (setexeccon(arg_selinux_context) < 0)
2653 return log_error_errno(errno, "setexeccon(\"%s\") failed: %m", arg_selinux_context);
2654 #endif
2655
2656 r = change_uid_gid(arg_user, &home);
2657 if (r < 0)
2658 return r;
2659
2660 if (arg_no_new_privileges)
2661 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0)
2662 return log_error_errno(errno, "Failed to disable new privileges: %m");
2663
2664 /* LXC sets container=lxc, so follow the scheme here */
2665 envp[n_env++] = strjoina("container=", arg_container_service_name);
2666
2667 envp[n_env] = strv_find_prefix(environ, "TERM=");
2668 if (envp[n_env])
2669 n_env++;
2670
2671 if ((asprintf((char**)(envp + n_env++), "HOME=%s", home ? home: "/root") < 0) ||
2672 (asprintf((char**)(envp + n_env++), "USER=%s", arg_user ? arg_user : "root") < 0) ||
2673 (asprintf((char**)(envp + n_env++), "LOGNAME=%s", arg_user ? arg_user : "root") < 0))
2674 return log_oom();
2675
2676 assert(!sd_id128_is_null(arg_uuid));
2677
2678 if (asprintf((char**)(envp + n_env++), "container_uuid=%s", id128_to_uuid_string(arg_uuid, as_uuid)) < 0)
2679 return log_oom();
2680
2681 if (fdset_size(fds) > 0) {
2682 r = fdset_cloexec(fds, false);
2683 if (r < 0)
2684 return log_error_errno(r, "Failed to unset O_CLOEXEC for file descriptors.");
2685
2686 if ((asprintf((char **)(envp + n_env++), "LISTEN_FDS=%u", fdset_size(fds)) < 0) ||
2687 (asprintf((char **)(envp + n_env++), "LISTEN_PID=1") < 0))
2688 return log_oom();
2689 }
2690 if (asprintf((char **)(envp + n_env++), "NOTIFY_SOCKET=%s", NSPAWN_NOTIFY_SOCKET_PATH) < 0)
2691 return log_oom();
2692
2693 env_use = strv_env_merge(2, envp, arg_setenv);
2694 if (!env_use)
2695 return log_oom();
2696
2697 /* Let the parent know that we are ready and
2698 * wait until the parent is ready with the
2699 * setup, too... */
2700 if (!barrier_place_and_sync(barrier)) /* #5 */
2701 return log_error_errno(SYNTHETIC_ERRNO(ESRCH),
2702 "Parent died too early");
2703
2704 if (arg_chdir)
2705 if (chdir(arg_chdir) < 0)
2706 return log_error_errno(errno, "Failed to change to specified working directory %s: %m", arg_chdir);
2707
2708 if (arg_start_mode == START_PID2) {
2709 r = stub_pid1(arg_uuid);
2710 if (r < 0)
2711 return r;
2712 }
2713
2714 /* Now, explicitly close the log, so that we then can close all remaining fds. Closing the log explicitly first
2715 * has the benefit that the logging subsystem knows about it, and is thus ready to be reopened should we need
2716 * it again. Note that the other fds closed here are at least the locking and barrier fds. */
2717 log_close();
2718 log_set_open_when_needed(true);
2719
2720 (void) fdset_close_others(fds);
2721
2722 if (arg_start_mode == START_BOOT) {
2723 char **a;
2724 size_t m;
2725
2726 /* Automatically search for the init system */
2727
2728 m = strv_length(arg_parameters);
2729 a = newa(char*, m + 2);
2730 memcpy_safe(a + 1, arg_parameters, m * sizeof(char*));
2731 a[1 + m] = NULL;
2732
2733 a[0] = (char*) "/usr/lib/systemd/systemd";
2734 execve(a[0], a, env_use);
2735
2736 a[0] = (char*) "/lib/systemd/systemd";
2737 execve(a[0], a, env_use);
2738
2739 a[0] = (char*) "/sbin/init";
2740 execve(a[0], a, env_use);
2741
2742 exec_target = "/usr/lib/systemd/systemd, /lib/systemd/systemd, /sbin/init";
2743 } else if (!strv_isempty(arg_parameters)) {
2744 const char *dollar_path;
2745
2746 exec_target = arg_parameters[0];
2747
2748 /* Use the user supplied search $PATH if there is one, or DEFAULT_PATH_COMPAT if not to search the
2749 * binary. */
2750 dollar_path = strv_env_get(env_use, "PATH");
2751 if (dollar_path) {
2752 if (putenv((char*) dollar_path) != 0)
2753 return log_error_errno(errno, "Failed to update $PATH: %m");
2754 }
2755
2756 execvpe(arg_parameters[0], arg_parameters, env_use);
2757 } else {
2758 if (!arg_chdir)
2759 /* If we cannot change the directory, we'll end up in /, that is expected. */
2760 (void) chdir(home ?: "/root");
2761
2762 execle("/bin/bash", "-bash", NULL, env_use);
2763 execle("/bin/sh", "-sh", NULL, env_use);
2764
2765 exec_target = "/bin/bash, /bin/sh";
2766 }
2767
2768 return log_error_errno(errno, "execv(%s) failed: %m", exec_target);
2769 }
2770
2771 static int setup_sd_notify_child(void) {
2772 _cleanup_close_ int fd = -1;
2773 union sockaddr_union sa = {
2774 .un.sun_family = AF_UNIX,
2775 .un.sun_path = NSPAWN_NOTIFY_SOCKET_PATH,
2776 };
2777 int r;
2778
2779 fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2780 if (fd < 0)
2781 return log_error_errno(errno, "Failed to allocate notification socket: %m");
2782
2783 (void) mkdir_parents(NSPAWN_NOTIFY_SOCKET_PATH, 0755);
2784 (void) sockaddr_un_unlink(&sa.un);
2785
2786 r = bind(fd, &sa.sa, SOCKADDR_UN_LEN(sa.un));
2787 if (r < 0)
2788 return log_error_errno(errno, "bind(" NSPAWN_NOTIFY_SOCKET_PATH ") failed: %m");
2789
2790 r = userns_lchown(NSPAWN_NOTIFY_SOCKET_PATH, 0, 0);
2791 if (r < 0)
2792 return log_error_errno(r, "Failed to chown " NSPAWN_NOTIFY_SOCKET_PATH ": %m");
2793
2794 r = setsockopt_int(fd, SOL_SOCKET, SO_PASSCRED, true);
2795 if (r < 0)
2796 return log_error_errno(r, "SO_PASSCRED failed: %m");
2797
2798 return TAKE_FD(fd);
2799 }
2800
2801 static int outer_child(
2802 Barrier *barrier,
2803 const char *directory,
2804 const char *console,
2805 DissectedImage *dissected_image,
2806 bool interactive,
2807 bool secondary,
2808 int pid_socket,
2809 int uuid_socket,
2810 int notify_socket,
2811 int kmsg_socket,
2812 int rtnl_socket,
2813 int uid_shift_socket,
2814 int unified_cgroup_hierarchy_socket,
2815 FDSet *fds,
2816 int netns_fd) {
2817
2818 _cleanup_close_ int fd = -1;
2819 int r, which_failed;
2820 pid_t pid;
2821 ssize_t l;
2822
2823 /* This is the "outer" child process, i.e the one forked off by the container manager itself. It already has
2824 * its own CLONE_NEWNS namespace (which was created by the clone()). It still lives in the host's CLONE_NEWPID,
2825 * CLONE_NEWUTS, CLONE_NEWIPC, CLONE_NEWUSER and CLONE_NEWNET namespaces. After it completed a number of
2826 * initializations a second child (the "inner" one) is forked off it, and it exits. */
2827
2828 assert(barrier);
2829 assert(directory);
2830 assert(console);
2831 assert(pid_socket >= 0);
2832 assert(uuid_socket >= 0);
2833 assert(notify_socket >= 0);
2834 assert(kmsg_socket >= 0);
2835
2836 if (prctl(PR_SET_PDEATHSIG, SIGKILL) < 0)
2837 return log_error_errno(errno, "PR_SET_PDEATHSIG failed: %m");
2838
2839 if (interactive) {
2840 int terminal;
2841
2842 terminal = open_terminal(console, O_RDWR);
2843 if (terminal < 0)
2844 return log_error_errno(terminal, "Failed to open console: %m");
2845
2846 /* Make sure we can continue logging to the original stderr, even if stderr points elsewhere now */
2847 r = log_dup_console();
2848 if (r < 0)
2849 return log_error_errno(r, "Failed to duplicate stderr: %m");
2850
2851 r = rearrange_stdio(terminal, terminal, terminal); /* invalidates 'terminal' on success and failure */
2852 if (r < 0)
2853 return log_error_errno(r, "Failed to move console to stdin/stdout/stderr: %m");
2854 }
2855
2856 r = reset_audit_loginuid();
2857 if (r < 0)
2858 return r;
2859
2860 /* Mark everything as slave, so that we still
2861 * receive mounts from the real root, but don't
2862 * propagate mounts to the real root. */
2863 r = mount_verbose(LOG_ERR, NULL, "/", NULL, MS_SLAVE|MS_REC, NULL);
2864 if (r < 0)
2865 return r;
2866
2867 if (dissected_image) {
2868 /* If we are operating on a disk image, then mount its root directory now, but leave out the rest. We
2869 * can read the UID shift from it if we need to. Further down we'll mount the rest, but then with the
2870 * uid shift known. That way we can mount VFAT file systems shifted to the right place right away. This
2871 * makes sure ESP partitions and userns are compatible. */
2872
2873 r = dissected_image_mount(dissected_image, directory, arg_uid_shift,
2874 DISSECT_IMAGE_MOUNT_ROOT_ONLY|DISSECT_IMAGE_DISCARD_ON_LOOP|
2875 (arg_read_only ? DISSECT_IMAGE_READ_ONLY : 0)|
2876 (arg_start_mode == START_BOOT ? DISSECT_IMAGE_VALIDATE_OS : 0));
2877 if (r < 0)
2878 return r;
2879 }
2880
2881 r = determine_uid_shift(directory);
2882 if (r < 0)
2883 return r;
2884
2885 if (arg_userns_mode != USER_NAMESPACE_NO) {
2886 /* Let the parent know which UID shift we read from the image */
2887 l = send(uid_shift_socket, &arg_uid_shift, sizeof(arg_uid_shift), MSG_NOSIGNAL);
2888 if (l < 0)
2889 return log_error_errno(errno, "Failed to send UID shift: %m");
2890 if (l != sizeof(arg_uid_shift))
2891 return log_error_errno(SYNTHETIC_ERRNO(EIO),
2892 "Short write while sending UID shift.");
2893
2894 if (arg_userns_mode == USER_NAMESPACE_PICK) {
2895 /* When we are supposed to pick the UID shift, the parent will check now whether the UID shift
2896 * we just read from the image is available. If yes, it will send the UID shift back to us, if
2897 * not it will pick a different one, and send it back to us. */
2898
2899 l = recv(uid_shift_socket, &arg_uid_shift, sizeof(arg_uid_shift), 0);
2900 if (l < 0)
2901 return log_error_errno(errno, "Failed to recv UID shift: %m");
2902 if (l != sizeof(arg_uid_shift))
2903 return log_error_errno(SYNTHETIC_ERRNO(EIO),
2904 "Short read while receiving UID shift.");
2905 }
2906
2907 log_full(arg_quiet ? LOG_DEBUG : LOG_INFO,
2908 "Selected user namespace base " UID_FMT " and range " UID_FMT ".", arg_uid_shift, arg_uid_range);
2909 }
2910
2911 if (dissected_image) {
2912 /* Now we know the uid shift, let's now mount everything else that might be in the image. */
2913 r = dissected_image_mount(dissected_image, directory, arg_uid_shift,
2914 DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY|DISSECT_IMAGE_DISCARD_ON_LOOP|(arg_read_only ? DISSECT_IMAGE_READ_ONLY : 0));
2915 if (r < 0)
2916 return r;
2917 }
2918
2919 if (arg_unified_cgroup_hierarchy == CGROUP_UNIFIED_UNKNOWN) {
2920 /* OK, we don't know yet which cgroup mode to use yet. Let's figure it out, and tell the parent. */
2921
2922 r = detect_unified_cgroup_hierarchy_from_image(directory);
2923 if (r < 0)
2924 return r;
2925
2926 l = send(unified_cgroup_hierarchy_socket, &arg_unified_cgroup_hierarchy, sizeof(arg_unified_cgroup_hierarchy), MSG_NOSIGNAL);
2927 if (l < 0)
2928 return log_error_errno(errno, "Failed to send cgroup mode: %m");
2929 if (l != sizeof(arg_unified_cgroup_hierarchy))
2930 return log_error_errno(SYNTHETIC_ERRNO(EIO),
2931 "Short write while sending cgroup mode.");
2932
2933 unified_cgroup_hierarchy_socket = safe_close(unified_cgroup_hierarchy_socket);
2934 }
2935
2936 /* Turn directory into bind mount */
2937 r = mount_verbose(LOG_ERR, directory, directory, NULL, MS_BIND|MS_REC, NULL);
2938 if (r < 0)
2939 return r;
2940
2941 r = setup_pivot_root(
2942 directory,
2943 arg_pivot_root_new,
2944 arg_pivot_root_old);
2945 if (r < 0)
2946 return r;
2947
2948 r = setup_volatile(
2949 directory,
2950 arg_volatile_mode,
2951 arg_userns_mode != USER_NAMESPACE_NO,
2952 arg_uid_shift,
2953 arg_uid_range,
2954 arg_selinux_context);
2955 if (r < 0)
2956 return r;
2957
2958 r = setup_volatile_state(
2959 directory,
2960 arg_volatile_mode,
2961 arg_userns_mode != USER_NAMESPACE_NO,
2962 arg_uid_shift,
2963 arg_uid_range,
2964 arg_selinux_context);
2965 if (r < 0)
2966 return r;
2967
2968 /* Mark everything as shared so our mounts get propagated down. This is
2969 * required to make new bind mounts available in systemd services
2970 * inside the containter that create a new mount namespace.
2971 * See https://github.com/systemd/systemd/issues/3860
2972 * Further submounts (such as /dev) done after this will inherit the
2973 * shared propagation mode. */
2974 r = mount_verbose(LOG_ERR, NULL, directory, NULL, MS_SHARED|MS_REC, NULL);
2975 if (r < 0)
2976 return r;
2977
2978 r = recursive_chown(directory, arg_uid_shift, arg_uid_range);
2979 if (r < 0)
2980 return r;
2981
2982 r = base_filesystem_create(directory, arg_uid_shift, (gid_t) arg_uid_shift);
2983 if (r < 0)
2984 return r;
2985
2986 if (arg_read_only) {
2987 r = bind_remount_recursive(directory, true, NULL);
2988 if (r < 0)
2989 return log_error_errno(r, "Failed to make tree read-only: %m");
2990 }
2991
2992 r = mount_all(directory,
2993 arg_mount_settings,
2994 arg_uid_shift,
2995 arg_selinux_apifs_context);
2996 if (r < 0)
2997 return r;
2998
2999 r = copy_devnodes(directory);
3000 if (r < 0)
3001 return r;
3002
3003 dev_setup(directory, arg_uid_shift, arg_uid_shift);
3004
3005 r = setup_pts(directory);
3006 if (r < 0)
3007 return r;
3008
3009 r = setup_propagate(directory);
3010 if (r < 0)
3011 return r;
3012
3013 r = setup_dev_console(directory, console);
3014 if (r < 0)
3015 return r;
3016
3017 r = setup_keyring();
3018 if (r < 0)
3019 return r;
3020
3021 r = setup_seccomp(arg_caps_retain, arg_syscall_whitelist, arg_syscall_blacklist);
3022 if (r < 0)
3023 return r;
3024
3025 r = setup_timezone(directory);
3026 if (r < 0)
3027 return r;
3028
3029 r = setup_resolv_conf(directory);
3030 if (r < 0)
3031 return r;
3032
3033 r = setup_machine_id(directory);
3034 if (r < 0)
3035 return r;
3036
3037 r = setup_journal(directory);
3038 if (r < 0)
3039 return r;
3040
3041 r = mount_custom(
3042 directory,
3043 arg_custom_mounts,
3044 arg_n_custom_mounts,
3045 arg_userns_mode != USER_NAMESPACE_NO,
3046 arg_uid_shift,
3047 arg_uid_range,
3048 arg_selinux_apifs_context);
3049 if (r < 0)
3050 return r;
3051
3052 if (!arg_use_cgns || !cg_ns_supported()) {
3053 r = mount_cgroups(
3054 directory,
3055 arg_unified_cgroup_hierarchy,
3056 arg_userns_mode != USER_NAMESPACE_NO,
3057 arg_uid_shift,
3058 arg_uid_range,
3059 arg_selinux_apifs_context,
3060 false);
3061 if (r < 0)
3062 return r;
3063 }
3064
3065 r = mount_move_root(directory);
3066 if (r < 0)
3067 return log_error_errno(r, "Failed to move root directory: %m");
3068
3069 fd = setup_sd_notify_child();
3070 if (fd < 0)
3071 return fd;
3072
3073 r = setrlimit_closest_all((const struct rlimit *const*) arg_rlimit, &which_failed);
3074 if (r < 0)
3075 return log_error_errno(r, "Failed to apply resource limit RLIMIT_%s: %m", rlimit_to_string(which_failed));
3076
3077 pid = raw_clone(SIGCHLD|CLONE_NEWNS|
3078 arg_clone_ns_flags |
3079 (arg_userns_mode != USER_NAMESPACE_NO ? CLONE_NEWUSER : 0));
3080 if (pid < 0)
3081 return log_error_errno(errno, "Failed to fork inner child: %m");
3082 if (pid == 0) {
3083 pid_socket = safe_close(pid_socket);
3084 uuid_socket = safe_close(uuid_socket);
3085 notify_socket = safe_close(notify_socket);
3086 uid_shift_socket = safe_close(uid_shift_socket);
3087
3088 /* The inner child has all namespaces that are
3089 * requested, so that we all are owned by the user if
3090 * user namespaces are turned on. */
3091
3092 if (arg_network_namespace_path) {
3093 r = namespace_enter(-1, -1, netns_fd, -1, -1);
3094 if (r < 0)
3095 return log_error_errno(r, "Failed to join network namespace: %m");
3096 }
3097
3098 r = inner_child(barrier, directory, secondary, kmsg_socket, rtnl_socket, fds);
3099 if (r < 0)
3100 _exit(EXIT_FAILURE);
3101
3102 _exit(EXIT_SUCCESS);
3103 }
3104
3105 l = send(pid_socket, &pid, sizeof(pid), MSG_NOSIGNAL);
3106 if (l < 0)
3107 return log_error_errno(errno, "Failed to send PID: %m");
3108 if (l != sizeof(pid))
3109 return log_error_errno(SYNTHETIC_ERRNO(EIO),
3110 "Short write while sending PID.");
3111
3112 l = send(uuid_socket, &arg_uuid, sizeof(arg_uuid), MSG_NOSIGNAL);
3113 if (l < 0)
3114 return log_error_errno(errno, "Failed to send machine ID: %m");
3115 if (l != sizeof(arg_uuid))
3116 return log_error_errno(SYNTHETIC_ERRNO(EIO),
3117 "Short write while sending machine ID.");
3118
3119 l = send_one_fd(notify_socket, fd, 0);
3120 if (l < 0)
3121 return log_error_errno(errno, "Failed to send notify fd: %m");
3122
3123 pid_socket = safe_close(pid_socket);
3124 uuid_socket = safe_close(uuid_socket);
3125 notify_socket = safe_close(notify_socket);
3126 kmsg_socket = safe_close(kmsg_socket);
3127 rtnl_socket = safe_close(rtnl_socket);
3128 netns_fd = safe_close(netns_fd);
3129
3130 return 0;
3131 }
3132
3133 static int uid_shift_pick(uid_t *shift, LockFile *ret_lock_file) {
3134 bool tried_hashed = false;
3135 unsigned n_tries = 100;
3136 uid_t candidate;
3137 int r;
3138
3139 assert(shift);
3140 assert(ret_lock_file);
3141 assert(arg_userns_mode == USER_NAMESPACE_PICK);
3142 assert(arg_uid_range == 0x10000U);
3143
3144 candidate = *shift;
3145
3146 (void) mkdir("/run/systemd/nspawn-uid", 0755);
3147
3148 for (;;) {
3149 char lock_path[STRLEN("/run/systemd/nspawn-uid/") + DECIMAL_STR_MAX(uid_t) + 1];
3150 _cleanup_(release_lock_file) LockFile lf = LOCK_FILE_INIT;
3151
3152 if (--n_tries <= 0)
3153 return -EBUSY;
3154
3155 if (candidate < CONTAINER_UID_BASE_MIN || candidate > CONTAINER_UID_BASE_MAX)
3156 goto next;
3157 if ((candidate & UINT32_C(0xFFFF)) != 0)
3158 goto next;
3159
3160 xsprintf(lock_path, "/run/systemd/nspawn-uid/" UID_FMT, candidate);
3161 r = make_lock_file(lock_path, LOCK_EX|LOCK_NB, &lf);
3162 if (r == -EBUSY) /* Range already taken by another nspawn instance */
3163 goto next;
3164 if (r < 0)
3165 return r;
3166
3167 /* Make some superficial checks whether the range is currently known in the user database */
3168 if (getpwuid(candidate))
3169 goto next;
3170 if (getpwuid(candidate + UINT32_C(0xFFFE)))
3171 goto next;
3172 if (getgrgid(candidate))
3173 goto next;
3174 if (getgrgid(candidate + UINT32_C(0xFFFE)))
3175 goto next;
3176
3177 *ret_lock_file = lf;
3178 lf = (struct LockFile) LOCK_FILE_INIT;
3179 *shift = candidate;
3180 return 0;
3181
3182 next:
3183 if (arg_machine && !tried_hashed) {
3184 /* Try to hash the base from the container name */
3185
3186 static const uint8_t hash_key[] = {
3187 0xe1, 0x56, 0xe0, 0xf0, 0x4a, 0xf0, 0x41, 0xaf,
3188 0x96, 0x41, 0xcf, 0x41, 0x33, 0x94, 0xff, 0x72
3189 };
3190
3191 candidate = (uid_t) siphash24(arg_machine, strlen(arg_machine), hash_key);
3192
3193 tried_hashed = true;
3194 } else
3195 random_bytes(&candidate, sizeof(candidate));
3196
3197 candidate = (candidate % (CONTAINER_UID_BASE_MAX - CONTAINER_UID_BASE_MIN)) + CONTAINER_UID_BASE_MIN;
3198 candidate &= (uid_t) UINT32_C(0xFFFF0000);
3199 }
3200 }
3201
3202 static int setup_uid_map(pid_t pid) {
3203 char uid_map[STRLEN("/proc//uid_map") + DECIMAL_STR_MAX(uid_t) + 1], line[DECIMAL_STR_MAX(uid_t)*3+3+1];
3204 int r;
3205
3206 assert(pid > 1);
3207
3208 xsprintf(uid_map, "/proc/" PID_FMT "/uid_map", pid);
3209 xsprintf(line, UID_FMT " " UID_FMT " " UID_FMT "\n", 0, arg_uid_shift, arg_uid_range);
3210 r = write_string_file(uid_map, line, WRITE_STRING_FILE_DISABLE_BUFFER);
3211 if (r < 0)
3212 return log_error_errno(r, "Failed to write UID map: %m");
3213
3214 /* We always assign the same UID and GID ranges */
3215 xsprintf(uid_map, "/proc/" PID_FMT "/gid_map", pid);
3216 r = write_string_file(uid_map, line, WRITE_STRING_FILE_DISABLE_BUFFER);
3217 if (r < 0)
3218 return log_error_errno(r, "Failed to write GID map: %m");
3219
3220 return 0;
3221 }
3222
3223 static int nspawn_dispatch_notify_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
3224 char buf[NOTIFY_BUFFER_MAX+1];
3225 char *p = NULL;
3226 struct iovec iovec = {
3227 .iov_base = buf,
3228 .iov_len = sizeof(buf)-1,
3229 };
3230 union {
3231 struct cmsghdr cmsghdr;
3232 uint8_t buf[CMSG_SPACE(sizeof(struct ucred)) +
3233 CMSG_SPACE(sizeof(int) * NOTIFY_FD_MAX)];
3234 } control = {};
3235 struct msghdr msghdr = {
3236 .msg_iov = &iovec,
3237 .msg_iovlen = 1,
3238 .msg_control = &control,
3239 .msg_controllen = sizeof(control),
3240 };
3241 struct cmsghdr *cmsg;
3242 struct ucred *ucred = NULL;
3243 ssize_t n;
3244 pid_t inner_child_pid;
3245 _cleanup_strv_free_ char **tags = NULL;
3246
3247 assert(userdata);
3248
3249 inner_child_pid = PTR_TO_PID(userdata);
3250
3251 if (revents != EPOLLIN) {
3252 log_warning("Got unexpected poll event for notify fd.");
3253 return 0;
3254 }
3255
3256 n = recvmsg(fd, &msghdr, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);
3257 if (n < 0) {
3258 if (IN_SET(errno, EAGAIN, EINTR))
3259 return 0;
3260
3261 return log_warning_errno(errno, "Couldn't read notification socket: %m");
3262 }
3263 cmsg_close_all(&msghdr);
3264
3265 CMSG_FOREACH(cmsg, &msghdr) {
3266 if (cmsg->cmsg_level == SOL_SOCKET &&
3267 cmsg->cmsg_type == SCM_CREDENTIALS &&
3268 cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred))) {
3269
3270 ucred = (struct ucred*) CMSG_DATA(cmsg);
3271 }
3272 }
3273
3274 if (!ucred || ucred->pid != inner_child_pid) {
3275 log_debug("Received notify message without valid credentials. Ignoring.");
3276 return 0;
3277 }
3278
3279 if ((size_t) n >= sizeof(buf)) {
3280 log_warning("Received notify message exceeded maximum size. Ignoring.");
3281 return 0;
3282 }
3283
3284 buf[n] = 0;
3285 tags = strv_split(buf, "\n\r");
3286 if (!tags)
3287 return log_oom();
3288
3289 if (strv_find(tags, "READY=1"))
3290 sd_notifyf(false, "READY=1\n");
3291
3292 p = strv_find_startswith(tags, "STATUS=");
3293 if (p)
3294 sd_notifyf(false, "STATUS=Container running: %s", p);
3295
3296 return 0;
3297 }
3298
3299 static int setup_sd_notify_parent(sd_event *event, int fd, pid_t *inner_child_pid, sd_event_source **notify_event_source) {
3300 int r;
3301
3302 r = sd_event_add_io(event, notify_event_source, fd, EPOLLIN, nspawn_dispatch_notify_fd, inner_child_pid);
3303 if (r < 0)
3304 return log_error_errno(r, "Failed to allocate notify event source: %m");
3305
3306 (void) sd_event_source_set_description(*notify_event_source, "nspawn-notify");
3307
3308 return 0;
3309 }
3310
3311 static int merge_settings(Settings *settings, const char *path) {
3312 int rl;
3313
3314 assert(settings);
3315 assert(path);
3316
3317 /* Copy over bits from the settings, unless they have been explicitly masked by command line switches. Note
3318 * that this steals the fields of the Settings* structure, and hence modifies it. */
3319
3320 if ((arg_settings_mask & SETTING_START_MODE) == 0 &&
3321 settings->start_mode >= 0) {
3322 arg_start_mode = settings->start_mode;
3323 strv_free_and_replace(arg_parameters, settings->parameters);
3324 }
3325
3326 if ((arg_settings_mask & SETTING_EPHEMERAL) == 0)
3327 arg_ephemeral = settings->ephemeral;
3328
3329 if ((arg_settings_mask & SETTING_PIVOT_ROOT) == 0 &&
3330 settings->pivot_root_new) {
3331 free_and_replace(arg_pivot_root_new, settings->pivot_root_new);
3332 free_and_replace(arg_pivot_root_old, settings->pivot_root_old);
3333 }
3334
3335 if ((arg_settings_mask & SETTING_WORKING_DIRECTORY) == 0 &&
3336 settings->working_directory)
3337 free_and_replace(arg_chdir, settings->working_directory);
3338
3339 if ((arg_settings_mask & SETTING_ENVIRONMENT) == 0 &&
3340 settings->environment)
3341 strv_free_and_replace(arg_setenv, settings->environment);
3342
3343 if ((arg_settings_mask & SETTING_USER) == 0 &&
3344 settings->user)
3345 free_and_replace(arg_user, settings->user);
3346
3347 if ((arg_settings_mask & SETTING_CAPABILITY) == 0) {
3348 uint64_t plus;
3349
3350 plus = settings->capability;
3351 if (settings_private_network(settings))
3352 plus |= (1ULL << CAP_NET_ADMIN);
3353
3354 if (!arg_settings_trusted && plus != 0) {
3355 if (settings->capability != 0)
3356 log_warning("Ignoring Capability= setting, file %s is not trusted.", path);
3357 } else
3358 arg_caps_retain |= plus;
3359
3360 arg_caps_retain &= ~settings->drop_capability;
3361 }
3362
3363 if ((arg_settings_mask & SETTING_KILL_SIGNAL) == 0 &&
3364 settings->kill_signal > 0)
3365 arg_kill_signal = settings->kill_signal;
3366
3367 if ((arg_settings_mask & SETTING_PERSONALITY) == 0 &&
3368 settings->personality != PERSONALITY_INVALID)
3369 arg_personality = settings->personality;
3370
3371 if ((arg_settings_mask & SETTING_MACHINE_ID) == 0 &&
3372 !sd_id128_is_null(settings->machine_id)) {
3373
3374 if (!arg_settings_trusted)
3375 log_warning("Ignoring MachineID= setting, file %s is not trusted.", path);
3376 else
3377 arg_uuid = settings->machine_id;
3378 }
3379
3380 if ((arg_settings_mask & SETTING_READ_ONLY) == 0 &&
3381 settings->read_only >= 0)
3382 arg_read_only = settings->read_only;
3383
3384 if ((arg_settings_mask & SETTING_VOLATILE_MODE) == 0 &&
3385 settings->volatile_mode != _VOLATILE_MODE_INVALID)
3386 arg_volatile_mode = settings->volatile_mode;
3387
3388 if ((arg_settings_mask & SETTING_CUSTOM_MOUNTS) == 0 &&
3389 settings->n_custom_mounts > 0) {
3390
3391 if (!arg_settings_trusted)
3392 log_warning("Ignoring TemporaryFileSystem=, Bind= and BindReadOnly= settings, file %s is not trusted.", path);
3393 else {
3394 custom_mount_free_all(arg_custom_mounts, arg_n_custom_mounts);
3395 arg_custom_mounts = TAKE_PTR(settings->custom_mounts);
3396 arg_n_custom_mounts = settings->n_custom_mounts;
3397 settings->n_custom_mounts = 0;
3398 }
3399 }
3400
3401 if ((arg_settings_mask & SETTING_NETWORK) == 0 &&
3402 (settings->private_network >= 0 ||
3403 settings->network_veth >= 0 ||
3404 settings->network_bridge ||
3405 settings->network_zone ||
3406 settings->network_interfaces ||
3407 settings->network_macvlan ||
3408 settings->network_ipvlan ||
3409 settings->network_veth_extra)) {
3410
3411 if (!arg_settings_trusted)
3412 log_warning("Ignoring network settings, file %s is not trusted.", path);
3413 else {
3414 arg_network_veth = settings_network_veth(settings);
3415 arg_private_network = settings_private_network(settings);
3416
3417 strv_free_and_replace(arg_network_interfaces, settings->network_interfaces);
3418 strv_free_and_replace(arg_network_macvlan, settings->network_macvlan);
3419 strv_free_and_replace(arg_network_ipvlan, settings->network_ipvlan);
3420 strv_free_and_replace(arg_network_veth_extra, settings->network_veth_extra);
3421
3422 free_and_replace(arg_network_bridge, settings->network_bridge);
3423 free_and_replace(arg_network_zone, settings->network_zone);
3424 }
3425 }
3426
3427 if ((arg_settings_mask & SETTING_EXPOSE_PORTS) == 0 &&
3428 settings->expose_ports) {
3429
3430 if (!arg_settings_trusted)
3431 log_warning("Ignoring Port= setting, file %s is not trusted.", path);
3432 else {
3433 expose_port_free_all(arg_expose_ports);
3434 arg_expose_ports = TAKE_PTR(settings->expose_ports);
3435 }
3436 }
3437
3438 if ((arg_settings_mask & SETTING_USERNS) == 0 &&
3439 settings->userns_mode != _USER_NAMESPACE_MODE_INVALID) {
3440
3441 if (!arg_settings_trusted)
3442 log_warning("Ignoring PrivateUsers= and PrivateUsersChown= settings, file %s is not trusted.", path);
3443 else {
3444 arg_userns_mode = settings->userns_mode;
3445 arg_uid_shift = settings->uid_shift;
3446 arg_uid_range = settings->uid_range;
3447 arg_userns_chown = settings->userns_chown;
3448 }
3449 }
3450
3451 if ((arg_settings_mask & SETTING_NOTIFY_READY) == 0)
3452 arg_notify_ready = settings->notify_ready;
3453
3454 if ((arg_settings_mask & SETTING_SYSCALL_FILTER) == 0) {
3455
3456 if (!arg_settings_trusted && !strv_isempty(arg_syscall_whitelist))
3457 log_warning("Ignoring SystemCallFilter= settings, file %s is not trusted.", path);
3458 else {
3459 strv_free_and_replace(arg_syscall_whitelist, settings->syscall_whitelist);
3460 strv_free_and_replace(arg_syscall_blacklist, settings->syscall_blacklist);
3461 }
3462 }
3463
3464 for (rl = 0; rl < _RLIMIT_MAX; rl ++) {
3465 if ((arg_settings_mask & (SETTING_RLIMIT_FIRST << rl)))
3466 continue;
3467
3468 if (!settings->rlimit[rl])
3469 continue;
3470
3471 if (!arg_settings_trusted) {
3472 log_warning("Ignoring Limit%s= setting, file '%s' is not trusted.", rlimit_to_string(rl), path);
3473 continue;
3474 }
3475
3476 free_and_replace(arg_rlimit[rl], settings->rlimit[rl]);
3477 }
3478
3479 if ((arg_settings_mask & SETTING_HOSTNAME) == 0 &&
3480 settings->hostname)
3481 free_and_replace(arg_hostname, settings->hostname);
3482
3483 if ((arg_settings_mask & SETTING_NO_NEW_PRIVILEGES) == 0 &&
3484 settings->no_new_privileges >= 0)
3485 arg_no_new_privileges = settings->no_new_privileges;
3486
3487 if ((arg_settings_mask & SETTING_OOM_SCORE_ADJUST) == 0 &&
3488 settings->oom_score_adjust_set) {
3489
3490 if (!arg_settings_trusted)
3491 log_warning("Ignoring OOMScoreAdjust= setting, file '%s' is not trusted.", path);
3492 else {
3493 arg_oom_score_adjust = settings->oom_score_adjust;
3494 arg_oom_score_adjust_set = true;
3495 }
3496 }
3497
3498 if ((arg_settings_mask & SETTING_CPU_AFFINITY) == 0 &&
3499 settings->cpuset) {
3500
3501 if (!arg_settings_trusted)
3502 log_warning("Ignoring CPUAffinity= setting, file '%s' is not trusted.", path);
3503 else {
3504 if (arg_cpuset)
3505 CPU_FREE(arg_cpuset);
3506 arg_cpuset = TAKE_PTR(settings->cpuset);
3507 arg_cpuset_ncpus = settings->cpuset_ncpus;
3508 }
3509 }
3510
3511 if ((arg_settings_mask & SETTING_RESOLV_CONF) == 0 &&
3512 settings->resolv_conf != _RESOLV_CONF_MODE_INVALID)
3513 arg_resolv_conf = settings->resolv_conf;
3514
3515 if ((arg_settings_mask & SETTING_LINK_JOURNAL) == 0 &&
3516 settings->link_journal != _LINK_JOURNAL_INVALID) {
3517
3518 if (!arg_settings_trusted)
3519 log_warning("Ignoring journal link setting, file '%s' is not trusted.", path);
3520 else {
3521 arg_link_journal = settings->link_journal;
3522 arg_link_journal_try = settings->link_journal_try;
3523 }
3524 }
3525
3526 if ((arg_settings_mask & SETTING_TIMEZONE) == 0 &&
3527 settings->timezone != _TIMEZONE_MODE_INVALID)
3528 arg_timezone = settings->timezone;
3529
3530 return 0;
3531 }
3532
3533 static int load_settings(void) {
3534 _cleanup_(settings_freep) Settings *settings = NULL;
3535 _cleanup_fclose_ FILE *f = NULL;
3536 _cleanup_free_ char *p = NULL;
3537 const char *fn, *i;
3538 int r;
3539
3540 /* If all settings are masked, there's no point in looking for
3541 * the settings file */
3542 if ((arg_settings_mask & _SETTINGS_MASK_ALL) == _SETTINGS_MASK_ALL)
3543 return 0;
3544
3545 fn = strjoina(arg_machine, ".nspawn");
3546
3547 /* We first look in the admin's directories in /etc and /run */
3548 FOREACH_STRING(i, "/etc/systemd/nspawn", "/run/systemd/nspawn") {
3549 _cleanup_free_ char *j = NULL;
3550
3551 j = strjoin(i, "/", fn);
3552 if (!j)
3553 return log_oom();
3554
3555 f = fopen(j, "re");
3556 if (f) {
3557 p = TAKE_PTR(j);
3558
3559 /* By default, we trust configuration from /etc and /run */
3560 if (arg_settings_trusted < 0)
3561 arg_settings_trusted = true;
3562
3563 break;
3564 }
3565
3566 if (errno != ENOENT)
3567 return log_error_errno(errno, "Failed to open %s: %m", j);
3568 }
3569
3570 if (!f) {
3571 /* After that, let's look for a file next to the
3572 * actual image we shall boot. */
3573
3574 if (arg_image) {
3575 p = file_in_same_dir(arg_image, fn);
3576 if (!p)
3577 return log_oom();
3578 } else if (arg_directory) {
3579 p = file_in_same_dir(arg_directory, fn);
3580 if (!p)
3581 return log_oom();
3582 }
3583
3584 if (p) {
3585 f = fopen(p, "re");
3586 if (!f && errno != ENOENT)
3587 return log_error_errno(errno, "Failed to open %s: %m", p);
3588
3589 /* By default, we do not trust configuration from /var/lib/machines */
3590 if (arg_settings_trusted < 0)
3591 arg_settings_trusted = false;
3592 }
3593 }
3594
3595 if (!f)
3596 return 0;
3597
3598 log_debug("Settings are trusted: %s", yes_no(arg_settings_trusted));
3599
3600 r = settings_load(f, p, &settings);
3601 if (r < 0)
3602 return r;
3603
3604 return merge_settings(settings, p);
3605 }
3606
3607 static int run(int master,
3608 const char* console,
3609 DissectedImage *dissected_image,
3610 bool interactive,
3611 bool secondary,
3612 FDSet *fds,
3613 char veth_name[IFNAMSIZ], bool *veth_created,
3614 union in_addr_union *exposed,
3615 pid_t *pid, int *ret) {
3616
3617 static const struct sigaction sa = {
3618 .sa_handler = nop_signal_handler,
3619 .sa_flags = SA_NOCLDSTOP|SA_RESTART,
3620 };
3621
3622 _cleanup_(release_lock_file) LockFile uid_shift_lock = LOCK_FILE_INIT;
3623 _cleanup_close_ int etc_passwd_lock = -1;
3624 _cleanup_close_pair_ int
3625 kmsg_socket_pair[2] = { -1, -1 },
3626 rtnl_socket_pair[2] = { -1, -1 },
3627 pid_socket_pair[2] = { -1, -1 },
3628 uuid_socket_pair[2] = { -1, -1 },
3629 notify_socket_pair[2] = { -1, -1 },
3630 uid_shift_socket_pair[2] = { -1, -1 },
3631 unified_cgroup_hierarchy_socket_pair[2] = { -1, -1};
3632
3633 _cleanup_close_ int notify_socket= -1;
3634 _cleanup_(barrier_destroy) Barrier barrier = BARRIER_NULL;
3635 _cleanup_(sd_event_source_unrefp) sd_event_source *notify_event_source = NULL;
3636 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
3637 _cleanup_(pty_forward_freep) PTYForward *forward = NULL;
3638 _cleanup_(sd_netlink_unrefp) sd_netlink *rtnl = NULL;
3639 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
3640 ContainerStatus container_status = 0;
3641 char last_char = 0;
3642 int ifi = 0, r;
3643 ssize_t l;
3644 sigset_t mask_chld;
3645 _cleanup_close_ int netns_fd = -1;
3646
3647 assert_se(sigemptyset(&mask_chld) == 0);
3648 assert_se(sigaddset(&mask_chld, SIGCHLD) == 0);
3649
3650 if (arg_userns_mode == USER_NAMESPACE_PICK) {
3651 /* When we shall pick the UID/GID range, let's first lock /etc/passwd, so that we can safely
3652 * check with getpwuid() if the specific user already exists. Note that /etc might be
3653 * read-only, in which case this will fail with EROFS. But that's really OK, as in that case we
3654 * can be reasonably sure that no users are going to be added. Note that getpwuid() checks are
3655 * really just an extra safety net. We kinda assume that the UID range we allocate from is
3656 * really ours. */
3657
3658 etc_passwd_lock = take_etc_passwd_lock(NULL);
3659 if (etc_passwd_lock < 0 && etc_passwd_lock != -EROFS)
3660 return log_error_errno(etc_passwd_lock, "Failed to take /etc/passwd lock: %m");
3661 }
3662
3663 r = barrier_create(&barrier);
3664 if (r < 0)
3665 return log_error_errno(r, "Cannot initialize IPC barrier: %m");
3666
3667 if (socketpair(AF_UNIX, SOCK_SEQPACKET|SOCK_CLOEXEC, 0, kmsg_socket_pair) < 0)
3668 return log_error_errno(errno, "Failed to create kmsg socket pair: %m");
3669
3670 if (socketpair(AF_UNIX, SOCK_SEQPACKET|SOCK_CLOEXEC, 0, rtnl_socket_pair) < 0)
3671 return log_error_errno(errno, "Failed to create rtnl socket pair: %m");
3672
3673 if (socketpair(AF_UNIX, SOCK_SEQPACKET|SOCK_CLOEXEC, 0, pid_socket_pair) < 0)
3674 return log_error_errno(errno, "Failed to create pid socket pair: %m");
3675
3676 if (socketpair(AF_UNIX, SOCK_SEQPACKET|SOCK_CLOEXEC, 0, uuid_socket_pair) < 0)
3677 return log_error_errno(errno, "Failed to create id socket pair: %m");
3678
3679 if (socketpair(AF_UNIX, SOCK_SEQPACKET|SOCK_CLOEXEC, 0, notify_socket_pair) < 0)
3680 return log_error_errno(errno, "Failed to create notify socket pair: %m");
3681
3682 if (arg_userns_mode != USER_NAMESPACE_NO)
3683 if (socketpair(AF_UNIX, SOCK_SEQPACKET|SOCK_CLOEXEC, 0, uid_shift_socket_pair) < 0)
3684 return log_error_errno(errno, "Failed to create uid shift socket pair: %m");
3685
3686 if (arg_unified_cgroup_hierarchy == CGROUP_UNIFIED_UNKNOWN)
3687 if (socketpair(AF_UNIX, SOCK_SEQPACKET|SOCK_CLOEXEC, 0, unified_cgroup_hierarchy_socket_pair) < 0)
3688 return log_error_errno(errno, "Failed to create unified cgroup socket pair: %m");
3689
3690 /* Child can be killed before execv(), so handle SIGCHLD in order to interrupt
3691 * parent's blocking calls and give it a chance to call wait() and terminate. */
3692 r = sigprocmask(SIG_UNBLOCK, &mask_chld, NULL);
3693 if (r < 0)
3694 return log_error_errno(errno, "Failed to change the signal mask: %m");
3695
3696 r = sigaction(SIGCHLD, &sa, NULL);
3697 if (r < 0)
3698 return log_error_errno(errno, "Failed to install SIGCHLD handler: %m");
3699
3700 if (arg_network_namespace_path) {
3701 netns_fd = open(arg_network_namespace_path, O_RDONLY|O_NOCTTY|O_CLOEXEC);
3702 if (netns_fd < 0)
3703 return log_error_errno(errno, "Cannot open file %s: %m", arg_network_namespace_path);
3704
3705 r = fd_is_network_ns(netns_fd);
3706 if (r == -EUCLEAN)
3707 log_debug_errno(r, "Cannot determine if passed network namespace path '%s' really refers to a network namespace, assuming it does.", arg_network_namespace_path);
3708 else if (r < 0)
3709 return log_error_errno(r, "Failed to check %s fs type: %m", arg_network_namespace_path);
3710 else if (r == 0) {
3711 log_error("Path %s doesn't refer to a network namespace, refusing.", arg_network_namespace_path);
3712 return -EINVAL;
3713 }
3714 }
3715
3716 *pid = raw_clone(SIGCHLD|CLONE_NEWNS);
3717 if (*pid < 0)
3718 return log_error_errno(errno, "clone() failed%s: %m",
3719 errno == EINVAL ?
3720 ", do you have namespace support enabled in your kernel? (You need UTS, IPC, PID and NET namespacing built in)" : "");
3721
3722 if (*pid == 0) {
3723 /* The outer child only has a file system namespace. */
3724 barrier_set_role(&barrier, BARRIER_CHILD);
3725
3726 master = safe_close(master);
3727
3728 kmsg_socket_pair[0] = safe_close(kmsg_socket_pair[0]);
3729 rtnl_socket_pair[0] = safe_close(rtnl_socket_pair[0]);
3730 pid_socket_pair[0] = safe_close(pid_socket_pair[0]);
3731 uuid_socket_pair[0] = safe_close(uuid_socket_pair[0]);
3732 notify_socket_pair[0] = safe_close(notify_socket_pair[0]);
3733 uid_shift_socket_pair[0] = safe_close(uid_shift_socket_pair[0]);
3734 unified_cgroup_hierarchy_socket_pair[0] = safe_close(unified_cgroup_hierarchy_socket_pair[0]);
3735
3736 (void) reset_all_signal_handlers();
3737 (void) reset_signal_mask();
3738
3739 r = outer_child(&barrier,
3740 arg_directory,
3741 console,
3742 dissected_image,
3743 interactive,
3744 secondary,
3745 pid_socket_pair[1],
3746 uuid_socket_pair[1],
3747 notify_socket_pair[1],
3748 kmsg_socket_pair[1],
3749 rtnl_socket_pair[1],
3750 uid_shift_socket_pair[1],
3751 unified_cgroup_hierarchy_socket_pair[1],
3752 fds,
3753 netns_fd);
3754 if (r < 0)
3755 _exit(EXIT_FAILURE);
3756
3757 _exit(EXIT_SUCCESS);
3758 }
3759
3760 barrier_set_role(&barrier, BARRIER_PARENT);
3761
3762 fds = fdset_free(fds);
3763
3764 kmsg_socket_pair[1] = safe_close(kmsg_socket_pair[1]);
3765 rtnl_socket_pair[1] = safe_close(rtnl_socket_pair[1]);
3766 pid_socket_pair[1] = safe_close(pid_socket_pair[1]);
3767 uuid_socket_pair[1] = safe_close(uuid_socket_pair[1]);
3768 notify_socket_pair[1] = safe_close(notify_socket_pair[1]);
3769 uid_shift_socket_pair[1] = safe_close(uid_shift_socket_pair[1]);
3770 unified_cgroup_hierarchy_socket_pair[1] = safe_close(unified_cgroup_hierarchy_socket_pair[1]);
3771
3772 if (arg_userns_mode != USER_NAMESPACE_NO) {
3773 /* The child just let us know the UID shift it might have read from the image. */
3774 l = recv(uid_shift_socket_pair[0], &arg_uid_shift, sizeof arg_uid_shift, 0);
3775 if (l < 0)
3776 return log_error_errno(errno, "Failed to read UID shift: %m");
3777 if (l != sizeof arg_uid_shift) {
3778 log_error("Short read while reading UID shift.");
3779 return -EIO;
3780 }
3781
3782 if (arg_userns_mode == USER_NAMESPACE_PICK) {
3783 /* If we are supposed to pick the UID shift, let's try to use the shift read from the
3784 * image, but if that's already in use, pick a new one, and report back to the child,
3785 * which one we now picked. */
3786
3787 r = uid_shift_pick(&arg_uid_shift, &uid_shift_lock);
3788 if (r < 0)
3789 return log_error_errno(r, "Failed to pick suitable UID/GID range: %m");
3790
3791 l = send(uid_shift_socket_pair[0], &arg_uid_shift, sizeof arg_uid_shift, MSG_NOSIGNAL);
3792 if (l < 0)
3793 return log_error_errno(errno, "Failed to send UID shift: %m");
3794 if (l != sizeof arg_uid_shift) {
3795 log_error("Short write while writing UID shift.");
3796 return -EIO;
3797 }
3798 }
3799 }
3800
3801 if (arg_unified_cgroup_hierarchy == CGROUP_UNIFIED_UNKNOWN) {
3802 /* The child let us know the support cgroup mode it might have read from the image. */
3803 l = recv(unified_cgroup_hierarchy_socket_pair[0], &arg_unified_cgroup_hierarchy, sizeof(arg_unified_cgroup_hierarchy), 0);
3804 if (l < 0)
3805 return log_error_errno(errno, "Failed to read cgroup mode: %m");
3806 if (l != sizeof(arg_unified_cgroup_hierarchy)) {
3807 log_error("Short read while reading cgroup mode (%zu bytes).%s",
3808 l, l == 0 ? " The child is most likely dead." : "");
3809 return -EIO;
3810 }
3811 }
3812
3813 /* Wait for the outer child. */
3814 r = wait_for_terminate_and_check("(sd-namespace)", *pid, WAIT_LOG_ABNORMAL);
3815 if (r < 0)
3816 return r;
3817 if (r != EXIT_SUCCESS)
3818 return -EIO;
3819
3820 /* And now retrieve the PID of the inner child. */
3821 l = recv(pid_socket_pair[0], pid, sizeof *pid, 0);
3822 if (l < 0)
3823 return log_error_errno(errno, "Failed to read inner child PID: %m");
3824 if (l != sizeof *pid) {
3825 log_error("Short read while reading inner child PID.");
3826 return -EIO;
3827 }
3828
3829 /* We also retrieve container UUID in case it was generated by outer child */
3830 l = recv(uuid_socket_pair[0], &arg_uuid, sizeof arg_uuid, 0);
3831 if (l < 0)
3832 return log_error_errno(errno, "Failed to read container machine ID: %m");
3833 if (l != sizeof(arg_uuid)) {
3834 log_error("Short read while reading container machined ID.");
3835 return -EIO;
3836 }
3837
3838 /* We also retrieve the socket used for notifications generated by outer child */
3839 notify_socket = receive_one_fd(notify_socket_pair[0], 0);
3840 if (notify_socket < 0)
3841 return log_error_errno(notify_socket,
3842 "Failed to receive notification socket from the outer child: %m");
3843
3844 log_debug("Init process invoked as PID "PID_FMT, *pid);
3845
3846 if (arg_userns_mode != USER_NAMESPACE_NO) {
3847 if (!barrier_place_and_sync(&barrier)) { /* #1 */
3848 log_error("Child died too early.");
3849 return -ESRCH;
3850 }
3851
3852 r = setup_uid_map(*pid);
3853 if (r < 0)
3854 return r;
3855
3856 (void) barrier_place(&barrier); /* #2 */
3857 }
3858
3859 if (arg_private_network) {
3860 if (!arg_network_namespace_path) {
3861 /* Wait until the child has unshared its network namespace. */
3862 if (!barrier_place_and_sync(&barrier)) { /* #3 */
3863 log_error("Child died too early");
3864 return -ESRCH;
3865 }
3866 }
3867
3868 r = move_network_interfaces(*pid, arg_network_interfaces);
3869 if (r < 0)
3870 return r;
3871
3872 if (arg_network_veth) {
3873 r = setup_veth(arg_machine, *pid, veth_name,
3874 arg_network_bridge || arg_network_zone);
3875 if (r < 0)
3876 return r;
3877 else if (r > 0)
3878 ifi = r;
3879
3880 if (arg_network_bridge) {
3881 /* Add the interface to a bridge */
3882 r = setup_bridge(veth_name, arg_network_bridge, false);
3883 if (r < 0)
3884 return r;
3885 if (r > 0)
3886 ifi = r;
3887 } else if (arg_network_zone) {
3888 /* Add the interface to a bridge, possibly creating it */
3889 r = setup_bridge(veth_name, arg_network_zone, true);
3890 if (r < 0)
3891 return r;
3892 if (r > 0)
3893 ifi = r;
3894 }
3895 }
3896
3897 r = setup_veth_extra(arg_machine, *pid, arg_network_veth_extra);
3898 if (r < 0)
3899 return r;
3900
3901 /* We created the primary and extra veth links now; let's remember this, so that we know to
3902 remove them later on. Note that we don't bother with removing veth links that were created
3903 here when their setup failed half-way, because in that case the kernel should be able to
3904 remove them on its own, since they cannot be referenced by anything yet. */
3905 *veth_created = true;
3906
3907 r = setup_macvlan(arg_machine, *pid, arg_network_macvlan);
3908 if (r < 0)
3909 return r;
3910
3911 r = setup_ipvlan(arg_machine, *pid, arg_network_ipvlan);
3912 if (r < 0)
3913 return r;
3914 }
3915
3916 if (arg_register || !arg_keep_unit) {
3917 r = sd_bus_default_system(&bus);
3918 if (r < 0)
3919 return log_error_errno(r, "Failed to open system bus: %m");
3920
3921 r = sd_bus_set_close_on_exit(bus, false);
3922 if (r < 0)
3923 return log_error_errno(r, "Failed to disable close-on-exit behaviour: %m");
3924 }
3925
3926 if (!arg_keep_unit) {
3927 /* When a new scope is created for this container, then we'll be registered as its controller, in which
3928 * case PID 1 will send us a friendly RequestStop signal, when it is asked to terminate the
3929 * scope. Let's hook into that, and cleanly shut down the container, and print a friendly message. */
3930
3931 r = sd_bus_match_signal_async(
3932 bus,
3933 NULL,
3934 "org.freedesktop.systemd1",
3935 NULL,
3936 "org.freedesktop.systemd1.Scope",
3937 "RequestStop",
3938 on_request_stop, NULL, PID_TO_PTR(*pid));
3939 if (r < 0)
3940 return log_error_errno(r, "Failed to request RequestStop match: %m");
3941 }
3942
3943 if (arg_register) {
3944 r = register_machine(
3945 bus,
3946 arg_machine,
3947 *pid,
3948 arg_directory,
3949 arg_uuid,
3950 ifi,
3951 arg_slice,
3952 arg_custom_mounts, arg_n_custom_mounts,
3953 arg_kill_signal,
3954 arg_property,
3955 arg_keep_unit,
3956 arg_container_service_name);
3957 if (r < 0)
3958 return r;
3959
3960 } else if (!arg_keep_unit) {
3961 r = allocate_scope(
3962 bus,
3963 arg_machine,
3964 *pid,
3965 arg_slice,
3966 arg_custom_mounts, arg_n_custom_mounts,
3967 arg_kill_signal,
3968 arg_property);
3969 if (r < 0)
3970 return r;
3971
3972 } else if (arg_slice || arg_property)
3973 log_notice("Machine and scope registration turned off, --slice= and --property= settings will have no effect.");
3974
3975 r = sync_cgroup(*pid, arg_unified_cgroup_hierarchy, arg_uid_shift);
3976 if (r < 0)
3977 return r;
3978
3979 r = create_subcgroup(*pid, arg_keep_unit, arg_unified_cgroup_hierarchy);
3980 if (r < 0)
3981 return r;
3982
3983 r = chown_cgroup(*pid, arg_unified_cgroup_hierarchy, arg_uid_shift);
3984 if (r < 0)
3985 return r;
3986
3987 /* Notify the child that the parent is ready with all
3988 * its setup (including cgroup-ification), and that
3989 * the child can now hand over control to the code to
3990 * run inside the container. */
3991 (void) barrier_place(&barrier); /* #4 */
3992
3993 /* Block SIGCHLD here, before notifying child.
3994 * process_pty() will handle it with the other signals. */
3995 assert_se(sigprocmask(SIG_BLOCK, &mask_chld, NULL) >= 0);
3996
3997 /* Reset signal to default */
3998 r = default_signals(SIGCHLD, -1);
3999 if (r < 0)
4000 return log_error_errno(r, "Failed to reset SIGCHLD: %m");
4001
4002 r = sd_event_new(&event);
4003 if (r < 0)
4004 return log_error_errno(r, "Failed to get default event source: %m");
4005
4006 (void) sd_event_set_watchdog(event, true);
4007
4008 if (bus) {
4009 r = sd_bus_attach_event(bus, event, 0);
4010 if (r < 0)
4011 return log_error_errno(r, "Failed to attach bus to event loop: %m");
4012 }
4013
4014 r = setup_sd_notify_parent(event, notify_socket, PID_TO_PTR(*pid), &notify_event_source);
4015 if (r < 0)
4016 return r;
4017
4018 /* Let the child know that we are ready and wait that the child is completely ready now. */
4019 if (!barrier_place_and_sync(&barrier)) { /* #5 */
4020 log_error("Child died too early.");
4021 return -ESRCH;
4022 }
4023
4024 /* At this point we have made use of the UID we picked, and thus nss-mymachines
4025 * will make them appear in getpwuid(), thus we can release the /etc/passwd lock. */
4026 etc_passwd_lock = safe_close(etc_passwd_lock);
4027
4028 sd_notifyf(false,
4029 "STATUS=Container running.\n"
4030 "X_NSPAWN_LEADER_PID=" PID_FMT, *pid);
4031 if (!arg_notify_ready)
4032 (void) sd_notify(false, "READY=1\n");
4033
4034 if (arg_kill_signal > 0) {
4035 /* Try to kill the init system on SIGINT or SIGTERM */
4036 (void) sd_event_add_signal(event, NULL, SIGINT, on_orderly_shutdown, PID_TO_PTR(*pid));
4037 (void) sd_event_add_signal(event, NULL, SIGTERM, on_orderly_shutdown, PID_TO_PTR(*pid));
4038 } else {
4039 /* Immediately exit */
4040 (void) sd_event_add_signal(event, NULL, SIGINT, NULL, NULL);
4041 (void) sd_event_add_signal(event, NULL, SIGTERM, NULL, NULL);
4042 }
4043
4044 /* Exit when the child exits */
4045 (void) sd_event_add_signal(event, NULL, SIGCHLD, on_sigchld, PID_TO_PTR(*pid));
4046
4047 if (arg_expose_ports) {
4048 r = expose_port_watch_rtnl(event, rtnl_socket_pair[0], on_address_change, exposed, &rtnl);
4049 if (r < 0)
4050 return r;
4051
4052 (void) expose_port_execute(rtnl, arg_expose_ports, exposed);
4053 }
4054
4055 rtnl_socket_pair[0] = safe_close(rtnl_socket_pair[0]);
4056
4057 r = pty_forward_new(event, master,
4058 PTY_FORWARD_IGNORE_VHANGUP | (interactive ? 0 : PTY_FORWARD_READ_ONLY),
4059 &forward);
4060 if (r < 0)
4061 return log_error_errno(r, "Failed to create PTY forwarder: %m");
4062
4063 r = sd_event_loop(event);
4064 if (r < 0)
4065 return log_error_errno(r, "Failed to run event loop: %m");
4066
4067 pty_forward_get_last_char(forward, &last_char);
4068
4069 forward = pty_forward_free(forward);
4070
4071 if (!arg_quiet && last_char != '\n')
4072 putc('\n', stdout);
4073
4074 /* Kill if it is not dead yet anyway */
4075 if (bus) {
4076 if (arg_register)
4077 terminate_machine(bus, arg_machine);
4078 else if (!arg_keep_unit)
4079 terminate_scope(bus, arg_machine);
4080 }
4081
4082 /* Normally redundant, but better safe than sorry */
4083 (void) kill(*pid, SIGKILL);
4084
4085 r = wait_for_container(*pid, &container_status);
4086 *pid = 0;
4087
4088 if (r < 0)
4089 /* We failed to wait for the container, or the container exited abnormally. */
4090 return r;
4091 if (r > 0 || container_status == CONTAINER_TERMINATED) {
4092 /* r > 0 → The container exited with a non-zero status.
4093 * As a special case, we need to replace 133 with a different value,
4094 * because 133 is special-cased in the service file to reboot the container.
4095 * otherwise → The container exited with zero status and a reboot was not requested.
4096 */
4097 if (r == EXIT_FORCE_RESTART)
4098 r = EXIT_FAILURE; /* replace 133 with the general failure code */
4099 *ret = r;
4100 return 0; /* finito */
4101 }
4102
4103 /* CONTAINER_REBOOTED, loop again */
4104
4105 if (arg_keep_unit) {
4106 /* Special handling if we are running as a service: instead of simply
4107 * restarting the machine we want to restart the entire service, so let's
4108 * inform systemd about this with the special exit code 133. The service
4109 * file uses RestartForceExitStatus=133 so that this results in a full
4110 * nspawn restart. This is necessary since we might have cgroup parameters
4111 * set we want to have flushed out. */
4112 *ret = EXIT_FORCE_RESTART;
4113 return 0; /* finito */
4114 }
4115
4116 expose_port_flush(arg_expose_ports, exposed);
4117
4118 (void) remove_veth_links(veth_name, arg_network_veth_extra);
4119 *veth_created = false;
4120 return 1; /* loop again */
4121 }
4122
4123 static int initialize_rlimits(void) {
4124 /* The default resource limits the kernel passes to PID 1, as per kernel 4.16. Let's pass our container payload
4125 * the same values as the kernel originally passed to PID 1, in order to minimize differences between host and
4126 * container execution environments. */
4127
4128 static const struct rlimit kernel_defaults[_RLIMIT_MAX] = {
4129 [RLIMIT_AS] = { RLIM_INFINITY, RLIM_INFINITY },
4130 [RLIMIT_CORE] = { 0, RLIM_INFINITY },
4131 [RLIMIT_CPU] = { RLIM_INFINITY, RLIM_INFINITY },
4132 [RLIMIT_DATA] = { RLIM_INFINITY, RLIM_INFINITY },
4133 [RLIMIT_FSIZE] = { RLIM_INFINITY, RLIM_INFINITY },
4134 [RLIMIT_LOCKS] = { RLIM_INFINITY, RLIM_INFINITY },
4135 [RLIMIT_MEMLOCK] = { 65536, 65536 },
4136 [RLIMIT_MSGQUEUE] = { 819200, 819200 },
4137 [RLIMIT_NICE] = { 0, 0 },
4138 [RLIMIT_NOFILE] = { 1024, 4096 },
4139 [RLIMIT_RSS] = { RLIM_INFINITY, RLIM_INFINITY },
4140 [RLIMIT_RTPRIO] = { 0, 0 },
4141 [RLIMIT_RTTIME] = { RLIM_INFINITY, RLIM_INFINITY },
4142 [RLIMIT_STACK] = { 8388608, RLIM_INFINITY },
4143
4144 /* The kernel scales the default for RLIMIT_NPROC and RLIMIT_SIGPENDING based on the system's amount of
4145 * RAM. To provide best compatibility we'll read these limits off PID 1 instead of hardcoding them
4146 * here. This is safe as we know that PID 1 doesn't change these two limits and thus the original
4147 * kernel's initialization should still be valid during runtime — at least if PID 1 is systemd. Note
4148 * that PID 1 changes a number of other resource limits during early initialization which is why we
4149 * don't read the other limits from PID 1 but prefer the static table above. */
4150 };
4151
4152 int rl;
4153
4154 for (rl = 0; rl < _RLIMIT_MAX; rl++) {
4155 /* Let's only fill in what the user hasn't explicitly configured anyway */
4156 if ((arg_settings_mask & (SETTING_RLIMIT_FIRST << rl)) == 0) {
4157 const struct rlimit *v;
4158 struct rlimit buffer;
4159
4160 if (IN_SET(rl, RLIMIT_NPROC, RLIMIT_SIGPENDING)) {
4161 /* For these two let's read the limits off PID 1. See above for an explanation. */
4162
4163 if (prlimit(1, rl, NULL, &buffer) < 0)
4164 return log_error_errno(errno, "Failed to read resource limit RLIMIT_%s of PID 1: %m", rlimit_to_string(rl));
4165
4166 v = &buffer;
4167 } else
4168 v = kernel_defaults + rl;
4169
4170 arg_rlimit[rl] = newdup(struct rlimit, v, 1);
4171 if (!arg_rlimit[rl])
4172 return log_oom();
4173 }
4174
4175 if (DEBUG_LOGGING) {
4176 _cleanup_free_ char *k = NULL;
4177
4178 (void) rlimit_format(arg_rlimit[rl], &k);
4179 log_debug("Setting RLIMIT_%s to %s.", rlimit_to_string(rl), k);
4180 }
4181 }
4182
4183 return 0;
4184 }
4185
4186 int main(int argc, char *argv[]) {
4187 _cleanup_free_ char *console = NULL;
4188 _cleanup_close_ int master = -1;
4189 _cleanup_fdset_free_ FDSet *fds = NULL;
4190 int r, n_fd_passed, ret = EXIT_SUCCESS;
4191 char veth_name[IFNAMSIZ] = "";
4192 bool secondary = false, remove_directory = false, remove_image = false;
4193 pid_t pid = 0;
4194 union in_addr_union exposed = {};
4195 _cleanup_(release_lock_file) LockFile tree_global_lock = LOCK_FILE_INIT, tree_local_lock = LOCK_FILE_INIT;
4196 bool interactive, veth_created = false, remove_tmprootdir = false;
4197 char tmprootdir[] = "/tmp/nspawn-root-XXXXXX";
4198 _cleanup_(loop_device_unrefp) LoopDevice *loop = NULL;
4199 _cleanup_(decrypted_image_unrefp) DecryptedImage *decrypted_image = NULL;
4200 _cleanup_(dissected_image_unrefp) DissectedImage *dissected_image = NULL;
4201
4202 log_parse_environment();
4203 log_open();
4204
4205 /* Make sure rename_process() in the stub init process can work */
4206 saved_argv = argv;
4207 saved_argc = argc;
4208
4209 r = parse_argv(argc, argv);
4210 if (r <= 0)
4211 goto finish;
4212
4213 r = must_be_root();
4214 if (r < 0)
4215 goto finish;
4216
4217 r = initialize_rlimits();
4218 if (r < 0)
4219 goto finish;
4220
4221 r = determine_names();
4222 if (r < 0)
4223 goto finish;
4224
4225 r = load_settings();
4226 if (r < 0)
4227 goto finish;
4228
4229 r = verify_arguments();
4230 if (r < 0)
4231 goto finish;
4232
4233 r = detect_unified_cgroup_hierarchy_from_environment();
4234 if (r < 0)
4235 goto finish;
4236
4237 n_fd_passed = sd_listen_fds(false);
4238 if (n_fd_passed > 0) {
4239 r = fdset_new_listen_fds(&fds, false);
4240 if (r < 0) {
4241 log_error_errno(r, "Failed to collect file descriptors: %m");
4242 goto finish;
4243 }
4244 }
4245
4246 /* The "default" umask. This is appropriate for most file and directory
4247 * operations performed by nspawn, and is the umask that will be used for
4248 * the child. Functions like copy_devnodes() change the umask temporarily. */
4249 umask(0022);
4250
4251 if (arg_directory) {
4252 assert(!arg_image);
4253
4254 if (path_equal(arg_directory, "/") && !arg_ephemeral) {
4255 log_error("Spawning container on root directory is not supported. Consider using --ephemeral.");
4256 r = -EINVAL;
4257 goto finish;
4258 }
4259
4260 if (arg_ephemeral) {
4261 _cleanup_free_ char *np = NULL;
4262
4263 r = chase_symlinks_and_update(&arg_directory, 0);
4264 if (r < 0)
4265 goto finish;
4266
4267 /* If the specified path is a mount point we
4268 * generate the new snapshot immediately
4269 * inside it under a random name. However if
4270 * the specified is not a mount point we
4271 * create the new snapshot in the parent
4272 * directory, just next to it. */
4273 r = path_is_mount_point(arg_directory, NULL, 0);
4274 if (r < 0) {
4275 log_error_errno(r, "Failed to determine whether directory %s is mount point: %m", arg_directory);
4276 goto finish;
4277 }
4278 if (r > 0)
4279 r = tempfn_random_child(arg_directory, "machine.", &np);
4280 else
4281 r = tempfn_random(arg_directory, "machine.", &np);
4282 if (r < 0) {
4283 log_error_errno(r, "Failed to generate name for directory snapshot: %m");
4284 goto finish;
4285 }
4286
4287 r = image_path_lock(np, (arg_read_only ? LOCK_SH : LOCK_EX) | LOCK_NB, &tree_global_lock, &tree_local_lock);
4288 if (r < 0) {
4289 log_error_errno(r, "Failed to lock %s: %m", np);
4290 goto finish;
4291 }
4292
4293 r = btrfs_subvol_snapshot(arg_directory, np,
4294 (arg_read_only ? BTRFS_SNAPSHOT_READ_ONLY : 0) |
4295 BTRFS_SNAPSHOT_FALLBACK_COPY |
4296 BTRFS_SNAPSHOT_FALLBACK_DIRECTORY |
4297 BTRFS_SNAPSHOT_RECURSIVE |
4298 BTRFS_SNAPSHOT_QUOTA);
4299 if (r < 0) {
4300 log_error_errno(r, "Failed to create snapshot %s from %s: %m", np, arg_directory);
4301 goto finish;
4302 }
4303
4304 free_and_replace(arg_directory, np);
4305
4306 remove_directory = true;
4307
4308 } else {
4309 r = chase_symlinks_and_update(&arg_directory, arg_template ? CHASE_NONEXISTENT : 0);
4310 if (r < 0)
4311 goto finish;
4312
4313 r = image_path_lock(arg_directory, (arg_read_only ? LOCK_SH : LOCK_EX) | LOCK_NB, &tree_global_lock, &tree_local_lock);
4314 if (r == -EBUSY) {
4315 log_error_errno(r, "Directory tree %s is currently busy.", arg_directory);
4316 goto finish;
4317 }
4318 if (r < 0) {
4319 log_error_errno(r, "Failed to lock %s: %m", arg_directory);
4320 goto finish;
4321 }
4322
4323 if (arg_template) {
4324 r = chase_symlinks_and_update(&arg_template, 0);
4325 if (r < 0)
4326 goto finish;
4327
4328 r = btrfs_subvol_snapshot(arg_template, arg_directory,
4329 (arg_read_only ? BTRFS_SNAPSHOT_READ_ONLY : 0) |
4330 BTRFS_SNAPSHOT_FALLBACK_COPY |
4331 BTRFS_SNAPSHOT_FALLBACK_DIRECTORY |
4332 BTRFS_SNAPSHOT_FALLBACK_IMMUTABLE |
4333 BTRFS_SNAPSHOT_RECURSIVE |
4334 BTRFS_SNAPSHOT_QUOTA);
4335 if (r == -EEXIST)
4336 log_full(arg_quiet ? LOG_DEBUG : LOG_INFO,
4337 "Directory %s already exists, not populating from template %s.", arg_directory, arg_template);
4338 else if (r < 0) {
4339 log_error_errno(r, "Couldn't create snapshot %s from %s: %m", arg_directory, arg_template);
4340 goto finish;
4341 } else
4342 log_full(arg_quiet ? LOG_DEBUG : LOG_INFO,
4343 "Populated %s from template %s.", arg_directory, arg_template);
4344 }
4345 }
4346
4347 if (arg_start_mode == START_BOOT) {
4348 const char *p;
4349
4350 if (arg_pivot_root_new)
4351 p = prefix_roota(arg_directory, arg_pivot_root_new);
4352 else
4353 p = arg_directory;
4354
4355 if (path_is_os_tree(p) <= 0) {
4356 log_error("Directory %s doesn't look like an OS root directory (os-release file is missing). Refusing.", p);
4357 r = -EINVAL;
4358 goto finish;
4359 }
4360 } else {
4361 const char *p, *q;
4362
4363 if (arg_pivot_root_new)
4364 p = prefix_roota(arg_directory, arg_pivot_root_new);
4365 else
4366 p = arg_directory;
4367
4368 q = strjoina(p, "/usr/");
4369
4370 if (laccess(q, F_OK) < 0) {
4371 log_error("Directory %s doesn't look like it has an OS tree. Refusing.", p);
4372 r = -EINVAL;
4373 goto finish;
4374 }
4375 }
4376
4377 } else {
4378 assert(arg_image);
4379 assert(!arg_template);
4380
4381 r = chase_symlinks_and_update(&arg_image, 0);
4382 if (r < 0)
4383 goto finish;
4384
4385 if (arg_ephemeral) {
4386 _cleanup_free_ char *np = NULL;
4387
4388 r = tempfn_random(arg_image, "machine.", &np);
4389 if (r < 0) {
4390 log_error_errno(r, "Failed to generate name for image snapshot: %m");
4391 goto finish;
4392 }
4393
4394 r = image_path_lock(np, (arg_read_only ? LOCK_SH : LOCK_EX) | LOCK_NB, &tree_global_lock, &tree_local_lock);
4395 if (r < 0) {
4396 r = log_error_errno(r, "Failed to create image lock: %m");
4397 goto finish;
4398 }
4399
4400 r = copy_file(arg_image, np, O_EXCL, arg_read_only ? 0400 : 0600, FS_NOCOW_FL, COPY_REFLINK);
4401 if (r < 0) {
4402 r = log_error_errno(r, "Failed to copy image file: %m");
4403 goto finish;
4404 }
4405
4406 free_and_replace(arg_image, np);
4407
4408 remove_image = true;
4409 } else {
4410 r = image_path_lock(arg_image, (arg_read_only ? LOCK_SH : LOCK_EX) | LOCK_NB, &tree_global_lock, &tree_local_lock);
4411 if (r == -EBUSY) {
4412 r = log_error_errno(r, "Disk image %s is currently busy.", arg_image);
4413 goto finish;
4414 }
4415 if (r < 0) {
4416 r = log_error_errno(r, "Failed to create image lock: %m");
4417 goto finish;
4418 }
4419
4420 if (!arg_root_hash) {
4421 r = root_hash_load(arg_image, &arg_root_hash, &arg_root_hash_size);
4422 if (r < 0) {
4423 log_error_errno(r, "Failed to load root hash file for %s: %m", arg_image);
4424 goto finish;
4425 }
4426 }
4427 }
4428
4429 if (!mkdtemp(tmprootdir)) {
4430 r = log_error_errno(errno, "Failed to create temporary directory: %m");
4431 goto finish;
4432 }
4433
4434 remove_tmprootdir = true;
4435
4436 arg_directory = strdup(tmprootdir);
4437 if (!arg_directory) {
4438 r = log_oom();
4439 goto finish;
4440 }
4441
4442 r = loop_device_make_by_path(arg_image, arg_read_only ? O_RDONLY : O_RDWR, &loop);
4443 if (r < 0) {
4444 log_error_errno(r, "Failed to set up loopback block device: %m");
4445 goto finish;
4446 }
4447
4448 r = dissect_image_and_warn(
4449 loop->fd,
4450 arg_image,
4451 arg_root_hash, arg_root_hash_size,
4452 DISSECT_IMAGE_REQUIRE_ROOT,
4453 &dissected_image);
4454 if (r == -ENOPKG) {
4455 /* dissected_image_and_warn() already printed a brief error message. Extend on that with more details */
4456 log_notice("Note that the disk image needs to\n"
4457 " a) either contain only a single MBR partition of type 0x83 that is marked bootable\n"
4458 " b) or contain a single GPT partition of type 0FC63DAF-8483-4772-8E79-3D69D8477DE4\n"
4459 " c) or follow http://www.freedesktop.org/wiki/Specifications/DiscoverablePartitionsSpec/\n"
4460 " d) or contain a file system without a partition table\n"
4461 "in order to be bootable with systemd-nspawn.");
4462 goto finish;
4463 }
4464 if (r < 0)
4465 goto finish;
4466
4467 if (!arg_root_hash && dissected_image->can_verity)
4468 log_notice("Note: image %s contains verity information, but no root hash specified! Proceeding without integrity checking.", arg_image);
4469
4470 r = dissected_image_decrypt_interactively(dissected_image, NULL, arg_root_hash, arg_root_hash_size, 0, &decrypted_image);
4471 if (r < 0)
4472 goto finish;
4473
4474 /* Now that we mounted the image, let's try to remove it again, if it is ephemeral */
4475 if (remove_image && unlink(arg_image) >= 0)
4476 remove_image = false;
4477 }
4478
4479 r = custom_mount_prepare_all(arg_directory, arg_custom_mounts, arg_n_custom_mounts);
4480 if (r < 0)
4481 goto finish;
4482
4483 interactive =
4484 isatty(STDIN_FILENO) > 0 &&
4485 isatty(STDOUT_FILENO) > 0;
4486
4487 master = posix_openpt(O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
4488 if (master < 0) {
4489 r = log_error_errno(errno, "Failed to acquire pseudo tty: %m");
4490 goto finish;
4491 }
4492
4493 r = ptsname_malloc(master, &console);
4494 if (r < 0) {
4495 r = log_error_errno(r, "Failed to determine tty name: %m");
4496 goto finish;
4497 }
4498
4499 if (arg_selinux_apifs_context) {
4500 r = mac_selinux_apply(console, arg_selinux_apifs_context);
4501 if (r < 0)
4502 goto finish;
4503 }
4504
4505 if (unlockpt(master) < 0) {
4506 r = log_error_errno(errno, "Failed to unlock tty: %m");
4507 goto finish;
4508 }
4509
4510 if (!arg_quiet)
4511 log_info("Spawning container %s on %s.\nPress ^] three times within 1s to kill container.",
4512 arg_machine, arg_image ?: arg_directory);
4513
4514 assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGCHLD, SIGWINCH, SIGTERM, SIGINT, -1) >= 0);
4515
4516 if (prctl(PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0) < 0) {
4517 r = log_error_errno(errno, "Failed to become subreaper: %m");
4518 goto finish;
4519 }
4520
4521 for (;;) {
4522 r = run(master,
4523 console,
4524 dissected_image,
4525 interactive, secondary,
4526 fds,
4527 veth_name, &veth_created,
4528 &exposed,
4529 &pid, &ret);
4530 if (r <= 0)
4531 break;
4532 }
4533
4534 finish:
4535 sd_notify(false,
4536 r == 0 && ret == EXIT_FORCE_RESTART ? "STOPPING=1\nSTATUS=Restarting..." :
4537 "STOPPING=1\nSTATUS=Terminating...");
4538
4539 if (pid > 0)
4540 (void) kill(pid, SIGKILL);
4541
4542 /* Try to flush whatever is still queued in the pty */
4543 if (master >= 0) {
4544 (void) copy_bytes(master, STDOUT_FILENO, (uint64_t) -1, 0);
4545 master = safe_close(master);
4546 }
4547
4548 if (pid > 0)
4549 (void) wait_for_terminate(pid, NULL);
4550
4551 pager_close();
4552
4553 if (remove_directory && arg_directory) {
4554 int k;
4555
4556 k = rm_rf(arg_directory, REMOVE_ROOT|REMOVE_PHYSICAL|REMOVE_SUBVOLUME);
4557 if (k < 0)
4558 log_warning_errno(k, "Cannot remove '%s', ignoring: %m", arg_directory);
4559 }
4560
4561 if (remove_image && arg_image) {
4562 if (unlink(arg_image) < 0)
4563 log_warning_errno(errno, "Can't remove image file '%s', ignoring: %m", arg_image);
4564 }
4565
4566 if (remove_tmprootdir) {
4567 if (rmdir(tmprootdir) < 0)
4568 log_debug_errno(errno, "Can't remove temporary root directory '%s', ignoring: %m", tmprootdir);
4569 }
4570
4571 if (arg_machine) {
4572 const char *p;
4573
4574 p = strjoina("/run/systemd/nspawn/propagate/", arg_machine);
4575 (void) rm_rf(p, REMOVE_ROOT);
4576 }
4577
4578 expose_port_flush(arg_expose_ports, &exposed);
4579
4580 if (veth_created)
4581 (void) remove_veth_links(veth_name, arg_network_veth_extra);
4582 (void) remove_bridge(arg_network_zone);
4583
4584 free(arg_directory);
4585 free(arg_template);
4586 free(arg_image);
4587 free(arg_machine);
4588 free(arg_hostname);
4589 free(arg_user);
4590 free(arg_pivot_root_new);
4591 free(arg_pivot_root_old);
4592 free(arg_chdir);
4593 strv_free(arg_setenv);
4594 free(arg_network_bridge);
4595 strv_free(arg_network_interfaces);
4596 strv_free(arg_network_macvlan);
4597 strv_free(arg_network_ipvlan);
4598 strv_free(arg_network_veth_extra);
4599 strv_free(arg_parameters);
4600 free(arg_network_zone);
4601 free(arg_network_namespace_path);
4602 strv_free(arg_property);
4603 custom_mount_free_all(arg_custom_mounts, arg_n_custom_mounts);
4604 expose_port_free_all(arg_expose_ports);
4605 free(arg_root_hash);
4606 rlimit_free_all(arg_rlimit);
4607 strv_free(arg_syscall_whitelist);
4608 strv_free(arg_syscall_blacklist);
4609 arg_cpuset = cpu_set_mfree(arg_cpuset);
4610
4611 return r < 0 ? EXIT_FAILURE : ret;
4612 }