HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/nspawn/nspawn.c

300,508 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 1c687382baea8193c023ec86840c44042195bef9

Lines 2001–3000 of 6,878

        if (r < 0)
                return log_error_errno(r, "Failed to generate random boot id: %m");
 
        r = id128_write(p, ID128_FORMAT_UUID, rnd);
        if (r < 0)
                return log_error_errno(r, "Failed to write boot id: %m");
 
        return userns_lchown(p, 0, 0);
}
 
static int setup_boot_id(void) {
        int r;
 
        r = mount_nofollow_verbose(
                        LOG_ERR,
                        "/run/host/proc-sys-kernel-random-boot-id",
                        "/proc/sys/kernel/random/boot_id",
                        /* fstype= */ NULL,
                        MS_BIND,
                        /* options= */ NULL);
        if (r < 0)
                return r;
 
        return mount_nofollow_verbose(
                        LOG_ERR,
                        /* what= */ NULL,
                        "/proc/sys/kernel/random/boot_id",
                        /* fstype= */ NULL,
                        MS_BIND|MS_REMOUNT|MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV,
                        /* options= */ NULL);
}
 
static int bind_mount_devnode(const char *from, const char *to) {
        int r;
 
        assert(from);
        assert(to);
 
        r = touch(to);
        if (r < 0)
                return log_debug_errno(r, "Failed to touch %s: %m", to);
 
        r = mount_nofollow_verbose(LOG_DEBUG, from, to, NULL, MS_BIND, NULL);
        if (r < 0) {
                (void) unlink(to);
                return log_error_errno(r, "Failed to bind mount %s to %s: %m", from, to);
        }
 
        return 0;
}
 
static int copy_devnode_one(const char *dest, const char *node, bool check) {
        int r;
 
        assert(dest);
        assert(!isempty(node));
 
        BLOCK_WITH_UMASK(0000);
 
        _cleanup_free_ char *from = path_join("/dev/", node);
        if (!from)
                return log_oom();
 
        if (check) {
                /* If 'check' is true, create /dev/fuse only when it is accessible. The check is necessary,
                 * as some custom service units that invoke systemd-nspawn may enable DevicePolicy= without
                 * DeviceAllow= for the device node. */
                _cleanup_close_ int fd = open(from, O_CLOEXEC|O_RDWR);
                if (fd < 0) {
                        log_debug_errno(errno,
                                        "Failed to open %s, skipping creation of the device node in the container, ignoring: %m",
                                        from);
                        return 0;
                }
        }
 
        _cleanup_free_ char *to = path_join(dest, from);
        if (!to)
                return log_oom();
 
        struct stat st;
        if (stat(from, &st) < 0) {
                if (errno != ENOENT)
                        return log_error_errno(errno, "Failed to stat %s: %m", from);
 
                log_debug_errno(errno, "Device node %s does not exist, ignoring.", from);
                return 0;
        }
        r = stat_verify_device_node(&st);
        if (r < 0)
                return log_error_errno(r, "'%s' is not a device node.", from);
 
        /* Create the parent directory of the device node. Here, we assume that the path has at most one
         * subdirectory under /dev/, e.g. /dev/net/tun. */
        _cleanup_free_ char *parent = NULL;
        r = path_extract_directory(from, &parent);
        if (r < 0)
                return log_error_errno(r, "Failed to extract directory from %s: %m", from);
        r = userns_mkdir(dest, parent, 0755, 0, 0);
        if (r < 0)
                return log_error_errno(r, "Failed to create directory %s: %m", parent);
 
        r = RET_NERRNO(mknod(to, st.st_mode, st.st_rdev));
        if (r < 0) {
                /* Explicitly warn the user when /dev/ is already populated. */
                if (r == -EEXIST)
                        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);
 
                /* If arg_uid_shift != 0, then we cannot fall back to use bind mount. */
                if (!(arg_userns_mode == USER_NAMESPACE_NO ||
                      (arg_userns_mode == USER_NAMESPACE_FIXED && arg_uid_shift == 0))) {
 
                        if (arg_userns_mode != USER_NAMESPACE_MANAGED || !ERRNO_IS_NEG_PRIVILEGE(r))
                                return log_error_errno(r, "Failed to mknod(%s): %m", to);
 
                        log_debug_errno(r, "Failed to create device node '%s' and running in managed mode, resorting to bind mount: %m", to);
                }
 
                /* Some systems abusively restrict mknod but allow bind mounts. */
                if (bind_mount_devnode(from, to) < 0)
                        /* use the original error code. */
                        return log_error_errno(r, "Both mknod() and bind mount %s failed: %m", to);
        } else {
                /* mknod() succeeds, chown() it if necessary. */
                r = userns_lchown(to, 0, 0);
                if (r < 0)
                        return log_error_errno(r, "chown() of device node %s failed: %m", to);
        }
 
        _cleanup_free_ char *dn = path_join("/dev", S_ISCHR(st.st_mode) ? "char" : "block");
        if (!dn)
                return log_oom();
 
        r = userns_mkdir(dest, dn, 0755, 0, 0);
        if (r < 0)
                return log_error_errno(r, "Failed to create '%s': %m", dn);
 
        _cleanup_free_ char *sl = NULL;
        if (asprintf(&sl, "%s/" DEVNUM_FORMAT_STR, dn, DEVNUM_FORMAT_VAL(st.st_rdev)) < 0)
                return log_oom();
 
        _cleanup_free_ char *prefixed = path_join(dest, sl);
        if (!prefixed)
                return log_oom();
 
        _cleanup_free_ char *t = path_join("..", node);
        if (!t)
                return log_oom();
 
        if (symlink(t, prefixed) < 0)
                log_debug_errno(errno, "Failed to symlink '%s' to '%s', ignoring: %m", t, prefixed);
 
        return 0;
}
 
