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 1001–2000 of 6,878

                        arg_settings_mask |= SETTING_NETWORK;
                        break;
                }
 
                OPTION_LONG("network-namespace-path", "PATH",
                            "Set network namespace to the one represented by the specified kernel namespace file node"):
                        r = parse_path_argument(opts.arg, false, &arg_network_namespace_path);
                        if (r < 0)
                                return r;
                        arg_settings_mask |= SETTING_NETWORK;
                        break;
 
                OPTION('p', "port", "[PROTOCOL:]HOSTPORT[:CONTAINERPORT]",
                       "Expose a container IP port on the host"):
                        r = expose_port_parse(&arg_expose_ports, opts.arg);
                        if (r == -EEXIST)
                                return log_error_errno(r, "Duplicate port specification: %s", opts.arg);
                        if (r < 0)
                                return log_error_errno(r, "Failed to parse host port %s: %m", opts.arg);
                        arg_settings_mask |= SETTING_EXPOSE_PORTS;
                        break;
 
                OPTION_GROUP("Security"): {}
 
                OPTION_LONG("capability", "CAP",
                            "In addition to the default, retain specified capability"): {}
                OPTION_LONG("drop-capability", "CAP",
                            "Drop the specified capability from the default set"): {
                        uint64_t m;
                        r = parse_capability_spec(opts.arg, &m);
                        if (r <= 0)
                                return r;
 
                        if (streq(opts.opt->long_code, "capability"))
                                plus |= m;
                        else
                                minus |= m;
                        arg_settings_mask |= SETTING_CAPABILITY;
                        break;
                }
 
                OPTION_LONG("ambient-capability", "CAP",
                            "Sets the specified capability for the started process"): {
                        uint64_t m;
                        r = parse_capability_spec(opts.arg, &m);
                        if (r <= 0)
                                return r;
                        arg_caps_ambient |= m;
                        arg_settings_mask |= SETTING_CAPABILITY;
                        break;
                }
 
                OPTION_LONG("no-new-privileges", "BOOL",
                            "Set PR_SET_NO_NEW_PRIVS flag for container payload"):
                        r = parse_boolean_argument("--no-new-privileges=", opts.arg, &arg_no_new_privileges);
                        if (r < 0)
                                return r;
                        arg_settings_mask |= SETTING_NO_NEW_PRIVILEGES;
                        break;
 
                OPTION_LONG("system-call-filter", "LIST|~LIST",
                            "Permit/prohibit specific system calls"): {
                        bool negative;
                        const char *items;
 
                        negative = opts.arg[0] == '~';
                        items = negative ? opts.arg + 1 : opts.arg;
 
                        for (;;) {
                                _cleanup_free_ char *word = NULL;
 
                                r = extract_first_word(&items, &word, NULL, 0);
                                if (r == 0)
                                        break;
                                if (r == -ENOMEM)
                                        return log_oom();
                                if (r < 0)
                                        return log_error_errno(r, "Failed to parse system call filter: %m");
 
                                if (negative)
                                        r = strv_extend(&arg_syscall_deny_list, word);
                                else
                                        r = strv_extend(&arg_syscall_allow_list, word);
                                if (r < 0)
                                        return log_oom();
                        }
                        arg_settings_mask |= SETTING_SYSCALL_FILTER;
                        break;
                }
 
                OPTION_LONG("restrict-address-families", "LIST", "Restrict socket address families to the given allowlist"):
                        r = parse_address_families(opts.arg, &arg_restrict_address_families, &arg_restrict_address_families_is_allowlist);
                        if (r < 0)
                                return log_error_errno(r, "Failed to parse --restrict-address-families= argument: %s", opts.arg);
 
                        arg_settings_mask |= SETTING_RESTRICT_ADDRESS_FAMILIES;
                        break;
 
                OPTION('Z', "selinux-context", "SECLABEL",
                       "Set the SELinux security context to be used by processes in the container"):
                        arg_selinux_context = opts.arg;
                        break;
 
                OPTION('L', "selinux-apifs-context", "SECLABEL",
                       "Set the SELinux security context to be used by API/tmpfs file systems in the container"):
                        arg_selinux_apifs_context = opts.arg;
                        break;
 
                OPTION_GROUP("Resources"): {}
 
                OPTION_LONG("rlimit", "NAME=LIMIT", "Set a resource limit for the payload"): {
                        const char *eq;
                        _cleanup_free_ char *name = NULL;
                        int rl;
 
                        if (streq(opts.arg, "help"))
                                return DUMP_STRING_TABLE(rlimit, int, _RLIMIT_MAX);
 
                        eq = strchr(opts.arg, '=');
                        if (!eq)
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                                       "--rlimit= expects an '=' assignment.");
 
                        name = strndup(opts.arg, eq - opts.arg);
                        if (!name)
                                return log_oom();
 
                        rl = rlimit_from_string_harder(name);
                        if (rl < 0)
                                return log_error_errno(rl, "Unknown resource limit: %s", name);
 
                        if (!arg_rlimit[rl]) {
                                arg_rlimit[rl] = new0(struct rlimit, 1);
                                if (!arg_rlimit[rl])
                                        return log_oom();
                        }
 
                        r = rlimit_parse(rl, eq + 1, arg_rlimit[rl]);
                        if (r < 0)
                                return log_error_errno(r, "Failed to parse resource limit: %s", eq + 1);
 
                        arg_settings_mask |= SETTING_RLIMIT_FIRST << rl;
                        break;
                }
 
                OPTION_LONG("oom-score-adjust", "VALUE", "Adjust the OOM score value for the payload"):
                        r = parse_oom_score_adjust(opts.arg, &arg_oom_score_adjust);
                        if (r < 0)
                                return log_error_errno(r, "Failed to parse --oom-score-adjust= parameter: %s", opts.arg);
                        arg_oom_score_adjust_set = true;
                        arg_settings_mask |= SETTING_OOM_SCORE_ADJUST;
                        break;
 
                OPTION_LONG("cpu-affinity", "CPUS", "Adjust the CPU affinity of the container"): {
                        CPUSet cpuset;
 
                        r = parse_cpu_set(opts.arg, &cpuset);
                        if (r < 0)
                                return log_error_errno(r, "Failed to parse CPU affinity mask %s: %m", opts.arg);
 
                        cpu_set_done_and_replace(arg_cpu_set, cpuset);
                        arg_settings_mask |= SETTING_CPU_AFFINITY;
                        break;
                }
 
                OPTION_LONG("personality", "ARCH", "Pick personality for this container"):
                        arg_personality = personality_from_string(opts.arg);
                        if (arg_personality == PERSONALITY_INVALID)
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                                       "Unknown or unsupported personality '%s'.", opts.arg);
                        arg_settings_mask |= SETTING_PERSONALITY;
                        break;
 
                OPTION_GROUP("Integration"): {}
 
                OPTION_LONG("resolv-conf", "MODE", "Select mode of /etc/resolv.conf initialization"):
                        if (streq(opts.arg, "help"))
                                return DUMP_STRING_TABLE(resolv_conf_mode, ResolvConfMode, _RESOLV_CONF_MODE_MAX);
 
                        arg_resolv_conf = resolv_conf_mode_from_string(opts.arg);
                        if (arg_resolv_conf < 0)
                                return log_error_errno(arg_resolv_conf,
                                                       "Failed to parse /etc/resolv.conf mode: %s", opts.arg);
                        arg_settings_mask |= SETTING_RESOLV_CONF;
                        break;
 
                OPTION_LONG("timezone", "MODE", "Select mode of /etc/localtime initialization"):
                        if (streq(opts.arg, "help"))
                                return DUMP_STRING_TABLE(timezone_mode, TimezoneMode, _TIMEZONE_MODE_MAX);
 
                        arg_timezone = timezone_mode_from_string(opts.arg);
                        if (arg_timezone < 0)
                                return log_error_errno(arg_timezone,
                                                       "Failed to parse /etc/localtime mode: %s", opts.arg);
                        arg_settings_mask |= SETTING_TIMEZONE;
                        break;
 
                OPTION_LONG("link-journal", "MODE",
                            "Link up guest journal, one of no, auto, guest, host, try-guest, try-host"):
                        r = parse_link_journal(opts.arg, &arg_link_journal, &arg_link_journal_try);
                        if (r < 0)
                                return log_error_errno(r, "Failed to parse link journal mode %s", opts.arg);
                        arg_settings_mask |= SETTING_LINK_JOURNAL;
                        break;
 
                OPTION_SHORT('j', NULL, "Equivalent to --link-journal=try-guest"):
                        arg_link_journal = LINK_GUEST;
                        arg_link_journal_try = true;
                        arg_settings_mask |= SETTING_LINK_JOURNAL;
                        break;
 
                OPTION_LONG("forward-journal", "FILE|DIR", "Forward the container's journal to the host"):
                        r = parse_path_argument(opts.arg, /* suppress_root= */ false, &arg_forward_journal);
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_LONG("forward-journal-max-use", "BYTES", "Maximum disk space for forwarded journal"):
                        r = parse_size(opts.arg, 1024, &arg_forward_journal_max_use);
                        if (r < 0)
                                return log_error_errno(r, "Failed to parse --forward-journal-max-use= value: %s", opts.arg);
                        break;
 
                OPTION_LONG("forward-journal-keep-free", "BYTES", "Minimum disk space to keep free"):
                        r = parse_size(opts.arg, 1024, &arg_forward_journal_keep_free);
                        if (r < 0)
                                return log_error_errno(r, "Failed to parse --forward-journal-keep-free= value: %s", opts.arg);
                        break;
 
                OPTION_LONG("forward-journal-max-file-size", "BYTES", "Maximum size of individual journal files"):
                        r = parse_size(opts.arg, 1024, &arg_forward_journal_max_file_size);
                        if (r < 0)
                                return log_error_errno(r, "Failed to parse --forward-journal-max-file-size= value: %s", opts.arg);
                        break;
 
                OPTION_LONG("forward-journal-max-files", "N", "Maximum number of journal files to keep"):
                        r = safe_atou64(opts.arg, &arg_forward_journal_max_files);
                        if (r < 0)
                                return log_error_errno(r, "Failed to parse --forward-journal-max-files= value: %s", opts.arg);
                        break;
 
                OPTION_GROUP("Mounts"): {}
 
                OPTION_LONG("bind", "PATH[:PATH[:OPTIONS]]",
                            "Bind mount a file or directory from the host into the container"): {}
                OPTION_LONG("bind-ro", "PATH[:PATH[:OPTIONS]]",
                            "Similar, but creates a read-only bind mount"):
                        r = bind_mount_parse(&arg_custom_mounts, &arg_n_custom_mounts, opts.arg,
                                             streq(opts.opt->long_code, "bind-ro"));
                        if (r < 0)
                                return log_error_errno(r, "Failed to parse --bind(-ro)= argument %s: %m", opts.arg);
                        arg_settings_mask |= SETTING_CUSTOM_MOUNTS;
                        break;
 
                OPTION_LONG("inaccessible", "PATH",
                            "Over-mount file node with inaccessible node to mask it"):
                        r = inaccessible_mount_parse(&arg_custom_mounts, &arg_n_custom_mounts, opts.arg);
                        if (r < 0)
                                return log_error_errno(r, "Failed to parse --inaccessible= argument %s: %m", opts.arg);
                        arg_settings_mask |= SETTING_CUSTOM_MOUNTS;
                        break;
 
                OPTION_LONG("tmpfs", "PATH:[OPTIONS]",
                            "Mount an empty tmpfs to the specified directory"):
                        r = tmpfs_mount_parse(&arg_custom_mounts, &arg_n_custom_mounts, opts.arg);
                        if (r < 0)
                                return log_error_errno(r, "Failed to parse --tmpfs= argument %s: %m", opts.arg);
                        arg_settings_mask |= SETTING_CUSTOM_MOUNTS;
                        break;
 
                OPTION_LONG("overlay", "PATH[:PATH...]:PATH",
                            "Create an overlay mount from the host to the container"): {}
                OPTION_LONG("overlay-ro", "PATH[:PATH...]:PATH",
                            "Similar, but creates a read-only overlay mount"):
                        r = overlay_mount_parse(&arg_custom_mounts, &arg_n_custom_mounts, opts.arg,
                                                streq(opts.opt->long_code, "overlay-ro"));
                        if (r == -EADDRNOTAVAIL)
                                return log_error_errno(r, "--overlay(-ro)= needs at least two colon-separated directories specified.");
                        if (r < 0)
                                return log_error_errno(r, "Failed to parse --overlay(-ro)= argument %s: %m", opts.arg);
                        arg_settings_mask |= SETTING_CUSTOM_MOUNTS;
                        break;
 
                OPTION_LONG("bind-user", "NAME", "Bind user from host to container"):
                        if (!valid_user_group_name(opts.arg, 0))
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid user name to bind: %s", opts.arg);
                        if (strv_extend(&arg_bind_user, opts.arg) < 0)
                                return log_oom();
                        arg_settings_mask |= SETTING_BIND_USER;
                        break;
 
                OPTION_LONG("bind-user-shell", "BOOL|PATH",
                            "Configure the shell to use for --bind-user= users"): {
                        bool copy = false;
                        char *sh = NULL;
                        r = parse_user_shell(opts.arg, &sh, &copy);
                        if (r == -ENOMEM)
                                return log_oom();
                        if (r < 0)
                                return log_error_errno(r, "Invalid user shell to bind: %s", opts.arg);
 
                        free_and_replace(arg_bind_user_shell, sh);
                        arg_bind_user_shell_copy = copy;
                        arg_settings_mask |= SETTING_BIND_USER_SHELL;
                        break;
                }
 
                OPTION_LONG("bind-user-group", "GROUP",
                            "Add an auxiliary group to --bind-user= users"):
                        if (!valid_user_group_name(opts.arg, /* flags= */ 0))
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid bind user auxiliary group name: %s", opts.arg);
                        if (strv_extend(&arg_bind_user_groups, opts.arg) < 0)
                                return log_oom();
                        break;
 
                OPTION_GROUP("Input/Output"): {}
 
                OPTION_LONG("console", "MODE",
                            "Select how stdin/stdout/stderr and /dev/console are set up for the container"):
                        if (streq(opts.arg, "help"))
                                return DUMP_STRING_TABLE(console_mode, ConsoleMode, _CONSOLE_MODE_MAX);
 
                        arg_console_mode = console_mode_from_string(opts.arg);
                        if (arg_console_mode < 0)
                                return log_error_errno(arg_console_mode, "Unknown console mode: %s", opts.arg);
                        arg_settings_mask |= SETTING_CONSOLE_MODE;
                        break;
 
                OPTION('P', "pipe", NULL, "Equivalent to --console=pipe"):
                        arg_console_mode = CONSOLE_PIPE;
                        arg_settings_mask |= SETTING_CONSOLE_MODE;
                        break;
 
                OPTION_LONG("background", "COLOR", "Set ANSI color for background"):
                        r = parse_background_argument(opts.arg, &arg_background);
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_GROUP("Credentials"): {}
 
                OPTION_LONG("set-credential", "ID:VALUE",
                            "Pass a credential with literal value to container"):
                        r = machine_credential_set(&arg_credentials, opts.arg);
                        if (r < 0)
                                return r;
                        arg_settings_mask |= SETTING_CREDENTIALS;
                        break;
 
                OPTION_LONG("load-credential", "ID:PATH",
                            "Load credential to pass to container from file or AF_UNIX stream socket"):
                        r = machine_credential_load(&arg_credentials, opts.arg);
                        if (r < 0)
                                return r;
                        arg_settings_mask |= SETTING_CREDENTIALS;
                        break;
 
                OPTION_GROUP("Other"): {}
 
                OPTION_LONG("share-system", NULL, /* help= */ NULL):  /* not documented */
                        log_warning("Please do not use --share-system anymore, use $SYSTEMD_NSPAWN_SHARE_* instead.");
                        arg_clone_ns_flags = 0;
                        break;
 
                OPTION_LONG_FLAGS(OPTION_OPTIONAL_ARG, "user", "NAME", "Run in the user service manager scope"):
                        if (opts.arg)
                                /* --user=NAME is a deprecated alias for --uid=NAME */
                                log_warning("--user=NAME is deprecated, use --uid=NAME instead.");
                        else {
                                /* --user= used to require an argument (the container user to run as). It has
                                 * been repurposed to optionally set the runtime scope, with --uid= replacing
                                 * the old container user functionality. To maintain backwards compatibility
                                 * with the space-separated form (--user NAME), if the next opts.arg does not look
                                 * like an option, interpret it as a user name. */
                                const char *t = option_parser_peek_next_arg(&opts);
                                if (t && t[0] != '-') {
                                        opts.arg = option_parser_consume_next_arg(&opts);
                                        log_warning("--user NAME is deprecated, use --uid=NAME instead.");
                                }
                        }
 
                        if (opts.arg) {
                                r = free_and_strdup(&arg_user, opts.arg);
                                if (r < 0)
                                        return log_oom();
                                arg_settings_mask |= SETTING_USER;
                        } else
                                arg_runtime_scope = RUNTIME_SCOPE_USER;
                        break;
 
                OPTION_LONG("system", NULL, "Run in the system service manager scope"):
                        arg_runtime_scope = RUNTIME_SCOPE_SYSTEM;
                        break;
 
                OPTION_COMMON_INTROSPECT_CLI:
                        return introspect_cli(SD_JSON_FORMAT_OFF);
                }
        }
 
        char **args = option_parser_get_args(&opts);
        if (!strv_isempty(args)) {
                strv_free(arg_parameters);
                arg_parameters = strv_copy(args);
                if (!arg_parameters)
                        return log_oom();
 
                arg_settings_mask |= SETTING_START_MODE;
        }
 
        if (arg_ephemeral && arg_template && !arg_directory)
                /* User asked for ephemeral execution but specified --template= instead of --directory=. Semantically
                 * such an invocation makes some sense, see https://github.com/systemd/systemd/issues/3667. Let's
                 * accept this here, and silently make "--ephemeral --template=" equivalent to "--ephemeral
                 * --directory=". */
                arg_directory = TAKE_PTR(arg_template);
 
        /* Derive runtime scope from UID if not explicitly set via --user/--system */
        if (arg_runtime_scope < 0)
                arg_runtime_scope = getuid() == 0 ? RUNTIME_SCOPE_SYSTEM : RUNTIME_SCOPE_USER;
 
        if (arg_userns_mode == _USER_NAMESPACE_MODE_INVALID) {
                /* -U sets arg_userns_mode to _USER_NAMESPACE_MODE_INVALID to defer the PICK vs MANAGED
                 * resolution to here where arg_runtime_scope has its final value. */
                if (arg_runtime_scope == RUNTIME_SCOPE_USER)
                        arg_userns_mode = USER_NAMESPACE_MANAGED;
                else if (FLAGS_SET(arg_settings_mask, SETTING_USERNS))
                        arg_userns_mode = USER_NAMESPACE_PICK;
                else
                        arg_userns_mode = USER_NAMESPACE_NO;
        }
 
        if (!FLAGS_SET(arg_settings_mask, SETTING_NETWORK))
                /* Imply private networking for unprivileged operation, since kernel otherwise
                 * refuses mounting sysfs. */
                arg_private_network = arg_runtime_scope == RUNTIME_SCOPE_USER;
 
        arg_caps_retain |= plus;
        arg_caps_retain |= arg_private_network ? UINT64_C(1) << CAP_NET_ADMIN : 0;
        arg_caps_retain &= ~minus;
 
        if ((arg_forward_journal_max_use != UINT64_MAX ||
             arg_forward_journal_keep_free != UINT64_MAX ||
             arg_forward_journal_max_file_size != UINT64_MAX ||
             arg_forward_journal_max_files != UINT64_MAX) && !arg_forward_journal)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "--forward-journal-max-use=/--forward-journal-keep-free=/--forward-journal-max-file-size=/--forward-journal-max-files= require --forward-journal=.");
 
        /* Make sure to parse environment before we reset the settings mask below */
        r = parse_environment();
        if (r < 0)
                return r;
 
        /* Load all settings from .nspawn files */
        if (mask_no_settings)
                arg_settings_mask = 0;
 
        /* Don't load any settings from .nspawn files */
        if (mask_all_settings)
                arg_settings_mask = _SETTINGS_MASK_ALL;
 
        return 1;
}
 
