HALF ECHO LEARN / REFERENCE COLLECTION
v262.2src/repart/repart.c
Git blob: b40c7a91acf99c5ac898f4de16e45b142c19fa8c
Lines 3001–4000 of 11,995
Partition *p,
const char *path,
const char *const *conf_file_dirs) {
ConfigTableItem table[] = {
{ "Partition", "Type", config_parse_type, 0, &p->type },
{ "Partition", "Label", config_parse_label, 0, &p->new_label },
{ "Partition", "VolumeLabel", config_parse_volume_label, 0, &p->new_volume_label },
{ "Partition", "UUID", config_parse_uuid, 0, p },
{ "Partition", "Priority", config_parse_int32, 0, &p->priority },
{ "Partition", "Weight", config_parse_weight, 0, &p->weight },
{ "Partition", "PaddingWeight", config_parse_weight, 0, &p->padding_weight },
{ "Partition", "SizeMinBytes", config_parse_size4096, 1, &p->size_min },
{ "Partition", "SizeMaxBytes", config_parse_size4096, -1, &p->size_max },
{ "Partition", "PaddingMinBytes", config_parse_size4096, 1, &p->padding_min },
{ "Partition", "PaddingMaxBytes", config_parse_size4096, -1, &p->padding_max },
{ "Partition", "FactoryReset", config_parse_bool, 0, &p->factory_reset },
{ "Partition", "CopyBlocks", config_parse_copy_blocks, 0, p },
{ "Partition", "Format", config_parse_fstype, 0, &p->format },
{ "Partition", "CopyFiles", config_parse_copy_files, 0, p },
{ "Partition", "ExcludeFiles", config_parse_exclude_files, 0, &p->exclude_files_source },
{ "Partition", "ExcludeFilesTarget", config_parse_exclude_files, 0, &p->exclude_files_target },
{ "Partition", "MakeDirectories", config_parse_make_dirs, 0, &p->make_directories },
{ "Partition", "MakeSymlinks", config_parse_make_symlinks, 0, &p->make_symlinks },
{ "Partition", "Encrypt", config_parse_encrypt, 0, &p->encrypt },
{ "Partition", "Verity", config_parse_verity, 0, &p->verity },
{ "Partition", "VerityMatchKey", config_parse_string, 0, &p->verity_match_key },
{ "Partition", "Flags", config_parse_gpt_flags, 0, &p->gpt_flags },
{ "Partition", "ReadOnly", config_parse_tristate, 0, &p->read_only },
{ "Partition", "NoAuto", config_parse_tristate, 0, &p->no_auto },
{ "Partition", "GrowFileSystem", config_parse_tristate, 0, &p->growfs },
{ "Partition", "SplitName", config_parse_string, 0, &p->split_name_format },
{ "Partition", "Minimize", config_parse_minimize, 0, &p->minimize },
{ "Partition", "Subvolumes", config_parse_subvolumes, 0, &p->subvolumes },
{ "Partition", "DefaultSubvolume", config_parse_default_subvolume, 0, &p->default_subvolume },
{ "Partition", "VerityDataBlockSizeBytes", config_parse_block_size, 0, &p->verity_data_block_size },
{ "Partition", "VerityHashBlockSizeBytes", config_parse_block_size, 0, &p->verity_hash_block_size },
{ "Partition", "MountPoint", config_parse_mountpoint, 0, p },
{ "Partition", "EncryptedVolume", config_parse_encrypted_volume, 0, p },
{ "Partition", "TPM2PCRs", config_parse_tpm2_pcrs, 0, p },
{ "Partition", "KeyFile", config_parse_key_file, 0, p },
{ "Partition", "Integrity", config_parse_integrity, 0, &p->integrity },
{ "Partition", "IntegrityAlgorithm", config_parse_integrity_alg, 0, &p->integrity_alg },
{ "Partition", "EncryptKDF", config_parse_encrypt_kdf, 0, &p->encrypt_kdf },
{ "Partition", "Compression", config_parse_string, CONFIG_PARSE_STRING_SAFE_AND_ASCII, &p->compression },
{ "Partition", "CompressionLevel", config_parse_string, CONFIG_PARSE_STRING_SAFE_AND_ASCII, &p->compression_level },
{ "Partition", "SupplementFor", config_parse_string, 0, &p->supplement_for_name },
{ "Partition", "AddValidateFS", config_parse_tristate, 0, &p->add_validatefs },
{ "Partition", "FileSystemSectorSize", config_parse_fs_sector_size, 0, &p->fs_sector_size },
{ "Partition", "Discard", config_parse_tristate, 0, &p->discard },
{ "Partition", "BlockDeviceReplace", config_parse_path, 0, &p->block_device_replace },
{ "Partition", "VolumeName", config_parse_string, CONFIG_PARSE_STRING_SAFE, &p->volume_name },
{}
};
_cleanup_free_ char *filename = NULL;
const char* dropin_dirname;
int r;
assert(c);
assert(p);
assert(path);
r = path_extract_filename(path, &filename);
if (r < 0)
return log_error_errno(r, "Failed to extract filename from path '%s': %m", path);
dropin_dirname = strjoina(filename, ".d");
r = config_parse_many_full(
STRV_MAKE_CONST(path),
conf_file_dirs,
dropin_dirname,
c->definitions ? NULL : arg_root,
/* root_fd= */ -EBADF,
"Partition\0",
config_item_table_lookup, table,
CONFIG_PARSE_WARN,
p,
/* ret_stats_by_path= */ NULL,
&p->drop_in_files);
if (r < 0)
return r;
if (partition_type_exclude(&p->type))
return 0;
if (p->size_min != UINT64_MAX && p->size_max != UINT64_MAX && p->size_min > p->size_max)
return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
"SizeMinBytes= larger than SizeMaxBytes=, refusing.");
if (p->padding_min != UINT64_MAX && p->padding_max != UINT64_MAX && p->padding_min > p->padding_max)
return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
"PaddingMinBytes= larger than PaddingMaxBytes=, refusing.");
if (sd_id128_is_null(p->type.uuid))
return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
"Type= not defined, refusing.");
if ((p->copy_blocks_path || p->copy_blocks_auto) && (p->format || partition_needs_populate(p)))
return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
"Format=/CopyFiles=/MakeDirectories=/MakeSymlinks= and CopyBlocks= cannot be combined, refusing.");
if (p->block_device_replace && (p->format || partition_needs_populate(p)))
return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
"Format=/CopyFiles=/MakeDirectories=/MakeSymlinks= and BlockDeviceReplace= cannot be combined, refusing.");
if ((p->copy_blocks_path || p->copy_blocks_auto) && p->block_device_replace)
return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
"CopyBlocks= and BlockDeviceReplace= cannot be combined, refusing.");
if (p->block_device_replace && arg_offline == 1)
return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
"BlockDeviceReplace= is incompatible with --offline=yes, refusing.");
if (p->volume_name && !filename_is_valid(p->volume_name))
return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
"VolumeName= has an invalid filename value, refusing.");
if (p->volume_name && strlen(p->volume_name) > (DM_NAME_LEN - 1))
return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
"VolumeName= is too long, refusing.");
if (p->volume_name && p->encrypt == ENCRYPT_OFF)
return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
"VolumeName= requires Encrypt= to be enabled, refusing.");
if (p->volume_name && !p->block_device_replace)
return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
"VolumeName= requires BlockDeviceReplace= to be set, refusing.");
if (partition_needs_populate(p) && streq_ptr(p->format, "swap"))
return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
"Format=swap and CopyFiles=/MakeDirectories=/MakeSymlinks= cannot be combined, refusing.");
if (!p->format) {
const char *format = NULL;
if (p->type.designator == PARTITION_SWAP)
format = "swap";
else if (partition_needs_populate(p) || (p->encrypt != ENCRYPT_OFF && !(p->copy_blocks_path || p->copy_blocks_auto || p->block_device_replace)))
/* Pick "vfat" as file system for esp and xbootldr partitions, otherwise default to "ext4". */
format = IN_SET(p->type.designator, PARTITION_ESP, PARTITION_XBOOTLDR) ? "vfat" : "ext4";
if (format) {
p->format = strdup(format);
if (!p->format)
return log_oom();
}
}
if (streq_ptr(p->format, "empty")) {
p->format = mfree(p->format);
if (p->no_auto < 0 && gpt_partition_type_knows_no_auto(p->type))
p->no_auto = true;
if (!p->new_label) {
p->new_label = strdup("_empty");
if (!p->new_label)
return log_oom();
}
}
if (p->minimize != MINIMIZE_OFF && !p->format && p->verity != VERITY_HASH)
return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
"Minimize= can only be enabled if Format= or Verity=hash are set.");
if (p->minimize == MINIMIZE_BEST &&
p->format &&
!fstype_is_ro(p->format) &&
!streq(p->format, "btrfs") &&
p->verity != VERITY_HASH)
return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
"Minimize=best can only be used with read-only filesystems, btrfs, or Verity=hash.");
if (partition_needs_populate(p) && !mkfs_supports_root_option(p->format) && geteuid() != 0)
return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EPERM),
"Need to be root to populate %s filesystems with CopyFiles=/MakeDirectories=/MakeSymlinks=.",
p->format);
if (p->format && fstype_is_ro(p->format) && !partition_needs_populate(p))
return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
"Cannot format %s filesystem without source files, refusing.", p->format);
if (p->verity != VERITY_OFF || p->encrypt != ENCRYPT_OFF) {
r = dlopen_cryptsetup(LOG_DEBUG);
if (r < 0)
return log_syntax(NULL, LOG_ERR, path, 1, r,
"libcryptsetup not found, Verity=/Encrypt= are not supported: %m");
}
if (p->verity != VERITY_OFF && !p->verity_match_key)
return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
"VerityMatchKey= must be set if Verity=%s.", verity_mode_to_string(p->verity));
if (p->verity == VERITY_OFF && p->verity_match_key)
return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
"VerityMatchKey= can only be set if Verity= is not \"%s\".",
verity_mode_to_string(p->verity));
if (IN_SET(p->verity, VERITY_HASH, VERITY_SIG)) {
if (p->format || partition_needs_populate(p))
return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
"CopyFiles=/Format=/MakeDirectories=/MakeSymlinks= cannot be used with Verity=%s.",
verity_mode_to_string(p->verity));
/* Later we check that the same CopyBlocks= type (auto vs path) is used for the entire verity set.
* So we assume that CopyBlocks=auto is going to be correct and just path based blocks might result in
* a broken setup */
if (p->copy_blocks_path)
log_syntax(NULL, LOG_DEBUG, path, 1, 0,
"CopyBlocks= with Verity=%s bypasses dm-verity hash/signature computation; repart cannot verify the resulting setup is correct.",
verity_mode_to_string(p->verity));
}
if (IN_SET(p->verity, VERITY_HASH, VERITY_SIG) && p->encrypt != ENCRYPT_OFF)
return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
"Encrypting verity hash/signature partitions is not supported.");
if (p->verity == VERITY_SIG && (p->size_min != UINT64_MAX || p->size_max != UINT64_MAX))
return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
"SizeMinBytes=/SizeMaxBytes= cannot be used with Verity=%s.",
verity_mode_to_string(p->verity));
if (p->integrity == INTEGRITY_INLINE && p->encrypt == ENCRYPT_OFF)
return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
"Integrity=inline requires Encrypt=.");
if (p->default_subvolume && !ordered_hashmap_contains(p->subvolumes, p->default_subvolume))
return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
"DefaultSubvolume= must be one of the paths in Subvolumes=.");
if (p->supplement_for_name) {
if (!filename_part_is_valid(p->supplement_for_name))
return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
"SupplementFor= is an invalid filename: %s",
p->supplement_for_name);
if (p->copy_blocks_path || p->copy_blocks_auto || p->encrypt != ENCRYPT_OFF ||
p->verity != VERITY_OFF)
return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
"SupplementFor= cannot be combined with CopyBlocks=/Encrypt=/Verity=");
}
if (p->encrypt == ENCRYPT_OFF && p->discard > 0)
log_syntax(NULL, LOG_WARNING, path, 1, 0,
"Discard=yes has no effect with Encrypt=off.");
if (p->encrypt == ENCRYPT_OFF && p->encrypt_kdf >= 0)
log_syntax(NULL, LOG_WARNING, path, 1, 0,
"EncryptKDF= has no effect with Encrypt=off.");
if (p->encrypt != ENCRYPT_OFF && p->integrity == INTEGRITY_INLINE && p->discard > 0)
return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
"Integrity=inline is incompatible with Discard=yes.");
/* Verity partitions are read only, let's imply the RO flag hence, unless explicitly configured otherwise. */
if ((partition_designator_is_verity_hash(p->type.designator) ||
partition_designator_is_verity_sig(p->type.designator) ||
IN_SET(p->verity, VERITY_DATA, VERITY_SIG)) && p->read_only < 0)
p->read_only = true;
/* Default to "growfs" on, unless read-only */
if (gpt_partition_type_knows_growfs(p->type) &&
p->read_only <= 0)
p->growfs = true;
if (!p->split_name_format) {
char *s = strdup("%t");
if (!s)
return log_oom();
p->split_name_format = s;
} else if (streq(p->split_name_format, "-"))
p->split_name_format = mfree(p->split_name_format);
r = partition_finalize_fstype(p, path);
if (r < 0)
return r;
return 1;
}
static int find_verity_sibling(Context *context, Partition *p, VerityMode mode, Partition **ret) {
Partition *s = NULL;
assert(p);
assert(p->verity != VERITY_OFF);
assert(p->verity_match_key);
assert(mode != VERITY_OFF);
assert(p->verity != mode);
assert(ret);
/* Try to find the matching sibling partition of the given type for a verity partition. For a data
* partition, this is the corresponding hash partition with the same verity name (and vice versa for
* the hash partition). */
LIST_FOREACH(partitions, q, context->partitions) {
if (p == q)
continue;
if (q->verity != mode)
continue;
assert(q->verity_match_key);
if (!streq(p->verity_match_key, q->verity_match_key))
continue;
if (s)
return -ENOTUNIQ;
s = q;
}
if (!s)
return -ENXIO;
*ret = s;
return 0;
}
static int context_open_and_lock_backing_fd(const char *node, int operation, int mode, int *backing_fd) {
_cleanup_close_ int fd = -EBADF;
assert(node);
assert(backing_fd);
assert(IN_SET(mode, O_RDONLY, O_RDWR));
if (*backing_fd >= 0)
return 0;
fd = open(node, mode|O_CLOEXEC);
if (fd < 0)
return log_error_errno(errno, "Failed to open device '%s': %m", node);
/* Tell udev not to interfere while we are processing the device */
if (flock(fd, operation) < 0)
return log_error_errno(errno, "Failed to lock device '%s': %m", node);
log_debug("Device %s opened and locked.", node);
*backing_fd = TAKE_FD(fd);
return 1;
}
static int determine_current_padding(
struct fdisk_context *c,
struct fdisk_table *t,
struct fdisk_partition *p,
uint64_t secsz,
uint64_t grainsz,
uint64_t *ret,
bool *ret_is_last_partition) {
size_t n_partitions;
uint64_t offset, next = UINT64_MAX;
bool is_last_partition = false;
assert(c);
assert(t);
assert(p);
assert(ret);
if (!sym_fdisk_partition_has_end(p))
return log_error_errno(SYNTHETIC_ERRNO(EIO), "Partition has no end.");
offset = sym_fdisk_partition_get_end(p);
assert(offset < UINT64_MAX);
offset++; /* The end is one sector before the next partition or padding. */
assert(offset < UINT64_MAX / secsz);
offset *= secsz;
n_partitions = sym_fdisk_table_get_nents(t);
for (size_t i = 0; i < n_partitions; i++) {
struct fdisk_partition *q;
uint64_t start;
q = sym_fdisk_table_get_partition(t, i);
if (!q)
return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to read partition metadata.");
if (sym_fdisk_partition_is_used(q) <= 0)
continue;
if (!sym_fdisk_partition_has_start(q))
continue;
start = sym_fdisk_partition_get_start(q);
assert(start < UINT64_MAX / secsz);
start *= secsz;
if (start >= offset && (next == UINT64_MAX || next > start))
next = start;
}
if (next == UINT64_MAX) {
is_last_partition = true;
/* No later partition? In that case check the end of the usable area */
next = sym_fdisk_get_last_lba(c);
assert(next < UINT64_MAX);
next++; /* The last LBA is one sector before the end */
assert(next < UINT64_MAX / secsz);
next *= secsz;
if (offset > next)
return log_error_errno(SYNTHETIC_ERRNO(EIO), "Partition end beyond disk end.");
}
assert(next >= offset);
offset = round_up_size(offset, grainsz);
next = round_down_size(next, grainsz);
if (ret_is_last_partition)
*ret_is_last_partition = is_last_partition;
*ret = LESS_BY(next, offset); /* Saturated subtraction, rounding might have fucked things up */
return 0;
}
static int context_copy_from_one(Context *context, const char *src) {
_cleanup_close_ int fd = -EBADF;
_cleanup_(fdisk_unref_contextp) struct fdisk_context *c = NULL;
_cleanup_(fdisk_unref_tablep) struct fdisk_table *t = NULL;
Partition *last = NULL;
unsigned long secsz;
size_t n_partitions;
int r;
assert(src);
r = context_open_and_lock_backing_fd(src, LOCK_SH, O_RDONLY, &fd);
if (r < 0)
return r;
r = fd_verify_regular_or_block(fd);
if (r < 0)
return log_error_errno(r, "'%s' is not a file nor a block device: %m", src);
r = fdisk_new_context_at(fd, /* path= */ NULL, /* read_only= */ true, /* sector_size= */ UINT32_MAX, &c);
if (r < 0)
return log_error_errno(r, "Failed to create fdisk context: %m");
secsz = sym_fdisk_get_sector_size(c);
/* Insist on a power of two, and that it's a multiple of 512, i.e. the traditional sector size. */
if (secsz < 512 || !ISPOWEROF2(secsz))
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Sector size %lu is not a power of two larger than 512? Refusing.", secsz);
if (!sym_fdisk_is_labeltype(c, FDISK_DISKLABEL_GPT))
return log_error_errno(SYNTHETIC_ERRNO(EHWPOISON), "Cannot copy from disk %s with no GPT disk label.", src);
r = sym_fdisk_get_partitions(c, &t);
if (r < 0)
return log_error_errno(r, "Failed to acquire partition table: %m");
n_partitions = sym_fdisk_table_get_nents(t);
for (size_t i = 0; i < n_partitions; i++) {
_cleanup_(partition_freep) Partition *np = NULL;
_cleanup_free_ char *label_copy = NULL;
struct fdisk_partition *p;
const char *label;
uint64_t sz, start, padding;
sd_id128_t ptid, id;
GptPartitionType type;
bool is_last_partition;
p = sym_fdisk_table_get_partition(t, i);
if (!p)
return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to read partition metadata.");
if (sym_fdisk_partition_is_used(p) <= 0)
continue;
if (sym_fdisk_partition_has_start(p) <= 0 ||
sym_fdisk_partition_has_size(p) <= 0 ||
sym_fdisk_partition_has_partno(p) <= 0)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Found a partition without a position, size or number.");
r = fdisk_partition_get_type_as_id128(p, &ptid);
if (r < 0)
return log_error_errno(r, "Failed to query partition type UUID: %m");
type = gpt_partition_type_from_uuid(ptid);
r = fdisk_partition_get_uuid_as_id128(p, &id);
if (r < 0)
return log_error_errno(r, "Failed to query partition UUID: %m");
label = sym_fdisk_partition_get_name(p);
if (!isempty(label)) {
label_copy = strdup(label);
if (!label_copy)
return log_oom();
}
sz = sym_fdisk_partition_get_size(p);
assert(sz <= UINT64_MAX/secsz);
sz *= secsz;
start = sym_fdisk_partition_get_start(p);
assert(start <= UINT64_MAX/secsz);
start *= secsz;
if (partition_type_exclude(&type))
continue;
np = partition_new(context);
if (!np)
return log_oom();
np->type = type;
np->new_uuid = id;
np->new_uuid_is_set = true;
np->size_min = np->size_max = sz;
np->new_label = TAKE_PTR(label_copy);
np->definition_path = strdup(src);
if (!np->definition_path)
return log_oom();
np->split_name_format = strdup("%t");
if (!np->split_name_format)
return log_oom();
/* Pass grain size of 1 to disable rounding by grain as we don't know the grain size
* of the old image. We'll round paddings to the grain size of the new image later. */
r = determine_current_padding(c, t, p, secsz, /* grainsz= */ 1, &padding, &is_last_partition);
if (r < 0)
return r;
if (!is_last_partition)
np->padding_min = np->padding_max = padding;
np->copy_blocks_path = strdup(src);
if (!np->copy_blocks_path)
return log_oom();
np->copy_blocks_fd = r = RET_NERRNO(fcntl(fd, F_DUPFD_CLOEXEC, 3));
if (r < 0)
return log_error_errno(r, "Failed to duplicate file descriptor of %s: %m", src);
np->copy_blocks_offset = start;
np->copy_blocks_size = sz;
r = fdisk_partition_get_attrs_as_uint64(p, &np->gpt_flags);
if (r < 0)
return log_error_errno(r, "Failed to get partition flags: %m");
LIST_INSERT_AFTER(partitions, context->partitions, last, np);
last = TAKE_PTR(np);
context->n_partitions++;
}
return 0;
}
static int context_copy_from(Context *context) {
int r;
assert(context);
STRV_FOREACH(src, arg_copy_from) {
r = context_copy_from_one(context, *src);
if (r < 0)
return r;
}
return 0;
}
static bool check_cross_def_ranges_valid(uint64_t a_min, uint64_t a_max, uint64_t b_min, uint64_t b_max) {
if (a_min == UINT64_MAX && b_min == UINT64_MAX)
return true;
if (a_max == UINT64_MAX && b_max == UINT64_MAX)
return true;
return MAX(a_min != UINT64_MAX ? a_min : 0, b_min != UINT64_MAX ? b_min : 0) <= MIN(a_max, b_max);
}
static int supplement_find_target(const Context *context, const Partition *supplement, Partition **ret) {
int r;
assert(context);
assert(supplement);
assert(ret);
LIST_FOREACH(partitions, p, context->partitions) {
_cleanup_free_ char *filename = NULL;
if (p == supplement)
continue;
r = path_extract_filename(p->definition_path, &filename);
if (r < 0)
return log_error_errno(r,
"Failed to extract filename from path '%s': %m",
p->definition_path);
*ASSERT_PTR(endswith(filename, ".conf")) = 0; /* Remove the file extension */
if (!streq(supplement->supplement_for_name, filename))
continue;
if (p->supplement_for_name)
return log_syntax(NULL, LOG_ERR, supplement->definition_path, 1, SYNTHETIC_ERRNO(EINVAL),
"SupplementFor= target is itself configured as a supplement.");
if (p->suppressing_supplement)
return log_syntax(NULL, LOG_ERR, supplement->definition_path, 1, SYNTHETIC_ERRNO(EINVAL),
"SupplementFor= target already has a supplement defined: %s",
p->supplemented_by->definition_path);
*ret = p;
return 0;
}
return log_syntax(NULL, LOG_ERR, supplement->definition_path, 1, SYNTHETIC_ERRNO(EINVAL),
"Couldn't find target partition for SupplementFor=%s",
supplement->supplement_for_name);
}
static int context_read_definitions(Context *context) {
_cleanup_strv_free_ char **files = NULL;
Partition *last = LIST_FIND_TAIL(partitions, context->partitions);
const char *const *dirs;
int r;
assert(context);
(void) context_notify(context, PROGRESS_LOADING_DEFINITIONS, /* object= */ NULL, UINT_MAX);
dirs = (const char* const*) (context->definitions ?: CONF_PATHS_STRV("repart.d"));
r = conf_files_list_strv(
&files,
".conf",
context->definitions ? NULL : arg_root,
CONF_FILES_REGULAR|CONF_FILES_FILTER_MASKED|CONF_FILES_WARN|CONF_FILES_DONT_PREFIX_ROOT,
dirs);
if (r < 0)
return log_error_errno(r, "Failed to enumerate *.conf files: %m");
STRV_FOREACH(f, files) {
_cleanup_(partition_freep) Partition *p = NULL;
p = partition_new(context);
if (!p)
return log_oom();
p->definition_path = strdup(*f);
if (!p->definition_path)
return log_oom();
r = partition_read_definition(context, p, *f, dirs);
if (r < 0)
return r;
if (r == 0)
continue;
LIST_INSERT_AFTER(partitions, context->partitions, last, p);
last = TAKE_PTR(p);
context->n_partitions++;
}
/* Check that each configured verity hash/data partition has a matching verity data/hash partition. */
LIST_FOREACH(partitions, p, context->partitions) {
if (p->verity == VERITY_OFF)
continue;
for (VerityMode mode = VERITY_OFF + 1; mode < _VERITY_MODE_MAX; mode++) {
Partition *q = NULL;
if (p->verity == mode)
continue;
if (p->siblings[mode])
continue;
r = find_verity_sibling(context, p, mode, &q);
if (r == -ENXIO) {
if (mode != VERITY_SIG)
return log_syntax(NULL, LOG_ERR, p->definition_path, 1, SYNTHETIC_ERRNO(EINVAL),
"Missing verity %s partition for verity %s partition with VerityMatchKey=%s.",
verity_mode_to_string(mode), verity_mode_to_string(p->verity), p->verity_match_key);
} else if (r == -ENOTUNIQ)
return log_syntax(NULL, LOG_ERR, p->definition_path, 1, SYNTHETIC_ERRNO(EINVAL),
"Multiple verity %s partitions found for verity %s partition with VerityMatchKey=%s.",
verity_mode_to_string(mode), verity_mode_to_string(p->verity), p->verity_match_key);
else if (r < 0)
return log_syntax(NULL, LOG_ERR, p->definition_path, 1, r,
"Failed to find verity %s partition for verity %s partition with VerityMatchKey=%s.",
verity_mode_to_string(mode), verity_mode_to_string(p->verity), p->verity_match_key);
if (q) {
if (q->priority != p->priority)
return log_syntax(NULL, LOG_ERR, p->definition_path, 1, SYNTHETIC_ERRNO(EINVAL),
"Priority mismatch (%i != %i) for verity sibling partitions with VerityMatchKey=%s.",
p->priority, q->priority, p->verity_match_key);
p->siblings[mode] = q;
}
}
}
LIST_FOREACH(partitions, p, context->partitions) {
if (!IN_SET(p->verity, VERITY_HASH, VERITY_SIG))
continue;
/* We check all verity siblings up until our current type and ensure that if we are using CopyBlocks=
* the previous ones are using the same type of CopyBlocks=. */
for (VerityMode mode = VERITY_DATA; mode < p->verity; mode++) {
Partition *q = ASSERT_PTR(p->siblings[mode]);
if (p->copy_blocks_auto && !q->copy_blocks_auto)
return log_syntax(NULL, LOG_ERR, p->definition_path, 1, SYNTHETIC_ERRNO(EINVAL),
"CopyBlocks=auto set with Verity=%s but Verity=%s partition does not set CopyBlocks=auto.",
verity_mode_to_string(p->verity), verity_mode_to_string(mode));
if (p->copy_blocks_path && !q->copy_blocks_path)
return log_syntax(NULL, LOG_ERR, p->definition_path, 1, SYNTHETIC_ERRNO(EINVAL),
"CopyBlocks= set with Verity=%s but Verity=%s partition does not set CopyBlocks=.",
verity_mode_to_string(p->verity), verity_mode_to_string(mode));
}
}
LIST_FOREACH(partitions, p, context->partitions) {
Partition *dp;
if (p->verity != VERITY_HASH)
continue;
if (p->minimize == MINIMIZE_OFF)
continue;
assert_se(dp = p->siblings[VERITY_DATA]);
if (dp->minimize == MINIMIZE_OFF && !(dp->copy_blocks_path || dp->copy_blocks_auto))
return log_syntax(NULL, LOG_ERR, p->definition_path, 1, SYNTHETIC_ERRNO(EINVAL),
"Minimize= set for verity hash partition but data partition does not set CopyBlocks= or Minimize=.");
/* The verity hash of an encrypted data partition covers the ciphertext, which is generated
* with a fresh volume key only when the final image is built, hence it cannot be
* precalculated for minimizing purposes. */
if (dp->encrypt != ENCRYPT_OFF)
return log_syntax(NULL, LOG_ERR, p->definition_path, 1, SYNTHETIC_ERRNO(EINVAL),
"Minimize= cannot be set for verity hash partitions whose data partition is encrypted, use SizeMaxBytes= on the data partition instead.");
}
LIST_FOREACH(partitions, p, context->partitions) {
Partition *tgt = NULL;
if (!p->supplement_for_name)
continue;
r = supplement_find_target(context, p, &tgt);
if (r < 0)
return r;
if (tgt->copy_blocks_path || tgt->copy_blocks_auto || tgt->encrypt != ENCRYPT_OFF ||
tgt->verity != VERITY_OFF)
return log_syntax(NULL, LOG_ERR, p->definition_path, 1, SYNTHETIC_ERRNO(EINVAL),
"SupplementFor= target uses CopyBlocks=/Encrypt=/Verity=");
if (!check_cross_def_ranges_valid(p->size_min, p->size_max, tgt->size_min, tgt->size_max))
return log_syntax(NULL, LOG_ERR, p->definition_path, 1, SYNTHETIC_ERRNO(EINVAL),
"SizeMinBytes= larger than SizeMaxBytes= when merged with SupplementFor= target.");
if (!check_cross_def_ranges_valid(p->padding_min, p->padding_max, tgt->padding_min, tgt->padding_max))
return log_syntax(NULL, LOG_ERR, p->definition_path, 1, SYNTHETIC_ERRNO(EINVAL),
"PaddingMinBytes= larger than PaddingMaxBytes= when merged with SupplementFor= target.");
p->supplement_for = tgt;
tgt->supplemented_by = p;
tgt->suppressing_supplement = true;
}
return 0;
}
static int derive_uuid(sd_id128_t base, const char *token, sd_id128_t *ret) {
union {
uint8_t md[SHA256_DIGEST_SIZE];
sd_id128_t id;
} result;
assert(token);
assert(ret);
/* Derive a new UUID from the specified UUID in a stable and reasonably safe way. Specifically, we
* calculate the HMAC-SHA256 of the specified token string, keyed by the supplied base (typically the
* machine ID). We use the machine ID as key (and not as cleartext!) of the HMAC operation since it's
* the machine ID we don't want to leak. */
hmac_sha256(base.bytes, sizeof(base.bytes), token, strlen(token), result.md);
/* Take the first half, mark it as v4 UUID */
assert_cc(sizeof(result.md) == sizeof(result.id) * 2);
*ret = id128_make_v4_uuid(result.id);
return 0;
}
static void derive_salt(sd_id128_t base, const char *token, uint8_t ret[static SHA256_DIGEST_SIZE]) {
assert(token);
hmac_sha256(base.bytes, sizeof(base.bytes), token, strlen(token), ret);
}
static int context_load_fallback_metrics(Context *context) {
assert(context);
context->sector_size = arg_sector_size > 0 ? arg_sector_size : 512;
context->grain_size = determine_grain_size(context->sector_size);
context->default_fs_sector_size = arg_sector_size > 0 ? arg_sector_size : DEFAULT_FILESYSTEM_SECTOR_SIZE;
return 1; /* Starting from scratch */
}
static int context_open_mode(Context *context) {
return ASSERT_PTR(context)->dry_run ? O_RDONLY : O_RDWR;
}
static int context_load_partition_table(Context *context) {
_cleanup_close_ int fd = -EBADF;
_cleanup_(fdisk_unref_contextp) struct fdisk_context *c = NULL;
_cleanup_(fdisk_unref_tablep) struct fdisk_table *t = NULL;
uint64_t left_boundary = UINT64_MAX, first_lba, last_lba, nsectors;
bool from_scratch = false;
sd_id128_t disk_uuid;
size_t n_partitions;
uint64_t grainsz, fs_secsz = DEFAULT_FILESYSTEM_SECTOR_SIZE;
int r;
assert(context);
assert(context->node);
assert(!context->fdisk_context);
assert(context->fdisk_context_fd < 0);
assert(!context->free_areas);
assert(context->start == UINT64_MAX);
assert(context->end == UINT64_MAX);
assert(context->total == UINT64_MAX);
context_notify(context, PROGRESS_LOADING_TABLE, /* object= */ NULL, UINT_MAX);
c = sym_fdisk_new_context();
if (!c)
return log_oom();
if (arg_sector_size > 0) {
fs_secsz = arg_sector_size;
r = sym_fdisk_save_user_sector_size(c, /* phy= */ 0, arg_sector_size);
} else {
uint32_t ssz;
struct stat st;
r = context_open_and_lock_backing_fd(
context->node,
context->dry_run ? LOCK_SH : LOCK_EX,
context_open_mode(context),
&context->backing_fd);
if (r < 0)
return r;
if (fstat(context->backing_fd, &st) < 0)
return log_error_errno(errno, "Failed to stat %s: %m", context->node);
if (IN_SET(context->empty, EMPTY_REQUIRE, EMPTY_FORCE, EMPTY_CREATE) && S_ISREG(st.st_mode))
/* Don't probe sector size from partition table if we are supposed to start from an empty disk */
ssz = 512;
else {
/* Auto-detect sector size if not specified. */
r = probe_sector_size_prefer_ioctl(context->backing_fd, &ssz);
if (r < 0)
return log_error_errno(r, "Failed to probe sector size of '%s': %m", context->node);
/* If we found the sector size and we're operating on a block device, use it as the file
* system sector size as well, as we know its the sector size of the actual block device and
* not just the offset at which we found the GPT header. */
if (r > 0 && S_ISBLK(st.st_mode)) {
log_debug("Probed sector size of %s is %" PRIu32 " bytes.", context->node, ssz);
fs_secsz = ssz;
}
}
r = sym_fdisk_save_user_sector_size(c, /* phy= */ 0, ssz);
}
if (r < 0)
return log_error_errno(r, "Failed to set sector size: %m");
if (context->backing_fd < 0) {
fd = open(context->node, context_open_mode(context)|O_CLOEXEC);
if (fd < 0)
return log_error_errno(errno, "Failed to open backing node '%s': %m", context->node);
}
r = sym_fdisk_assign_device_by_fd(
c,
context->backing_fd >= 0 ? context->backing_fd : fd,
context->node,
context->dry_run);
if (r == -EINVAL && arg_size_auto) {
struct stat st;
/* libfdisk returns EINVAL if opening a file of size zero. Let's check for that, and accept
* it if automatic sizing is requested. */
if (context->backing_fd < 0)
r = fstat(fd, &st);
else
r = fstat(context->backing_fd, &st);
if (r < 0)
return log_error_errno(errno, "Failed to stat block device '%s': %m", context->node);
if (S_ISREG(st.st_mode) && st.st_size == 0) {
/* Use the fallback values if we have no better idea */
context->sector_size = sym_fdisk_get_sector_size(c);
context->default_fs_sector_size = fs_secsz;
context->grain_size = determine_grain_size(context->sector_size);
return /* from_scratch= */ true;
}
r = -EINVAL;
}
if (r < 0)
return log_error_errno(r, "Failed to open device '%s': %m", context->node);
if (context->backing_fd < 0) {
/* If we have no fd referencing the device yet, make a copy of the fd now, so that we have one */
r = context_open_and_lock_backing_fd(FORMAT_PROC_FD_PATH(sym_fdisk_get_devfd(c)),
context->dry_run ? LOCK_SH : LOCK_EX,
context_open_mode(context),
&context->backing_fd);
if (r < 0)
return r;
}
/* The offsets/sizes libfdisk returns to us will be in multiple of the sector size of the
* device. This is typically 512, and sometimes 4096. Let's query libfdisk once for it, and then use
* it for all our needs. Note that the values we use ourselves always are in bytes though, thus mean
* the same thing universally. Also note that regardless what kind of sector size is in use we'll
* place partitions at multiples of 4K. */
unsigned long secsz = sym_fdisk_get_sector_size(c);
/* Insist on a power of two, and that it's a multiple of 512, i.e. the traditional sector size. */
if (secsz < 512 || !ISPOWEROF2(secsz))
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Sector size %lu is not a power of two larger than 512? Refusing.", secsz);
/* Determine the grain size: by default at least 4K and a multiple of the sector size, but may be
* overridden via --grain-size=. */
grainsz = determine_grain_size(secsz);
log_debug("Sector size of device is %lu bytes. Using default filesystem sector size of %" PRIu64 " and grain size of %" PRIu64 ".", secsz, fs_secsz, grainsz);
switch (context->empty) {
case EMPTY_REFUSE:
/* Refuse empty disks, insist on an existing GPT partition table */
if (!sym_fdisk_is_labeltype(c, FDISK_DISKLABEL_GPT))
return log_notice_errno(SYNTHETIC_ERRNO(EHWPOISON), "Disk %s has no GPT disk label, not repartitioning.", context->node);
break;
case EMPTY_REQUIRE:
/* Require an empty disk, refuse any existing partition table */
r = sym_fdisk_has_label(c);
if (r < 0)
return log_error_errno(r, "Failed to determine whether disk %s has a disk label: %m", context->node);
if (r > 0)
return log_notice_errno(SYNTHETIC_ERRNO(EHWPOISON), "Disk %s already has a disk label, refusing.", context->node);
from_scratch = true;
break;
case EMPTY_ALLOW:
/* Allow both an empty disk and an existing partition table, but only GPT */
r = sym_fdisk_has_label(c);
if (r < 0)
return log_error_errno(r, "Failed to determine whether disk %s has a disk label: %m", context->node);
if (r > 0) {
if (!sym_fdisk_is_labeltype(c, FDISK_DISKLABEL_GPT))
return log_notice_errno(SYNTHETIC_ERRNO(EHWPOISON), "Disk %s has non-GPT disk label, not repartitioning.", context->node);
} else
from_scratch = true;
break;
case EMPTY_FORCE:
case EMPTY_CREATE:
/* Always reinitiaize the disk, don't consider what there was on the disk before */
from_scratch = true;
break;
default:
assert_not_reached();
}
if (from_scratch) {
r = sym_fdisk_create_disklabel(c, "gpt");