static int copy_devnodes(const char *dest) {
        int r = 0;
 
        assert(dest);
 
        /* Required basic device nodes. */
        FOREACH_STRING(node, "null", "zero", "full", "random", "urandom", "tty") {
                r = copy_devnode_one(dest, node, /* check= */ false);
                if (r < 0)
                        return r;
        }
 
        /* Optional device nodes. */
        FOREACH_STRING(node, "fuse", "net/tun") {
                r = copy_devnode_one(dest, node, /* check= */ true);
                if (r < 0)
                        return r;
        }
 
        return 0;
}
 
static int make_extra_nodes(const char *dest) {
        int r;
 
        BLOCK_WITH_UMASK(0000);
 
        FOREACH_ARRAY(node, arg_extra_nodes, arg_n_extra_nodes) {
                _cleanup_free_ char *path = NULL;
 
                r = chase(node->path, dest, CHASE_PREFIX_ROOT|CHASE_NONEXISTENT|CHASE_NOFOLLOW, &path, /* ret_fd= */ NULL);
                if (r < 0)
                        return log_error_errno(r, "Failed to resolve device node path '%s': %m", node->path);
 
                dev_t dev = S_ISCHR(node->mode) || S_ISBLK(node->mode) ? makedev(node->major, node->minor) : 0;
                if (mknod(path, node->mode, dev) < 0)
                        return log_error_errno(errno, "Failed to create device node '%s': %m", path);
 
                r = chmod_and_chown(path, node->mode, node->uid, node->gid);
                if (r < 0)
                        return log_error_errno(r, "Failed to adjust device node ownership of '%s': %m", path);
        }
 
        return 0;
}
 
static int setup_pts(const char *dest, uid_t chown_uid) {
        _cleanup_free_ char *options = NULL;
        int r;
 
#if HAVE_SELINUX
        if (arg_selinux_apifs_context)
                (void) asprintf(&options,
                                "newinstance,ptmxmode=0666,mode=" STRINGIFY(TTY_MODE) ",gid=" GID_FMT ",context=\"%s\"",
                                chown_uid + TTY_GID,
                                arg_selinux_apifs_context);
        else
#endif
                (void) asprintf(&options,
                                "newinstance,ptmxmode=0666,mode=" STRINGIFY(TTY_MODE) ",gid=" GID_FMT,
                                chown_uid + TTY_GID);
 
        if (!options)
                return log_oom();
 
        /* Mount /dev/pts itself */
        _cleanup_free_ char *p = path_join(dest, "/dev/pts");
        if (!p)
                return log_oom();
 
        r = RET_NERRNO(mkdir(p, 0755));
        if (r < 0)
                return log_error_errno(r, "Failed to create /dev/pts: %m");
 
        r = mount_nofollow_verbose(LOG_ERR, "devpts", p, "devpts", MS_NOSUID|MS_NOEXEC, options);
        if (r < 0)
                return r;
        r = userns_lchown(p, 0, 0);
        if (r < 0)
                return log_error_errno(r, "Failed to chown /dev/pts: %m");
 
        /* Create /dev/ptmx symlink */
        free(p);
        p = path_join(dest, "/dev/ptmx");
        if (!p)
                return log_oom();
 
        if (symlink("pts/ptmx", p) < 0)
                return log_error_errno(errno, "Failed to create /dev/ptmx symlink: %m");
        r = userns_lchown(p, 0, 0);
        if (r < 0)
                return log_error_errno(r, "Failed to chown /dev/ptmx: %m");
 
        /* And fix /dev/pts/ptmx ownership */
        free(p);
        p = path_join(dest, "/dev/pts/ptmx");
        if (!p)
                return log_oom();
 
        r = userns_lchown(p, 0, 0);
        if (r < 0)
                return log_error_errno(r, "Failed to chown /dev/pts/ptmx: %m");
 
        return 0;
}
 
