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 1–1000 of 11,995

/* SPDX-License-Identifier: LGPL-2.1-or-later */
 
#include <fcntl.h>
#include <linux/dm-ioctl.h>
#include <linux/magic.h>
#include <sys/file.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <unistd.h>
 
#include "sd-daemon.h"
#include "sd-id128.h"
#include "sd-json.h"
#include "sd-varlink.h"
 
#include "alloc-util.h"
#include "ask-password-api.h"
#include "blkid-util.h"
#include "blockdev-list.h"
#include "blockdev-util.h"
#include "btrfs-util.h"
#include "build.h"
#include "chase.h"
#include "chattr-util.h"
#include "conf-files.h"
#include "conf-parser.h"
#include "constants.h"
#include "copy.h"
#include "crypto-util.h"
#include "cryptsetup-util.h"
#include "device-util.h"
#include "devnum-util.h"
#include "dirent-util.h"
#include "dissect-image.h"
#include "errno-util.h"
#include "extract-word.h"
#include "factory-reset.h"
#include "fd-util.h"
#include "fdisk-util.h"
#include "fileio.h"
#include "format-table.h"
#include "format-util.h"
#include "fs-util.h"
#include "glyph-util.h"
#include "gpt.h"
#include "hexdecoct.h"
#include "hmac.h"
#include "id128-util.h"
#include "image-policy.h"
#include "initrd-util.h"
#include "install-file.h"
#include "io-util.h"
#include "iso9660.h"
#include "json-util.h"
#include "libmount-util.h"
#include "list.h"
#include "loop-util.h"
#include "main-func.h"
#include "mkdir.h"
#include "mkfs-util.h"
#include "mount-util.h"
#include "mountpoint-util.h"
#include "nulstr-util.h"
#include "parse-argument.h"
#include "parse-helpers.h"
#include "parse-util.h"
#include "pretty-print.h"
#include "process-util.h"
#include "random-util.h"
#include "ratelimit.h"
#include "repart-list-candidate-devices.h"
#include "reread-partition-table.h"
#include "resize-fs.h"
#include "rm-rf.h"
#include "set.h"
#include "sort-util.h"
#include "specifier.h"
#include "string-table.h"
#include "string-util.h"
#include "strv.h"
#include "sync-util.h"
#include "terminal-util.h"
#include "time-util.h"
#include "tmpfile-util.h"
#include "tpm2-pcr.h"
#include "tpm2-util.h"
#include "utf8.h"
#include "varlink-io.systemd.Repart.h"
#include "varlink-util.h"
#include "verbs.h"
#include "xattr-util.h"
 
/* If not configured otherwise use a minimal partition size of 10M */
#define DEFAULT_MIN_SIZE (10ULL*1024ULL*1024ULL)
 
/* Hard lower limit for new partition sizes */
#define HARD_MIN_SIZE 4096ULL
 
/* We know up front we're never going to put more than this in a verity sig partition. */
#define VERITY_SIG_SIZE (HARD_MIN_SIZE*4ULL)
 
/* LUKS2 takes off 16M of the partition size with its metadata by default */
#define LUKS2_METADATA_SIZE (16ULL*1024ULL*1024ULL)
 
/* To do LUKS2 offline encryption, we need to keep some extra free space at the end of the partition. */
#define LUKS2_METADATA_KEEP_FREE (LUKS2_METADATA_SIZE*2ULL)
 
/* The LUKS2 binary header reserves 48 bytes for the label, including the trailing NUL byte */
#define LUKS2_LABEL_MAX 47U
 
/* LUKS2 default volume key size (no integrity). */
#define VOLUME_KEY_SIZE (512ULL/8ULL)
 
/* Use 4K as the default filesystem sector size because as long as the partitions are aligned to 4K, the
 * filesystems will then also be compatible with sector sizes 512, 1024 and 2048. */
#define DEFAULT_FILESYSTEM_SECTOR_SIZE 4096ULL
 
/* Minimum sizes for the ESP depending on sector size. What the minimum is, is severely underdocumented, but
 * it appears for 4K sector size it must be 260M, and otherwise 100M. This is what Microsoft says here:
 *
 * https://learn.microsoft.com/en-us/windows-hardware/manufacture/desktop/configure-uefigpt-based-hard-drive-partitions?view=windows-11
 * https://learn.microsoft.com/en-us/windows-hardware/manufacture/desktop/oem-deployment-of-windows-desktop-editions-sample-scripts?view=windows-11&preserve-view=true#-createpartitions-uefitxt
 */
#define ESP_MIN_SIZE (100 * U64_MB)
#define ESP_MIN_SIZE_4K (260 * U64_MB)
 
#define APIVFS_TMP_DIRS_NULSTR "proc\0sys\0dev\0tmp\0run\0var/tmp\0"
 