static int verify_arguments(void) {
        int r;
 
        SET_FLAG(arg_mount_settings, MOUNT_UNMANAGED, arg_userns_mode != USER_NAMESPACE_MANAGED);
 
        /* We can mount selinuxfs only if we are privileged and can do so before userns. In managed mode we
         * have to enter the userns earlier, hence cannot do that. */
        /* SET_FLAG(arg_mount_settings, MOUNT_PRIVILEGED, arg_runtime_scope == RUNTIME_SCOPE_SYSTEM); */
        SET_FLAG(arg_mount_settings, MOUNT_PRIVILEGED, arg_userns_mode != USER_NAMESPACE_MANAGED);
 
        SET_FLAG(arg_mount_settings, MOUNT_USE_USERNS, arg_userns_mode != USER_NAMESPACE_NO);
 
        if (arg_private_network)
                SET_FLAG(arg_mount_settings, MOUNT_APPLY_APIVFS_NETNS, arg_private_network);
 
        if (arg_runtime_scope != RUNTIME_SCOPE_SYSTEM && arg_userns_mode != USER_NAMESPACE_MANAGED)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "User-scoped operation requires managed user namespaces, as otherwise no UID range can be acquired.");
 
        if (arg_userns_mode == USER_NAMESPACE_MANAGED && !arg_private_network)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Managed user namespace operation requires private networking, as otherwise /sys/ may not be mounted.");
 
        if (arg_delegate_container_ranges > 0 && arg_userns_mode != USER_NAMESPACE_MANAGED)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "--private-users-delegate= requires --private-users=managed.");
 
        if (!(arg_clone_ns_flags & CLONE_NEWPID) ||
            !(arg_clone_ns_flags & CLONE_NEWUTS)) {
                arg_register = 0;
                if (arg_start_mode != START_PID1)
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "--boot cannot be used without namespacing.");
        }
 
        if (arg_userns_ownership < 0)
                arg_userns_ownership =
                        IN_SET(arg_userns_mode, USER_NAMESPACE_PICK, USER_NAMESPACE_MANAGED) ? USER_NAMESPACE_OWNERSHIP_AUTO : USER_NAMESPACE_OWNERSHIP_OFF;
 
        if (arg_start_mode == START_BOOT && arg_kill_signal <= 0)
                arg_kill_signal = SIGRTMIN+3;
 
        if (arg_volatile_mode != VOLATILE_NO) /* Make sure all file systems contained in the image are mounted read-only if we are in volatile mode */
                arg_read_only = true;
 
        if (has_custom_root_mount(arg_custom_mounts, arg_n_custom_mounts))
                arg_read_only = true;
 
        if (!!arg_directory + !!arg_image + !!arg_mstack > 1)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "--directory=, --image= --mstack= may not be combined.");
 
        if (arg_template && (arg_image || arg_mstack))
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "--template= and --image=/--mstack= may not be combined.");
 
        if (arg_template && !(arg_directory || arg_machine))
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "--template= needs --directory= or --machine=.");
 
        if (arg_ephemeral && arg_template)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "--ephemeral and --template= may not be combined.");
 
        if (arg_ephemeral && arg_mstack)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "--ephemeral and --mstack= may not be combined.");
 
        /* Permit --ephemeral with --link-journal=try-* to satisfy principle of the least astonishment
         * (by common sense, "try" means "do not fail if not possible") */
        if (arg_ephemeral && !IN_SET(arg_link_journal, LINK_NO, LINK_AUTO) && !arg_link_journal_try)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "--ephemeral and --link-journal={host,guest} may not be combined.");
 
        if (arg_userns_mode != USER_NAMESPACE_NO && !userns_supported())
                return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "--private-users= is not supported, kernel compiled without user namespace support.");
 
        if (arg_userns_ownership == USER_NAMESPACE_OWNERSHIP_CHOWN && arg_read_only)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "--read-only and --private-users-ownership=chown may not be combined.");
 
        /* We don't support --private-users-ownership=chown together with any of the volatile modes since we
         * couldn't change the read-only part of the tree (i.e. /usr) anyway, or because it would trigger a
         * massive copy-up (in case of overlay) making the entire exercise pointless. */
        if (arg_userns_ownership == USER_NAMESPACE_OWNERSHIP_CHOWN && arg_volatile_mode != VOLATILE_NO)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "--volatile= and --private-users-ownership=chown may not be combined.");
 
        /* If --network-namespace-path is given with any other network-related option (except --private-network),
         * we need to error out, to avoid conflicts between different network options. */
        if (arg_network_namespace_path &&
                (arg_network_interfaces || arg_network_macvlan ||
                 arg_network_ipvlan || arg_network_veth_extra ||
                 arg_network_bridge || arg_network_zone ||
                 arg_network_veth))
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "--network-namespace-path= cannot be combined with other network options.");
 
        if (arg_network_bridge && arg_network_zone)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "--network-bridge= and --network-zone= may not be combined.");
 
        if (arg_userns_mode != USER_NAMESPACE_NO && (arg_mount_settings & MOUNT_APPLY_APIVFS_NETNS) && !arg_private_network)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid namespacing settings. Mounting sysfs with --private-users requires --private-network.");
 
        if (arg_userns_mode != USER_NAMESPACE_NO && !(arg_mount_settings & MOUNT_APPLY_APIVFS_RO))
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Cannot combine --private-users with read-write API VFS mounts.");
 
        if (arg_expose_ports && !arg_private_network)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Cannot use --port= without private networking.");
 
        if (arg_caps_ambient) {
                if (arg_caps_ambient == CAP_MASK_UNSET)
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "AmbientCapability= does not support the value all.");
 
                if ((arg_caps_ambient & arg_caps_retain) != arg_caps_ambient)
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "AmbientCapability= setting is not fully covered by Capability= setting.");
 
                if (arg_start_mode == START_BOOT)
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "AmbientCapability= setting is not useful for boot mode.");
        }
 
        /* Drop duplicate --bind-user= and --bind-user-group= entries */
        strv_uniq(arg_bind_user);
        strv_uniq(arg_bind_user_groups);
 
        if (arg_bind_user_shell && strv_isempty(arg_bind_user))
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Cannot use --bind-user-shell= without --bind-user=");
 
        if (!strv_isempty(arg_bind_user_groups) && strv_isempty(arg_bind_user))
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Cannot use --bind-user-group= without --bind-user=");
 
        r = custom_mount_check_all();
        if (r < 0)
                return r;
 
        if (arg_console_mode == CONSOLE_PIPE && isatty_safe(STDIN_FILENO) && isatty_safe(STDOUT_FILENO))
                log_full(arg_quiet ? LOG_DEBUG : LOG_NOTICE,
                        "Console mode 'pipe' selected, but standard input/output are connected to an interactive TTY. "
                        "Most likely you want to use 'interactive' console mode for proper interactivity and shell job control. "
                        "Proceeding anyway.");
 
        return 0;
}
 