static int setup_stdio_as_dev_console(void) {
        _cleanup_close_ int terminal = -EBADF;
        int r;
 
        /* We open the TTY in O_NOCTTY mode, so that we do not become controller yet. We'll do that later
         * explicitly, if we are configured to. */
        terminal = open_terminal("/dev/console", O_RDWR|O_NOCTTY);
        if (terminal < 0)
                return log_error_errno(terminal, "Failed to open console: %m");
 
        /* Make sure we can continue logging to the original stderr, even if
         * stderr points elsewhere now */
        r = log_dup_console();
        if (r < 0)
                return log_error_errno(r, "Failed to duplicate stderr: %m");
 
        /* invalidates 'terminal' on success and failure */
        r = rearrange_stdio(terminal, terminal, terminal);
        TAKE_FD(terminal);
        if (r < 0)
                return log_error_errno(r, "Failed to move console to stdin/stdout/stderr: %m");
 
        return 0;
}
 
static int setup_dev_console(const char *console) {
        _cleanup_free_ char *p = NULL;
        int r;
 
        /* Create /dev/console symlink */
        r = path_make_relative("/dev", console, &p);
        if (r < 0)
                return log_error_errno(r, "Failed to create relative path: %m");
 
        if (symlink(p, "/dev/console") < 0)
                return log_error_errno(errno, "Failed to create /dev/console symlink: %m");
 
        return 0;
}
 
static int setup_keyring(void) {
        key_serial_t keyring;
 
        /* Allocate a new session keyring for the container. This makes sure the keyring of the session
         * systemd-nspawn was invoked from doesn't leak into the container. Note that by default we block
         * keyctl() and request_key() anyway via seccomp so doing this operation isn't strictly necessary,
         * but in case people explicitly allow-list these system calls let's make sure we don't leak anything
         * into the container. */
 
        keyring = keyctl(KEYCTL_JOIN_SESSION_KEYRING, 0, 0, 0, 0);
        if (keyring == -1) {
                if (errno == ENOSYS)
                        log_debug_errno(errno, "Kernel keyring not supported, ignoring.");
                else if (ERRNO_IS_PRIVILEGE(errno))
                        log_debug_errno(errno, "Kernel keyring access prohibited, ignoring.");
                else
                        return log_error_errno(errno, "Setting up kernel keyring failed: %m");
        }
 
        return 0;
}
 
int make_run_host(const char *root) {
        int r;
 
        assert(root);
 
        r = userns_mkdir(root, "/run/host", 0755, 0, 0);
        if (r < 0)
                return log_error_errno(r, "Failed to create /run/host/: %m");
 
        return 0;
}
 