#define AUTOMATIC_FSTAB_HEADER_START "# Start section ↓ of automatically generated fstab by systemd-repart"
#define AUTOMATIC_FSTAB_HEADER_END   "# End section ↑ of automatically generated fstab by systemd-repart"
 
/* Note: When growing and placing new partitions we always align to 4K sector size. It's how newer hard disks
 * are designed, and if everything is aligned to that performance is best. And for older hard disks with 512B
 * sector size devices were generally assumed to have an even number of sectors, hence at the worst we'll
 * waste 3K per partition, which is probably fine. */
 
typedef enum EmptyMode {
        EMPTY_UNSET,    /* no choice has been made yet */
        EMPTY_REFUSE,   /* refuse empty disks, never create a partition table */
        EMPTY_ALLOW,    /* allow empty disks, create partition table if necessary */
        EMPTY_REQUIRE,  /* require an empty disk, create a partition table */
        EMPTY_FORCE,    /* make disk empty, erase everything, create a partition table always */
        EMPTY_CREATE,   /* create disk as loopback file, create a partition table always */
        _EMPTY_MODE_MAX,
        _EMPTY_MODE_INVALID = -EINVAL,
} EmptyMode;
 
typedef enum FilterPartitionType {
        FILTER_PARTITIONS_NONE,
        FILTER_PARTITIONS_EXCLUDE,
        FILTER_PARTITIONS_INCLUDE,
        _FILTER_PARTITIONS_MAX,
        _FILTER_PARTITIONS_INVALID = -EINVAL,
} FilterPartitionsType;
 
typedef enum AppendMode {
        APPEND_NO,
        APPEND_AUTO,
        APPEND_REPLACE,
        _APPEND_MODE_MAX,
        _APPEND_MODE_INVALID = -EINVAL,
} AppendMode;
 
static EmptyMode arg_empty = EMPTY_UNSET;
static bool arg_dry_run = true;
static char *arg_node = NULL;
static bool arg_node_none = false;
static char *arg_root = NULL;
static char *arg_image = NULL;
static char **arg_definitions = NULL;
static bool arg_discard = true;
static bool arg_can_factory_reset = false;
static int arg_factory_reset = -1;
static sd_id128_t arg_seed = SD_ID128_NULL;
static bool arg_randomize = false;
static int arg_pretty = -1;
static uint64_t arg_size = UINT64_MAX;
static bool arg_size_auto = false;
static sd_json_format_flags_t arg_json_format_flags = SD_JSON_FORMAT_OFF;
static PagerFlags arg_pager_flags = 0;
static bool arg_legend = true;
static struct iovec arg_key = {};
static char *arg_private_key = NULL;
static KeySourceType arg_private_key_source_type = OPENSSL_KEY_SOURCE_FILE;
static char *arg_private_key_source = NULL;
static char *arg_certificate = NULL;
static CertificateSourceType arg_certificate_source_type = OPENSSL_CERTIFICATE_SOURCE_FILE;
static char *arg_certificate_source = NULL;
static char *arg_tpm2_device = NULL;
static uint32_t arg_tpm2_seal_key_handle = 0;
static char *arg_tpm2_device_key = NULL;
static Tpm2PCRValue *arg_tpm2_hash_pcr_values = NULL;
static size_t arg_tpm2_n_hash_pcr_values = 0;
static char *arg_tpm2_public_key = NULL;
static char *arg_tpm2_public_key_policyref = NULL;
static uint32_t arg_tpm2_public_key_pcr_mask = 0;
static char *arg_tpm2_pcrlock = NULL;
static bool arg_split = false;
static GptPartitionType *arg_filter_partitions = NULL;
static size_t arg_n_filter_partitions = 0;
static FilterPartitionsType arg_filter_partitions_type = FILTER_PARTITIONS_NONE;
static GptPartitionType *arg_defer_partitions = NULL;
static size_t arg_n_defer_partitions = 0;
static bool arg_defer_partitions_empty = false;
static bool arg_defer_partitions_factory_reset = false;
static uint64_t arg_sector_size = 0;
static uint64_t arg_grain_size = 0;
static ImagePolicy *arg_image_policy = NULL;
static Architecture arg_architecture = _ARCHITECTURE_INVALID;
static int arg_offline = -1;
static char **arg_copy_from = NULL;
static char *arg_copy_source = NULL;
static char *arg_make_ddi = NULL;
static AppendMode arg_append_fstab = APPEND_NO;
static char *arg_generate_fstab = NULL;
static char *arg_generate_crypttab = NULL;
static Set *arg_verity_settings = NULL;
static bool arg_relax_copy_block_security = false;
static bool arg_varlink = false;
static int arg_cow = -1;
static bool arg_eltorito = false;
static char *arg_eltorito_system = NULL;
static char *arg_eltorito_volume = NULL;
static char *arg_eltorito_publisher = NULL;
 