static int split_boot_parameters(void) {
        _cleanup_strv_free_ char **kept = NULL;
        int r;
 
        /* When the kernel hands the command line to PID 1, any KEY=VALUE assignment whose KEY does not
         * contain a '.' is exported as an environment variable (with '-' replaced by '_'), rather than
         * passed as an argument. Mimic the same split here so users can pass kernel-cmdline-style
         * arguments after the container path and get the behavior they'd get on a real boot. */
 
        if (arg_start_mode != START_BOOT)
                return 0;
 
        STRV_FOREACH(p, arg_parameters) {
                _cleanup_free_ char *key = NULL, *value = NULL;
 
                if (split_pair(*p, "=", &key, &value) >= 0 && !strchr(key, '.')) {
                        string_replace_char(key, '-', '_');
 
                        if (env_name_is_valid(key) && env_value_is_valid(value)) {
                                r = strv_env_assign(&arg_setenv, key, value);
                                if (r < 0)
                                        return log_error_errno(r, "Cannot assign environment variable: %m");
 
                                arg_settings_mask |= SETTING_ENVIRONMENT;
                                continue;
                        }
                }
 
                r = strv_extend(&kept, *p);
                if (r < 0)
                        return log_oom();
        }
 
        strv_free_and_replace(arg_parameters, kept);
        return 0;
}
 