static int setup_credentials(const char *root) {
        bool world_readable = false;
        int r;
 
        if (arg_credentials.n_credentials == 0)
                return 0;
 
        /* If starting a single-process container as a non-root user, the uid will only be resolved after we
         * are inside the inner child, when credential directories and files are already read-only, so they
         * are unusable as the single process won't have access to them. We also don't have access to the
         * uid that will actually be used from here, as we are setting credentials up from the outer child.
         * In order to make them usable as requested by the configuration, make them world readable in that
         * case, as by definition there are no other processes in that case besides the one being started,
         * which is being configured to be able to access credentials, and any of its children which will
         * inherit its privileges anyway. To ensure this, also enforce (and document) that
         * --no-new-privileges is necessary for this combination to work. */
        if (arg_no_new_privileges && !isempty(arg_user) && !STR_IN_SET(arg_user, "root", "0") &&
            arg_start_mode == START_PID1)
                world_readable = true;
 
        r = make_run_host(root);
        if (r < 0)
                return r;
 
        r = userns_mkdir(root, "/run/host/credentials", world_readable ? 0777 : 0700, 0, 0);
        if (r < 0)
                return log_error_errno(r, "Failed to create /run/host/credentials: %m");
 
        _cleanup_free_ char *q = path_join(root, "/run/host/credentials");
        if (!q)
                return log_oom();
 
        r = mount_nofollow_verbose(LOG_ERR, NULL, q, "ramfs", MS_NOSUID|MS_NOEXEC|MS_NODEV, "mode=0700");
        if (r < 0)
                return r;
 
        FOREACH_ARRAY(cred, arg_credentials.credentials, arg_credentials.n_credentials) {
                _cleanup_free_ char *j = NULL;
                _cleanup_close_ int fd = -EBADF;
 
                j = path_join(q, cred->id);
                if (!j)
                        return log_oom();
 
                fd = open(j, O_CREAT|O_EXCL|O_WRONLY|O_CLOEXEC|O_NOFOLLOW, world_readable ? 0666 : 0600);
                if (fd < 0)
                        return log_error_errno(errno, "Failed to create credential file %s: %m", j);
 
                r = loop_write(fd, cred->data, cred->size);
                if (r < 0)
                        return log_error_errno(r, "Failed to write credential to file %s: %m", j);
 
                if (fchmod(fd, world_readable ? 0444 : 0400) < 0)
                        return log_error_errno(errno, "Failed to adjust access mode of %s: %m", j);
 
                if (in_child_chown())
                        if (fchown(fd, arg_uid_shift, arg_uid_shift) < 0)
                                return log_error_errno(errno, "Failed to adjust ownership of %s: %m", j);
        }
 
        if (chmod(q, world_readable ? 0555 : 0500) < 0)
                return log_error_errno(errno, "Failed to adjust access mode of %s: %m", q);
 
        r = userns_lchown(q, 0, 0);
        if (r < 0)
                return r;
 
        /* Make both mount and superblock read-only now */
        r = mount_nofollow_verbose(LOG_ERR, NULL, q, NULL, MS_REMOUNT|MS_BIND|MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV, NULL);
        if (r < 0)
                return r;
 
        return mount_nofollow_verbose(LOG_ERR, NULL, q, NULL, MS_REMOUNT|MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV, "mode=0500");
}
 
static int setup_kmsg_fifo(const char *directory) {
        _cleanup_free_ char *p = NULL;
 
        assert(directory);
 
        p = path_join(directory, "/run/host/proc-kmsg");
        if (!p)
                return log_oom();
 
        BLOCK_WITH_UMASK(0000);
 
        if (mkfifo(p, 0600) < 0)
                return log_error_errno(errno, "mkfifo() for /run/host/proc-kmsg failed: %m");
 
        return userns_lchown(p, 0, 0);
}
 
static int setup_kmsg(int fd_inner_socket) {
        _cleanup_close_ int fd = -EBADF;
        int r;
 
        assert(fd_inner_socket >= 0);
 
        /* We bind mount the kmsg FIFO (created in the outer child) to /proc/kmsg. While FIFOs on the reading
         * side behave very similar to /proc/kmsg, their writing side behaves differently from /dev/kmsg in
         * that writing blocks when nothing is reading. In order to avoid any problems with containers
         * deadlocking due to this we simply make /dev/kmsg unavailable to the container. */
 
        r = mount_nofollow_verbose(LOG_ERR, "/run/host/proc-kmsg", "/proc/kmsg", NULL, MS_BIND, NULL);
        if (r < 0)
                return r;
 
        fd = open("/run/host/proc-kmsg", O_RDWR|O_NONBLOCK|O_CLOEXEC);
        if (fd < 0)
                return log_error_errno(errno, "Failed to open fifo: %m");
 
        /* NB: We intentionally do not unlink the backing FIFO. See setup_boot_id_file() for details. */
 
        /* Store away the fd in the socket, so that it stays open as long as we run the child */
        r = send_one_fd(fd_inner_socket, fd, 0);
        if (r < 0)
                return log_error_errno(r, "Failed to send FIFO fd: %m");
 
        return 0;
}
 
struct ExposeArgs {
        union in_addr_union address4;
        union in_addr_union address6;
        sd_netlink *nfnl;
};
 
static int on_address_change(sd_netlink *rtnl, sd_netlink_message *m, void *userdata) {
        struct ExposeArgs *args = ASSERT_PTR(userdata);
 
        assert(rtnl);
        assert(m);
 
        (void) expose_port_execute(rtnl, args->nfnl, arg_expose_ports, AF_INET, &args->address4);
        (void) expose_port_execute(rtnl, args->nfnl, arg_expose_ports, AF_INET6, &args->address6);
        return 0;
}
 
static int setup_hostname(void) {
        int r;
 
        if ((arg_clone_ns_flags & CLONE_NEWUTS) == 0)
                return 0;
 
        r = sethostname_idempotent(arg_hostname ?: arg_machine);
        if (r < 0)
                return log_error_errno(r, "Failed to set hostname: %m");
 
        return 0;
}
 