STATIC_DESTRUCTOR_REGISTER(arg_node, freep);
STATIC_DESTRUCTOR_REGISTER(arg_root, freep);
STATIC_DESTRUCTOR_REGISTER(arg_image, freep);
STATIC_DESTRUCTOR_REGISTER(arg_definitions, strv_freep);
STATIC_DESTRUCTOR_REGISTER(arg_key, iovec_done_erase);
STATIC_DESTRUCTOR_REGISTER(arg_private_key, freep);
STATIC_DESTRUCTOR_REGISTER(arg_private_key_source, freep);
STATIC_DESTRUCTOR_REGISTER(arg_certificate, freep);
STATIC_DESTRUCTOR_REGISTER(arg_certificate_source, freep);
STATIC_DESTRUCTOR_REGISTER(arg_tpm2_device, freep);
STATIC_DESTRUCTOR_REGISTER(arg_tpm2_device_key, freep);
STATIC_DESTRUCTOR_REGISTER(arg_tpm2_hash_pcr_values, freep);
STATIC_DESTRUCTOR_REGISTER(arg_tpm2_public_key, freep);
STATIC_DESTRUCTOR_REGISTER(arg_tpm2_public_key_policyref, freep);
STATIC_DESTRUCTOR_REGISTER(arg_tpm2_pcrlock, freep);
STATIC_DESTRUCTOR_REGISTER(arg_filter_partitions, freep);
STATIC_DESTRUCTOR_REGISTER(arg_defer_partitions, freep);
STATIC_DESTRUCTOR_REGISTER(arg_image_policy, image_policy_freep);
STATIC_DESTRUCTOR_REGISTER(arg_copy_from, strv_freep);
STATIC_DESTRUCTOR_REGISTER(arg_copy_source, freep);
STATIC_DESTRUCTOR_REGISTER(arg_make_ddi, freep);
STATIC_DESTRUCTOR_REGISTER(arg_generate_fstab, freep);
STATIC_DESTRUCTOR_REGISTER(arg_generate_crypttab, freep);
STATIC_DESTRUCTOR_REGISTER(arg_verity_settings, set_freep);
STATIC_DESTRUCTOR_REGISTER(arg_eltorito_system, freep);
STATIC_DESTRUCTOR_REGISTER(arg_eltorito_volume, freep);
STATIC_DESTRUCTOR_REGISTER(arg_eltorito_publisher, freep);
 
COMMAND(
        "systemd-repart\0",
        "Grow and add partitions to a partition table, and generate disk images (DDIs).",
        .argspec = "[DEVICE]\0",
        .man_pages = "systemd-repart(8)\0",
        .pager_flags = &arg_pager_flags,
);
 
typedef enum ProgressPhase {
        PROGRESS_LOADING_DEFINITIONS,
        PROGRESS_LOADING_TABLE,
        PROGRESS_OPENING_COPY_BLOCK_SOURCES,
        PROGRESS_OPENING_BLOCK_DEVICE_REPLACE_SOURCES,
        PROGRESS_ACQUIRING_PARTITION_LABELS,
        PROGRESS_MINIMIZING,
        PROGRESS_PLACING,
        PROGRESS_WIPING_DISK,
        PROGRESS_WIPING_PARTITION,
        PROGRESS_COPYING_PARTITION,
        PROGRESS_FORMATTING_PARTITION,
        PROGRESS_ADJUSTING_PARTITION,
        PROGRESS_WRITING_TABLE,
        PROGRESS_REREADING_TABLE,
        PROGRESS_REPLACING_DEVICE,
        _PROGRESS_PHASE_MAX,
        _PROGRESS_PHASE_INVALID = -EINVAL,
} ProgressPhase;
 
typedef struct FreeArea FreeArea;
 
typedef enum EncryptMode {
        ENCRYPT_OFF,
        ENCRYPT_KEY_FILE,
        ENCRYPT_TPM2,
        ENCRYPT_KEY_FILE_TPM2,
        _ENCRYPT_MODE_MAX,
        _ENCRYPT_MODE_INVALID = -EINVAL,
} EncryptMode;
 
typedef enum IntegrityMode {
        INTEGRITY_OFF,
        INTEGRITY_INLINE,
        _INTEGRITY_MODE_MAX,
        _INTEGRITY_MODE_INVALID = -EINVAL,
} IntegrityMode;
 
typedef enum IntegrityAlg {
        INTEGRITY_ALG_HMAC_SHA1,
        INTEGRITY_ALG_HMAC_SHA256,
        INTEGRITY_ALG_HMAC_SHA512,
        _INTEGRITY_ALG_MAX,
        _INTEGRITY_ALG_INVALID = -EINVAL,
} IntegrityAlg;
 