static int verify_network_interfaces_initialized(void) {
        int r;
        r = test_network_interfaces_initialized(arg_network_interfaces);
        if (r < 0)
                return r;
 
        r = test_network_interfaces_initialized(arg_network_macvlan);
        if (r < 0)
                return r;
 
        r = test_network_interfaces_initialized(arg_network_ipvlan);
        if (r < 0)
                return r;
 
        return 0;
}
 
static int in_child_chown(void) {
        /* Returns true when chown()ing inodes we create inside the outer child is required. Basically, we
         * need the chowning when we implement userns ourselves. If userns is off we don#t need to chown(),
         * obviously. And if we are in managed mode we already entered the userns, and hence don#t need to
         * manually chown either. */
        return IN_SET(arg_userns_mode, USER_NAMESPACE_PICK, USER_NAMESPACE_FIXED);
}
 
int userns_chown_at(int fd, const char *fname, uid_t uid, gid_t gid, int flags) {
        assert(fd >= 0 || fd == AT_FDCWD);
 
        if (!in_child_chown())
                return 0;
 
        if (uid == UID_INVALID && gid == GID_INVALID)
                return 0;
 
        if (uid != UID_INVALID) {
                uid += arg_uid_shift;
 
                if (uid < arg_uid_shift || uid >= arg_uid_shift + arg_uid_range)
                        return -EOVERFLOW;
        }
 
        if (gid != GID_INVALID) {
                gid += (gid_t) arg_uid_shift;
 
                if (gid < (gid_t) arg_uid_shift || gid >= (gid_t) (arg_uid_shift + arg_uid_range))
                        return -EOVERFLOW;
        }
 
        if (isempty(fname))
                flags |= AT_EMPTY_PATH;
 
        return RET_NERRNO(fchownat(fd, strempty(fname), uid, gid, flags));
}
 