static int setup_journal(const char *directory, uid_t uid_shift, uid_t uid_range) {
        _cleanup_free_ char *d = NULL;
        sd_id128_t this_id;
        bool try;
        int r;
 
        /* Don't link journals in ephemeral mode */
        if (arg_ephemeral)
                return 0;
 
        if (arg_link_journal == LINK_NO)
                return 0;
 
        try = arg_link_journal_try || arg_link_journal == LINK_AUTO;
 
        r = sd_id128_get_machine(&this_id);
        if (r < 0)
                return log_error_errno(r, "Failed to retrieve machine ID: %m");
 
        if (sd_id128_equal(arg_uuid, this_id)) {
                log_full(try ? LOG_WARNING : LOG_ERR,
                         "Host and machine ids are equal (%s): refusing to link journals", SD_ID128_TO_STRING(arg_uuid));
                if (try)
                        return 0;
                return -EEXIST;
        }
 
        FOREACH_STRING(dirname, "/var", "/var/log", "/var/log/journal") {
                r = userns_mkdir(directory, dirname, 0755, 0, 0);
                if (r < 0) {
                        bool ignore = r == -EROFS && try;
                        log_full_errno(ignore ? LOG_DEBUG : LOG_ERR, r,
                                       "Failed to create %s%s: %m", dirname, ignore ? ", ignoring" : "");
                        return ignore ? 0 : r;
                }
        }
 
        _cleanup_free_ char *p = path_join("/var/log/journal/", SD_ID128_TO_STRING(arg_uuid));
        if (!p)
                return log_oom();
 
        _cleanup_free_ char *q = path_join(directory, p);
        if (!q)
                return log_oom();
 
        if (path_is_mount_point(p) > 0) {
                if (try)
                        return 0;
 
                return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
                                       "%s: already a mount point, refusing to use for journal", p);
        }
 
        if (path_is_mount_point(q) > 0) {
                if (try)
                        return 0;
 
                return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
                                       "%s: already a mount point, refusing to use for journal", q);
        }
 
        r = readlink_and_make_absolute(p, &d);
        if (r >= 0) {
                if (IN_SET(arg_link_journal, LINK_GUEST, LINK_AUTO) &&
                    path_equal(d, q)) {
 
                        r = userns_mkdir(directory, p, 0755, 0, 0);
                        if (r < 0)
                                log_warning_errno(r, "Failed to create directory %s: %m", q);
                        return 0;
                }
 
                if (unlink(p) < 0)
                        return log_error_errno(errno, "Failed to remove symlink %s: %m", p);
        } else if (r == -EINVAL) {
 
                if (arg_link_journal == LINK_GUEST &&
                    rmdir(p) < 0) {
 
                        if (errno == ENOTDIR) {
                                log_error("%s already exists and is neither a symlink nor a directory", p);
                                return r;
                        } else
                                return log_error_errno(errno, "Failed to remove %s: %m", p);
                }
        } else if (r != -ENOENT)
                return log_error_errno(r, "readlink(%s) failed: %m", p);
 
        if (arg_link_journal == LINK_GUEST) {
 
                if (symlink(q, p) < 0) {
                        if (try) {
                                log_debug_errno(errno, "Failed to symlink %s to %s, skipping journal setup: %m", q, p);
                                return 0;
                        } else
                                return log_error_errno(errno, "Failed to symlink %s to %s: %m", q, p);
                }
 
                r = userns_mkdir(directory, p, 0755, 0, 0);
                if (r < 0)
                        log_warning_errno(r, "Failed to create directory %s: %m", q);
                return 0;
        }
 
        if (arg_link_journal == LINK_HOST) {
                /* don't create parents here — if the host doesn't have
                 * permanent journal set up, don't force it here */
 
                r = RET_NERRNO(mkdir(p, 0755));
                if (r < 0 && r != -EEXIST) {
                        if (try) {
                                log_debug_errno(r, "Failed to create %s, skipping journal setup: %m", p);
                                return 0;
                        } else
                                return log_error_errno(r, "Failed to create %s: %m", p);
                }
 
        } else if (access(p, F_OK) < 0)
                return 0;
 
        if (dir_is_empty(q, /* ignore_hidden_or_backup= */ false) == 0)
                log_warning("%s is not empty, proceeding anyway.", q);
 
        r = userns_mkdir(directory, p, 0755, 0, 0);
        if (r < 0)
                return log_error_errno(r, "Failed to create %s: %m", q);
 
        return mount_custom(
                        directory,
                        &(CustomMount) {
                                .type = CUSTOM_MOUNT_BIND,
                                .options = (char*) (uid_is_valid(uid_shift) ? "rootidmap" : NULL),
                                .source = p,
                                .destination = p,
                                .destination_uid = UID_INVALID,
                        },
                        /* n= */ 1,
                        uid_shift,
                        uid_range,
                        arg_selinux_apifs_context,
                        MOUNT_NON_ROOT_ONLY);
}
 
