HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/repart/repart.c

483,181 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: b40c7a91acf99c5ac898f4de16e45b142c19fa8c

Lines 10001–11000 of 11,995

 
                /* Massage the size a bit because just going by actual data used in the sparse file isn't
                 * fool-proof. */
                uint64_t heuristic = streq(p->format, "xfs") ? fsz : fsz / 2;
                fsz = round_up_size(fsz + heuristic, context->grain_size);
                fsz = MAX(partition_min_size(context, p), fsz);
 
                if (fsz > partition_max_size(context, p))
                        return log_error_errno(SYNTHETIC_ERRNO(E2BIG),
                                               "Minimal partition size of %s filesystem of partition %s exceeds configured maximum size (%s > %s)",
                                               p->format, strna(hint), FORMAT_BYTES(fsz), FORMAT_BYTES(partition_max_size(context, p)));
 
                log_info("Minimal partition size of %s filesystem of partition %s is %s",
                         p->format, strna(hint), FORMAT_BYTES(fsz));
 
                d = loop_device_unref(d);
 
                /* Erase the previous filesystem first. */
                if (ftruncate(fd, 0) < 0)
                        return log_error_errno(errno, "Failed to erase temporary file: %m");
 
                if (ftruncate(fd, fsz) < 0)
                        return log_error_errno(errno, "Failed to truncate temporary file to %s: %m", FORMAT_BYTES(fsz));
 
                if (arg_offline <= 0) {
                        r = loop_device_make(fd, O_RDWR, 0, UINT64_MAX, context->sector_size, 0, LOCK_EX, &d);
                        if (r < 0 && loop_device_error_is_fatal(p, r))
                                return log_error_errno(r, "Failed to make loopback device of %s: %m", temp);
                }
 
                r = make_filesystem(
                                d ? d->node : temp,
                                p->format,
                                strempty(p->new_label),
                                root,
                                p->fs_uuid,
                                partition_mkfs_flags(p),
                                partition_fs_sector_size(context, p),
                                p->compression,
                                p->compression_level,
                                extra_mkfs_options);
                if (r < 0)
                        return r;
 
                if (!root) {
                        assert(d);
 
                        r = partition_populate_filesystem(context, p, d->node);
                        if (r < 0)
                                return r;
                }
 
                if (fstat(fd, &st) < 0)
                        return log_error_errno(errno, "Failed to stat temporary file: %m");
 
                p->copy_blocks_path = TAKE_PTR(temp);
                p->copy_blocks_path_is_our_file = true;
                p->copy_blocks_fd = TAKE_FD(fd);
                p->copy_blocks_size = st.st_size;
        }
 
        /* Now that we've done the data partitions, do the verity hash partitions. We do these in a separate
         * step because they might depend on data generated in the previous step. */
 
        LIST_FOREACH(partitions, p, context->partitions) {
                _cleanup_(unlink_and_freep) char *temp = NULL;
                _cleanup_free_ char *hint = NULL;
                _cleanup_close_ int fd = -EBADF;
                struct stat st;
                Partition *dp;
 
                if (p->dropped)
                        continue;
 
                if (PARTITION_EXISTS(p)) /* Never format existing partitions */
                        continue;
 
                if (p->copy_blocks_fd >= 0)
                        continue;
 
                if (p->minimize == MINIMIZE_OFF)
                        continue;
 
                if (p->verity != VERITY_HASH)
                        continue;
 
                assert_se(dp = p->siblings[VERITY_DATA]);
                assert(!dp->dropped);
                assert(dp->copy_blocks_path);
 
                (void) partition_hint(p, context->node, &hint);
 
                log_info("Pre-populating verity hash data of partition %s to calculate minimal partition size",
                         strna(hint));
 
                if (!vt) {
                        r = var_tmp_dir(&vt);
                        if (r < 0)
                                return log_error_errno(r, "Could not determine temporary directory: %m");
                }
 
                r = tempfn_random_child(vt, "repart", &temp);
                if (r < 0)
                        return log_error_errno(r, "Failed to generate temporary file path: %m");
 
                fd = xopenat_full(
                                AT_FDCWD,
                                temp,
                                O_RDONLY|O_CLOEXEC|O_CREAT|O_NONBLOCK,
                                attrs & FS_NOCOW_FL ? XO_NOCOW : 0,
                                0600);
                if (fd < 0)
                        return log_error_errno(fd, "Failed to open temporary file %s: %m", temp);
 
                r = partition_format_verity_hash(context, p, temp, dp->copy_blocks_path);
                if (r < 0)
                        return r;
 
                if (fstat(fd, &st) < 0)
                        return log_error_errno(errno, "Failed to stat temporary file: %m");
 
                log_info("Minimal partition size of verity hash partition %s is %s",
                         strna(hint), FORMAT_BYTES(st.st_size));
 
                p->copy_blocks_path = TAKE_PTR(temp);
                p->copy_blocks_path_is_our_file = true;
                p->copy_blocks_fd = TAKE_FD(fd);
                p->copy_blocks_size = st.st_size;
        }
 
        return 0;
}
 