typedef enum EncryptKDF {
        ENCRYPT_KDF_ARGON2ID,
        ENCRYPT_KDF_PBKDF2,
        ENCRYPT_KDF_MINIMAL,
        _ENCRYPT_KDF_MAX,
        _ENCRYPT_KDF_INVALID = -EINVAL,
} EncryptKDF;
 
typedef enum VerityMode {
        VERITY_OFF,
        VERITY_DATA,
        VERITY_HASH,
        VERITY_SIG,
        _VERITY_MODE_MAX,
        _VERITY_MODE_INVALID = -EINVAL,
} VerityMode;
 
typedef enum MinimizeMode {
        MINIMIZE_OFF,
        MINIMIZE_BEST,
        MINIMIZE_GUESS,
        _MINIMIZE_MODE_MAX,
        _MINIMIZE_MODE_INVALID = -EINVAL,
} MinimizeMode;
 
typedef struct PartitionMountPoint {
        char *where;
        char *options;
} PartitionMountPoint;
 
static void partition_mountpoint_free_many(PartitionMountPoint *f, size_t n) {
        assert(f || n == 0);
 
        FOREACH_ARRAY(i, f, n) {
                free(i->where);
                free(i->options);
        }
 
        free(f);
}
 
typedef struct PartitionEncryptedVolume {
        char *name;
        char *keyfile;
        char *options;
        bool fixate_volume_key;
} PartitionEncryptedVolume;
 
static PartitionEncryptedVolume* partition_encrypted_volume_free(PartitionEncryptedVolume *c) {
        if (!c)
                return NULL;
 
        free(c->name);
        free(c->keyfile);
        free(c->options);
 
        return mfree(c);
}
 
typedef struct CopyFiles {
        char *source;
        char *target;
        CopyFlags flags;
} CopyFiles;
 
static void copy_files_free_many(CopyFiles *f, size_t n) {
        assert(f || n == 0);
 
        FOREACH_ARRAY(i, f, n) {
                free(i->source);
                free(i->target);
        }
 
        free(f);
}
 
static BtrfsSubvolFlags subvolume_flags_from_string_one(const char *s) {
        /* This is a bitmask (i.e. not dense), hence we don't use the "string-table.h" stuff here. */
 
        assert(s);
 
        if (streq(s, "ro"))
                return BTRFS_SUBVOL_RO;
 
        if (streq(s, "nodatacow"))
                return BTRFS_SUBVOL_NODATACOW;
 
        return _BTRFS_SUBVOL_FLAGS_INVALID;
}
 
static BtrfsSubvolFlags subvolume_flags_from_string(const char *s) {
        BtrfsSubvolFlags flags = 0;
        int r;
 
        assert(s);
 
        for (;;) {
                _cleanup_free_ char *f = NULL;
                BtrfsSubvolFlags ff;
 
                r = extract_first_word(&s, &f, ",", EXTRACT_DONT_COALESCE_SEPARATORS);
                if (r < 0)
                        return r;
                if (r == 0)
                        break;
 
                ff = subvolume_flags_from_string_one(f);
                if (ff < 0)
                        return -EBADRQC; /* recognizable error */
 
                flags |= ff;
        }
 
        return flags;
}
 
typedef struct Subvolume {
        char *path;
        BtrfsSubvolFlags flags;
} Subvolume;
 
static Subvolume* subvolume_free(Subvolume *s) {
        if (!s)
                return NULL;
 
        free(s->path);
        return mfree(s);
}
 
DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(subvolume_hash_ops, char, path_hash_func, path_compare, Subvolume, subvolume_free);
 
typedef struct Context Context;
 
typedef struct {
        uint64_t devid;
        int mountpoint_fd;
        int source_fd;
        char *source_path;
        uint64_t source_size;
        bool done;
} BtrfsReplacement;
 
static BtrfsReplacement* btrfs_replacement_free(BtrfsReplacement *b) {
        if (!b)
                return NULL;
 
        safe_close(b->mountpoint_fd);
        safe_close(b->source_fd);
        free(b->source_path);
        return mfree(b);
}
 
DEFINE_TRIVIAL_CLEANUP_FUNC(BtrfsReplacement*, btrfs_replacement_free);
 