static int drop_capabilities(uid_t uid) {
        CapabilityQuintet q;
 
        /* Let's initialize all five capability sets to something valid. If the quintet was configured via
         * OCI use that, but fill in missing bits. If it wasn't then derive the quintet in full from
         * arg_caps_retain. */
 
        if (capability_quintet_is_set(&arg_full_capabilities)) {
                q = arg_full_capabilities;
 
                if (q.bounding == UINT64_MAX)
                        q.bounding = uid == 0 ? arg_caps_retain : 0;
 
                if (q.effective == UINT64_MAX)
                        q.effective = uid == 0 ? q.bounding : 0;
 
                if (q.inheritable == UINT64_MAX)
                        q.inheritable = uid == 0 ? q.bounding : arg_caps_ambient;
 
                if (q.permitted == UINT64_MAX)
                        q.permitted = uid == 0 ? q.bounding : arg_caps_ambient;
 
                if (q.ambient == UINT64_MAX)
                        q.ambient = arg_caps_ambient;
 
                if (capability_quintet_mangle(&q))
                        return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Cannot set capabilities that are not in the current bounding set.");
 
        } else {
                q = (CapabilityQuintet) {
                        .bounding = arg_caps_retain,
                        .effective = uid == 0 ? arg_caps_retain : 0,
                        .inheritable = uid == 0 ? arg_caps_retain : arg_caps_ambient,
                        .permitted = uid == 0 ? arg_caps_retain : arg_caps_ambient,
                        .ambient = arg_caps_ambient,
                };
 
                /* If we're not using OCI, proceed with mangled capabilities (so we don't error out)
                 * in order to maintain the same behavior as systemd < 242. */
                if (capability_quintet_mangle(&q))
                        log_full(arg_quiet ? LOG_DEBUG : LOG_WARNING,
                                 "Some capabilities will not be set because they are not in the current bounding set.");
 
        }
 
        return capability_quintet_enforce(&q);
}
 
static int reset_audit_loginuid(void) {
        _cleanup_free_ char *p = NULL;
        int r;
 
        if ((arg_clone_ns_flags & CLONE_NEWPID) == 0)
                return 0;
 
        /* if we are in managed userns mode, then we are already in our userns, hence we cannot reset the
         * loginuid anyway, hence don't bother */
        if (arg_userns_mode == USER_NAMESPACE_MANAGED)
                return 0;
 
        r = read_virtual_file("/proc/self/loginuid", SIZE_MAX, &p, /* ret_size= */ NULL);
        if (r == -ENOENT)
                return 0;
        if (r < 0)
                return log_error_errno(r, "Failed to read /proc/self/loginuid: %m");
 
        /* Already reset? */
        if (streq(p, "4294967295"))
                return 0;
 
        r = write_string_file("/proc/self/loginuid", "4294967295", WRITE_STRING_FILE_DISABLE_BUFFER);
        if (r < 0)
                return log_error_errno(r, "Failed to reset audit login UID: %m");
 
        return 0;
}
 
static int mount_tunnel_dig(const char *root) {
        int r;
 
        if (arg_userns_mode == USER_NAMESPACE_MANAGED) {
                log_debug("Not digging mount tunnel, because running in managed user namespace mode.");
                return 0;
        }
 
        (void) mkdir_p("/run/systemd/nspawn/", 0755);
        (void) mkdir_p("/run/systemd/nspawn/propagate", 0600);
        _cleanup_free_ char *p = path_join("/run/systemd/nspawn/propagate/", arg_machine);
        if (!p)
                return log_oom();
 
        (void) mkdir_p(p, 0600);
 
        r = make_run_host(root);
        if (r < 0)
                return r;
 
        r = userns_mkdir(root, NSPAWN_MOUNT_TUNNEL, 0600, 0, 0);
        if (r < 0)
                return log_error_errno(r, "Failed to create "NSPAWN_MOUNT_TUNNEL": %m");
 
        _cleanup_free_ char *q = path_join(root, NSPAWN_MOUNT_TUNNEL);
        if (!q)
                return log_oom();
 
        r = mount_nofollow_verbose(LOG_ERR, p, q, NULL, MS_BIND, NULL);
        if (r < 0)
                return r;
 
        r = mount_nofollow_verbose(LOG_ERR, NULL, q, NULL, MS_BIND|MS_REMOUNT|MS_RDONLY, NULL);
        if (r < 0)
                return r;
 
        return 0;
}
 