static int context_load_keys(Context *context) {
#if HAVE_OPENSSL
        int r;
 
        assert(context);
 
        if (arg_certificate) {
                if (arg_certificate_source_type == OPENSSL_CERTIFICATE_SOURCE_FILE) {
                        r = parse_path_argument(arg_certificate, /* suppress_root= */ false, &arg_certificate);
                        if (r < 0)
                                return r;
                }
 
                r = openssl_load_x509_certificate(
                                arg_certificate_source_type,
                                arg_certificate_source,
                                arg_certificate,
                                &context->certificate);
                if (r < 0)
                        return log_error_errno(r, "Failed to load X.509 certificate from %s: %m", arg_certificate);
        }
 
        if (arg_private_key) {
                if (arg_private_key_source_type == OPENSSL_KEY_SOURCE_FILE) {
                        r = parse_path_argument(arg_private_key, /* suppress_root= */ false, &arg_private_key);
                        if (r < 0)
                                return r;
                }
 
                r = openssl_load_private_key(
                                arg_private_key_source_type,
                                arg_private_key_source,
                                arg_private_key,
                                &(AskPasswordRequest) {
                                        .tty_fd = -EBADF,
                                        .id = "repart-private-key-pin",
                                        .keyring = arg_private_key,
                                        .credential = "repart.private-key-pin",
                                        .until = USEC_INFINITY,
                                        .hup_fd = -EBADF,
                                },
                                &context->private_key,
                                &context->ui);
                if (r < 0)
                        return log_error_errno(r, "Failed to load private key from %s: %m", arg_private_key);
        }
 
#endif
        return 0;
}
 
static int parse_partition_types(const char *p, GptPartitionType **partitions, size_t *n_partitions) {
        int r;
 
        assert(partitions);
        assert(n_partitions);
 
        for (;;) {
                _cleanup_free_ char *name = NULL;
                GptPartitionType type;
 
                r = extract_first_word(&p, &name, ",", EXTRACT_CUNESCAPE|EXTRACT_DONT_COALESCE_SEPARATORS);
                if (r == 0)
                        break;
                if (r < 0)
                        return log_error_errno(r, "Failed to extract partition type identifier or GUID: %s", p);
 
                r = gpt_partition_type_from_string(name, &type);
                if (r < 0)
                        return log_error_errno(r, "'%s' is not a valid partition type identifier or GUID", name);
 
                if (!GREEDY_REALLOC(*partitions, *n_partitions + 1))
                        return log_oom();
 
                (*partitions)[(*n_partitions)++] = type;
        }
 
        return 0;
}
 
static int parse_join_signature(const char *p, Set **verity_settings_map) {
        _cleanup_(verity_settings_freep) VeritySettings *verity_settings = NULL;
        _cleanup_free_ char *root_hash = NULL;
        const char *signature;
        _cleanup_(iovec_done) struct iovec content = {};
        int r;
 
        assert(p);
        assert(verity_settings_map);
 
        r = extract_first_word(&p, &root_hash, ":", 0);
        if (r < 0)
                return log_error_errno(r, "Failed to parse signature parameter '%s': %m", p);
        if (!p)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Expected hash:sig");
        if ((signature = startswith(p, "base64:"))) {
                r = unbase64mem(signature, &content.iov_base, &content.iov_len);
                if (r < 0)
                        return log_error_errno(r, "Failed to parse root hash signature '%s': %m", signature);
        } else {
                r = read_full_file(p, (char**) &content.iov_base, &content.iov_len);
                if (r < 0)
                        return log_error_errno(r, "Failed to read root hash signature file '%s': %m", p);
        }
        if (!iovec_is_set(&content))
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Empty verity signature specified.");
        if (content.iov_len > VERITY_SIG_SIZE)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Verity signatures larger than %llu are not allowed.",
                                       VERITY_SIG_SIZE);
 
        verity_settings = new(VeritySettings, 1);
        if (!verity_settings)
                return log_oom();
 
        *verity_settings = (VeritySettings) {
                .root_hash_sig = TAKE_STRUCT(content),
        };
 
        r = unhexmem(root_hash, &verity_settings->root_hash.iov_base, &verity_settings->root_hash.iov_len);
        if (r < 0)
                return log_error_errno(r, "Failed to parse root hash '%s': %m", root_hash);
        if (verity_settings->root_hash.iov_len < sizeof(sd_id128_t))
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Root hash must be at least 128-bit long: %s",
                                       root_hash);
 
        r = set_ensure_put(verity_settings_map, &verity_settings_hash_ops, verity_settings);
        if (r < 0)
                return log_error_errno(r, "Failed to add entry to hashmap: %m");
 
        TAKE_PTR(verity_settings);
 
        return 0;
}
 
