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