typedef struct Partition {
        Context *context;
 
        char *definition_path;
        char **drop_in_files;
 
        GptPartitionType type;
        sd_id128_t current_uuid, new_uuid;
        bool new_uuid_is_set;
        char *current_label, *new_label;      /* Used for the GPT partition label + fs superblock label */
        char *new_volume_label;               /* used for LUKS superblock */
        sd_id128_t fs_uuid, luks_uuid, verity_uuid;
        uint8_t verity_salt[SHA256_DIGEST_SIZE];
 
        bool dropped;
        bool factory_reset;
        bool discarded;
        int32_t priority;
 
        uint32_t weight, padding_weight;
 
        uint64_t current_size, new_size;
        uint64_t size_min, size_max;
 
        uint64_t current_padding, new_padding;
        uint64_t padding_min, padding_max;
 
        uint64_t partno;
        uint64_t offset;
 
        struct fdisk_partition *current_partition;
        struct fdisk_partition *new_partition;
        FreeArea *padding_area;
        FreeArea *allocated_to_area;
 
        char *copy_blocks_path;
        bool copy_blocks_path_is_our_file;
        bool copy_blocks_auto;
        const char *copy_blocks_root;
        int copy_blocks_fd;
        uint64_t copy_blocks_offset;
        uint64_t copy_blocks_size;
        uint64_t copy_blocks_done;
 
        char *format;
        char *block_device_replace;
        BtrfsReplacement *btrfs_replaced;
        char *volume_name;
        char **exclude_files_source;
        char **exclude_files_target;
        char **make_directories;
        char **make_symlinks;
        OrderedHashmap *subvolumes;
        char *default_subvolume;
        EncryptMode encrypt;
        struct iovec key;
        Tpm2PCRValue *tpm2_hash_pcr_values;
        size_t tpm2_n_hash_pcr_values;
        IntegrityMode integrity;
        IntegrityAlg integrity_alg;
        EncryptKDF encrypt_kdf;
        VerityMode verity;
        char *verity_match_key;
        MinimizeMode minimize;
        uint64_t verity_data_block_size;
        uint64_t verity_hash_block_size;
        char *compression;
        char *compression_level;
        uint64_t fs_sector_size;
        int discard;
 
        int add_validatefs;
        CopyFiles *copy_files;
        size_t n_copy_files;
 
        uint64_t gpt_flags;
        int no_auto;
        int read_only;
        int growfs;
 
        struct iovec roothash;
 
        char *split_name_format;
        char *split_path;
 
        PartitionMountPoint *mountpoints;
        size_t n_mountpoints;
 
        PartitionEncryptedVolume *encrypted_volume;
 
        unsigned last_percent;
        RateLimit progress_ratelimit;
 
        char *supplement_for_name;
        struct Partition *supplement_for, *supplemented_by;
        bool suppressing_supplement;
 
        struct Partition *siblings[_VERITY_MODE_MAX];
 
        LIST_FIELDS(struct Partition, partitions);
} Partition;
 
#define PARTITION_IS_FOREIGN(p) (!(p)->definition_path)
#define PARTITION_EXISTS(p) (!!(p)->current_partition)
#define PARTITION_SUPPRESSED(p) ((p)->supplement_for && (p)->supplement_for->suppressing_supplement)
 
struct FreeArea {
        Partition *after;
        uint64_t size;
        uint64_t allocated;
};
 
struct Context {
        char **definitions;
 
        LIST_HEAD(Partition, partitions);
        size_t n_partitions;
 
        FreeArea **free_areas;
        size_t n_free_areas;
 
        uint64_t start, end, total;
 
        struct fdisk_context *fdisk_context;
        int fdisk_context_fd;
        uint64_t sector_size, grain_size, default_fs_sector_size;
 
        sd_id128_t seed;
 
        char *node;
        bool node_is_our_file;
        int backing_fd;
 
        EmptyMode empty;
        bool dry_run;
 
        bool from_scratch;
 
#if HAVE_OPENSSL
        X509 *certificate;
        OpenSSLAskPasswordUI *ui;
        EVP_PKEY *private_key;
#endif
 
        bool defer_partitions_empty;
        bool defer_partitions_factory_reset;
 
        sd_varlink *link; /* If 'more' is used on the Varlink call, we'll send progress info over this link */
 
        bool needs_rescan;
};
 
static const char *empty_mode_table[_EMPTY_MODE_MAX] = {
        [EMPTY_UNSET]   = "unset",
        [EMPTY_REFUSE]  = "refuse",
        [EMPTY_ALLOW]   = "allow",
        [EMPTY_REQUIRE] = "require",
        [EMPTY_FORCE]   = "force",
        [EMPTY_CREATE]  = "create",
};
 
static const char *append_mode_table[_APPEND_MODE_MAX] = {
        [APPEND_NO]      = "no",
        [APPEND_AUTO]    = "auto",
        [APPEND_REPLACE] = "replace",
};
 
static const char *encrypt_mode_table[_ENCRYPT_MODE_MAX] = {
        [ENCRYPT_OFF] = "off",
        [ENCRYPT_KEY_FILE] = "key-file",
        [ENCRYPT_TPM2] = "tpm2",
        [ENCRYPT_KEY_FILE_TPM2] = "key-file+tpm2",
};
 