static int parse_argv(int argc, char *argv[]) {
        assert(argc >= 0);
        assert(argv);
 
        OptionParser opts = { argc, argv };
        bool auto_public_key_pcr_mask = true, auto_pcrlock = true;
        int r;
 
        FOREACH_OPTION_OR_RETURN(c, &opts)
                switch (c) {
 
                OPTION_GROUP("Options"): {}
 
                OPTION_COMMON_HELP:
                        return command_print_help();
 
                OPTION_COMMON_VERSION:
                        return version();
 
                OPTION_COMMON_NO_PAGER:
                        arg_pager_flags |= PAGER_DISABLE;
                        break;
 
                OPTION_COMMON_NO_LEGEND:
                        arg_legend = false;
                        break;
 
                OPTION_GROUP("Operation"): {}
 
                OPTION_SHORT('n', NULL, "Run dry-run operation"):
                        arg_dry_run = true;
                        break;
 
                OPTION_LONG("dry-run", "BOOL",
                            "Whether to run dry-run operation"):
                        r = parse_boolean_argument("--dry-run=", opts.arg, &arg_dry_run);
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_LONG("empty", "MODE",
                            "How to handle empty disks lacking partition tables (refuse, allow, require, force, create)"):
                        if (isempty(opts.arg)) {
                                arg_empty = EMPTY_UNSET;
                                break;
                        }
 
                        arg_empty = empty_mode_from_string(opts.arg);
                        if (arg_empty < 0)
                                return log_error_errno(arg_empty, "Failed to parse --empty= parameter: %s", opts.arg);
 
                        break;
 
                OPTION_LONG("offline", "BOOL",
                            "Whether to build the image offline"):
                        r = parse_tristate_argument_with_auto("--offline=", opts.arg, &arg_offline);
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_LONG("discard", "BOOL",
                            "Whether to discard backing blocks for new partitions"):
                        r = parse_boolean_argument("--discard=", opts.arg, &arg_discard);
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_LONG("cow", "BOOL|auto",
                            "Whether to enable copy-on-write for newly created image files"):
                        r = parse_tristate_argument_with_auto("--cow=", opts.arg, &arg_cow);
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_LONG("sector-size", "SIZE",
                            "Set the logical sector size for the image"):
                        r = parse_sector_size(opts.arg, &arg_sector_size);
                        if (r < 0)
                                return r;
 
                        break;
 
                OPTION_LONG("grain-size", "BYTES",
                            "Set the grain size for partition alignment"):
                        r = parse_size(opts.arg, 1024, &arg_grain_size);
                        if (r < 0)
                                return log_error_errno(r, "Failed to parse --grain-size= parameter: %s", opts.arg);
                        if (arg_grain_size < 512 || !ISPOWEROF2(arg_grain_size))
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Grain size must be a power of 2 >= 512.");
 
                        break;
 
                OPTION_LONG("architecture", "ARCH",
                            "Set the generic architecture for the image"):
                        r = architecture_from_string(opts.arg);
                        if (r < 0)
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid architecture '%s'.", opts.arg);
 
                        arg_architecture = r;
                        break;
 
                OPTION_LONG("size", "BYTES",
                            "Grow loopback file to specified size"): {
                        uint64_t parsed, rounded;
 
                        if (streq(opts.arg, "auto")) {
                                arg_size = UINT64_MAX;
                                arg_size_auto = true;
                                break;
                        }
 
                        r = parse_size(opts.arg, 1024, &parsed);
                        if (r < 0)
                                return log_error_errno(r, "Failed to parse --size= parameter: %s", opts.arg);
 
                        rounded = round_up_size(parsed, 4096);
                        if (rounded == 0)
                                return log_error_errno(SYNTHETIC_ERRNO(ERANGE), "Specified image size too small, refusing.");
                        if (rounded == UINT64_MAX)
                                return log_error_errno(SYNTHETIC_ERRNO(ERANGE), "Specified image size too large, refusing.");
 
                        if (rounded != parsed)
                                log_warning("Specified size is not a multiple of 4096, rounding up automatically. (%" PRIu64 " %s %" PRIu64 ")",
                                            parsed, glyph(GLYPH_ARROW_RIGHT), rounded);
 
                        arg_size = rounded;
                        arg_size_auto = false;
                        break;
                }
 
                OPTION_LONG("seed", "UUID",
                            "128-bit seed UUID to derive all UUIDs from"):
                        if (isempty(opts.arg)) {
                                arg_seed = SD_ID128_NULL;
                                arg_randomize = false;
                        } else if (streq(opts.arg, "random"))
                                arg_randomize = true;
                        else {
                                r = sd_id128_from_string(opts.arg, &arg_seed);
                                if (r < 0)
                                        return log_error_errno(r, "Failed to parse seed: %s", opts.arg);
 
                                arg_randomize = false;
                        }
 
                        break;
 
                OPTION_LONG("split", "BOOL",
                            "Whether to generate split artifacts"):
                        r = parse_boolean_argument("--split=", opts.arg, NULL);
                        if (r < 0)
                                return r;
 
                        arg_split = r;
                        break;
 
                OPTION_GROUP("Output"): {}
 
                OPTION_LONG("pretty", "BOOL",
                            "Whether to show pretty summary before doing changes"):
                        r = parse_boolean_argument("--pretty=", opts.arg, NULL);
                        if (r < 0)
                                return r;
                        arg_pretty = r;
                        break;
 
                OPTION_COMMON_JSON:
                        r = parse_json_argument(opts.arg, &arg_json_format_flags);
                        if (r <= 0)
                                return r;
 
                        break;
 
                OPTION_GROUP("Factory Reset"): {}
 
                OPTION_LONG("factory-reset", "BOOL",
                            "Whether to remove data partitions before recreating them"):
                        r = parse_boolean_argument("--factory-reset=", opts.arg, NULL);
                        if (r < 0)
                                return r;
                        arg_factory_reset = r;
                        break;
 
                OPTION_LONG("can-factory-reset", NULL,
                            "Test whether factory reset is defined"):
                        arg_can_factory_reset = true;
                        break;
 
                OPTION_GROUP("Configuration & Image Control"): {}
 
                OPTION_LONG("root", "PATH",
                            "Operate relative to root path"):
                        r = parse_path_argument(opts.arg, /* suppress_root= */ false, &arg_root);
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_LONG("image", "PATH",
                            "Operate relative to image file"):
                        r = parse_path_argument(opts.arg, /* suppress_root= */ false, &arg_image);
                        if (r < 0)
                                return r;
 
                        arg_relax_copy_block_security = false;
 
                        break;
 
                OPTION_LONG("image-policy", "POLICY",
                            "Specify disk image dissection policy"):
                        r = parse_image_policy_argument(opts.arg, &arg_image_policy);
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_LONG("definitions", "DIR",
                            "Find partition definitions in specified directory"): {
                        _cleanup_free_ char *path = NULL;
                        r = parse_path_argument(opts.arg, false, &path);
                        if (r < 0)
                                return r;
                        if (strv_consume(&arg_definitions, TAKE_PTR(path)) < 0)
                                return log_oom();
                        break;
                }
 
                OPTION_LONG("list-devices", NULL,
                            "List candidate block devices to operate on"):
                        r = blockdev_list(
                                        BLOCKDEV_LIST_SHOW_SYMLINKS|
                                        BLOCKDEV_LIST_REQUIRE_PARTITION_SCANNING|
                                        BLOCKDEV_LIST_IGNORE_RAMDISK|
                                        BLOCKDEV_LIST_IGNORE_READ_ONLY,
                                        /* ret_devices= */ NULL,
                                        /* ret_n_devices= */ NULL);
                        if (r < 0)
                                return r;
 
                        return 0;
 
                OPTION_GROUP("Verity"): {}
 
                OPTION_COMMON_PRIVATE_KEY("Private key to use when generating verity roothash signatures"):
                        r = free_and_strdup_warn(&arg_private_key, opts.arg);
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_COMMON_PRIVATE_KEY_SOURCE:
                        r = parse_openssl_key_source_argument(
                                        opts.arg,
                                        &arg_private_key_source,
                                        &arg_private_key_source_type);
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_COMMON_CERTIFICATE("PEM certificate to use when generating verity roothash signatures"):
                        r = free_and_strdup_warn(&arg_certificate, opts.arg);
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_COMMON_CERTIFICATE_SOURCE:
                        r = parse_openssl_certificate_source_argument(
                                        opts.arg,
                                        &arg_certificate_source,
                                        &arg_certificate_source_type);
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_LONG("join-signature", "HASH:SIG",
                            "Specify root hash and pkcs7 signature of root hash for verity as a tuple of "
                            "hex-encoded hash and a DER-encoded PKCS7, either as a path to a file or as an "
                            "ASCII base64-encoded string prefixed by 'base64:'"):
                        r = parse_join_signature(opts.arg, &arg_verity_settings);
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_GROUP("Encryption"): {}
 
                OPTION_LONG("key-file", "PATH",
                            "Key to use when encrypting partitions"):
                        r = parse_key_file(opts.arg, &arg_key);
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_LONG("tpm2-device", "PATH",
                            "Path to TPM2 device node to use"): {
                        _cleanup_free_ char *device = NULL;
 
                        if (streq(opts.arg, "list"))
                                return tpm2_list_devices(/* legend= */ true, /* quiet= */ false);
 
                        if (!streq(opts.arg, "auto")) {
                                device = strdup(opts.arg);
                                if (!device)
                                        return log_oom();
                        }
 
                        free(arg_tpm2_device);
                        arg_tpm2_device = TAKE_PTR(device);
                        break;
                }
 
                OPTION_LONG("tpm2-device-key", "PATH",
                            "Enroll a TPM2 device using its public key"):
                        r = parse_path_argument(opts.arg, /* suppress_root= */ false, &arg_tpm2_device_key);
                        if (r < 0)
                                return r;
 
                        break;
 
                OPTION_LONG("tpm2-seal-key-handle", "HANDLE",
                            "Specify handle of key to use for sealing"):
                        r = safe_atou32_full(opts.arg, 16, &arg_tpm2_seal_key_handle);
                        if (r < 0)
                                return log_error_errno(r, "Could not parse TPM2 seal key handle index '%s': %m", opts.arg);
 
                        break;
 
                OPTION_LONG("tpm2-pcrs", "PCR1+PCR2+…",
                            "TPM2 PCR indexes to use for TPM2 enrollment"):
                        r = tpm2_parse_pcr_argument_append(opts.arg, &arg_tpm2_hash_pcr_values, &arg_tpm2_n_hash_pcr_values);
                        if (r < 0)
                                return r;
 
                        break;
 
                OPTION_LONG("tpm2-public-key", "PATH",
                            "Enroll signed TPM2 PCR policy against PEM public key"):
                        r = parse_path_argument(opts.arg, /* suppress_root= */ false, &arg_tpm2_public_key);
                        if (r < 0)
                                return r;
 
                        break;
 
                OPTION_LONG("tpm2-public-key-policyref", "STRING",
                            "Enroll signed TPM2 PCR policy with the specified policy reference"):
                        r = free_and_strdup_warn(&arg_tpm2_public_key_policyref, opts.arg);
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_LONG("tpm2-public-key-pcrs", "PCR1+PCR2+…",
                            "Enroll signed TPM2 PCR policy for specified TPM2 PCRs"):
                        auto_public_key_pcr_mask = false;
                        r = tpm2_parse_pcr_argument_to_mask(opts.arg, &arg_tpm2_public_key_pcr_mask);
                        if (r < 0)
                                return r;
 
                        break;
 
                OPTION_LONG("tpm2-pcrlock", "PATH",
                            "Specify pcrlock policy to lock against"):
                        r = parse_path_argument(opts.arg, /* suppress_root= */ false, &arg_tpm2_pcrlock);
                        if (r < 0)
                                return r;
 
                        auto_pcrlock = false;
                        break;
 
                OPTION_GROUP("Partition Control"): {}
 
                OPTION_LONG("include-partitions", "PART1,PART2…",
                            "Ignore partitions not of the specified types"):
                        if (arg_filter_partitions_type == FILTER_PARTITIONS_EXCLUDE)
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                                       "Combination of --include-partitions= and --exclude-partitions= is invalid.");
 
                        r = parse_partition_types(opts.arg, &arg_filter_partitions, &arg_n_filter_partitions);
                        if (r < 0)
                                return r;
 
                        arg_filter_partitions_type = FILTER_PARTITIONS_INCLUDE;
 
                        break;
 
                OPTION_LONG("exclude-partitions", "PART1,PART2…",
                            "Ignore partitions of the specified types"):
                        if (arg_filter_partitions_type == FILTER_PARTITIONS_INCLUDE)
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                                       "Combination of --include-partitions= and --exclude-partitions= is invalid.");
 
                        r = parse_partition_types(opts.arg, &arg_filter_partitions, &arg_n_filter_partitions);
                        if (r < 0)
                                return r;
 
                        arg_filter_partitions_type = FILTER_PARTITIONS_EXCLUDE;
 
                        break;
 
                OPTION_LONG("defer-partitions", "PART1,PART2…",
                            "Take partitions of the specified types into account but don't populate them yet"):
                        r = parse_partition_types(opts.arg, &arg_defer_partitions, &arg_n_defer_partitions);
                        if (r < 0)
                                return r;
 
                        break;
 
                OPTION_LONG("defer-partitions-empty", "BOOL",
                            "Defer all partitions marked for formatting as empty"):
                        r = parse_boolean_argument("--defer-partitions-empty=", opts.arg, &arg_defer_partitions_empty);
                        if (r < 0)
                                return r;
 
                        break;
 
                OPTION_LONG("defer-partitions-factory-reset", "BOOL",
                            "Defer all partitions marked for factory reset"):
                        r = parse_boolean_argument("--defer-partitions-factory-reset=", opts.arg, &arg_defer_partitions_factory_reset);
                        if (r < 0)
                                return r;
 
                        break;
 
                OPTION_GROUP("Copying"): {}
 
                OPTION('s', "copy-source", "PATH",
                       "Specify the primary source tree to copy files from"):
                        r = parse_path_argument(opts.arg, /* suppress_root= */ false, &arg_copy_source);
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_LONG("copy-from", "IMAGE",
                            "Copy partitions from the given image"): {
                        _cleanup_free_ char *p = NULL;
 
                        r = parse_path_argument(opts.arg, /* suppress_root= */ false, &p);
                        if (r < 0)
                                return r;
 
                        if (strv_consume(&arg_copy_from, TAKE_PTR(p)) < 0)
                                return log_oom();
 
                        break;
                }
 
                OPTION_GROUP("DDI Profile"): {}
 
                OPTION_LONG("make-ddi", "TYPE",
                            "Create a DDI of the given type"):
                        if (!filename_is_valid(opts.arg))
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid DDI type: %s", opts.arg);
 
                        r = free_and_strdup_warn(&arg_make_ddi, opts.arg);
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_SHORT('S', NULL, "Same as --make-ddi=sysext, make a system extension"):
                        r = free_and_strdup_warn(&arg_make_ddi, "sysext");
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_SHORT('C', NULL, "Same as --make-ddi=confext, make a configuration extension"):
                        r = free_and_strdup_warn(&arg_make_ddi, "confext");
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_SHORT('P', NULL, "Same as --make-ddi=portable, make a portable service"):
                        r = free_and_strdup_warn(&arg_make_ddi, "portable");
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_GROUP("Auxiliary Resource Generation"): {}
 
                OPTION_LONG("append-fstab", "MODE",
                            "How to join the content of a pre-existing fstab with the generated one "
                            "(no, auto, replace)"):
                        if (isempty(opts.arg)) {
                                arg_append_fstab = APPEND_AUTO;
                                break;
                        }
 
                        arg_append_fstab = append_mode_from_string(opts.arg);
                        if (arg_append_fstab < 0)
                                return log_error_errno(arg_append_fstab, "Failed to parse --append-fstab= parameter: %s", opts.arg);
                        break;
 
                OPTION_LONG("generate-fstab", "PATH",
                            "Write fstab configuration to the given path"):
                        r = parse_path_argument(opts.arg, /* suppress_root= */ false, &arg_generate_fstab);
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_LONG("generate-crypttab", "PATH",
                            "Write crypttab configuration to the given path"):
                        r = parse_path_argument(opts.arg, /* suppress_root= */ false, &arg_generate_crypttab);
                        if (r < 0)
                                return r;
                        break;
 
                OPTION_GROUP("El Torito boot catalog"): {}
 
                OPTION_LONG("el-torito", "BOOL",
                            "Whether to add a boot catalog to boot the ESP"):
                        r = parse_boolean_argument("--el-torito=", opts.arg, &arg_eltorito);
                        if (r < 0)
                                return r;
 
                        break;
 
                OPTION_LONG("el-torito-system", "STRING",
                            "Set the system identifier in the ISO9660 descriptor"):
                        if (!iso9660_system_name_valid(opts.arg))
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid value '%s' for --el-torito-system=.", opts.arg);
 
                        r = free_and_strdup_warn(&arg_eltorito_system, opts.arg);
                        if (r < 0)
                                return r;
 
                        break;
 
                OPTION_LONG("el-torito-volume", "STRING",
                            "Set the volume identifier in the ISO9660 descriptor"):
                        if (!iso9660_volume_name_valid(opts.arg))
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid value '%s' for --el-torito-volume=.", opts.arg);
 
                        r = free_and_strdup_warn(&arg_eltorito_volume, opts.arg);
                        if (r < 0)
                                return r;
 
                        break;
 
                OPTION_LONG("el-torito-publisher", "STRING",
                            "Set the publisher identifier in the ISO9660 descriptor"):
                        if (!iso9660_publisher_name_valid(opts.arg))
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid value '%s' for --el-torito-publisher=.", opts.arg);
 
                        r = free_and_strdup_warn(&arg_eltorito_publisher, opts.arg);
                        if (r < 0)
                                return r;
 
                        break;
 
                OPTION_COMMON_INTROSPECT_CLI:
                        return introspect_cli(arg_json_format_flags);
                }
 
        if (option_parser_get_n_args(&opts) > 1)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Expected at most one argument, the path to the block device or image file.");
 
        if (arg_make_ddi) {
                if (arg_definitions)
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Combination of --make-ddi= and --definitions= is not supported.");
                if (!IN_SET(arg_empty, EMPTY_UNSET, EMPTY_CREATE))
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Combination of --make-ddi= and --empty=%s is not supported.", empty_mode_to_string(arg_empty));
 
                /* Imply automatic sizing in DDI mode */
                if (arg_size == UINT64_MAX)
                        arg_size_auto = true;
 
                if (!arg_copy_source)
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No --copy-source= specified, refusing.");
 
                r = dir_is_empty(arg_copy_source, /* ignore_hidden_or_backup= */ false);
                if (r < 0)
                        return log_error_errno(r, "Failed to determine if '%s' is empty: %m", arg_copy_source);
                if (r > 0)
                        return log_error_errno(SYNTHETIC_ERRNO(ENOENT), "Source directory '%s' is empty, refusing to create empty image.", arg_copy_source);
 
                if (sd_id128_is_null(arg_seed) && !arg_randomize) {
                        /* We don't want that /etc/machine-id leaks into any image built this way, hence
                         * let's randomize the seed if not specified explicitly */
                        log_notice("No seed value specified, randomizing generated UUIDs, resulting image will not be reproducible.");
                        arg_randomize = true;
                }
 
                arg_empty = EMPTY_CREATE;
        }
 
        if (arg_empty == EMPTY_UNSET) /* default to refuse mode, if not otherwise specified */
                arg_empty = EMPTY_REFUSE;
 
        if (!set_isempty(arg_verity_settings) && !arg_certificate)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Verity signature specified without --certificate=.");
 
        if (arg_factory_reset > 0 && IN_SET(arg_empty, EMPTY_FORCE, EMPTY_REQUIRE, EMPTY_CREATE))
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Combination of --factory-reset=yes and --empty=force/--empty=require/--empty=create is invalid.");
 
        if (arg_can_factory_reset)
                arg_dry_run = true; /* When --can-factory-reset is specified we don't make changes, hence
                                     * non-dry-run mode makes no sense. Thus, imply dry run mode so that we
                                     * open things strictly read-only. */
        else if (arg_empty == EMPTY_CREATE)
                arg_dry_run = false; /* Imply --dry-run=no if we create the loopback file anew. After all we
                                      * cannot really break anyone's partition tables that way. */
 
        /* Disable pager once we are not just reviewing, but doing things. */
        if (!arg_dry_run)
                arg_pager_flags |= PAGER_DISABLE;
 
        if (arg_empty == EMPTY_CREATE && arg_size == UINT64_MAX && !arg_size_auto)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "If --empty=create is specified, --size= must be specified, too.");
 
        if (arg_image && arg_root)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Please specify either --root= or --image=, the combination of both is not supported.");
        else if (!arg_image && !arg_root && in_initrd()) {
 
                /* By default operate on /sysusr/ or /sysroot/ when invoked in the initrd. We prefer the
                 * former, if it is mounted, so that we have deterministic behaviour on systems where /usr/
                 * is vendor-supplied but the root fs formatted on first boot. */
                r = path_is_mount_point("/sysusr/usr");
                if (r <= 0) {
                        if (r < 0 && r != -ENOENT)
                                log_debug_errno(r, "Unable to determine whether /sysusr/usr is a mount point, assuming it is not: %m");
 
                        arg_root = strdup("/sysroot");
                } else
                        arg_root = strdup("/sysusr");
                if (!arg_root)
                        return log_oom();
 
                arg_relax_copy_block_security = true;
        }
 
        char **args = option_parser_get_args(&opts);
        if (!strv_isempty(args)) {
                if (empty_or_dash(args[0]))
                        arg_node_none = true;
                else {
                        arg_node = strdup(args[0]);
                        if (!arg_node)
                                return log_oom();
                        arg_node_none = false;
                }
        }
 
        if (IN_SET(arg_empty, EMPTY_FORCE, EMPTY_REQUIRE, EMPTY_CREATE) && !arg_node && !arg_image)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "A path to a device node or image file must be specified when --make-ddi=, --empty=force, --empty=require or --empty=create are used.");
 
        if (arg_split && !arg_node)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "A path to an image file must be specified when --split is used.");
 
        if (auto_pcrlock) {
                assert(!arg_tpm2_pcrlock);
 
                r = tpm2_pcrlock_search_file(NULL, NULL, &arg_tpm2_pcrlock);
                if (r < 0) {
                        if (r != -ENOENT)
                                log_warning_errno(r, "Search for pcrlock.json failed, assuming it does not exist: %m");
                } else
                        log_debug("Automatically using pcrlock policy '%s'.", arg_tpm2_pcrlock);
        }
 
        if (auto_public_key_pcr_mask) {
                assert(arg_tpm2_public_key_pcr_mask == 0);
                arg_tpm2_public_key_pcr_mask = INDEX_TO_MASK(uint32_t, TPM2_PCR_KERNEL_BOOT);
        }
 
        if (arg_pretty < 0 && isatty_safe(STDOUT_FILENO))
                arg_pretty = true;
 
        if (arg_architecture >= 0) {
                FOREACH_ARRAY(p, arg_filter_partitions, arg_n_filter_partitions)
                        *p = gpt_partition_type_override_architecture(*p, arg_architecture);
 
                FOREACH_ARRAY(p, arg_defer_partitions, arg_n_defer_partitions)
                        *p = gpt_partition_type_override_architecture(*p, arg_architecture);
        }
 
        if (arg_append_fstab && !arg_generate_fstab)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No --generate-fstab= specified for --append-fstab=%s.", append_mode_to_string(arg_append_fstab));
 
        r = sd_varlink_invocation(SD_VARLINK_ALLOW_ACCEPT);
        if (r < 0)
                return log_error_errno(r, "Failed to check if invoked in Varlink mode: %m");
        if (r > 0) {
                arg_varlink = true;
                arg_pager_flags |= PAGER_DISABLE;
        }
 
        return 1;
}
 
