HALF ECHO LEARN / REFERENCE COLLECTION
v262.2src/repart/repart.c
Git blob: b40c7a91acf99c5ac898f4de16e45b142c19fa8c
Lines 8001–9000 of 11,995
gpt_partition_type_uuid_to_string_harder(p->type.uuid, buffer));
}
}
return f;
}
static int context_mangle_partitions(Context *context) {
int r;
assert(context);
LIST_FOREACH(partitions, p, context->partitions) {
if (p->dropped)
continue;
if (partition_defer(context, p))
continue;
(void) context_notify(context, PROGRESS_ADJUSTING_PARTITION, p->definition_path, UINT_MAX);
assert(p->new_size != UINT64_MAX);
assert(p->offset != UINT64_MAX);
assert(p->partno != UINT64_MAX);
if (PARTITION_EXISTS(p)) {
bool changed = false;
assert(p->current_partition);
if (p->new_size != p->current_size) {
assert(p->new_size >= p->current_size);
assert(p->new_size % context->sector_size == 0);
r = sym_fdisk_partition_size_explicit(p->current_partition, true);
if (r < 0)
return log_error_errno(r, "Failed to enable explicit sizing: %m");
r = sym_fdisk_partition_set_size(p->current_partition, p->new_size / context->sector_size);
if (r < 0)
return log_error_errno(r, "Failed to grow partition: %m");
log_info("Growing existing partition %" PRIu64 ".", p->partno);
changed = true;
}
if (!sd_id128_equal(p->new_uuid, p->current_uuid)) {
r = sym_fdisk_partition_set_uuid(p->current_partition, SD_ID128_TO_UUID_STRING(p->new_uuid));
if (r < 0)
return log_error_errno(r, "Failed to set partition UUID: %m");
log_info("Initializing UUID of existing partition %" PRIu64 ".", p->partno);
changed = true;
}
if (!streq_ptr(p->new_label, p->current_label)) {
r = sym_fdisk_partition_set_name(p->current_partition, strempty(p->new_label));
if (r < 0)
return log_error_errno(r, "Failed to set partition label: %m");
log_info("Setting partition label of existing partition %" PRIu64 ".", p->partno);
changed = true;
}
if (changed) {
assert(!PARTITION_IS_FOREIGN(p)); /* never touch foreign partitions */
r = sym_fdisk_set_partition(context->fdisk_context, p->partno, p->current_partition);
if (r < 0)
return log_error_errno(r, "Failed to update partition: %m");
}
} else {
_cleanup_(fdisk_unref_partitionp) struct fdisk_partition *q = NULL;
_cleanup_(fdisk_unref_parttypep) struct fdisk_parttype *t = NULL;
assert(!p->new_partition);
assert(p->offset % context->sector_size == 0);
assert(p->new_size % context->sector_size == 0);
assert(p->new_label);
t = sym_fdisk_new_parttype();
if (!t)
return log_oom();
r = sym_fdisk_parttype_set_typestr(t, SD_ID128_TO_UUID_STRING(p->type.uuid));
if (r < 0)
return log_error_errno(r, "Failed to initialize partition type: %m");
q = sym_fdisk_new_partition();
if (!q)
return log_oom();
r = sym_fdisk_partition_set_type(q, t);
if (r < 0)
return log_error_errno(r, "Failed to set partition type: %m");
r = sym_fdisk_partition_size_explicit(q, true);
if (r < 0)
return log_error_errno(r, "Failed to enable explicit sizing: %m");
r = sym_fdisk_partition_set_start(q, p->offset / context->sector_size);
if (r < 0)
return log_error_errno(r, "Failed to position partition: %m");
r = sym_fdisk_partition_set_size(q, p->new_size / context->sector_size);
if (r < 0)
return log_error_errno(r, "Failed to grow partition: %m");
r = sym_fdisk_partition_set_partno(q, p->partno);
if (r < 0)
return log_error_errno(r, "Failed to set partition number: %m");
r = sym_fdisk_partition_set_uuid(q, SD_ID128_TO_UUID_STRING(p->new_uuid));
if (r < 0)
return log_error_errno(r, "Failed to set partition UUID: %m");
r = sym_fdisk_partition_set_name(q, strempty(p->new_label));
if (r < 0)
return log_error_errno(r, "Failed to set partition label: %m");
/* Merge the no auto + read only + growfs setting with the literal flags, and set them for the partition */
r = set_gpt_flags(q, partition_merge_flags(p));
if (r < 0)
return log_error_errno(r, "Failed to set GPT partition flags: %m");
log_info("Adding new partition %" PRIu64 " to partition table.", p->partno);
r = sym_fdisk_add_partition(context->fdisk_context, q, NULL);
if (r < 0)
return log_error_errno(r, "Failed to add partition: %m");
assert(!p->new_partition);
p->new_partition = TAKE_PTR(q);
}
}
return 0;
}
static int split_name_printf(Partition *p, char **ret) {
assert(p);
const Specifier table[] = {
{ 't', specifier_string, GPT_PARTITION_TYPE_UUID_TO_STRING_HARDER(p->type.uuid) },
{ 'T', specifier_id128, &p->type.uuid },
{ 'U', specifier_id128, &p->new_uuid },
{ 'n', specifier_uint64, &p->partno },
COMMON_SYSTEM_SPECIFIERS,
{}
};
return specifier_printf(p->split_name_format, NAME_MAX, table, arg_root, p, ret);
}
static int split_node(const char *node, char **ret_base, char **ret_ext) {
_cleanup_free_ char *base = NULL, *ext = NULL;
char *e;
int r;
assert(node);
assert(ret_base);
assert(ret_ext);
r = path_extract_filename(node, &base);
if (r == O_DIRECTORY || r == -EADDRNOTAVAIL)
return log_error_errno(r, "Device node %s cannot be a directory", node);
if (r < 0)
return log_error_errno(r, "Failed to extract filename from %s: %m", node);
e = endswith(base, ".raw");
if (e) {
ext = strdup(e);
if (!ext)
return log_oom();
*e = 0;
}
*ret_base = TAKE_PTR(base);
*ret_ext = TAKE_PTR(ext);
return 0;
}
static int split_name_resolve(Context *context) {
_cleanup_free_ char *parent = NULL, *base = NULL, *ext = NULL;
int r;
assert(context);
r = path_extract_directory(context->node, &parent);
if (r < 0 && r != -EDESTADDRREQ)
return log_error_errno(r, "Failed to extract directory from %s: %m", context->node);
r = split_node(context->node, &base, &ext);
if (r < 0)
return r;
LIST_FOREACH(partitions, p, context->partitions) {
_cleanup_free_ char *resolved = NULL;
if (p->dropped)
continue;
if (!p->split_name_format)
continue;
r = split_name_printf(p, &resolved);
if (r < 0)
return log_error_errno(r, "Failed to resolve specifiers in %s: %m", p->split_name_format);
if (parent)
p->split_path = strjoin(parent, "/", base, ".", resolved, ext);
else
p->split_path = strjoin(base, ".", resolved, ext);
if (!p->split_path)
return log_oom();
}
LIST_FOREACH(partitions, p, context->partitions) {
if (!p->split_path)
continue;
LIST_FOREACH(partitions, q, context->partitions) {
if (p == q)
continue;
if (!q->split_path)
continue;
if (!streq(p->split_path, q->split_path))
continue;
return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ),
"%s and %s have the same resolved split name \"%s\", refusing.",
p->definition_path, q->definition_path, p->split_path);
}
}
return 0;
}
static int context_split(Context *context) {
unsigned attrs = 0;
int fd = -EBADF, r;
if (!arg_split)
return 0;
assert(context);
/* We can't do resolution earlier because the partition UUIDs for verity partitions are only filled
* in after they've been generated. */
r = split_name_resolve(context);
if (r < 0)
return r;
LIST_FOREACH(partitions, p, context->partitions) {
_cleanup_close_ int fdt = -EBADF;
if (p->dropped)
continue;
if (!p->split_path)
continue;
if (partition_defer(context, p))
continue;
if (fd < 0) {
assert_se((fd = sym_fdisk_get_devfd(context->fdisk_context)) >= 0);
r = read_attr_fd(fd, &attrs);
if (r < 0 && !ERRNO_IS_NEG_NOT_SUPPORTED(r))
log_warning_errno(r, "Failed to read file attributes of %s, ignoring: %m", context->node);
}
fdt = xopenat_full(
AT_FDCWD,
p->split_path,
O_WRONLY|O_NOCTTY|O_CLOEXEC|O_NOFOLLOW|O_CREAT|O_EXCL,
attrs & FS_NOCOW_FL ? XO_NOCOW : 0,
0666);
if (fdt < 0)
return log_error_errno(fdt, "Failed to open split partition file %s: %m", p->split_path);
if (lseek(fd, p->offset, SEEK_SET) < 0)
return log_error_errno(errno, "Failed to seek to partition offset: %m");
/* Verity signature partitions contain a JSON object NUL-padded out to the partition
* size. The on-disk partition must keep the padding, but the split-out file is a
* standalone artifact, so trim the trailing NUL bytes there to avoid tripping jq. */
if (partition_designator_is_verity_sig(p->type.designator)) {
_cleanup_free_ char *buf = malloc(p->new_size);
if (!buf)
return log_oom();
r = loop_read_exact(fd, buf, p->new_size, /* do_poll= */ false);
if (r < 0)
return log_error_errno(r, "Failed to read verity signature partition: %m");
size_t len = strnlen(buf, p->new_size);
if (len == 0)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Verity signature partition is empty");
r = loop_write(fdt, buf, len);
if (r < 0)
return log_error_errno(r, "Failed to write to split partition %s: %m", p->split_path);
} else {
r = copy_bytes(fd, fdt, p->new_size, COPY_HOLES|COPY_TRUNCATE);
if (r < 0)
return log_error_errno(r, "Failed to copy to split partition %s: %m", p->split_path);
}
}
return 0;
}
static int write_primary_descriptor(
int fd,
uint32_t root_sector,
usec_t usec,
bool utc,
const char *system_id,
const char *volume_id,
const char *publisher_id) {
int r;
assert(fd >= 0);
struct iso9660_primary_volume_descriptor desc = {
.header = {
.type = 1,
.version = 1,
},
.volume_space_size_little = htole32(ISO9660_START + ISO9660_SIZE),
.volume_space_size_big = htobe32(ISO9660_START + ISO9660_SIZE),
.volume_set_size_little = htole16(1),
.volume_set_size_big = htobe16(1),
.volume_sequence_number_little = htole16(1),
.volume_sequence_number_big = htobe16(1),
.logical_block_size_little = htole16(ISO9660_BLOCK_SIZE),
.logical_block_size_big = htobe16(ISO9660_BLOCK_SIZE),
.file_structure_version = 1,
.root_directory_entry = {
.len = sizeof(struct iso9660_directory_entry),
.extent_loc_little = htole32(root_sector),
.extent_loc_big = htobe32(root_sector),
.data_len_little = htole32(2*sizeof(struct iso9660_directory_entry)), /* 2 entries with ident size 1: . and .. */
.data_len_big = htobe32(2*sizeof(struct iso9660_directory_entry)), /* 2 entries with ident size 1: . and .. */
.flags = 2, /* directory */
.volume_seq_num_little = htole16(1),
.volume_seq_num_big = htobe16(1),
.ident_len = 1,
.ident[0] = 0, /* special value for root */
}
};
iso9660_set_const_string(desc.header.identifier, sizeof(desc.header.identifier), "CD001", /* allow_a_chars= */ true);
r = iso9660_dir_datetime_from_usec(usec, utc, &desc.root_directory_entry.time);
if (r < 0)
return r;
r = iso9660_set_string(desc.system_identifier, sizeof(desc.system_identifier), system_id, /* allow_a_chars= */ true);
if (r < 0)
return r;
/* In theory the volume identifier should be d-chars, but in practice, a-chars are allowed */
r = iso9660_set_string(desc.volume_identifier, sizeof(desc.volume_identifier), volume_id, /* allow_a_chars= */ true);
if (r < 0)
return r;
iso9660_set_const_string(desc.volume_set_identifier, sizeof(desc.volume_set_identifier), NULL, /* allow_a_chars= */ false);
r = iso9660_set_string(desc.publisher_identifier, sizeof(desc.publisher_identifier), publisher_id, /* allow_a_chars= */ true);
if (r < 0)
return r;
iso9660_set_const_string(desc.data_preparer_identifier, sizeof(desc.data_preparer_identifier), NULL, /* allow_a_chars= */ true);
iso9660_set_const_string(desc.application_identifier, sizeof(desc.application_identifier), "SYSTEMD-REPART", /* allow_a_chars= */ true);
iso9660_set_const_string(desc.copyright_file_identifier, sizeof(desc.copyright_file_identifier), NULL, /* allow_a_chars= */ false);
iso9660_set_const_string(desc.abstract_file_identifier, sizeof(desc.abstract_file_identifier), NULL, /* allow_a_chars= */ false);
iso9660_set_const_string(desc.bibliographic_file_identifier, sizeof(desc.bibliographic_file_identifier), NULL, /* allow_a_chars= */ false);
r = iso9660_datetime_from_usec(usec, utc, &desc.volume_creation_date);
if (r < 0)
return r;
r = iso9660_datetime_from_usec(usec, utc, &desc.volume_modification_date);
if (r < 0)
return r;
iso9660_datetime_zero(&desc.volume_expiration_date);
iso9660_datetime_zero(&desc.volume_effective_date);
r = pwrite_full(fd, &desc, sizeof(desc), ISO9660_PRIMARY_DESCRIPTOR*ISO9660_BLOCK_SIZE);
if (r < 0)
return log_error_errno(r, "Failed to write ISO9660 primary descriptor: %m");
return 0;
}
static int write_eltorito_descriptor(int fd, uint32_t catalog_sector) {
int r;
assert(fd >= 0);
struct iso9660_eltorito_descriptor desc = {
.header = {
.type = 0,
.version = 1,
},
.boot_catalog_sector = htole32(catalog_sector),
};
iso9660_set_const_string(desc.header.identifier, sizeof(desc.header.identifier), "CD001", /* allow_a_chars= */ true);
strncpy(desc.boot_system_identifier, "EL TORITO SPECIFICATION", sizeof(desc.boot_system_identifier));
r = pwrite_full(fd, &desc, sizeof(desc), ISO9660_ELTORITO_DESCRIPTOR*ISO9660_BLOCK_SIZE);
if (r < 0)
return log_error_errno(r, "Failed to write ISO9660 El-Torito descriptor: %m");
return 0;
}
static int write_terminal_descriptor(int fd) {
int r;
assert(fd >= 0);
struct iso9660_terminal_descriptor desc = {
.header = {
.type = 255,
.version = 1,
},
};
iso9660_set_const_string(desc.header.identifier, sizeof(desc.header.identifier), "CD001", /* allow_a_chars= */ true);
r = pwrite_full(fd, &desc, sizeof(desc), ISO9660_TERMINAL_DESCRIPTOR*ISO9660_BLOCK_SIZE);
if (r < 0)
return log_error_errno(r, "Failed to write ISO9660 terminal descriptor: %m");
return 0;
}
static uint16_t calculate_validation_entry_checksum(const void *p, size_t size) {
assert(p || size == 0);
assert(size % 2 == 0);
uint16_t checksum = 0;
for (size_t i = 0; i < (size/2); i++)
checksum -= le16toh(((const le16_t*)p)[i]);
return checksum;
}
static int write_boot_catalog(int fd, uint32_t load_block) {
int r;
assert(fd >= 0);
struct el_torito_validation_entry ve = {
.header_indicator = 1,
.platform = 0xef, /* EFI */
.key_bytes = {0x55, 0xaa},
};
ve.checksum = htole16(calculate_validation_entry_checksum(&ve, sizeof(ve)));
struct el_torito_initial_entry ie = {
.boot_indicator = 0x88, /* bootable */
.boot_media_type = 0, /* no emul */
/* From UEFI specification:
* > If the value of Sector Count is set to 0 or 1, EFI will assume the system partition
* > consumes the space from the beginning of the “no emulation” image to the end of the
* > CD-ROM.
*/
.sector_count = htole16(0),
.load_rba = htole32(load_block),
};
struct el_torito_section_header sh = {
.header_indicator = 0x91, /* final header */
.nentries = htole16(0), /* no more entries */
};
uint8_t sector[ISO9660_BLOCK_SIZE] = {};
uint8_t *p = sector;
p = mempcpy(p, &ve, sizeof(ve));
p = mempcpy(p, &ie, sizeof(ie));
p = mempcpy(p, &sh, sizeof(sh));
assert((size_t) (p - sector) <= sizeof(sector));
r = pwrite_full(fd, §or, sizeof(sector), ISO9660_BOOT_CATALOG*ISO9660_BLOCK_SIZE);
if (r < 0)
return log_error_errno(r, "Failed to write El-Torito boot catalog: %m");
return 0;
}
static int write_directories(
int fd,
usec_t usec,
bool utc,
uint32_t root_sector) {
int r;
assert(fd >= 0);
uint32_t dir_size = 2*sizeof(struct iso9660_directory_entry); /* 2 entries with ident size 1: . and .. */
struct iso9660_directory_entry self = {
.len = sizeof(struct iso9660_directory_entry),
.extent_loc_little = htole32(root_sector),
.extent_loc_big = htobe32(root_sector),
.data_len_little = htole32(dir_size),
.data_len_big = htobe32(dir_size),
.flags = 2, /* directory */
.volume_seq_num_little = htole16(1),
.volume_seq_num_big = htobe16(1),
.ident_len = 1,
.ident[0] = 0, /* special value for self */
};
r = iso9660_dir_datetime_from_usec(usec, utc, &self.time);
if (r < 0)
return r;
struct iso9660_directory_entry parent = {
.len = sizeof(struct iso9660_directory_entry),
.extent_loc_little = htole32(root_sector),
.extent_loc_big = htobe32(root_sector),
.data_len_little = htole32(dir_size),
.data_len_big = htobe32(dir_size),
.flags = 2, /* directory */
.volume_seq_num_little = htole16(1),
.volume_seq_num_big = htobe16(1),
.ident_len = 1,
.ident[0] = 1, /* special value for parent */
};
// TODO: we should probably add some text file explaining there is no content through ISO9660
r = iso9660_dir_datetime_from_usec(usec, utc, &parent.time);
if (r < 0)
return r;
uint8_t sector[ISO9660_BLOCK_SIZE] = {};
uint8_t *p = sector;
p = mempcpy(p, &self, sizeof(self));
p = mempcpy(p, &parent, sizeof(parent));
assert((size_t) (p - sector) <= sizeof(sector));
r = pwrite_full(fd, §or, sizeof(sector), ISO9660_ROOT_DIRECTORY*ISO9660_BLOCK_SIZE);
if (r < 0)
return log_error_errno(r, "Failed to write ISO9660 root directory: %m");
return 0;
}
static int write_eltorito(
int fd,
usec_t usec,
bool utc,
uint32_t load_block, /* in iso9660 blocks */
const char *system_id,
const char *volume_id,
const char *publisher_id) {
int r;
assert(fd >= 0);
r = write_primary_descriptor(fd, ISO9660_ROOT_DIRECTORY, usec, utc, system_id, volume_id, publisher_id);
if (r < 0)
return r;
r = write_eltorito_descriptor(fd, ISO9660_BOOT_CATALOG);
if (r < 0)
return r;
r = write_terminal_descriptor(fd);
if (r < 0)
return r;
r = write_boot_catalog(fd, load_block);
if (r < 0)
return r;
r = write_directories(fd, usec, utc, ISO9660_ROOT_DIRECTORY);
if (r < 0)
return r;
return 0;
}
static int context_verify_eltorito_overlap(Context *context) {
/* Check if the partition table collides with the ISO9660 El Torito area. */
assert(context);
if (!arg_eltorito)
return 0;
/* Check how many GPT partition entries can be stored. */
size_t nents = sym_fdisk_get_npartitions(context->fdisk_context);
/* The GPT contains
* - 1 unused block (protective MBR)
* - GPT header
* - N entries of 128 bytes each.
*/
size_t first_free_offset = 2*context->sector_size + round_up_size(nents*128, context->sector_size);
if (first_free_offset > ISO9660_START*ISO9660_BLOCK_SIZE)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "The partition table is overlapping with the El Torito boot catalog.");
/* The first lba is the first block where a partition could exist. Even if there is no partition
* there, we should still not overlap with it since a partition could be added later.
* It is unexpected for tools to change the first lba in the GPT header. So this should be safe.
*/
if (sym_fdisk_get_first_lba(context->fdisk_context) * context->sector_size < (ISO9660_START+ISO9660_SIZE)*ISO9660_BLOCK_SIZE)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "El Torito is overlapping with the first partition block.");
return 0;
}
static int context_find_esp_offset(Context *context, uint64_t *ret) {
assert(ret);
uint64_t esp_offset = UINT64_MAX;
LIST_FOREACH(partitions, p, context->partitions) {
if (p->dropped || PARTITION_IS_FOREIGN(p))
continue;
if (p->type.designator == PARTITION_ESP) {
esp_offset = p->offset;
break;
}
}
if (esp_offset == UINT64_MAX)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "El Torito boot catalog requires an ESP.");
if (esp_offset / ISO9660_BLOCK_SIZE > UINT32_MAX)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "ESP offset is farther than El Torito boot catalog can support.");
if (esp_offset % ISO9660_BLOCK_SIZE != 0)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "ESP offset not aligned on 2K blocks.");
*ret = esp_offset;
return 0;
}
static int context_partscan(Context *context) {
int capable, r;
assert(context);
context->needs_rescan = false;
capable = blockdev_partscan_enabled_fd(sym_fdisk_get_devfd(context->fdisk_context));
if (capable == -ENOTBLK)
log_debug("Not telling kernel to reread partition table, since we are not operating on a block device.");
else if (capable < 0)
return log_error_errno(capable, "Failed to check if block device supports partition scanning: %m");
else if (capable > 0) {
log_info("Informing kernel about changed partitions...");
(void) context_notify(context, PROGRESS_REREADING_TABLE, /* object= */ NULL, UINT_MAX);
r = reread_partition_table_fd(sym_fdisk_get_devfd(context->fdisk_context), /* flags= */ 0);
if (r < 0)
return log_error_errno(r, "Failed to reread partition table: %m");
} else
log_notice("Not telling kernel to reread partition table, because selected image does not support kernel partition block devices.");
return 0;
}
static int context_write_partition_table(Context *context) {
_cleanup_(fdisk_unref_tablep) struct fdisk_table *original_table = NULL;
int r;
assert(context);
if (!context->from_scratch && !context_changed(context)) {
log_info("No changes.");
return 0;
}
if (context->dry_run) {
log_notice("Refusing to repartition, please re-run with --dry-run=no.");
return 0;
}
log_info("Applying changes to %s.", context->node);
if (context->from_scratch && context->empty != EMPTY_CREATE) {
(void) context_notify(context, PROGRESS_WIPING_DISK, /* object= */ NULL, UINT_MAX);
/* Erase everything if we operate from scratch, except if the image was just created anyway, and thus is definitely empty. */
r = context_wipe_range(context, 0, context->total);
if (r < 0)
return r;
log_info("Wiped block device.");
/* Wiping the partition table does not remove the kernel partition devices, do a rescan now
* to avoid -EBUSY later. */
r = reread_partition_table_fd(sym_fdisk_get_devfd(context->fdisk_context), /* flags= */ 0);
if (r < 0 && !IN_SET(r, -ENOTBLK, -ENOTTY))
log_warning_errno(r, "Failed to reread partition table after wiping, ignoring: %m");
if (arg_discard) {
r = context_discard_range(context, 0, context->total);
if (r == -EOPNOTSUPP)
log_info("Storage does not support discard, not discarding entire block device data.");
else if (r < 0)
return log_error_errno(r, "Failed to discard entire block device: %m");
else if (r > 0)
log_info("Discarded entire block device.");
}
}
r = sym_fdisk_get_partitions(context->fdisk_context, &original_table);
if (r < 0)
return log_error_errno(r, "Failed to acquire partition table: %m");
/* Wipe fs signatures and discard sectors where the new partitions are going to be placed and in the
* gaps between partitions, just to be sure. */
r = context_wipe_and_discard(context);
if (r < 0)
goto error;
r = context_copy_blocks(context);
if (r < 0)
goto error;
r = context_mkfs(context);
if (r < 0)
goto error;
/* We are now moving destructively btrfs filesystems into the disk before we have written the
* partitions. This is OK because the main use case is that the btrfs filesystems moved are initially
* volatile (in ram disk for example) with little data to save. But we do not want to finish the gpt
* table in case we lose power and reboot and try to boot that incomplete disk.
*/
r = context_block_device_replace(context);
if (r < 0)
goto error;
r = context_mangle_partitions(context);
if (r < 0)
goto error;
log_info("Writing new partition table.");
(void) context_notify(context, PROGRESS_WRITING_TABLE, /* object= */ NULL, UINT_MAX);
r = sym_fdisk_write_disklabel(context->fdisk_context);
if (r < 0) {
r = log_error_errno(r, "Failed to write partition table: %m");
goto error;
}
context_btrfs_replace_resize(context);
r = context_partscan(context);
if (r < 0)
return r;
log_info("Partition table written.");
return 0;
error:
context_btrfs_replace_back(context);
if (context->needs_rescan)
(void) context_partscan(context);
return r;
}
static int context_write_eltorito(Context *context) {
int r;
assert(context);
if (!arg_eltorito)
return 0;
if (context->dry_run)
return 0;
bool utc = true;
usec_t usec = parse_source_date_epoch();
if (usec == USEC_INFINITY) {
usec = now(CLOCK_REALTIME);
utc = false;
}
uint64_t esp_offset;
r = context_find_esp_offset(context, &esp_offset);
if (r < 0)
return r;
log_info("Writing El Torito boot catalog.");
r = write_eltorito(
sym_fdisk_get_devfd(context->fdisk_context),
usec,
utc,
esp_offset / ISO9660_BLOCK_SIZE,
arg_eltorito_system,
arg_eltorito_volume,
arg_eltorito_publisher);
if (r < 0)
return log_error_errno(r, "Failed to write El Torito boot catalog: %m");
return 0;
}
static int context_read_seed(Context *context, const char *root) {
int r;
assert(context);
if (!sd_id128_is_null(context->seed))
return 0;
if (!arg_randomize) {
r = id128_get_machine(root, &context->seed);
if (r >= 0)
return 0;
if (!ERRNO_IS_MACHINE_ID_UNSET(r))
return log_error_errno(r, "Failed to parse machine ID of image: %m");
log_info("No machine ID set, using randomized partition UUIDs.");
}
r = sd_id128_randomize(&context->seed);
if (r < 0)
return log_error_errno(r, "Failed to generate randomized seed: %m");
return 0;
}
static int context_factory_reset(Context *context) {
size_t n = 0;
int r;
assert(context);
if (arg_factory_reset <= 0)
return 0;
if (context->from_scratch) /* Nothing to reset if we start from scratch */
return 0;
if (context->dry_run) {
log_notice("Refusing to factory reset, please re-run with --dry-run=no.");
return 0;
}
log_info("Applying factory reset.");
LIST_FOREACH(partitions, p, context->partitions) {
if (!p->factory_reset || !PARTITION_EXISTS(p))
continue;
assert(p->partno != UINT64_MAX);
log_info("Removing partition %" PRIu64 " for factory reset.", p->partno);
r = sym_fdisk_delete_partition(context->fdisk_context, p->partno);
if (r < 0)
return log_error_errno(r, "Failed to remove partition %" PRIu64 ": %m", p->partno);
n++;
}
if (n == 0) {
log_info("Factory reset requested, but no partitions to delete found.");
return 0;
}
r = sym_fdisk_write_disklabel(context->fdisk_context);
if (r < 0)
return log_error_errno(r, "Failed to write disk label: %m");
/* We do not want to stop if partscan has errors */
(void) context_partscan(context);
log_info("Successfully deleted %zu partitions.", n);
return 1;
}
static int context_can_factory_reset(Context *context) {
assert(context);
LIST_FOREACH(partitions, p, context->partitions)
if (p->factory_reset && PARTITION_EXISTS(p))
return true;
return false;
}
static int resolve_copy_blocks_auto_candidate(
dev_t partition_devno,
GptPartitionType partition_type,
dev_t restrict_devno,
sd_id128_t *ret_uuid) {
#if HAVE_BLKID
_cleanup_(blkid_free_probep) blkid_probe b = NULL;
_cleanup_close_ int fd = -EBADF;
_cleanup_free_ char *p = NULL;
const char *pttype;
sd_id128_t pt_parsed, u;
blkid_partition pp;
dev_t whole_devno;
blkid_partlist pl;
int r;
/* Checks if the specified partition has the specified GPT type UUID, and is located on the specified
* 'restrict_devno' device. The type check is particularly relevant if we have Verity volume which is
* backed by two separate partitions: the data and the hash partitions, and we need to find the right
* one of the two. */
r = block_get_whole_disk(partition_devno, &whole_devno);
if (r < 0)
return log_error_errno(
r,
"Unable to determine containing block device of partition %u:%u: %m",
major(partition_devno), minor(partition_devno));
if (restrict_devno != (dev_t) -1 &&
restrict_devno != whole_devno)
return log_error_errno(
SYNTHETIC_ERRNO(EPERM),
"Partition %u:%u is located outside of block device %u:%u, refusing.",
major(partition_devno), minor(partition_devno),
major(restrict_devno), minor(restrict_devno));
fd = r = device_open_from_devnum(S_IFBLK, whole_devno, O_RDONLY|O_CLOEXEC|O_NONBLOCK, &p);
if (r < 0)
return log_error_errno(r, "Failed to open block device " DEVNUM_FORMAT_STR ": %m",
DEVNUM_FORMAT_VAL(whole_devno));
r = dlopen_libblkid(LOG_ERR);
if (r < 0)
return r;
b = sym_blkid_new_probe();
if (!b)
return log_oom();
errno = 0;
r = sym_blkid_probe_set_device(b, fd, 0, 0);
if (r != 0)
return log_error_errno(errno_or_else(ENOMEM), "Failed to open block device '%s': %m", p);
(void) sym_blkid_probe_enable_partitions(b, 1);
(void) sym_blkid_probe_set_partitions_flags(b, BLKID_PARTS_ENTRY_DETAILS);
errno = 0;
r = sym_blkid_do_safeprobe(b);
if (r == _BLKID_SAFEPROBE_ERROR)
return log_error_errno(errno_or_else(EIO), "Unable to probe for partition table of '%s': %m", p);
if (IN_SET(r, _BLKID_SAFEPROBE_AMBIGUOUS, _BLKID_SAFEPROBE_NOT_FOUND)) {
log_debug("Didn't find partition table on block device '%s'.", p);
return false;
}
assert(r == _BLKID_SAFEPROBE_FOUND);
(void) sym_blkid_probe_lookup_value(b, "PTTYPE", &pttype, NULL);
if (!streq_ptr(pttype, "gpt")) {
log_debug("Didn't find a GPT partition table on '%s'.", p);
return false;
}
errno = 0;
pl = sym_blkid_probe_get_partitions(b);
if (!pl)
return log_error_errno(errno_or_else(EIO), "Unable read partition table of '%s': %m", p);
pp = sym_blkid_partlist_devno_to_partition(pl, partition_devno);
if (!pp) {
log_debug("Partition %u:%u has no matching partition table entry on '%s'.",
major(partition_devno), minor(partition_devno), p);
return false;
}