/* Going forward, the plan is to add two more modes:
 * [INTEGRITY_DATA] = "data" (interleave data and integrity tags on the same device),
 * [INTEGRITY_META] = "meta" (use a separate device for storing integrity tags).
 * Also, INTEGRITY_INLINE will be using hardware sector integrity fields when used
 * without encryption. */
static const char *integrity_mode_table[_INTEGRITY_MODE_MAX] = {
        [INTEGRITY_OFF]    = "off",    /* no integrity protection */
        [INTEGRITY_INLINE] = "inline", /* luks2 storage when encrypted */
};
 
static const char *integrity_alg_table[_INTEGRITY_ALG_MAX] = {
        [INTEGRITY_ALG_HMAC_SHA1]   = "hmac-sha1",
        [INTEGRITY_ALG_HMAC_SHA256] = "hmac-sha256",
        [INTEGRITY_ALG_HMAC_SHA512] = "hmac-sha512",
};
 
static const char *encrypt_kdf_table[_ENCRYPT_KDF_MAX] = {
        [ENCRYPT_KDF_ARGON2ID] = "argon2id",
        [ENCRYPT_KDF_PBKDF2]   = "pbkdf2",
        [ENCRYPT_KDF_MINIMAL]  = "minimal",
};
 
static const char *verity_mode_table[_VERITY_MODE_MAX] = {
        [VERITY_OFF]  = "off",
        [VERITY_DATA] = "data",
        [VERITY_HASH] = "hash",
        [VERITY_SIG]  = "signature",
};
 
static const char *minimize_mode_table[_MINIMIZE_MODE_MAX] = {
        [MINIMIZE_OFF]   = "off",
        [MINIMIZE_BEST]  = "best",
        [MINIMIZE_GUESS] = "guess",
};
 
static const char *progress_phase_table[_PROGRESS_PHASE_MAX] = {
        [PROGRESS_LOADING_DEFINITIONS]                  = "loading-definitions",
        [PROGRESS_LOADING_TABLE]                        = "loading-table",
        [PROGRESS_OPENING_COPY_BLOCK_SOURCES]           = "opening-copy-block-sources",
        [PROGRESS_OPENING_BLOCK_DEVICE_REPLACE_SOURCES] = "opening-block-device-replace-sources",
        [PROGRESS_ACQUIRING_PARTITION_LABELS]           = "acquiring-partition-labels",
        [PROGRESS_MINIMIZING]                           = "minimizing",
        [PROGRESS_PLACING]                              = "placing",
        [PROGRESS_WIPING_DISK]                          = "wiping-disk",
        [PROGRESS_WIPING_PARTITION]                     = "wiping-partition",
        [PROGRESS_COPYING_PARTITION]                    = "copying-partition",
        [PROGRESS_FORMATTING_PARTITION]                 = "formatting-partition",
        [PROGRESS_ADJUSTING_PARTITION]                  = "adjusting-partition",
        [PROGRESS_WRITING_TABLE]                        = "writing-table",
        [PROGRESS_REREADING_TABLE]                      = "rereading-table",
        [PROGRESS_REPLACING_DEVICE]                     = "replacing-device",
};
 
static uint64_t determine_grain_size(uint64_t sector_size) {
        return MAX(arg_grain_size > 0 ? arg_grain_size : 4096U, sector_size);
}
 
DEFINE_PRIVATE_STRING_TABLE_LOOKUP(empty_mode, EmptyMode);
DEFINE_PRIVATE_STRING_TABLE_LOOKUP(append_mode, AppendMode);
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING_WITH_BOOLEAN(encrypt_mode, EncryptMode, ENCRYPT_KEY_FILE);
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING_WITH_BOOLEAN(integrity_mode, IntegrityMode, INTEGRITY_INLINE);
DEFINE_PRIVATE_STRING_TABLE_LOOKUP(integrity_alg, IntegrityAlg);
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(encrypt_kdf, EncryptKDF);
DEFINE_PRIVATE_STRING_TABLE_LOOKUP(verity_mode, VerityMode);
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING_WITH_BOOLEAN(minimize_mode, MinimizeMode, MINIMIZE_BEST);
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(progress_phase, ProgressPhase);
 
static uint64_t round_down_size(uint64_t v, uint64_t p) {
        return (v / p) * p;
}
 
static uint64_t round_up_size(uint64_t v, uint64_t p) {
 
        v = DIV_ROUND_UP(v, p);
 
        if (v > UINT64_MAX / p)
                return UINT64_MAX; /* overflow */
 
        return v * p;
}
 