int userns_lchown(const char *path, uid_t uid, gid_t gid) {
        return userns_chown_at(AT_FDCWD, path, uid, gid, AT_SYMLINK_NOFOLLOW);
}
 
int userns_mkdir(const char *root, const char *path, mode_t mode, uid_t uid, gid_t gid) {
        int r;
 
        assert(path);
 
        _cleanup_close_ int parent_fd = -EBADF;
        _cleanup_free_ char *dname = NULL;
        r = chase(path, root, CHASE_PARENT|CHASE_PREFIX_ROOT|CHASE_EXTRACT_FILENAME, &dname, &parent_fd);
        if (r < 0)
                return r;
 
        _cleanup_close_ int dir_fd = open_mkdir_at(parent_fd, dname, O_EXCL|O_CLOEXEC, mode);
        if (dir_fd == -EEXIST)
                return 0;
        if (dir_fd < 0)
                return dir_fd;
 
        return userns_chown_at(dir_fd, /* fname= */ NULL, uid, gid, AT_SYMLINK_NOFOLLOW|AT_EMPTY_PATH);
}
 
static const char *timezone_from_path(const char *path) {
        return PATH_STARTSWITH_SET(
                        path,
                        "../usr/share/zoneinfo/",
                        "/usr/share/zoneinfo/");
}
 
