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