static int mount_tunnel_open(void) {
        int r;
 
        if (arg_userns_mode == USER_NAMESPACE_MANAGED) {
                log_debug("Not opening up mount tunnel, because running in managed user namespace mode.");
                return 0;
        }
 
        r = mount_follow_verbose(LOG_ERR, NULL, NSPAWN_MOUNT_TUNNEL, NULL, MS_SLAVE, NULL);
        if (r < 0)
                return r;
 
        return 0;
}
 
static int setup_machine_id(const char *directory) {
        int r;
 
        /* If the UUID in the container is already set, then that's what counts, and we use. If it isn't set, and the
         * caller passed --uuid=, then we'll pass it in the $container_uuid env var to PID 1 of the container. The
         * assumption is that PID 1 will then write it to /etc/machine-id to make it persistent. If --uuid= is not
         * passed we generate a random UUID, and pass it via $container_uuid. In effect this means that /etc/machine-id
         * in the container and our idea of the container UUID will always be in sync (at least if PID 1 in the
         * container behaves nicely). */
 
        r = id128_get_machine(directory, &arg_uuid);
        if (ERRNO_IS_NEG_MACHINE_ID_UNSET(r)) {
                /* If the file is missing, empty, or uninitialized, we don't mind */
                if (sd_id128_is_null(arg_uuid)) {
                        r = sd_id128_randomize(&arg_uuid);
                        if (r < 0)
                                return log_error_errno(r, "Failed to acquire randomized machine UUID: %m");
                }
        } else if (r < 0)
                return log_error_errno(r, "Failed to read machine ID from container image: %m");
 
        return 0;
}
 
static int setup_varlink_socket(const char *directory, const char *name) {
        int r;
 
        assert(directory);
 
        if (arg_delegate_container_ranges == 0)
                return 0;
 
        r = make_run_host(directory);
        if (r < 0)
                return r;
 
        _cleanup_free_ char *src = path_join("/run/systemd", name);
        if (!src)
                return log_oom();
 
        _cleanup_free_ char *dest = path_join(directory, "/run/host", name);
        if (!dest)
                return log_oom();
 
        r = touch(dest);
        if (r < 0)
                return log_error_errno(r, "Failed to create %s: %m", dest);
 
        r = userns_lchown(dest, 0, 0);
        if (r < 0)
                return log_error_errno(r, "Failed to chown %s: %m", dest);
 
        return mount_nofollow_verbose(
                        LOG_ERR,
                        src,
                        dest,
                        /* fstype= */ NULL,
                        MS_BIND|MS_RDONLY,
                        /* options= */ NULL);
}
 
static int recursive_chown(const char *directory, uid_t shift, uid_t range) {
        int r;
 
        assert(directory);
 
        if (arg_userns_mode == USER_NAMESPACE_NO || arg_userns_ownership != USER_NAMESPACE_OWNERSHIP_CHOWN)
                return 0;
 
        r = path_patch_uid(directory, arg_uid_shift, arg_uid_range);
        if (r == -EOPNOTSUPP)
                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.");
        if (r == -EBADE)
                return log_error_errno(r, "Upper 16 bits of root directory UID and GID do not match.");
        if (r < 0)
                return log_error_errno(r, "Failed to adjust UID/GID shift of OS tree: %m");
        if (r == 0)
                log_debug("Root directory of image is already owned by the right UID/GID range, skipping recursive chown operation.");
        else
                log_debug("Patched directory tree to match UID/GID range.");
 
        return r;
}
 
/*
 * Return values:
 * < 0 : pidref_wait_for_terminate() failed to get the state of the
 *       container, the container was terminated by a signal, or
 *       failed for an unknown reason.  No change is made to the
 *       container argument.
 * > 0 : The program executed in the container terminated with an
 *       error.  The exit code of the program executed in the
 *       container is returned.  The container argument has been set
 *       to CONTAINER_TERMINATED.
 *   0 : The container is being rebooted, has been shut down or exited
 *       successfully.  The container argument has been set to either
 *       CONTAINER_TERMINATED or CONTAINER_REBOOTED.
 *
 * That is, success is indicated by a return value of zero, and an
 * error is indicated by a non-zero value.
 */