static bool etc_writable(void) {
        return !arg_read_only || IN_SET(arg_volatile_mode, VOLATILE_YES, VOLATILE_OVERLAY);
}
 
static int setup_timezone(const char *dest) {
        _cleanup_free_ char *p = NULL, *etc = NULL;
        const char *where, *check;
        TimezoneMode m;
        int r;
 
        assert(dest);
 
        if (IN_SET(arg_timezone, TIMEZONE_AUTO, TIMEZONE_SYMLINK)) {
                r = readlink_malloc("/etc/localtime", &p);
                if (r == -ENOENT && arg_timezone == TIMEZONE_AUTO)
                        m = etc_writable() ? TIMEZONE_DELETE : TIMEZONE_OFF;
                else if (r == -EINVAL && arg_timezone == TIMEZONE_AUTO) /* regular file? */
                        m = etc_writable() ? TIMEZONE_COPY : TIMEZONE_BIND;
                else if (r < 0) {
                        log_warning_errno(r, "Failed to read host's /etc/localtime symlink, not updating container timezone: %m");
                        /* To handle warning, delete /etc/localtime and replace it with a symbolic link to a time zone data
                         * file.
                         *
                         * Example:
                         * ln -s /usr/share/zoneinfo/UTC /etc/localtime
                         */
                        return 0;
                } else if (arg_timezone == TIMEZONE_AUTO)
                        m = etc_writable() ? TIMEZONE_SYMLINK : TIMEZONE_BIND;
                else
                        m = arg_timezone;
        } else
                m = arg_timezone;
 
        if (m == TIMEZONE_OFF)
                return 0;
 
        r = chase("/etc", dest, CHASE_PREFIX_ROOT, &etc, NULL);
        if (r < 0) {
                log_warning_errno(r, "Failed to resolve /etc path in container, ignoring: %m");
                return 0;
        }
 
        where = strjoina(etc, "/localtime");
 
        switch (m) {
 
        case TIMEZONE_DELETE:
                if (unlink(where) < 0)
                        log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_WARNING, errno, "Failed to remove '%s', ignoring: %m", where);
 
                return 0;
 
        case TIMEZONE_SYMLINK: {
                _cleanup_free_ char *q = NULL;
                const char *z, *what;
 
                z = timezone_from_path(p);
                if (!z) {
                        log_warning("/etc/localtime does not point into /usr/share/zoneinfo/, not updating container timezone.");
                        return 0;
                }
 
                r = readlink_malloc(where, &q);
                if (r >= 0 && streq_ptr(timezone_from_path(q), z))
                        return 0; /* Already pointing to the right place? Then do nothing .. */
 
                check = strjoina(dest, "/usr/share/zoneinfo/", z);
                r = chase(check, dest, 0, NULL, NULL);
                if (r < 0)
                        log_debug_errno(r, "Timezone %s does not exist (or is not accessible) in container, not creating symlink: %m", z);
                else {
                        if (unlink(where) < 0 && errno != ENOENT) {
                                log_full_errno(ERRNO_IS_FS_WRITE_REFUSED(errno) ? LOG_DEBUG : LOG_WARNING, /* Don't complain on read-only images */
                                               errno, "Failed to remove existing timezone info %s in container, ignoring: %m", where);
                                return 0;
                        }
 
                        what = strjoina("../usr/share/zoneinfo/", z);
                        if (symlink(what, where) < 0) {
                                log_full_errno(ERRNO_IS_FS_WRITE_REFUSED(errno) ? LOG_DEBUG : LOG_WARNING,
                                               errno, "Failed to correct timezone of container, ignoring: %m");
                                return 0;
                        }
 
                        break;
                }
 
                _fallthrough_;
        }
 
        case TIMEZONE_BIND: {
                _cleanup_free_ char *resolved = NULL;
                int found;
 
                found = chase(where, dest, CHASE_NONEXISTENT, &resolved, NULL);
                if (found < 0) {
                        log_warning_errno(found, "Failed to resolve /etc/localtime path in container, ignoring: %m");
                        return 0;
                }
 
                if (found == 0) /* missing? */
                        (void) touch(resolved);
 
                r = mount_nofollow_verbose(LOG_WARNING, "/etc/localtime", resolved, NULL, MS_BIND, NULL);
                if (r >= 0)
                        return mount_nofollow_verbose(LOG_ERR, NULL, resolved, NULL, MS_BIND|MS_REMOUNT|MS_RDONLY|MS_NOSUID|MS_NODEV, NULL);
 
                _fallthrough_;
        }
 
        case TIMEZONE_COPY:
                /* If mounting failed, try to copy */
                r = copy_file_atomic("/etc/localtime", where, 0644, COPY_REPLACE);
                if (r < 0) {
                        log_full_errno(ERRNO_IS_NEG_FS_WRITE_REFUSED(r) ? LOG_DEBUG : LOG_WARNING, r,
                                       "Failed to copy /etc/localtime to %s, ignoring: %m", where);
                        return 0;
                }
 
                break;
 
        default:
                assert_not_reached();
        }
 
        /* Fix permissions of the symlink or file copy we just created */
        r = userns_lchown(where, 0, 0);
        if (r < 0)
                log_warning_errno(r, "Failed to chown /etc/localtime, ignoring: %m");
 
        return 0;
}
 