/* calculates the size of a dm-verity hash partition's contents */
static int calculate_verity_hash_size(
                uint64_t data_bytes,
                uint64_t hash_block_size,
                uint64_t data_block_size,
                uint64_t *ret_bytes) {
 
        assert(ret_bytes);
 
        /* The calculation here is based on the documented on-disk format of the dm-verity
         * https://docs.kernel.org/admin-guide/device-mapper/verity.html#hash-tree
         *
         * Upstream implementation:
         * https://gitlab.com/cryptsetup/cryptsetup/-/blob/v2.7.5/lib/verity/verity_hash.c */
 
        uint64_t data_blocks = DIV_ROUND_UP(data_bytes, data_block_size);
        if (data_blocks > UINT64_MAX / data_block_size)
                return -EOVERFLOW;
 
        /* hashes that fit in one hash block (node in the merkle tree) */
        uint64_t hashes_per_hash_block = hash_block_size / SHA256_DIGEST_SIZE;
 
        /* initialize with 2 for the root of the merkle tree + the superblock */
        uint64_t hash_blocks = 2;
 
        /* iterate through the levels of the merkle tree bottom up */
        uint64_t remaining_blocks = data_blocks;
 
        while (remaining_blocks > hashes_per_hash_block) {
                uint64_t hash_blocks_for_level;
                /* number of hash blocks required to reference the underlying blocks */
                hash_blocks_for_level = DIV_ROUND_UP(remaining_blocks, hashes_per_hash_block);
 
                if (hash_blocks > UINT64_MAX - hash_blocks_for_level)
                        return -EOVERFLOW;
 
                /* add current layer to the total number of hash blocks */
                hash_blocks += hash_blocks_for_level;
                /* hashes on this level serve as the blocks on which the next level is built */
                remaining_blocks = hash_blocks_for_level;
        }
 
        if (hash_blocks > UINT64_MAX / hash_block_size)
                return -EOVERFLOW;
 
        *ret_bytes = hash_blocks * hash_block_size;
 
        return 0;
}
 
static Partition *partition_new(Context *c) {
        Partition *p;
 
        p = new(Partition, 1);
        if (!p)
                return NULL;
 
        *p = (Partition) {
                .context = c,
                .weight = 1000,
                .padding_weight = 0,
                .current_size = UINT64_MAX,
                .new_size = UINT64_MAX,
                .size_min = UINT64_MAX,
                .size_max = UINT64_MAX,
                .current_padding = UINT64_MAX,
                .new_padding = UINT64_MAX,
                .padding_min = UINT64_MAX,
                .padding_max = UINT64_MAX,
                .partno = UINT64_MAX,
                .offset = UINT64_MAX,
                .copy_blocks_fd = -EBADF,
                .copy_blocks_offset = UINT64_MAX,
                .copy_blocks_size = UINT64_MAX,
                .no_auto = -1,
                .read_only = -1,
                .growfs = -1,
                .verity_data_block_size = UINT64_MAX,
                .verity_hash_block_size = UINT64_MAX,
                .add_validatefs = -1,
                .last_percent = UINT_MAX,
                .progress_ratelimit = { 100 * USEC_PER_MSEC, 1 },
                .fs_sector_size = UINT64_MAX,
                .discard = -1,
                .encrypt_kdf = _ENCRYPT_KDF_INVALID,
        };
 
        return p;
}
 
static void partition_unlink_supplement(Partition *p) {
        assert(p);
 
        assert(!p->supplement_for || !p->supplemented_by); /* Can't be both */
 
        if (p->supplemented_by) {
                assert(p->supplemented_by->supplement_for == p);
 
                p->supplemented_by->supplement_for = NULL;
        }
 
        if (p->supplement_for) {
                assert(p->supplement_for->supplemented_by == p);
 
                p->supplement_for->supplemented_by = NULL;
                p->supplement_for->suppressing_supplement = false;
        }
 
        p->supplement_for_name = mfree(p->supplement_for_name);
        p->supplemented_by = p->supplement_for = NULL;
        p->suppressing_supplement = false;
}
 
static Partition* partition_free(Partition *p) {
        if (!p)
                return NULL;
 
        free(p->current_label);
        free(p->new_label);
        free(p->new_volume_label);
        free(p->definition_path);
        strv_free(p->drop_in_files);
 
        if (p->current_partition)
                sym_fdisk_unref_partition(p->current_partition);
        if (p->new_partition)
                sym_fdisk_unref_partition(p->new_partition);
 
        if (p->copy_blocks_path_is_our_file)
                unlink_and_free(p->copy_blocks_path);
        else
                free(p->copy_blocks_path);
        safe_close(p->copy_blocks_fd);
 
        free(p->format);
        free(p->block_device_replace);
        btrfs_replacement_free(p->btrfs_replaced);
        free(p->volume_name);
        strv_free(p->exclude_files_source);
        strv_free(p->exclude_files_target);
        strv_free(p->make_directories);
        strv_free(p->make_symlinks);
        ordered_hashmap_free(p->subvolumes);
        free(p->default_subvolume);
        free(p->tpm2_hash_pcr_values);
        free(p->verity_match_key);
        free(p->compression);
        free(p->compression_level);
 
        iovec_done_erase(&p->key);
 
        copy_files_free_many(p->copy_files, p->n_copy_files);
 
        iovec_done(&p->roothash);
 
        free(p->split_name_format);
        unlink_and_free(p->split_path);
        partition_mountpoint_free_many(p->mountpoints, p->n_mountpoints);
        p->mountpoints = NULL;
        p->n_mountpoints = 0;
 
        partition_encrypted_volume_free(p->encrypted_volume);
 
        partition_unlink_supplement(p);
 
        return mfree(p);
}
 
