1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
25 #include <sys/types.h>
26 #include <sys/syscall.h>
27 #include <sys/mount.h>
33 #include <sys/prctl.h>
36 #include <sys/signalfd.h>
40 #include <sys/socket.h>
41 #include <linux/netlink.h>
43 #include <linux/veth.h>
44 #include <sys/personality.h>
45 #include <linux/loop.h>
50 #include <selinux/selinux.h>
58 #include <blkid/blkid.h>
61 #include "sd-daemon.h"
71 #include "cgroup-util.h"
73 #include "path-util.h"
74 #include "loopback-setup.h"
75 #include "dev-setup.h"
80 #include "bus-error.h"
82 #include "bus-kernel.h"
85 #include "rtnl-util.h"
86 #include "udev-util.h"
87 #include "blkid-util.h"
89 #include "siphash24.h"
91 #include "base-filesystem.h"
93 #include "event-util.h"
94 #include "capability.h"
96 #include "btrfs-util.h"
97 #include "machine-image.h"
99 #include "in-addr-util.h"
101 #include "local-addresses.h"
104 #include "seccomp-util.h"
107 typedef struct ExposePort {
110 uint16_t container_port;
111 LIST_FIELDS(struct ExposePort, ports);
114 typedef enum ContainerStatus {
115 CONTAINER_TERMINATED,
119 typedef enum LinkJournal {
126 typedef enum Volatile {
132 static char *arg_directory = NULL;
133 static char *arg_template = NULL;
134 static char *arg_user = NULL;
135 static sd_id128_t arg_uuid = {};
136 static char *arg_machine = NULL;
137 static const char *arg_selinux_context = NULL;
138 static const char *arg_selinux_apifs_context = NULL;
139 static const char *arg_slice = NULL;
140 static bool arg_private_network = false;
141 static bool arg_read_only = false;
142 static bool arg_boot = false;
143 static bool arg_ephemeral = false;
144 static LinkJournal arg_link_journal = LINK_AUTO;
145 static bool arg_link_journal_try = false;
146 static uint64_t arg_retain =
147 (1ULL << CAP_CHOWN) |
148 (1ULL << CAP_DAC_OVERRIDE) |
149 (1ULL << CAP_DAC_READ_SEARCH) |
150 (1ULL << CAP_FOWNER) |
151 (1ULL << CAP_FSETID) |
152 (1ULL << CAP_IPC_OWNER) |
154 (1ULL << CAP_LEASE) |
155 (1ULL << CAP_LINUX_IMMUTABLE) |
156 (1ULL << CAP_NET_BIND_SERVICE) |
157 (1ULL << CAP_NET_BROADCAST) |
158 (1ULL << CAP_NET_RAW) |
159 (1ULL << CAP_SETGID) |
160 (1ULL << CAP_SETFCAP) |
161 (1ULL << CAP_SETPCAP) |
162 (1ULL << CAP_SETUID) |
163 (1ULL << CAP_SYS_ADMIN) |
164 (1ULL << CAP_SYS_CHROOT) |
165 (1ULL << CAP_SYS_NICE) |
166 (1ULL << CAP_SYS_PTRACE) |
167 (1ULL << CAP_SYS_TTY_CONFIG) |
168 (1ULL << CAP_SYS_RESOURCE) |
169 (1ULL << CAP_SYS_BOOT) |
170 (1ULL << CAP_AUDIT_WRITE) |
171 (1ULL << CAP_AUDIT_CONTROL) |
173 static char **arg_bind = NULL;
174 static char **arg_bind_ro = NULL;
175 static char **arg_tmpfs = NULL;
176 static char **arg_setenv = NULL;
177 static bool arg_quiet = false;
178 static bool arg_share_system = false;
179 static bool arg_register = true;
180 static bool arg_keep_unit = false;
181 static char **arg_network_interfaces = NULL;
182 static char **arg_network_macvlan = NULL;
183 static char **arg_network_ipvlan = NULL;
184 static bool arg_network_veth = false;
185 static const char *arg_network_bridge = NULL;
186 static unsigned long arg_personality = 0xffffffffLU;
187 static char *arg_image = NULL;
188 static Volatile arg_volatile = VOLATILE_NO;
189 static ExposePort *arg_expose_ports = NULL;
190 static char **arg_property = NULL;
191 static uid_t arg_uid_shift = UID_INVALID, arg_uid_range = 0x10000U;
192 static bool arg_userns = false;
194 static void help(void) {
195 printf("%s [OPTIONS...] [PATH] [ARGUMENTS...]\n\n"
196 "Spawn a minimal namespace container for debugging, testing and building.\n\n"
197 " -h --help Show this help\n"
198 " --version Print version string\n"
199 " -q --quiet Do not show status information\n"
200 " -D --directory=PATH Root directory for the container\n"
201 " --template=PATH Initialize root directory from template directory,\n"
203 " -x --ephemeral Run container with snapshot of root directory, and\n"
204 " remove it after exit\n"
205 " -i --image=PATH File system device or disk image for the container\n"
206 " -b --boot Boot up full system (i.e. invoke init)\n"
207 " -u --user=USER Run the command under specified user or uid\n"
208 " -M --machine=NAME Set the machine name for the container\n"
209 " --uuid=UUID Set a specific machine UUID for the container\n"
210 " -S --slice=SLICE Place the container in the specified slice\n"
211 " --property=NAME=VALUE Set scope unit property\n"
212 " --private-network Disable network in container\n"
213 " --network-interface=INTERFACE\n"
214 " Assign an existing network interface to the\n"
216 " --network-macvlan=INTERFACE\n"
217 " Create a macvlan network interface based on an\n"
218 " existing network interface to the container\n"
219 " --network-ipvlan=INTERFACE\n"
220 " Create a ipvlan network interface based on an\n"
221 " existing network interface to the container\n"
222 " -n --network-veth Add a virtual ethernet connection between host\n"
224 " --network-bridge=INTERFACE\n"
225 " Add a virtual ethernet connection between host\n"
226 " and container and add it to an existing bridge on\n"
228 " --private-users[=UIDBASE[:NUIDS]]\n"
229 " Run within user namespace\n"
230 " -p --port=[PROTOCOL:]HOSTPORT[:CONTAINERPORT]\n"
231 " Expose a container IP port on the host\n"
232 " -Z --selinux-context=SECLABEL\n"
233 " Set the SELinux security context to be used by\n"
234 " processes in the container\n"
235 " -L --selinux-apifs-context=SECLABEL\n"
236 " Set the SELinux security context to be used by\n"
237 " API/tmpfs file systems in the container\n"
238 " --capability=CAP In addition to the default, retain specified\n"
240 " --drop-capability=CAP Drop the specified capability from the default set\n"
241 " --link-journal=MODE Link up guest journal, one of no, auto, guest, host,\n"
242 " try-guest, try-host\n"
243 " -j Equivalent to --link-journal=try-guest\n"
244 " --read-only Mount the root directory read-only\n"
245 " --bind=PATH[:PATH] Bind mount a file or directory from the host into\n"
247 " --bind-ro=PATH[:PATH] Similar, but creates a read-only bind mount\n"
248 " --tmpfs=PATH:[OPTIONS] Mount an empty tmpfs to the specified directory\n"
249 " --setenv=NAME=VALUE Pass an environment variable to PID 1\n"
250 " --share-system Share system namespaces with host\n"
251 " --register=BOOLEAN Register container as machine\n"
252 " --keep-unit Do not register a scope for the machine, reuse\n"
253 " the service unit nspawn is running in\n"
254 " --volatile[=MODE] Run the system in volatile mode\n"
255 , program_invocation_short_name);
258 static int set_sanitized_path(char **b, const char *path) {
264 p = canonicalize_file_name(path);
269 p = path_make_absolute_cwd(path);
275 *b = path_kill_slashes(p);
279 static int parse_argv(int argc, char *argv[]) {
296 ARG_NETWORK_INTERFACE,
307 static const struct option options[] = {
308 { "help", no_argument, NULL, 'h' },
309 { "version", no_argument, NULL, ARG_VERSION },
310 { "directory", required_argument, NULL, 'D' },
311 { "template", required_argument, NULL, ARG_TEMPLATE },
312 { "ephemeral", no_argument, NULL, 'x' },
313 { "user", required_argument, NULL, 'u' },
314 { "private-network", no_argument, NULL, ARG_PRIVATE_NETWORK },
315 { "boot", no_argument, NULL, 'b' },
316 { "uuid", required_argument, NULL, ARG_UUID },
317 { "read-only", no_argument, NULL, ARG_READ_ONLY },
318 { "capability", required_argument, NULL, ARG_CAPABILITY },
319 { "drop-capability", required_argument, NULL, ARG_DROP_CAPABILITY },
320 { "link-journal", required_argument, NULL, ARG_LINK_JOURNAL },
321 { "bind", required_argument, NULL, ARG_BIND },
322 { "bind-ro", required_argument, NULL, ARG_BIND_RO },
323 { "tmpfs", required_argument, NULL, ARG_TMPFS },
324 { "machine", required_argument, NULL, 'M' },
325 { "slice", required_argument, NULL, 'S' },
326 { "setenv", required_argument, NULL, ARG_SETENV },
327 { "selinux-context", required_argument, NULL, 'Z' },
328 { "selinux-apifs-context", required_argument, NULL, 'L' },
329 { "quiet", no_argument, NULL, 'q' },
330 { "share-system", no_argument, NULL, ARG_SHARE_SYSTEM },
331 { "register", required_argument, NULL, ARG_REGISTER },
332 { "keep-unit", no_argument, NULL, ARG_KEEP_UNIT },
333 { "network-interface", required_argument, NULL, ARG_NETWORK_INTERFACE },
334 { "network-macvlan", required_argument, NULL, ARG_NETWORK_MACVLAN },
335 { "network-ipvlan", required_argument, NULL, ARG_NETWORK_IPVLAN },
336 { "network-veth", no_argument, NULL, 'n' },
337 { "network-bridge", required_argument, NULL, ARG_NETWORK_BRIDGE },
338 { "personality", required_argument, NULL, ARG_PERSONALITY },
339 { "image", required_argument, NULL, 'i' },
340 { "volatile", optional_argument, NULL, ARG_VOLATILE },
341 { "port", required_argument, NULL, 'p' },
342 { "property", required_argument, NULL, ARG_PROPERTY },
343 { "private-users", optional_argument, NULL, ARG_PRIVATE_USERS },
348 uint64_t plus = 0, minus = 0;
353 while ((c = getopt_long(argc, argv, "+hD:u:bL:M:jS:Z:qi:xp:n", options, NULL)) >= 0)
362 puts(PACKAGE_STRING);
363 puts(SYSTEMD_FEATURES);
367 r = set_sanitized_path(&arg_directory, optarg);
369 return log_error_errno(r, "Invalid root directory: %m");
374 r = set_sanitized_path(&arg_template, optarg);
376 return log_error_errno(r, "Invalid template directory: %m");
381 r = set_sanitized_path(&arg_image, optarg);
383 return log_error_errno(r, "Invalid image path: %m");
388 arg_ephemeral = true;
393 arg_user = strdup(optarg);
399 case ARG_NETWORK_BRIDGE:
400 arg_network_bridge = optarg;
405 arg_network_veth = true;
406 arg_private_network = true;
409 case ARG_NETWORK_INTERFACE:
410 if (strv_extend(&arg_network_interfaces, optarg) < 0)
413 arg_private_network = true;
416 case ARG_NETWORK_MACVLAN:
417 if (strv_extend(&arg_network_macvlan, optarg) < 0)
420 arg_private_network = true;
423 case ARG_NETWORK_IPVLAN:
424 if (strv_extend(&arg_network_ipvlan, optarg) < 0)
429 case ARG_PRIVATE_NETWORK:
430 arg_private_network = true;
438 r = sd_id128_from_string(optarg, &arg_uuid);
440 log_error("Invalid UUID: %s", optarg);
450 if (isempty(optarg)) {
454 if (!machine_name_is_valid(optarg)) {
455 log_error("Invalid machine name: %s", optarg);
459 r = free_and_strdup(&arg_machine, optarg);
467 arg_selinux_context = optarg;
471 arg_selinux_apifs_context = optarg;
475 arg_read_only = true;
479 case ARG_DROP_CAPABILITY: {
480 const char *state, *word;
483 FOREACH_WORD_SEPARATOR(word, length, optarg, ",", state) {
484 _cleanup_free_ char *t;
486 t = strndup(word, length);
490 if (streq(t, "all")) {
491 if (c == ARG_CAPABILITY)
492 plus = (uint64_t) -1;
494 minus = (uint64_t) -1;
498 cap = capability_from_name(t);
500 log_error("Failed to parse capability %s.", t);
504 if (c == ARG_CAPABILITY)
505 plus |= 1ULL << (uint64_t) cap;
507 minus |= 1ULL << (uint64_t) cap;
515 arg_link_journal = LINK_GUEST;
516 arg_link_journal_try = true;
519 case ARG_LINK_JOURNAL:
520 if (streq(optarg, "auto")) {
521 arg_link_journal = LINK_AUTO;
522 arg_link_journal_try = false;
523 } else if (streq(optarg, "no")) {
524 arg_link_journal = LINK_NO;
525 arg_link_journal_try = false;
526 } else if (streq(optarg, "guest")) {
527 arg_link_journal = LINK_GUEST;
528 arg_link_journal_try = false;
529 } else if (streq(optarg, "host")) {
530 arg_link_journal = LINK_HOST;
531 arg_link_journal_try = false;
532 } else if (streq(optarg, "try-guest")) {
533 arg_link_journal = LINK_GUEST;
534 arg_link_journal_try = true;
535 } else if (streq(optarg, "try-host")) {
536 arg_link_journal = LINK_HOST;
537 arg_link_journal_try = true;
539 log_error("Failed to parse link journal mode %s", optarg);
547 _cleanup_free_ char *a = NULL, *b = NULL;
551 x = c == ARG_BIND ? &arg_bind : &arg_bind_ro;
553 e = strchr(optarg, ':');
555 a = strndup(optarg, e - optarg);
565 if (!path_is_absolute(a) || !path_is_absolute(b)) {
566 log_error("Invalid bind mount specification: %s", optarg);
570 r = strv_extend(x, a);
574 r = strv_extend(x, b);
582 _cleanup_free_ char *a = NULL, *b = NULL;
585 e = strchr(optarg, ':');
587 a = strndup(optarg, e - optarg);
591 b = strdup("mode=0755");
597 if (!path_is_absolute(a)) {
598 log_error("Invalid tmpfs specification: %s", optarg);
602 r = strv_push(&arg_tmpfs, a);
608 r = strv_push(&arg_tmpfs, b);
620 if (!env_assignment_is_valid(optarg)) {
621 log_error("Environment variable assignment '%s' is not valid.", optarg);
625 n = strv_env_set(arg_setenv, optarg);
629 strv_free(arg_setenv);
638 case ARG_SHARE_SYSTEM:
639 arg_share_system = true;
643 r = parse_boolean(optarg);
645 log_error("Failed to parse --register= argument: %s", optarg);
653 arg_keep_unit = true;
656 case ARG_PERSONALITY:
658 arg_personality = personality_from_string(optarg);
659 if (arg_personality == 0xffffffffLU) {
660 log_error("Unknown or unsupported personality '%s'.", optarg);
669 arg_volatile = VOLATILE_YES;
671 r = parse_boolean(optarg);
673 if (streq(optarg, "state"))
674 arg_volatile = VOLATILE_STATE;
676 log_error("Failed to parse --volatile= argument: %s", optarg);
680 arg_volatile = r ? VOLATILE_YES : VOLATILE_NO;
686 const char *split, *e;
687 uint16_t container_port, host_port;
691 if ((e = startswith(optarg, "tcp:")))
692 protocol = IPPROTO_TCP;
693 else if ((e = startswith(optarg, "udp:")))
694 protocol = IPPROTO_UDP;
697 protocol = IPPROTO_TCP;
700 split = strchr(e, ':');
702 char v[split - e + 1];
704 memcpy(v, e, split - e);
707 r = safe_atou16(v, &host_port);
708 if (r < 0 || host_port <= 0) {
709 log_error("Failed to parse host port: %s", optarg);
713 r = safe_atou16(split + 1, &container_port);
715 r = safe_atou16(e, &container_port);
716 host_port = container_port;
719 if (r < 0 || container_port <= 0) {
720 log_error("Failed to parse host port: %s", optarg);
724 LIST_FOREACH(ports, p, arg_expose_ports) {
725 if (p->protocol == protocol && p->host_port == host_port) {
726 log_error("Duplicate port specification: %s", optarg);
731 p = new(ExposePort, 1);
735 p->protocol = protocol;
736 p->host_port = host_port;
737 p->container_port = container_port;
739 LIST_PREPEND(ports, arg_expose_ports, p);
745 if (strv_extend(&arg_property, optarg) < 0)
750 case ARG_PRIVATE_USERS:
752 _cleanup_free_ char *buffer = NULL;
753 const char *range, *shift;
755 range = strchr(optarg, ':');
757 buffer = strndup(optarg, range - optarg);
763 if (safe_atou32(range, &arg_uid_range) < 0 || arg_uid_range <= 0) {
764 log_error("Failed to parse UID range: %s", range);
770 if (parse_uid(shift, &arg_uid_shift) < 0) {
771 log_error("Failed to parse UID: %s", optarg);
783 assert_not_reached("Unhandled option");
786 if (arg_share_system)
787 arg_register = false;
789 if (arg_boot && arg_share_system) {
790 log_error("--boot and --share-system may not be combined.");
794 if (arg_keep_unit && cg_pid_get_owner_uid(0, NULL) >= 0) {
795 log_error("--keep-unit may not be used when invoked from a user session.");
799 if (arg_directory && arg_image) {
800 log_error("--directory= and --image= may not be combined.");
804 if (arg_template && arg_image) {
805 log_error("--template= and --image= may not be combined.");
809 if (arg_template && !(arg_directory || arg_machine)) {
810 log_error("--template= needs --directory= or --machine=.");
814 if (arg_ephemeral && arg_template) {
815 log_error("--ephemeral and --template= may not be combined.");
819 if (arg_ephemeral && arg_image) {
820 log_error("--ephemeral and --image= may not be combined.");
824 if (arg_ephemeral && !IN_SET(arg_link_journal, LINK_NO, LINK_AUTO)) {
825 log_error("--ephemeral and --link-journal= may not be combined.");
829 if (arg_volatile != VOLATILE_NO && arg_read_only) {
830 log_error("Cannot combine --read-only with --volatile. Note that --volatile already implies a read-only base hierarchy.");
834 if (arg_expose_ports && !arg_private_network) {
835 log_error("Cannot use --port= without private networking.");
839 arg_retain = (arg_retain | plus | (arg_private_network ? 1ULL << CAP_NET_ADMIN : 0)) & ~minus;
844 static int mount_all(const char *dest) {
846 typedef struct MountPoint {
855 static const MountPoint mount_table[] = {
856 { "proc", "/proc", "proc", NULL, MS_NOSUID|MS_NOEXEC|MS_NODEV, true },
857 { "/proc/sys", "/proc/sys", NULL, NULL, MS_BIND, true }, /* Bind mount first */
858 { NULL, "/proc/sys", NULL, NULL, MS_BIND|MS_RDONLY|MS_REMOUNT, true }, /* Then, make it r/o */
859 { "sysfs", "/sys", "sysfs", NULL, MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV, true },
860 { "tmpfs", "/dev", "tmpfs", "mode=755", MS_NOSUID|MS_STRICTATIME, true },
861 { "devpts", "/dev/pts", "devpts","newinstance,ptmxmode=0666,mode=620,gid=" STRINGIFY(TTY_GID), MS_NOSUID|MS_NOEXEC, true },
862 { "tmpfs", "/dev/shm", "tmpfs", "mode=1777", MS_NOSUID|MS_NODEV|MS_STRICTATIME, true },
863 { "tmpfs", "/run", "tmpfs", "mode=755", MS_NOSUID|MS_NODEV|MS_STRICTATIME, true },
864 { "tmpfs", "/tmp", "tmpfs", "mode=1777", MS_STRICTATIME, true },
866 { "/sys/fs/selinux", "/sys/fs/selinux", NULL, NULL, MS_BIND, false }, /* Bind mount first */
867 { NULL, "/sys/fs/selinux", NULL, NULL, MS_BIND|MS_RDONLY|MS_REMOUNT, false }, /* Then, make it r/o */
874 for (k = 0; k < ELEMENTSOF(mount_table); k++) {
875 _cleanup_free_ char *where = NULL;
877 _cleanup_free_ char *options = NULL;
882 where = strjoin(dest, "/", mount_table[k].where, NULL);
886 t = path_is_mount_point(where, true);
888 log_error_errno(t, "Failed to detect whether %s is a mount point: %m", where);
896 /* Skip this entry if it is not a remount. */
897 if (mount_table[k].what && t > 0)
900 t = mkdir_p(where, 0755);
902 if (mount_table[k].fatal) {
903 log_error_errno(t, "Failed to create directory %s: %m", where);
908 log_warning_errno(t, "Failed to create directory %s: %m", where);
914 if (arg_selinux_apifs_context &&
915 (streq_ptr(mount_table[k].what, "tmpfs") || streq_ptr(mount_table[k].what, "devpts"))) {
916 options = strjoin(mount_table[k].options, ",context=\"", arg_selinux_apifs_context, "\"", NULL);
923 o = mount_table[k].options;
925 if (arg_userns && arg_uid_shift != UID_INVALID && streq_ptr(mount_table[k].type, "tmpfs")) {
926 char *uid_options = NULL;
929 asprintf(&uid_options, "%s,uid=" UID_FMT ",gid=" UID_FMT, o, arg_uid_shift, arg_uid_shift);
931 asprintf(&uid_options, "uid=" UID_FMT ",gid=" UID_FMT, arg_uid_shift, arg_uid_shift);
936 o = options = uid_options;
939 if (mount(mount_table[k].what,
942 mount_table[k].flags,
945 if (mount_table[k].fatal) {
946 log_error_errno(errno, "mount(%s) failed: %m", where);
951 log_warning_errno(errno, "mount(%s) failed: %m", where);
958 static int mount_binds(const char *dest, char **l, bool ro) {
961 STRV_FOREACH_PAIR(x, y, l) {
962 _cleanup_free_ char *where = NULL;
963 struct stat source_st, dest_st;
966 if (stat(*x, &source_st) < 0)
967 return log_error_errno(errno, "Failed to stat %s: %m", *x);
969 where = strappend(dest, *y);
973 r = stat(where, &dest_st);
975 if (S_ISDIR(source_st.st_mode) && !S_ISDIR(dest_st.st_mode)) {
976 log_error("Cannot bind mount directory %s on file %s.", *x, where);
979 if (!S_ISDIR(source_st.st_mode) && S_ISDIR(dest_st.st_mode)) {
980 log_error("Cannot bind mount file %s on directory %s.", *x, where);
983 } else if (errno == ENOENT) {
984 r = mkdir_parents_label(where, 0755);
986 return log_error_errno(r, "Failed to bind mount %s: %m", *x);
988 log_error_errno(errno, "Failed to bind mount %s: %m", *x);
992 /* Create the mount point. Any non-directory file can be
993 * mounted on any non-directory file (regular, fifo, socket,
996 if (S_ISDIR(source_st.st_mode)) {
997 r = mkdir_label(where, 0755);
998 if (r < 0 && errno != EEXIST)
999 return log_error_errno(r, "Failed to create mount point %s: %m", where);
1003 return log_error_errno(r, "Failed to create mount point %s: %m", where);
1006 if (mount(*x, where, "bind", MS_BIND, NULL) < 0)
1007 return log_error_errno(errno, "mount(%s) failed: %m", where);
1010 r = bind_remount_recursive(where, true);
1012 return log_error_errno(r, "Read-Only bind mount failed: %m");
1019 static int mount_cgroup_hierarchy(const char *dest, const char *controller, const char *hierarchy, bool read_only) {
1023 to = strjoina(dest, "/sys/fs/cgroup/", hierarchy);
1025 r = path_is_mount_point(to, false);
1027 return log_error_errno(r, "Failed to determine if %s is mounted already: %m", to);
1033 /* The superblock mount options of the mount point need to be
1034 * identical to the hosts', and hence writable... */
1035 if (mount("cgroup", to, "cgroup", MS_NOSUID|MS_NOEXEC|MS_NODEV, controller) < 0)
1036 return log_error_errno(errno, "Failed to mount to %s: %m", to);
1038 /* ... hence let's only make the bind mount read-only, not the
1041 if (mount(NULL, to, NULL, MS_BIND|MS_REMOUNT|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_RDONLY, NULL) < 0)
1042 return log_error_errno(errno, "Failed to remount %s read-only: %m", to);
1047 static int mount_cgroup(const char *dest) {
1048 _cleanup_set_free_free_ Set *controllers = NULL;
1049 _cleanup_free_ char *own_cgroup_path = NULL;
1050 const char *cgroup_root, *systemd_root, *systemd_own;
1053 controllers = set_new(&string_hash_ops);
1057 r = cg_kernel_controllers(controllers);
1059 return log_error_errno(r, "Failed to determine cgroup controllers: %m");
1061 r = cg_pid_get_path(NULL, 0, &own_cgroup_path);
1063 return log_error_errno(r, "Failed to determine our own cgroup path: %m");
1065 cgroup_root = strjoina(dest, "/sys/fs/cgroup");
1066 if (mount("tmpfs", cgroup_root, "tmpfs", MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_STRICTATIME, "mode=755") < 0)
1067 return log_error_errno(errno, "Failed to mount tmpfs to /sys/fs/cgroup: %m");
1070 _cleanup_free_ char *controller = NULL, *origin = NULL, *combined = NULL;
1072 controller = set_steal_first(controllers);
1076 origin = strappend("/sys/fs/cgroup/", controller);
1080 r = readlink_malloc(origin, &combined);
1082 /* Not a symbolic link, but directly a single cgroup hierarchy */
1084 r = mount_cgroup_hierarchy(dest, controller, controller, true);
1089 return log_error_errno(r, "Failed to read link %s: %m", origin);
1091 _cleanup_free_ char *target = NULL;
1093 target = strjoin(dest, "/sys/fs/cgroup/", controller, NULL);
1097 /* A symbolic link, a combination of controllers in one hierarchy */
1099 if (!filename_is_valid(combined)) {
1100 log_warning("Ignoring invalid combined hierarchy %s.", combined);
1104 r = mount_cgroup_hierarchy(dest, combined, combined, true);
1108 if (symlink(combined, target) < 0)
1109 return log_error_errno(errno, "Failed to create symlink for combined hierarchy: %m");
1113 r = mount_cgroup_hierarchy(dest, "name=systemd,xattr", "systemd", false);
1117 /* Make our own cgroup a (writable) bind mount */
1118 systemd_own = strjoina(dest, "/sys/fs/cgroup/systemd", own_cgroup_path);
1119 if (mount(systemd_own, systemd_own, NULL, MS_BIND, NULL) < 0)
1120 return log_error_errno(errno, "Failed to turn %s into a bind mount: %m", own_cgroup_path);
1122 /* And then remount the systemd cgroup root read-only */
1123 systemd_root = strjoina(dest, "/sys/fs/cgroup/systemd");
1124 if (mount(NULL, systemd_root, NULL, MS_BIND|MS_REMOUNT|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_RDONLY, NULL) < 0)
1125 return log_error_errno(errno, "Failed to mount cgroup root read-only: %m");
1127 if (mount(NULL, cgroup_root, NULL, MS_REMOUNT|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_STRICTATIME|MS_RDONLY, "mode=755") < 0)
1128 return log_error_errno(errno, "Failed to remount %s read-only: %m", cgroup_root);
1133 static int mount_tmpfs(const char *dest) {
1136 STRV_FOREACH_PAIR(i, o, arg_tmpfs) {
1137 _cleanup_free_ char *where = NULL;
1140 where = strappend(dest, *i);
1144 r = mkdir_label(where, 0755);
1145 if (r < 0 && r != -EEXIST)
1146 return log_error_errno(r, "Creating mount point for tmpfs %s failed: %m", where);
1148 if (mount("tmpfs", where, "tmpfs", MS_NODEV|MS_STRICTATIME, *o) < 0)
1149 return log_error_errno(errno, "tmpfs mount to %s failed: %m", where);
1155 static int setup_timezone(const char *dest) {
1156 _cleanup_free_ char *where = NULL, *p = NULL, *q = NULL, *check = NULL, *what = NULL;
1162 /* Fix the timezone, if possible */
1163 r = readlink_malloc("/etc/localtime", &p);
1165 log_warning("/etc/localtime is not a symlink, not updating container timezone.");
1169 z = path_startswith(p, "../usr/share/zoneinfo/");
1171 z = path_startswith(p, "/usr/share/zoneinfo/");
1173 log_warning("/etc/localtime does not point into /usr/share/zoneinfo/, not updating container timezone.");
1177 where = strappend(dest, "/etc/localtime");
1181 r = readlink_malloc(where, &q);
1183 y = path_startswith(q, "../usr/share/zoneinfo/");
1185 y = path_startswith(q, "/usr/share/zoneinfo/");
1187 /* Already pointing to the right place? Then do nothing .. */
1188 if (y && streq(y, z))
1192 check = strjoin(dest, "/usr/share/zoneinfo/", z, NULL);
1196 if (access(check, F_OK) < 0) {
1197 log_warning("Timezone %s does not exist in container, not updating container timezone.", z);
1201 what = strappend("../usr/share/zoneinfo/", z);
1205 r = mkdir_parents(where, 0755);
1207 log_error_errno(r, "Failed to create directory for timezone info %s in container: %m", where);
1213 if (r < 0 && errno != ENOENT) {
1214 log_error_errno(errno, "Failed to remove existing timezone info %s in container: %m", where);
1219 if (symlink(what, where) < 0) {
1220 log_error_errno(errno, "Failed to correct timezone of container: %m");
1227 static int setup_resolv_conf(const char *dest) {
1228 _cleanup_free_ char *where = NULL;
1233 if (arg_private_network)
1236 /* Fix resolv.conf, if possible */
1237 where = strappend(dest, "/etc/resolv.conf");
1241 /* We don't really care for the results of this really. If it
1242 * fails, it fails, but meh... */
1243 r = mkdir_parents(where, 0755);
1245 log_warning_errno(r, "Failed to create parent directory for resolv.conf %s: %m", where);
1250 r = copy_file("/etc/resolv.conf", where, O_TRUNC|O_NOFOLLOW, 0644, 0);
1252 log_warning_errno(r, "Failed to copy /etc/resolv.conf to %s: %m", where);
1260 static int setup_volatile_state(const char *directory) {
1266 if (arg_volatile != VOLATILE_STATE)
1269 /* --volatile=state means we simply overmount /var
1270 with a tmpfs, and the rest read-only. */
1272 r = bind_remount_recursive(directory, true);
1274 return log_error_errno(r, "Failed to remount %s read-only: %m", directory);
1276 p = strjoina(directory, "/var");
1278 if (r < 0 && errno != EEXIST)
1279 return log_error_errno(errno, "Failed to create %s: %m", directory);
1281 if (mount("tmpfs", p, "tmpfs", MS_STRICTATIME, "mode=755") < 0)
1282 return log_error_errno(errno, "Failed to mount tmpfs to /var: %m");
1287 static int setup_volatile(const char *directory) {
1288 bool tmpfs_mounted = false, bind_mounted = false;
1289 char template[] = "/tmp/nspawn-volatile-XXXXXX";
1295 if (arg_volatile != VOLATILE_YES)
1298 /* --volatile=yes means we mount a tmpfs to the root dir, and
1299 the original /usr to use inside it, and that read-only. */
1301 if (!mkdtemp(template))
1302 return log_error_errno(errno, "Failed to create temporary directory: %m");
1304 if (mount("tmpfs", template, "tmpfs", MS_STRICTATIME, "mode=755") < 0) {
1305 log_error_errno(errno, "Failed to mount tmpfs for root directory: %m");
1310 tmpfs_mounted = true;
1312 f = strjoina(directory, "/usr");
1313 t = strjoina(template, "/usr");
1316 if (r < 0 && errno != EEXIST) {
1317 log_error_errno(errno, "Failed to create %s: %m", t);
1322 if (mount(f, t, "bind", MS_BIND|MS_REC, NULL) < 0) {
1323 log_error_errno(errno, "Failed to create /usr bind mount: %m");
1328 bind_mounted = true;
1330 r = bind_remount_recursive(t, true);
1332 log_error_errno(r, "Failed to remount %s read-only: %m", t);
1336 if (mount(template, directory, NULL, MS_MOVE, NULL) < 0) {
1337 log_error_errno(errno, "Failed to move root mount: %m");
1355 static char* id128_format_as_uuid(sd_id128_t id, char s[37]) {
1358 "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
1359 SD_ID128_FORMAT_VAL(id));
1364 static int setup_boot_id(const char *dest) {
1365 _cleanup_free_ char *from = NULL, *to = NULL;
1366 sd_id128_t rnd = {};
1372 if (arg_share_system)
1375 /* Generate a new randomized boot ID, so that each boot-up of
1376 * the container gets a new one */
1378 from = strappend(dest, "/dev/proc-sys-kernel-random-boot-id");
1379 to = strappend(dest, "/proc/sys/kernel/random/boot_id");
1383 r = sd_id128_randomize(&rnd);
1385 return log_error_errno(r, "Failed to generate random boot id: %m");
1387 id128_format_as_uuid(rnd, as_uuid);
1389 r = write_string_file(from, as_uuid);
1391 return log_error_errno(r, "Failed to write boot id: %m");
1393 if (mount(from, to, "bind", MS_BIND, NULL) < 0) {
1394 log_error_errno(errno, "Failed to bind mount boot id: %m");
1396 } else if (mount(from, to, "bind", MS_BIND|MS_REMOUNT|MS_RDONLY, NULL))
1397 log_warning_errno(errno, "Failed to make boot id read-only: %m");
1403 static int copy_devnodes(const char *dest) {
1405 static const char devnodes[] =
1416 _cleanup_umask_ mode_t u;
1422 NULSTR_FOREACH(d, devnodes) {
1423 _cleanup_free_ char *from = NULL, *to = NULL;
1426 from = strappend("/dev/", d);
1427 to = strjoin(dest, "/dev/", d, NULL);
1431 if (stat(from, &st) < 0) {
1433 if (errno != ENOENT)
1434 return log_error_errno(errno, "Failed to stat %s: %m", from);
1436 } else if (!S_ISCHR(st.st_mode) && !S_ISBLK(st.st_mode)) {
1438 log_error("%s is not a char or block device, cannot copy", from);
1442 r = mkdir_parents(to, 0775);
1444 log_error_errno(r, "Failed to create parent directory of %s: %m", to);
1448 if (mknod(to, st.st_mode, st.st_rdev) < 0)
1449 return log_error_errno(errno, "mknod(%s) failed: %m", to);
1456 static int setup_ptmx(const char *dest) {
1457 _cleanup_free_ char *p = NULL;
1459 p = strappend(dest, "/dev/ptmx");
1463 if (symlink("pts/ptmx", p) < 0)
1464 return log_error_errno(errno, "Failed to create /dev/ptmx symlink: %m");
1469 static int setup_dev_console(const char *dest, const char *console) {
1470 _cleanup_umask_ mode_t u;
1480 if (stat("/dev/null", &st) < 0)
1481 return log_error_errno(errno, "Failed to stat /dev/null: %m");
1483 r = chmod_and_chown(console, 0600, 0, 0);
1485 return log_error_errno(r, "Failed to correct access mode for TTY: %m");
1487 /* We need to bind mount the right tty to /dev/console since
1488 * ptys can only exist on pts file systems. To have something
1489 * to bind mount things on we create a device node first, and
1490 * use /dev/null for that since we the cgroups device policy
1491 * allows us to create that freely, while we cannot create
1492 * /dev/console. (Note that the major minor doesn't actually
1493 * matter here, since we mount it over anyway). */
1495 to = strjoina(dest, "/dev/console");
1496 if (mknod(to, (st.st_mode & ~07777) | 0600, st.st_rdev) < 0)
1497 return log_error_errno(errno, "mknod() for /dev/console failed: %m");
1499 if (mount(console, to, "bind", MS_BIND, NULL) < 0)
1500 return log_error_errno(errno, "Bind mount for /dev/console failed: %m");
1505 static int setup_kmsg(const char *dest, int kmsg_socket) {
1506 _cleanup_free_ char *from = NULL, *to = NULL;
1507 _cleanup_umask_ mode_t u;
1510 struct cmsghdr cmsghdr;
1511 uint8_t buf[CMSG_SPACE(sizeof(int))];
1513 struct msghdr mh = {
1514 .msg_control = &control,
1515 .msg_controllen = sizeof(control),
1517 struct cmsghdr *cmsg;
1520 assert(kmsg_socket >= 0);
1524 /* We create the kmsg FIFO as /dev/kmsg, but immediately
1525 * delete it after bind mounting it to /proc/kmsg. While FIFOs
1526 * on the reading side behave very similar to /proc/kmsg,
1527 * their writing side behaves differently from /dev/kmsg in
1528 * that writing blocks when nothing is reading. In order to
1529 * avoid any problems with containers deadlocking due to this
1530 * we simply make /dev/kmsg unavailable to the container. */
1531 if (asprintf(&from, "%s/dev/kmsg", dest) < 0 ||
1532 asprintf(&to, "%s/proc/kmsg", dest) < 0)
1535 if (mkfifo(from, 0600) < 0)
1536 return log_error_errno(errno, "mkfifo() for /dev/kmsg failed: %m");
1538 r = chmod_and_chown(from, 0600, 0, 0);
1540 return log_error_errno(r, "Failed to correct access mode for /dev/kmsg: %m");
1542 if (mount(from, to, "bind", MS_BIND, NULL) < 0)
1543 return log_error_errno(errno, "Bind mount for /proc/kmsg failed: %m");
1545 fd = open(from, O_RDWR|O_NDELAY|O_CLOEXEC);
1547 return log_error_errno(errno, "Failed to open fifo: %m");
1549 cmsg = CMSG_FIRSTHDR(&mh);
1550 cmsg->cmsg_level = SOL_SOCKET;
1551 cmsg->cmsg_type = SCM_RIGHTS;
1552 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
1553 memcpy(CMSG_DATA(cmsg), &fd, sizeof(int));
1555 mh.msg_controllen = cmsg->cmsg_len;
1557 /* Store away the fd in the socket, so that it stays open as
1558 * long as we run the child */
1559 k = sendmsg(kmsg_socket, &mh, MSG_NOSIGNAL);
1563 return log_error_errno(errno, "Failed to send FIFO fd: %m");
1565 /* And now make the FIFO unavailable as /dev/kmsg... */
1570 static int send_rtnl(int send_fd) {
1572 struct cmsghdr cmsghdr;
1573 uint8_t buf[CMSG_SPACE(sizeof(int))];
1575 struct msghdr mh = {
1576 .msg_control = &control,
1577 .msg_controllen = sizeof(control),
1579 struct cmsghdr *cmsg;
1580 _cleanup_close_ int fd = -1;
1583 assert(send_fd >= 0);
1585 if (!arg_expose_ports)
1588 fd = socket(PF_NETLINK, SOCK_RAW|SOCK_CLOEXEC|SOCK_NONBLOCK, NETLINK_ROUTE);
1590 return log_error_errno(errno, "failed to allocate container netlink: %m");
1592 cmsg = CMSG_FIRSTHDR(&mh);
1593 cmsg->cmsg_level = SOL_SOCKET;
1594 cmsg->cmsg_type = SCM_RIGHTS;
1595 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
1596 memcpy(CMSG_DATA(cmsg), &fd, sizeof(int));
1598 mh.msg_controllen = cmsg->cmsg_len;
1600 /* Store away the fd in the socket, so that it stays open as
1601 * long as we run the child */
1602 k = sendmsg(send_fd, &mh, MSG_NOSIGNAL);
1604 return log_error_errno(errno, "Failed to send netlink fd: %m");
1609 static int flush_ports(union in_addr_union *exposed) {
1611 int r, af = AF_INET;
1615 if (!arg_expose_ports)
1618 if (in_addr_is_null(af, exposed))
1621 log_debug("Lost IP address.");
1623 LIST_FOREACH(ports, p, arg_expose_ports) {
1624 r = fw_add_local_dnat(false,
1635 log_warning_errno(r, "Failed to modify firewall: %m");
1638 *exposed = IN_ADDR_NULL;
1642 static int expose_ports(sd_rtnl *rtnl, union in_addr_union *exposed) {
1643 _cleanup_free_ struct local_address *addresses = NULL;
1644 _cleanup_free_ char *pretty = NULL;
1645 union in_addr_union new_exposed;
1648 int af = AF_INET, r;
1652 /* Invoked each time an address is added or removed inside the
1655 if (!arg_expose_ports)
1658 r = local_addresses(rtnl, 0, af, &addresses);
1660 return log_error_errno(r, "Failed to enumerate local addresses: %m");
1663 addresses[0].family == af &&
1664 addresses[0].scope < RT_SCOPE_LINK;
1667 return flush_ports(exposed);
1669 new_exposed = addresses[0].address;
1670 if (in_addr_equal(af, exposed, &new_exposed))
1673 in_addr_to_string(af, &new_exposed, &pretty);
1674 log_debug("New container IP is %s.", strna(pretty));
1676 LIST_FOREACH(ports, p, arg_expose_ports) {
1678 r = fw_add_local_dnat(true,
1687 in_addr_is_null(af, exposed) ? NULL : exposed);
1689 log_warning_errno(r, "Failed to modify firewall: %m");
1692 *exposed = new_exposed;
1696 static int on_address_change(sd_rtnl *rtnl, sd_rtnl_message *m, void *userdata) {
1697 union in_addr_union *exposed = userdata;
1703 expose_ports(rtnl, exposed);
1707 static int watch_rtnl(sd_event *event, int recv_fd, union in_addr_union *exposed, sd_rtnl **ret) {
1709 struct cmsghdr cmsghdr;
1710 uint8_t buf[CMSG_SPACE(sizeof(int))];
1712 struct msghdr mh = {
1713 .msg_control = &control,
1714 .msg_controllen = sizeof(control),
1716 struct cmsghdr *cmsg;
1717 _cleanup_rtnl_unref_ sd_rtnl *rtnl = NULL;
1722 assert(recv_fd >= 0);
1725 if (!arg_expose_ports)
1728 k = recvmsg(recv_fd, &mh, MSG_NOSIGNAL);
1730 return log_error_errno(errno, "Failed to recv netlink fd: %m");
1732 cmsg = CMSG_FIRSTHDR(&mh);
1733 assert(cmsg->cmsg_level == SOL_SOCKET);
1734 assert(cmsg->cmsg_type == SCM_RIGHTS);
1735 assert(cmsg->cmsg_len == CMSG_LEN(sizeof(int)));
1736 memcpy(&fd, CMSG_DATA(cmsg), sizeof(int));
1738 r = sd_rtnl_open_fd(&rtnl, fd, 1, RTNLGRP_IPV4_IFADDR);
1741 return log_error_errno(r, "Failed to create rtnl object: %m");
1744 r = sd_rtnl_add_match(rtnl, RTM_NEWADDR, on_address_change, exposed);
1746 return log_error_errno(r, "Failed to subscribe to RTM_NEWADDR messages: %m");
1748 r = sd_rtnl_add_match(rtnl, RTM_DELADDR, on_address_change, exposed);
1750 return log_error_errno(r, "Failed to subscribe to RTM_DELADDR messages: %m");
1752 r = sd_rtnl_attach_event(rtnl, event, 0);
1754 return log_error_errno(r, "Failed to add to even loop: %m");
1762 static int setup_hostname(void) {
1764 if (arg_share_system)
1767 if (sethostname_idempotent(arg_machine) < 0)
1773 static int setup_journal(const char *directory) {
1774 sd_id128_t machine_id, this_id;
1775 _cleanup_free_ char *p = NULL, *b = NULL, *q = NULL, *d = NULL;
1779 /* Don't link journals in ephemeral mode */
1783 p = strappend(directory, "/etc/machine-id");
1787 r = read_one_line_file(p, &b);
1788 if (r == -ENOENT && arg_link_journal == LINK_AUTO)
1791 return log_error_errno(r, "Failed to read machine ID from %s: %m", p);
1794 if (isempty(id) && arg_link_journal == LINK_AUTO)
1797 /* Verify validity */
1798 r = sd_id128_from_string(id, &machine_id);
1800 return log_error_errno(r, "Failed to parse machine ID from %s: %m", p);
1802 r = sd_id128_get_machine(&this_id);
1804 return log_error_errno(r, "Failed to retrieve machine ID: %m");
1806 if (sd_id128_equal(machine_id, this_id)) {
1807 log_full(arg_link_journal == LINK_AUTO ? LOG_WARNING : LOG_ERR,
1808 "Host and machine ids are equal (%s): refusing to link journals", id);
1809 if (arg_link_journal == LINK_AUTO)
1814 if (arg_link_journal == LINK_NO)
1818 p = strappend("/var/log/journal/", id);
1819 q = strjoin(directory, "/var/log/journal/", id, NULL);
1823 if (path_is_mount_point(p, false) > 0) {
1824 if (arg_link_journal != LINK_AUTO) {
1825 log_error("%s: already a mount point, refusing to use for journal", p);
1832 if (path_is_mount_point(q, false) > 0) {
1833 if (arg_link_journal != LINK_AUTO) {
1834 log_error("%s: already a mount point, refusing to use for journal", q);
1841 r = readlink_and_make_absolute(p, &d);
1843 if ((arg_link_journal == LINK_GUEST ||
1844 arg_link_journal == LINK_AUTO) &&
1847 r = mkdir_p(q, 0755);
1849 log_warning_errno(errno, "Failed to create directory %s: %m", q);
1854 return log_error_errno(errno, "Failed to remove symlink %s: %m", p);
1855 } else if (r == -EINVAL) {
1857 if (arg_link_journal == LINK_GUEST &&
1860 if (errno == ENOTDIR) {
1861 log_error("%s already exists and is neither a symlink nor a directory", p);
1864 log_error_errno(errno, "Failed to remove %s: %m", p);
1868 } else if (r != -ENOENT) {
1869 log_error_errno(errno, "readlink(%s) failed: %m", p);
1873 if (arg_link_journal == LINK_GUEST) {
1875 if (symlink(q, p) < 0) {
1876 if (arg_link_journal_try) {
1877 log_debug_errno(errno, "Failed to symlink %s to %s, skipping journal setup: %m", q, p);
1880 log_error_errno(errno, "Failed to symlink %s to %s: %m", q, p);
1885 r = mkdir_p(q, 0755);
1887 log_warning_errno(errno, "Failed to create directory %s: %m", q);
1891 if (arg_link_journal == LINK_HOST) {
1892 /* don't create parents here -- if the host doesn't have
1893 * permanent journal set up, don't force it here */
1896 if (arg_link_journal_try) {
1897 log_debug_errno(errno, "Failed to create %s, skipping journal setup: %m", p);
1900 log_error_errno(errno, "Failed to create %s: %m", p);
1905 } else if (access(p, F_OK) < 0)
1908 if (dir_is_empty(q) == 0)
1909 log_warning("%s is not empty, proceeding anyway.", q);
1911 r = mkdir_p(q, 0755);
1913 log_error_errno(errno, "Failed to create %s: %m", q);
1917 if (mount(p, q, "bind", MS_BIND, NULL) < 0)
1918 return log_error_errno(errno, "Failed to bind mount journal from host into guest: %m");
1923 static int drop_capabilities(void) {
1924 return capability_bounding_set_drop(~arg_retain, false);
1927 static int register_machine(pid_t pid, int local_ifindex) {
1928 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1929 _cleanup_bus_close_unref_ sd_bus *bus = NULL;
1935 r = sd_bus_default_system(&bus);
1937 return log_error_errno(r, "Failed to open system bus: %m");
1939 if (arg_keep_unit) {
1940 r = sd_bus_call_method(
1942 "org.freedesktop.machine1",
1943 "/org/freedesktop/machine1",
1944 "org.freedesktop.machine1.Manager",
1945 "RegisterMachineWithNetwork",
1950 SD_BUS_MESSAGE_APPEND_ID128(arg_uuid),
1954 strempty(arg_directory),
1955 local_ifindex > 0 ? 1 : 0, local_ifindex);
1957 _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
1960 r = sd_bus_message_new_method_call(
1963 "org.freedesktop.machine1",
1964 "/org/freedesktop/machine1",
1965 "org.freedesktop.machine1.Manager",
1966 "CreateMachineWithNetwork");
1968 return bus_log_create_error(r);
1970 r = sd_bus_message_append(
1974 SD_BUS_MESSAGE_APPEND_ID128(arg_uuid),
1978 strempty(arg_directory),
1979 local_ifindex > 0 ? 1 : 0, local_ifindex);
1981 return bus_log_create_error(r);
1983 r = sd_bus_message_open_container(m, 'a', "(sv)");
1985 return bus_log_create_error(r);
1987 if (!isempty(arg_slice)) {
1988 r = sd_bus_message_append(m, "(sv)", "Slice", "s", arg_slice);
1990 return bus_log_create_error(r);
1993 r = sd_bus_message_append(m, "(sv)", "DevicePolicy", "s", "strict");
1995 return bus_log_create_error(r);
1997 r = sd_bus_message_append(m, "(sv)", "DeviceAllow", "a(ss)", 9,
1998 /* Allow the container to
1999 * access and create the API
2000 * device nodes, so that
2001 * PrivateDevices= in the
2002 * container can work
2007 "/dev/random", "rwm",
2008 "/dev/urandom", "rwm",
2010 "/dev/net/tun", "rwm",
2011 /* Allow the container
2012 * access to ptys. However,
2014 * container to ever create
2015 * these device nodes. */
2016 "/dev/pts/ptmx", "rw",
2019 return log_error_errno(r, "Failed to add device whitelist: %m");
2021 STRV_FOREACH(i, arg_property) {
2022 r = sd_bus_message_open_container(m, 'r', "sv");
2024 return bus_log_create_error(r);
2026 r = bus_append_unit_property_assignment(m, *i);
2030 r = sd_bus_message_close_container(m);
2032 return bus_log_create_error(r);
2035 r = sd_bus_message_close_container(m);
2037 return bus_log_create_error(r);
2039 r = sd_bus_call(bus, m, 0, &error, NULL);
2043 log_error("Failed to register machine: %s", bus_error_message(&error, r));
2050 static int terminate_machine(pid_t pid) {
2051 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
2052 _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
2053 _cleanup_bus_close_unref_ sd_bus *bus = NULL;
2060 r = sd_bus_default_system(&bus);
2062 return log_error_errno(r, "Failed to open system bus: %m");
2064 r = sd_bus_call_method(
2066 "org.freedesktop.machine1",
2067 "/org/freedesktop/machine1",
2068 "org.freedesktop.machine1.Manager",
2075 /* Note that the machine might already have been
2076 * cleaned up automatically, hence don't consider it a
2077 * failure if we cannot get the machine object. */
2078 log_debug("Failed to get machine: %s", bus_error_message(&error, r));
2082 r = sd_bus_message_read(reply, "o", &path);
2084 return bus_log_parse_error(r);
2086 r = sd_bus_call_method(
2088 "org.freedesktop.machine1",
2090 "org.freedesktop.machine1.Machine",
2096 log_debug("Failed to terminate machine: %s", bus_error_message(&error, r));
2103 static int reset_audit_loginuid(void) {
2104 _cleanup_free_ char *p = NULL;
2107 if (arg_share_system)
2110 r = read_one_line_file("/proc/self/loginuid", &p);
2114 return log_error_errno(r, "Failed to read /proc/self/loginuid: %m");
2116 /* Already reset? */
2117 if (streq(p, "4294967295"))
2120 r = write_string_file("/proc/self/loginuid", "4294967295");
2122 log_error("Failed to reset audit login UID. This probably means that your kernel is too\n"
2123 "old and you have audit enabled. Note that the auditing subsystem is known to\n"
2124 "be incompatible with containers on old kernels. Please make sure to upgrade\n"
2125 "your kernel or to off auditing with 'audit=0' on the kernel command line before\n"
2126 "using systemd-nspawn. Sleeping for 5s... (%s)\n", strerror(-r));
2134 #define HOST_HASH_KEY SD_ID128_MAKE(1a,37,6f,c7,46,ec,45,0b,ad,a3,d5,31,06,60,5d,b1)
2135 #define CONTAINER_HASH_KEY SD_ID128_MAKE(c3,c4,f9,19,b5,57,b2,1c,e6,cf,14,27,03,9c,ee,a2)
2136 #define MACVLAN_HASH_KEY SD_ID128_MAKE(00,13,6d,bc,66,83,44,81,bb,0c,f9,51,1f,24,a6,6f)
2138 static int generate_mac(struct ether_addr *mac, sd_id128_t hash_key, uint64_t idx) {
2144 l = strlen(arg_machine);
2145 sz = sizeof(sd_id128_t) + l;
2151 /* fetch some persistent data unique to the host */
2152 r = sd_id128_get_machine((sd_id128_t*) v);
2156 /* combine with some data unique (on this host) to this
2157 * container instance */
2158 i = mempcpy(v + sizeof(sd_id128_t), arg_machine, l);
2161 memcpy(i, &idx, sizeof(idx));
2164 /* Let's hash the host machine ID plus the container name. We
2165 * use a fixed, but originally randomly created hash key here. */
2166 siphash24(result, v, sz, hash_key.bytes);
2168 assert_cc(ETH_ALEN <= sizeof(result));
2169 memcpy(mac->ether_addr_octet, result, ETH_ALEN);
2171 /* see eth_random_addr in the kernel */
2172 mac->ether_addr_octet[0] &= 0xfe; /* clear multicast bit */
2173 mac->ether_addr_octet[0] |= 0x02; /* set local assignment bit (IEEE802) */
2178 static int setup_veth(pid_t pid, char iface_name[IFNAMSIZ], int *ifi) {
2179 _cleanup_rtnl_message_unref_ sd_rtnl_message *m = NULL;
2180 _cleanup_rtnl_unref_ sd_rtnl *rtnl = NULL;
2181 struct ether_addr mac_host, mac_container;
2184 if (!arg_private_network)
2187 if (!arg_network_veth)
2190 /* Use two different interface name prefixes depending whether
2191 * we are in bridge mode or not. */
2192 snprintf(iface_name, IFNAMSIZ - 1, "%s-%s",
2193 arg_network_bridge ? "vb" : "ve", arg_machine);
2195 r = generate_mac(&mac_container, CONTAINER_HASH_KEY, 0);
2197 return log_error_errno(r, "Failed to generate predictable MAC address for container side: %m");
2199 r = generate_mac(&mac_host, HOST_HASH_KEY, 0);
2201 return log_error_errno(r, "Failed to generate predictable MAC address for host side: %m");
2203 r = sd_rtnl_open(&rtnl, 0);
2205 return log_error_errno(r, "Failed to connect to netlink: %m");
2207 r = sd_rtnl_message_new_link(rtnl, &m, RTM_NEWLINK, 0);
2209 return log_error_errno(r, "Failed to allocate netlink message: %m");
2211 r = sd_rtnl_message_append_string(m, IFLA_IFNAME, iface_name);
2213 return log_error_errno(r, "Failed to add netlink interface name: %m");
2215 r = sd_rtnl_message_append_ether_addr(m, IFLA_ADDRESS, &mac_host);
2217 return log_error_errno(r, "Failed to add netlink MAC address: %m");
2219 r = sd_rtnl_message_open_container(m, IFLA_LINKINFO);
2221 return log_error_errno(r, "Failed to open netlink container: %m");
2223 r = sd_rtnl_message_open_container_union(m, IFLA_INFO_DATA, "veth");
2225 return log_error_errno(r, "Failed to open netlink container: %m");
2227 r = sd_rtnl_message_open_container(m, VETH_INFO_PEER);
2229 return log_error_errno(r, "Failed to open netlink container: %m");
2231 r = sd_rtnl_message_append_string(m, IFLA_IFNAME, "host0");
2233 return log_error_errno(r, "Failed to add netlink interface name: %m");
2235 r = sd_rtnl_message_append_ether_addr(m, IFLA_ADDRESS, &mac_container);
2237 return log_error_errno(r, "Failed to add netlink MAC address: %m");
2239 r = sd_rtnl_message_append_u32(m, IFLA_NET_NS_PID, pid);
2241 return log_error_errno(r, "Failed to add netlink namespace field: %m");
2243 r = sd_rtnl_message_close_container(m);
2245 return log_error_errno(r, "Failed to close netlink container: %m");
2247 r = sd_rtnl_message_close_container(m);
2249 return log_error_errno(r, "Failed to close netlink container: %m");
2251 r = sd_rtnl_message_close_container(m);
2253 return log_error_errno(r, "Failed to close netlink container: %m");
2255 r = sd_rtnl_call(rtnl, m, 0, NULL);
2257 return log_error_errno(r, "Failed to add new veth interfaces: %m");
2259 i = (int) if_nametoindex(iface_name);
2261 return log_error_errno(errno, "Failed to resolve interface %s: %m", iface_name);
2268 static int setup_bridge(const char veth_name[], int *ifi) {
2269 _cleanup_rtnl_message_unref_ sd_rtnl_message *m = NULL;
2270 _cleanup_rtnl_unref_ sd_rtnl *rtnl = NULL;
2273 if (!arg_private_network)
2276 if (!arg_network_veth)
2279 if (!arg_network_bridge)
2282 bridge = (int) if_nametoindex(arg_network_bridge);
2284 return log_error_errno(errno, "Failed to resolve interface %s: %m", arg_network_bridge);
2288 r = sd_rtnl_open(&rtnl, 0);
2290 return log_error_errno(r, "Failed to connect to netlink: %m");
2292 r = sd_rtnl_message_new_link(rtnl, &m, RTM_SETLINK, 0);
2294 return log_error_errno(r, "Failed to allocate netlink message: %m");
2296 r = sd_rtnl_message_link_set_flags(m, IFF_UP, IFF_UP);
2298 return log_error_errno(r, "Failed to set IFF_UP flag: %m");
2300 r = sd_rtnl_message_append_string(m, IFLA_IFNAME, veth_name);
2302 return log_error_errno(r, "Failed to add netlink interface name field: %m");
2304 r = sd_rtnl_message_append_u32(m, IFLA_MASTER, bridge);
2306 return log_error_errno(r, "Failed to add netlink master field: %m");
2308 r = sd_rtnl_call(rtnl, m, 0, NULL);
2310 return log_error_errno(r, "Failed to add veth interface to bridge: %m");
2315 static int parse_interface(struct udev *udev, const char *name) {
2316 _cleanup_udev_device_unref_ struct udev_device *d = NULL;
2317 char ifi_str[2 + DECIMAL_STR_MAX(int)];
2320 ifi = (int) if_nametoindex(name);
2322 return log_error_errno(errno, "Failed to resolve interface %s: %m", name);
2324 sprintf(ifi_str, "n%i", ifi);
2325 d = udev_device_new_from_device_id(udev, ifi_str);
2327 return log_error_errno(errno, "Failed to get udev device for interface %s: %m", name);
2329 if (udev_device_get_is_initialized(d) <= 0) {
2330 log_error("Network interface %s is not initialized yet.", name);
2337 static int move_network_interfaces(pid_t pid) {
2338 _cleanup_udev_unref_ struct udev *udev = NULL;
2339 _cleanup_rtnl_unref_ sd_rtnl *rtnl = NULL;
2343 if (!arg_private_network)
2346 if (strv_isempty(arg_network_interfaces))
2349 r = sd_rtnl_open(&rtnl, 0);
2351 return log_error_errno(r, "Failed to connect to netlink: %m");
2355 log_error("Failed to connect to udev.");
2359 STRV_FOREACH(i, arg_network_interfaces) {
2360 _cleanup_rtnl_message_unref_ sd_rtnl_message *m = NULL;
2363 ifi = parse_interface(udev, *i);
2367 r = sd_rtnl_message_new_link(rtnl, &m, RTM_SETLINK, ifi);
2369 return log_error_errno(r, "Failed to allocate netlink message: %m");
2371 r = sd_rtnl_message_append_u32(m, IFLA_NET_NS_PID, pid);
2373 return log_error_errno(r, "Failed to append namespace PID to netlink message: %m");
2375 r = sd_rtnl_call(rtnl, m, 0, NULL);
2377 return log_error_errno(r, "Failed to move interface %s to namespace: %m", *i);
2383 static int setup_macvlan(pid_t pid) {
2384 _cleanup_udev_unref_ struct udev *udev = NULL;
2385 _cleanup_rtnl_unref_ sd_rtnl *rtnl = NULL;
2390 if (!arg_private_network)
2393 if (strv_isempty(arg_network_macvlan))
2396 r = sd_rtnl_open(&rtnl, 0);
2398 return log_error_errno(r, "Failed to connect to netlink: %m");
2402 log_error("Failed to connect to udev.");
2406 STRV_FOREACH(i, arg_network_macvlan) {
2407 _cleanup_rtnl_message_unref_ sd_rtnl_message *m = NULL;
2408 _cleanup_free_ char *n = NULL;
2409 struct ether_addr mac;
2412 ifi = parse_interface(udev, *i);
2416 r = generate_mac(&mac, MACVLAN_HASH_KEY, idx++);
2418 return log_error_errno(r, "Failed to create MACVLAN MAC address: %m");
2420 r = sd_rtnl_message_new_link(rtnl, &m, RTM_NEWLINK, 0);
2422 return log_error_errno(r, "Failed to allocate netlink message: %m");
2424 r = sd_rtnl_message_append_u32(m, IFLA_LINK, ifi);
2426 return log_error_errno(r, "Failed to add netlink interface index: %m");
2428 n = strappend("mv-", *i);
2432 strshorten(n, IFNAMSIZ-1);
2434 r = sd_rtnl_message_append_string(m, IFLA_IFNAME, n);
2436 return log_error_errno(r, "Failed to add netlink interface name: %m");
2438 r = sd_rtnl_message_append_ether_addr(m, IFLA_ADDRESS, &mac);
2440 return log_error_errno(r, "Failed to add netlink MAC address: %m");
2442 r = sd_rtnl_message_append_u32(m, IFLA_NET_NS_PID, pid);
2444 return log_error_errno(r, "Failed to add netlink namespace field: %m");
2446 r = sd_rtnl_message_open_container(m, IFLA_LINKINFO);
2448 return log_error_errno(r, "Failed to open netlink container: %m");
2450 r = sd_rtnl_message_open_container_union(m, IFLA_INFO_DATA, "macvlan");
2452 return log_error_errno(r, "Failed to open netlink container: %m");
2454 r = sd_rtnl_message_append_u32(m, IFLA_MACVLAN_MODE, MACVLAN_MODE_BRIDGE);
2456 return log_error_errno(r, "Failed to append macvlan mode: %m");
2458 r = sd_rtnl_message_close_container(m);
2460 return log_error_errno(r, "Failed to close netlink container: %m");
2462 r = sd_rtnl_message_close_container(m);
2464 return log_error_errno(r, "Failed to close netlink container: %m");
2466 r = sd_rtnl_call(rtnl, m, 0, NULL);
2468 return log_error_errno(r, "Failed to add new macvlan interfaces: %m");
2474 static int setup_ipvlan(pid_t pid) {
2475 _cleanup_udev_unref_ struct udev *udev = NULL;
2476 _cleanup_rtnl_unref_ sd_rtnl *rtnl = NULL;
2480 if (!arg_private_network)
2483 if (strv_isempty(arg_network_ipvlan))
2486 r = sd_rtnl_open(&rtnl, 0);
2488 return log_error_errno(r, "Failed to connect to netlink: %m");
2492 log_error("Failed to connect to udev.");
2496 STRV_FOREACH(i, arg_network_ipvlan) {
2497 _cleanup_rtnl_message_unref_ sd_rtnl_message *m = NULL;
2498 _cleanup_free_ char *n = NULL;
2501 ifi = parse_interface(udev, *i);
2505 r = sd_rtnl_message_new_link(rtnl, &m, RTM_NEWLINK, 0);
2507 return log_error_errno(r, "Failed to allocate netlink message: %m");
2509 r = sd_rtnl_message_append_u32(m, IFLA_LINK, ifi);
2511 return log_error_errno(r, "Failed to add netlink interface index: %m");
2513 n = strappend("iv-", *i);
2517 strshorten(n, IFNAMSIZ-1);
2519 r = sd_rtnl_message_append_string(m, IFLA_IFNAME, n);
2521 return log_error_errno(r, "Failed to add netlink interface name: %m");
2523 r = sd_rtnl_message_append_u32(m, IFLA_NET_NS_PID, pid);
2525 return log_error_errno(r, "Failed to add netlink namespace field: %m");
2527 r = sd_rtnl_message_open_container(m, IFLA_LINKINFO);
2529 return log_error_errno(r, "Failed to open netlink container: %m");
2531 r = sd_rtnl_message_open_container_union(m, IFLA_INFO_DATA, "ipvlan");
2533 return log_error_errno(r, "Failed to open netlink container: %m");
2535 r = sd_rtnl_message_append_u16(m, IFLA_IPVLAN_MODE, IPVLAN_MODE_L2);
2537 return log_error_errno(r, "Failed to add ipvlan mode: %m");
2539 r = sd_rtnl_message_close_container(m);
2541 return log_error_errno(r, "Failed to close netlink container: %m");
2543 r = sd_rtnl_message_close_container(m);
2545 return log_error_errno(r, "Failed to close netlink container: %m");
2547 r = sd_rtnl_call(rtnl, m, 0, NULL);
2549 return log_error_errno(r, "Failed to add new ipvlan interfaces: %m");
2555 static int setup_seccomp(void) {
2558 static const int blacklist[] = {
2559 SCMP_SYS(kexec_load),
2560 SCMP_SYS(open_by_handle_at),
2567 static const int kmod_blacklist[] = {
2568 SCMP_SYS(init_module),
2569 SCMP_SYS(finit_module),
2570 SCMP_SYS(delete_module),
2573 scmp_filter_ctx seccomp;
2577 seccomp = seccomp_init(SCMP_ACT_ALLOW);
2581 r = seccomp_add_secondary_archs(seccomp);
2583 log_error_errno(r, "Failed to add secondary archs to seccomp filter: %m");
2587 for (i = 0; i < ELEMENTSOF(blacklist); i++) {
2588 r = seccomp_rule_add(seccomp, SCMP_ACT_ERRNO(EPERM), blacklist[i], 0);
2590 continue; /* unknown syscall */
2592 log_error_errno(r, "Failed to block syscall: %m");
2597 /* If the CAP_SYS_MODULE capability is not requested then
2598 * we'll block the kmod syscalls too */
2599 if (!(arg_retain & (1ULL << CAP_SYS_MODULE))) {
2600 for (i = 0; i < ELEMENTSOF(kmod_blacklist); i++) {
2601 r = seccomp_rule_add(seccomp, SCMP_ACT_ERRNO(EPERM), kmod_blacklist[i], 0);
2603 continue; /* unknown syscall */
2605 log_error_errno(r, "Failed to block syscall: %m");
2612 Audit is broken in containers, much of the userspace audit
2613 hookup will fail if running inside a container. We don't
2614 care and just turn off creation of audit sockets.
2616 This will make socket(AF_NETLINK, *, NETLINK_AUDIT) fail
2617 with EAFNOSUPPORT which audit userspace uses as indication
2618 that audit is disabled in the kernel.
2621 r = seccomp_rule_add(
2623 SCMP_ACT_ERRNO(EAFNOSUPPORT),
2626 SCMP_A0(SCMP_CMP_EQ, AF_NETLINK),
2627 SCMP_A2(SCMP_CMP_EQ, NETLINK_AUDIT));
2629 log_error_errno(r, "Failed to add audit seccomp rule: %m");
2633 r = seccomp_attr_set(seccomp, SCMP_FLTATR_CTL_NNP, 0);
2635 log_error_errno(r, "Failed to unset NO_NEW_PRIVS: %m");
2639 r = seccomp_load(seccomp);
2641 log_error_errno(r, "Failed to install seccomp audit filter: %m");
2644 seccomp_release(seccomp);
2652 static int setup_propagate(const char *root) {
2655 (void) mkdir_p("/run/systemd/nspawn/", 0755);
2656 (void) mkdir_p("/run/systemd/nspawn/propagate", 0600);
2657 p = strjoina("/run/systemd/nspawn/propagate/", arg_machine);
2658 (void) mkdir_p(p, 0600);
2660 q = strjoina(root, "/run/systemd/nspawn/incoming");
2661 mkdir_parents(q, 0755);
2664 if (mount(p, q, NULL, MS_BIND, NULL) < 0)
2665 return log_error_errno(errno, "Failed to install propagation bind mount.");
2667 if (mount(NULL, q, NULL, MS_BIND|MS_REMOUNT|MS_RDONLY, NULL) < 0)
2668 return log_error_errno(errno, "Failed to make propagation mount read-only");
2673 static int setup_image(char **device_path, int *loop_nr) {
2674 struct loop_info64 info = {
2675 .lo_flags = LO_FLAGS_AUTOCLEAR|LO_FLAGS_PARTSCAN
2677 _cleanup_close_ int fd = -1, control = -1, loop = -1;
2678 _cleanup_free_ char* loopdev = NULL;
2682 assert(device_path);
2686 fd = open(arg_image, O_CLOEXEC|(arg_read_only ? O_RDONLY : O_RDWR)|O_NONBLOCK|O_NOCTTY);
2688 return log_error_errno(errno, "Failed to open %s: %m", arg_image);
2690 if (fstat(fd, &st) < 0)
2691 return log_error_errno(errno, "Failed to stat %s: %m", arg_image);
2693 if (S_ISBLK(st.st_mode)) {
2696 p = strdup(arg_image);
2710 if (!S_ISREG(st.st_mode)) {
2711 log_error_errno(errno, "%s is not a regular file or block device: %m", arg_image);
2715 control = open("/dev/loop-control", O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK);
2717 return log_error_errno(errno, "Failed to open /dev/loop-control: %m");
2719 nr = ioctl(control, LOOP_CTL_GET_FREE);
2721 return log_error_errno(errno, "Failed to allocate loop device: %m");
2723 if (asprintf(&loopdev, "/dev/loop%i", nr) < 0)
2726 loop = open(loopdev, O_CLOEXEC|(arg_read_only ? O_RDONLY : O_RDWR)|O_NONBLOCK|O_NOCTTY);
2728 return log_error_errno(errno, "Failed to open loop device %s: %m", loopdev);
2730 if (ioctl(loop, LOOP_SET_FD, fd) < 0)
2731 return log_error_errno(errno, "Failed to set loopback file descriptor on %s: %m", loopdev);
2734 info.lo_flags |= LO_FLAGS_READ_ONLY;
2736 if (ioctl(loop, LOOP_SET_STATUS64, &info) < 0)
2737 return log_error_errno(errno, "Failed to set loopback settings on %s: %m", loopdev);
2739 *device_path = loopdev;
2750 #define PARTITION_TABLE_BLURB \
2751 "Note that the disk image needs to either contain only a single MBR partition of\n" \
2752 "type 0x83 that is marked bootable, or a sinlge GPT partition of type" \
2753 "0FC63DAF-8483-4772-8E79-3D69D8477DE4 or follow\n" \
2754 " http://www.freedesktop.org/wiki/Specifications/DiscoverablePartitionsSpec/\n" \
2755 "to be bootable with systemd-nspawn."
2757 static int dissect_image(
2759 char **root_device, bool *root_device_rw,
2760 char **home_device, bool *home_device_rw,
2761 char **srv_device, bool *srv_device_rw,
2765 int home_nr = -1, srv_nr = -1;
2766 #ifdef GPT_ROOT_NATIVE
2769 #ifdef GPT_ROOT_SECONDARY
2770 int secondary_root_nr = -1;
2772 _cleanup_free_ char *home = NULL, *root = NULL, *secondary_root = NULL, *srv = NULL, *generic = NULL;
2773 _cleanup_udev_enumerate_unref_ struct udev_enumerate *e = NULL;
2774 _cleanup_udev_device_unref_ struct udev_device *d = NULL;
2775 _cleanup_blkid_free_probe_ blkid_probe b = NULL;
2776 _cleanup_udev_unref_ struct udev *udev = NULL;
2777 struct udev_list_entry *first, *item;
2778 bool home_rw = true, root_rw = true, secondary_root_rw = true, srv_rw = true, generic_rw = true;
2779 bool is_gpt, is_mbr, multiple_generic = false;
2780 const char *pttype = NULL;
2787 assert(root_device);
2788 assert(home_device);
2793 b = blkid_new_probe();
2798 r = blkid_probe_set_device(b, fd, 0, 0);
2803 log_error_errno(errno, "Failed to set device on blkid probe: %m");
2807 blkid_probe_enable_partitions(b, 1);
2808 blkid_probe_set_partitions_flags(b, BLKID_PARTS_ENTRY_DETAILS);
2811 r = blkid_do_safeprobe(b);
2812 if (r == -2 || r == 1) {
2813 log_error("Failed to identify any partition table on\n"
2815 PARTITION_TABLE_BLURB, arg_image);
2817 } else if (r != 0) {
2820 log_error_errno(errno, "Failed to probe: %m");
2824 blkid_probe_lookup_value(b, "PTTYPE", &pttype, NULL);
2826 is_gpt = streq_ptr(pttype, "gpt");
2827 is_mbr = streq_ptr(pttype, "dos");
2829 if (!is_gpt && !is_mbr) {
2830 log_error("No GPT or MBR partition table discovered on\n"
2832 PARTITION_TABLE_BLURB, arg_image);
2837 pl = blkid_probe_get_partitions(b);
2842 log_error("Failed to list partitions of %s", arg_image);
2850 if (fstat(fd, &st) < 0)
2851 return log_error_errno(errno, "Failed to stat block device: %m");
2853 d = udev_device_new_from_devnum(udev, 'b', st.st_rdev);
2861 log_error("Kernel partitions never appeared.");
2865 e = udev_enumerate_new(udev);
2869 r = udev_enumerate_add_match_parent(e, d);
2873 r = udev_enumerate_scan_devices(e);
2875 return log_error_errno(r, "Failed to scan for partition devices of %s: %m", arg_image);
2877 /* Count the partitions enumerated by the kernel */
2879 first = udev_enumerate_get_list_entry(e);
2880 udev_list_entry_foreach(item, first)
2883 /* Count the partitions enumerated by blkid */
2884 m = blkid_partlist_numof_partitions(pl);
2888 log_error("blkid and kernel partition list do not match.");
2894 /* The kernel has probed fewer partitions than
2895 * blkid? Maybe the kernel prober is still
2896 * running or it got EBUSY because udev
2897 * already opened the device. Let's reprobe
2898 * the device, which is a synchronous call
2899 * that waits until probing is complete. */
2901 for (j = 0; j < 20; j++) {
2903 r = ioctl(fd, BLKRRPART, 0);
2906 if (r >= 0 || r != -EBUSY)
2909 /* If something else has the device
2910 * open, such as an udev rule, the
2911 * ioctl will return EBUSY. Since
2912 * there's no way to wait until it
2913 * isn't busy anymore, let's just wait
2914 * a bit, and try again.
2916 * This is really something they
2917 * should fix in the kernel! */
2919 usleep(50 * USEC_PER_MSEC);
2923 return log_error_errno(r, "Failed to reread partition table: %m");
2926 e = udev_enumerate_unref(e);
2929 first = udev_enumerate_get_list_entry(e);
2930 udev_list_entry_foreach(item, first) {
2931 _cleanup_udev_device_unref_ struct udev_device *q;
2933 unsigned long long flags;
2939 q = udev_device_new_from_syspath(udev, udev_list_entry_get_name(item));
2944 log_error_errno(errno, "Failed to get partition device of %s: %m", arg_image);
2948 qn = udev_device_get_devnum(q);
2952 if (st.st_rdev == qn)
2955 node = udev_device_get_devnode(q);
2959 pp = blkid_partlist_devno_to_partition(pl, qn);
2963 flags = blkid_partition_get_flags(pp);
2965 nr = blkid_partition_get_partno(pp);
2973 if (flags & GPT_FLAG_NO_AUTO)
2976 stype = blkid_partition_get_type_string(pp);
2980 if (sd_id128_from_string(stype, &type_id) < 0)
2983 if (sd_id128_equal(type_id, GPT_HOME)) {
2985 if (home && nr >= home_nr)
2989 home_rw = !(flags & GPT_FLAG_READ_ONLY);
2991 r = free_and_strdup(&home, node);
2995 } else if (sd_id128_equal(type_id, GPT_SRV)) {
2997 if (srv && nr >= srv_nr)
3001 srv_rw = !(flags & GPT_FLAG_READ_ONLY);
3003 r = free_and_strdup(&srv, node);
3007 #ifdef GPT_ROOT_NATIVE
3008 else if (sd_id128_equal(type_id, GPT_ROOT_NATIVE)) {
3010 if (root && nr >= root_nr)
3014 root_rw = !(flags & GPT_FLAG_READ_ONLY);
3016 r = free_and_strdup(&root, node);
3021 #ifdef GPT_ROOT_SECONDARY
3022 else if (sd_id128_equal(type_id, GPT_ROOT_SECONDARY)) {
3024 if (secondary_root && nr >= secondary_root_nr)
3027 secondary_root_nr = nr;
3028 secondary_root_rw = !(flags & GPT_FLAG_READ_ONLY);
3030 r = free_and_strdup(&secondary_root, node);
3035 else if (sd_id128_equal(type_id, GPT_LINUX_GENERIC)) {
3038 multiple_generic = true;
3040 generic_rw = !(flags & GPT_FLAG_READ_ONLY);
3042 r = free_and_strdup(&generic, node);
3048 } else if (is_mbr) {
3051 if (flags != 0x80) /* Bootable flag */
3054 type = blkid_partition_get_type(pp);
3055 if (type != 0x83) /* Linux partition */
3059 multiple_generic = true;
3063 r = free_and_strdup(&root, node);