static int have_resolv_conf(const char *path) {
        assert(path);
 
        if (access(path, F_OK) < 0) {
                if (errno == ENOENT)
                        return 0;
 
                return log_debug_errno(errno, "Failed to determine whether '%s' is available: %m", path);
        }
 
        return 1;
}
 
static int resolved_listening(void) {
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
        _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
        _cleanup_free_ char *dns_stub_listener_mode = NULL;
        int r;
 
        /* Check if resolved is listening */
 
        r = sd_bus_open_system(&bus);
        if (r < 0)
                return log_debug_errno(r, "Failed to open system bus: %m");
 
        r = bus_name_has_owner(bus, "org.freedesktop.resolve1", NULL);
        if (r < 0)
                return log_debug_errno(r, "Failed to check whether the 'org.freedesktop.resolve1' bus name is taken: %m");
        if (r == 0)
                return 0;
 
        r = bus_get_property_string(bus, bus_resolve_mgr, "DNSStubListener", &error, &dns_stub_listener_mode);
        if (r < 0)
                return log_debug_errno(r, "Failed to query DNSStubListener property: %s", bus_error_message(&error, r));
 
        return STR_IN_SET(dns_stub_listener_mode, "udp", "yes");
}
 
static int setup_resolv_conf(const char *dest) {
        _cleanup_free_ char *etc = NULL;
        const char *where, *what;
        ResolvConfMode m;
        int r;
 
        assert(dest);
 
        if (arg_resolv_conf == RESOLV_CONF_AUTO) {
                if (arg_private_network)
                        m = RESOLV_CONF_OFF;
                else if (have_resolv_conf(PRIVATE_STUB_RESOLV_CONF) > 0 && resolved_listening() > 0)
                        m = etc_writable() ? RESOLV_CONF_COPY_STUB : RESOLV_CONF_BIND_STUB;
                else if (have_resolv_conf("/etc/resolv.conf") > 0)
                        m = etc_writable() ? RESOLV_CONF_COPY_HOST : RESOLV_CONF_BIND_HOST;
                else
                        m = etc_writable() ? RESOLV_CONF_DELETE : RESOLV_CONF_OFF;
 
        } else
                m = arg_resolv_conf;
 
        if (m == RESOLV_CONF_OFF)
                return 0;
 
        r = chase("/etc", dest, CHASE_PREFIX_ROOT, &etc, NULL);
        if (r < 0) {
                log_warning_errno(r, "Failed to resolve /etc path in container, ignoring: %m");
                return 0;
        }
 
        where = strjoina(etc, "/resolv.conf");
 
        if (m == RESOLV_CONF_DELETE) {
                if (unlink(where) < 0)
                        log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_WARNING, errno, "Failed to remove '%s', ignoring: %m", where);
 
                return 0;
        }
 
        if (IN_SET(m, RESOLV_CONF_BIND_STATIC, RESOLV_CONF_REPLACE_STATIC, RESOLV_CONF_COPY_STATIC))
                what = PRIVATE_STATIC_RESOLV_CONF;
        else if (IN_SET(m, RESOLV_CONF_BIND_UPLINK, RESOLV_CONF_REPLACE_UPLINK, RESOLV_CONF_COPY_UPLINK))
                what = PRIVATE_UPLINK_RESOLV_CONF;
        else if (IN_SET(m, RESOLV_CONF_BIND_STUB, RESOLV_CONF_REPLACE_STUB, RESOLV_CONF_COPY_STUB))
                what = PRIVATE_STUB_RESOLV_CONF;
        else
                what = "/etc/resolv.conf";
 
        if (IN_SET(m, RESOLV_CONF_BIND_HOST, RESOLV_CONF_BIND_STATIC, RESOLV_CONF_BIND_UPLINK, RESOLV_CONF_BIND_STUB)) {
                _cleanup_free_ char *resolved = NULL;
                int found;
 
                found = chase(where, dest, CHASE_NONEXISTENT|CHASE_NOFOLLOW, &resolved, NULL);
                if (found < 0) {
                        log_warning_errno(found, "Failed to resolve /etc/resolv.conf path in container, ignoring: %m");
                        return 0;
                }
 
                if (found == 0) /* missing? */
                        (void) touch(resolved);
 
                r = mount_nofollow_verbose(LOG_WARNING, what, resolved, NULL, MS_BIND, NULL);
                if (r >= 0)
                        return mount_nofollow_verbose(LOG_ERR, NULL, resolved, NULL, MS_BIND|MS_REMOUNT|MS_RDONLY|MS_NOSUID|MS_NODEV, NULL);
 
                /* If that didn't work, let's copy the file */
        }
 
        if (IN_SET(m, RESOLV_CONF_REPLACE_HOST, RESOLV_CONF_REPLACE_STATIC, RESOLV_CONF_REPLACE_UPLINK, RESOLV_CONF_REPLACE_STUB))
                r = copy_file_atomic(what, where, 0644, COPY_REPLACE);
        else
                r = copy_file(what, where, O_TRUNC|O_NOFOLLOW, 0644, /* copy_flags= */ 0);
        if (r < 0) {
                /* If the file already exists as symlink, let's suppress the warning, under the assumption that
                 * resolved or something similar runs inside and the symlink points there.
                 *
                 * If the disk image is read-only, there's also no point in complaining.
                 */
                log_full_errno(!IN_SET(RESOLV_CONF_COPY_HOST, RESOLV_CONF_COPY_STATIC, RESOLV_CONF_COPY_UPLINK, RESOLV_CONF_COPY_STUB) &&
                               (r == -ELOOP || ERRNO_IS_NEG_FS_WRITE_REFUSED(r)) ? LOG_DEBUG : LOG_WARNING, r,
                               "Failed to copy /etc/resolv.conf to %s, ignoring: %m", where);
                return 0;
        }
 
        r = userns_lchown(where, 0, 0);
        if (r < 0)
                log_warning_errno(r, "Failed to chown /etc/resolv.conf, ignoring: %m");
 
        return 0;
}
 
static int setup_boot_id_file(const char *directory) {
        _cleanup_free_ char *p = NULL;
        sd_id128_t rnd;
        int r;
 
        assert(directory);
 
        /* Generate a new randomized boot ID, so that each boot-up of the container gets a new one. We create
         * the backing file here in the outer child already, since /run/host/ is mounted read-only by the time
         * the inner child runs. We intentionally do not unlink it: bind mounts of unlinked files cannot be
         * replicated to other mount namespaces (both the old and new mount APIs fail with ENOENT). Since
         * mount_private_apivfs() needs to replicate submounts like boot_id when setting up a fresh /proc
         * instance, the backing file must remain on disk. It lives in /run/host/ which is cleaned up on
         * shutdown anyway. */
 
        p = path_join(directory, "/run/host/proc-sys-kernel-random-boot-id");
        if (!p)
                return log_oom();
 
        r = sd_id128_randomize(&rnd);