static void partition_foreignize(Partition *p) {
        assert(p);
        assert(PARTITION_EXISTS(p));
 
        /* Reset several parameters set through definition file to make the partition foreign. */
 
        p->definition_path = mfree(p->definition_path);
        p->drop_in_files = strv_free(p->drop_in_files);
 
        p->copy_blocks_path = mfree(p->copy_blocks_path);
        p->copy_blocks_fd = safe_close(p->copy_blocks_fd);
        p->copy_blocks_root = NULL;
 
        p->format = mfree(p->format);
        p->block_device_replace = mfree(p->block_device_replace);
        p->btrfs_replaced = btrfs_replacement_free(p->btrfs_replaced);
        p->volume_name = mfree(p->volume_name);
        p->exclude_files_source = strv_free(p->exclude_files_source);
        p->exclude_files_target = strv_free(p->exclude_files_target);
        p->make_directories = strv_free(p->make_directories);
        p->make_symlinks = strv_free(p->make_symlinks);
        p->subvolumes = ordered_hashmap_free(p->subvolumes);
        p->default_subvolume = mfree(p->default_subvolume);
        p->tpm2_hash_pcr_values = mfree(p->tpm2_hash_pcr_values);
        p->verity_match_key = mfree(p->verity_match_key);
        p->compression = mfree(p->compression);
        p->compression_level = mfree(p->compression_level);
 
        iovec_done_erase(&p->key);
 
        copy_files_free_many(p->copy_files, p->n_copy_files);
        p->copy_files = NULL;
        p->n_copy_files = 0;
 
        p->priority = 0;
        p->weight = 1000;
        p->padding_weight = 0;
        p->size_min = UINT64_MAX;
        p->size_max = UINT64_MAX;
        p->padding_min = UINT64_MAX;
        p->padding_max = UINT64_MAX;
        p->no_auto = -1;
        p->read_only = -1;
        p->growfs = -1;
        p->verity = VERITY_OFF;
        p->add_validatefs = false;
        p->fs_sector_size = UINT64_MAX;
        p->discard = -1;
 
        partition_mountpoint_free_many(p->mountpoints, p->n_mountpoints);
        p->mountpoints = NULL;
        p->n_mountpoints = 0;
 
        p->encrypted_volume = partition_encrypted_volume_free(p->encrypted_volume);
 
        partition_unlink_supplement(p);
}
 
static bool partition_type_exclude(const GptPartitionType *type) {
        if (arg_filter_partitions_type == FILTER_PARTITIONS_NONE)
                return false;
 
        for (size_t i = 0; i < arg_n_filter_partitions; i++)
                if (sd_id128_equal(type->uuid, arg_filter_partitions[i].uuid))
                        return arg_filter_partitions_type == FILTER_PARTITIONS_EXCLUDE;
 
        return arg_filter_partitions_type == FILTER_PARTITIONS_INCLUDE;
}
 
static bool partition_type_defer(const GptPartitionType *type) {
        for (size_t i = 0; i < arg_n_defer_partitions; i++)
                if (sd_id128_equal(type->uuid, arg_defer_partitions[i].uuid))
                        return true;
 
        return false;
}
 
static Partition* partition_unlink_and_free(Context *context, Partition *p) {
        if (!p)
                return NULL;
 
        LIST_REMOVE(partitions, context->partitions, p);
 
        assert(context->n_partitions > 0);
        context->n_partitions--;
 
        return partition_free(p);
}
 
DEFINE_TRIVIAL_CLEANUP_FUNC(Partition*, partition_free);
 
static Context* context_new(
                char **definitions,
                EmptyMode empty,
                bool dry_run,
                sd_id128_t seed) {
 
        _cleanup_strv_free_ char **d = NULL;
        if (!strv_isempty(definitions)) {
                d = strv_copy(definitions);
                if (!d)
                        return NULL;
        }
 
        Context *context = new(Context, 1);
        if (!context)
                return NULL;
 
        *context = (Context) {
                .definitions = TAKE_PTR(d),
                .start = UINT64_MAX,
                .end = UINT64_MAX,
                .total = UINT64_MAX,
                .seed = seed,
                .empty = empty,
                .dry_run = dry_run,