static int parse_proc_cmdline_factory_reset(void) {
        if (arg_factory_reset >= 0) /* Never override what is specified on the process command line */
                return 0;
 
        if (!in_initrd()) /* Never honour kernel command line factory reset request outside of the initrd */
                return 0;
 
        FactoryResetMode f = factory_reset_mode();
        if (f < 0)
                return log_error_errno(f, "Failed to determine factory reset status: %m");
        if (f != FACTORY_RESET_UNSPECIFIED) {
                arg_factory_reset = f == FACTORY_RESET_ON;
 
                if (arg_factory_reset)
                        log_notice("Honouring factory reset requested via kernel command line or EFI variable.");
        }
 
        return 0;
}
 
static int acquire_root_devno(
                const char *p,
                const char *root,
                int mode,
                char **ret,
                int *ret_fd) {
 
        _cleanup_free_ char *found_path = NULL, *node = NULL;
        dev_t devno, fd_devno = MODE_INVALID;
        _cleanup_close_ int fd = -EBADF;
        struct stat st;
        int r;
 
        assert(p);
        assert(ret);
        assert(ret_fd);
 
        fd = chase_and_open(p, root, CHASE_PREFIX_ROOT, (mode & ~O_ACCMODE_STRICT) | O_RDONLY, &found_path);
        if (fd < 0)
                return fd;
 
        if (fstat(fd, &st) < 0)
                return -errno;