static int wait_for_container(PidRef *pid, ContainerStatus *container) {
        siginfo_t status;
        int r;
 
        assert(pidref_is_set(pid));
        assert(container);
 
        r = pidref_wait_for_terminate(pid, &status);
        if (r < 0)
                return log_warning_errno(r, "Failed to wait for container: %m");
 
        pidref_done(pid);
 
        switch (status.si_code) {
 
        case CLD_EXITED:
                if (status.si_status == 0)
                        log_full(arg_quiet ? LOG_DEBUG : LOG_INFO, "Container %s exited successfully.", arg_machine);
                else
                        log_full(arg_quiet ? LOG_DEBUG : LOG_INFO, "Container %s failed with error code %i.", arg_machine, status.si_status);
 
                *container = CONTAINER_TERMINATED;
                return status.si_status;
 
        case CLD_KILLED:
                if (status.si_status == SIGINT) {
                        log_full(arg_quiet ? LOG_DEBUG : LOG_INFO, "Container %s has been shut down.", arg_machine);
                        *container = CONTAINER_TERMINATED;
                        return 0;
 
                } else if (status.si_status == SIGHUP) {
                        log_full(arg_quiet ? LOG_DEBUG : LOG_INFO, "Container %s is being rebooted.", arg_machine);
                        *container = CONTAINER_REBOOTED;
                        return 0;
                }
 
                _fallthrough_;
        case CLD_DUMPED:
                return log_error_errno(SYNTHETIC_ERRNO(EIO),
                                       "Container %s terminated by signal %s.", arg_machine, signal_to_string(status.si_status));
 
        default:
                return log_error_errno(SYNTHETIC_ERRNO(EIO),
                                       "Container %s failed due to unknown reason.", arg_machine);
        }
}
 
static int on_orderly_shutdown(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
        PidRef *pid = userdata;
 
        assert(si);
 
        if (pidref_is_set(pid))
                if (pidref_kill(pid, arg_kill_signal) >= 0) {
                        log_info("Trying to halt container by sending SIG%s to container PID 1. Send SIG%s again to trigger immediate termination.",
                                 signal_to_string(arg_kill_signal), signal_to_string(si->ssi_signo));
                        sd_event_source_set_userdata(s, NULL);
                        sd_notify(/* unset_environment= */ false, NOTIFY_STOPPING_MESSAGE);
                        return 0;
                }
 
        log_debug("Got %s, exiting.", signal_to_string(si->ssi_signo));
 
        sd_event_exit(sd_event_source_get_event(s), 0);
        return 0;
}
 
static int on_sigchld(sd_event_source *s, const struct signalfd_siginfo *ssi, void *userdata) {
 
        assert(s);
        assert(ssi);
 
        PidRef *pid = ASSERT_PTR(userdata);
        for (;;) {
                siginfo_t si = {};
 
                if (waitid(P_ALL, 0, &si, WNOHANG|WNOWAIT|WEXITED) < 0)
                        return log_error_errno(errno, "Failed to waitid(): %m");
                if (si.si_pid == 0) /* No pending children. */
                        break;
                if (si.si_pid == pid->pid) {
                        /* The main process we care for has exited. Return from
                         * signal handler but leave the zombie. */
                        sd_event_exit(sd_event_source_get_event(s), 0);
                        break;
                }
 
                /* Reap all other children. */
                (void) waitid(P_PID, si.si_pid, &si, WNOHANG|WEXITED);
        }
 
        return 0;
}
 
static int on_request_stop(sd_bus_message *m, void *userdata, sd_bus_error *error) {
        PidRef *pid = ASSERT_PTR(userdata);
 
        assert(m);
 
        if (arg_kill_signal > 0) {
                log_info("Container termination requested. Attempting to halt container.");
                (void) pidref_kill(pid, arg_kill_signal);
        } else {
                log_info("Container termination requested. Exiting.");
                sd_event_exit(sd_bus_get_event(sd_bus_message_get_bus(m)), 0);
        }
 
        return 0;
}
 
static int pick_paths(void) {
        int r;
 
        if (arg_directory) {
                _cleanup_(pick_result_done) PickResult result = PICK_RESULT_NULL;
                PickFilter filter = *pick_filter_image_dir;
 
                filter.architecture = arg_architecture;
 
                r = path_pick_update_warn(
                                &arg_directory,
                                &filter,
                                /* n_filters= */ 1,
                                PICK_ARCHITECTURE|PICK_TRIES,
                                &result);
                if (r < 0) {
                        /* Accept ENOENT here so that the --template= logic can work */
                        if (r != -ENOENT)
                                return r;
                } else
                        arg_architecture = result.architecture;
        }
 
        if (arg_image) {
                _cleanup_(pick_result_done) PickResult result = PICK_RESULT_NULL;
                PickFilter filter = *pick_filter_image_raw;
 
                filter.architecture = arg_architecture;