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