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 7001–8000 of 11,995

 
                        r = path_extract_directory(line->target, &dn);
                        if (r < 0)
                                return log_error_errno(r, "Failed to extract directory from '%s': %m", line->target);
 
                        r = mkdir_p_root_full(root, dn, UID_INVALID, GID_INVALID, 0755, ts, subvolumes);
                        if (r < 0)
                                return log_error_errno(r, "Failed to create parent directory: %m");
 
                        pfd = chase_and_open(dn, root, CHASE_PREFIX_ROOT, O_RDONLY|O_DIRECTORY|O_CLOEXEC, NULL);
                        if (pfd < 0)
                                return log_error_errno(pfd, "Failed to open parent directory of target: %m");
 
                        tfd = openat(pfd, fn, O_CREAT|O_EXCL|O_WRONLY|O_CLOEXEC, 0700);
                        if (tfd < 0)
                                return log_error_errno(errno, "Failed to create target file '%s': %m", line->target);
 
                        r = copy_bytes(sfd, tfd, UINT64_MAX, COPY_HOLES|COPY_SIGINT|COPY_TRUNCATE);
                        if (r < 0)
                                return log_error_errno(r, "Failed to copy '%s' to '%s%s': %m", line->source, strempty(arg_copy_source), line->target);
 
                        (void) copy_xattr(sfd, NULL, tfd, NULL, COPY_ALL_XATTRS);
                        if (copy_ownership)
                                (void) copy_access(sfd, tfd);
                        (void) copy_times_full(sfd, tfd, /* flags= */ 0, ts);
 
                        /* Creating the file bumped the parent directory's mtime. */
                        r = clamp_directory_mtime(pfd, ts);
                        if (r < 0)
                                return log_error_errno(r, "Failed to set timestamp of '%s': %m", dn);
                }
        }
 
        return 0;
}
 
static int do_make_directories(Partition *p, const char *root) {
        _cleanup_hashmap_free_ Hashmap *subvolumes = NULL;
        _cleanup_free_ char **override_dirs = NULL;
        int r;
 
        assert(p);
        assert(root);
 
        r = make_subvolumes_hashmap(p, &subvolumes);
        if (r < 0)
                return r;
 
        if (p->suppressing_supplement) {
                r = shallow_join_strv(&override_dirs, p->make_directories, p->supplemented_by->make_directories);
                if (r < 0)
                        return r;
        }
 
        STRV_FOREACH(d, override_dirs ?: p->make_directories) {
                r = mkdir_p_root_full(root, *d, UID_INVALID, GID_INVALID, 0755, parse_source_date_epoch(), subvolumes);
                if (r < 0)
                        return log_error_errno(r, "Failed to create directory '%s' in file system: %m", *d);
        }
 
        return 0;
}
 
static int do_make_symlinks(Partition *p, const char *root) {
        usec_t ts = parse_source_date_epoch();
        int r;
 
        assert(p);
        assert(root);
 
        STRV_FOREACH_PAIR(path, target, p->make_symlinks) {
                _cleanup_close_ int parent_fd = -EBADF;
                _cleanup_free_ char *f = NULL;
 
                r = chase(*path, root, CHASE_PREFIX_ROOT|CHASE_PARENT|CHASE_EXTRACT_FILENAME, &f, &parent_fd);
                if (r < 0)
                        return log_error_errno(r, "Failed to resolve %s in %s", *path, root);
 
                if (symlinkat(*target, parent_fd, f) < 0)
                        return log_error_errno(errno, "Failed to create symlink at %s to %s: %m", *path, *target);
 
                /* The new symlink carries the wall clock, and creating it bumped the directory we put
                 * it into. We are the last population step, so nothing overwrites this again. */
                if (ts != USEC_INFINITY &&
                    utimensat(parent_fd, f,
                              (const struct timespec[2]) { *TIMESPEC_STORE(ts), *TIMESPEC_STORE(ts) },
                              AT_SYMLINK_NOFOLLOW) < 0)
                        return log_error_errno(errno, "Failed to set timestamp of symlink '%s': %m", *path);
 
                r = clamp_directory_mtime(parent_fd, ts);
                if (r < 0)
                        return log_error_errno(r, "Failed to set timestamp of '%s': %m", *path);
        }
 
        return 0;
}
 
static int make_subvolumes_read_only(Partition *p, const char *root) {
        _cleanup_free_ char *path = NULL;
        Subvolume *subvolume;
        int r;
 
        ORDERED_HASHMAP_FOREACH(subvolume, p->subvolumes) {
                if (!FLAGS_SET(subvolume->flags, BTRFS_SUBVOL_RO))
                        continue;
 
                path = path_join(root, subvolume->path);
                if (!path)
                        return log_oom();
 
                r = btrfs_subvol_set_read_only(path, true);
                if (r < 0)
                        return log_error_errno(r, "Failed to make subvolume '%s' read-only: %m", subvolume->path);
        }
 
        if (p->suppressing_supplement) {
                r = make_subvolumes_read_only(p->supplemented_by, root);
                if (r < 0)
                        return r;
        }
 
        return 0;
}
 
static int set_default_subvolume(Partition *p, const char *root) {
        _cleanup_free_ char *path = NULL;
        int r;
 
        assert(p);
        assert(root);
 
        if (!p->default_subvolume)
                return 0;
 
        path = path_join(root, p->default_subvolume);
        if (!path)
                return log_oom();
 
        r = btrfs_subvol_make_default(path);
        if (r < 0)
                return log_error_errno(r, "Failed to make '%s' the default subvolume: %m", p->default_subvolume);
 
        return 0;
}
 
static int partition_acquire_sibling_labels(const Partition *p, char ***ret) {
        assert(p);
        assert(ret);
 
        _cleanup_strv_free_ char **l = NULL;
        if (p->new_label) {
                l = strv_new(p->new_label);
                if (!l)
                        return log_oom();
        }
 
        FOREACH_ELEMENT(sibling, p->siblings) {
                Partition *s = *sibling;
 
                if (!s || s == p || !s->new_label || strv_contains(l, s->new_label))
                        continue;
 
                if (strv_extend(&l, s->new_label) < 0)
                        return log_oom();
        }
 
        strv_sort(l); /* bring into a systematic order to make things reproducible */
 
        *ret = TAKE_PTR(l);
        return 0;
}
 
static int partition_acquire_sibling_uuids(const Partition *p, char ***ret) {
        assert(p);
        assert(ret);
 
        _cleanup_strv_free_ char **l = NULL;
        l = strv_new(SD_ID128_TO_UUID_STRING(p->type.uuid));
        if (!l)
                return log_oom();
 
        FOREACH_ELEMENT(sibling, p->siblings) {
                Partition *s = *sibling;
 
                if (!s || s == p)
                        continue;
 
                const char *u = SD_ID128_TO_UUID_STRING(s->type.uuid);
                if (strv_contains(l, u))
                        continue;
 
                if (strv_extend(&l, u) < 0)
                        return log_oom();
        }
 
        strv_sort(l); /* bring into a systematic order to make things reproducible */
 
        *ret = TAKE_PTR(l);
        return 0;
}
 
 
static int do_make_validatefs_xattrs(const Partition *p, const char *root) {
        int r;
 
        assert(p);
        assert(root);
 
        if (!partition_add_validatefs(p))
                return 0;
 
        _cleanup_close_ int fd = open(root, O_DIRECTORY|O_CLOEXEC);
        if (fd < 0)
                return log_error_errno(errno, "Failed to open root inode '%s': %m", root);
 
        _cleanup_strv_free_ char **l = NULL;
        r = partition_acquire_sibling_labels(p, &l);
        if (r < 0)
                return r;
        if (!strv_isempty(l)) {
                r = xsetxattr_strv(fd, /* path= */ NULL, AT_EMPTY_PATH, "user.validatefs.gpt_label", l);
                if (r < 0)
                        return log_error_errno(r, "Failed to set 'user.validatefs.gpt_label' extended attribute: %m");
        }
        l = strv_free(l);
 
        r = partition_acquire_sibling_uuids(p, &l);
        if (r < 0)
                return r;
        r = xsetxattr_strv(fd, /* path= */ NULL, AT_EMPTY_PATH, "user.validatefs.gpt_type_uuid", l);
        if (r < 0)
                return log_error_errno(r, "Failed to set 'user.validatefs.gpt_type_uuid' extended attribute: %m");
        l = strv_free(l);
 
        /* Prefer the data from MountPoint= if specified, otherwise use data we derive from the partition type */
        if (p->n_mountpoints > 0) {
                FOREACH_ARRAY(m, p->mountpoints, p->n_mountpoints)
                        if (strv_extend(&l, m->where) < 0)
                                return log_oom();
        } else {
                const char *m = gpt_partition_type_mountpoint_nulstr(p->type);
                if (m) {
                        l = strv_split_nulstr(m);
                        if (!l)
                                return log_oom();
                }
        }
 
        if (!strv_isempty(l)) {
                r = xsetxattr_strv(fd, /* path= */ NULL, AT_EMPTY_PATH, "user.validatefs.mount_point", l);
                if (r < 0)
                        return log_error_errno(r, "Failed to set 'user.validatefs.mount_point' extended attribute: %m");
        }
 
        return 0;
}
 
static int partition_populate_directory(Context *context, Partition *p, char **ret) {
        _cleanup_(rm_rf_physical_and_freep) char *root = NULL;
        const char *vt;
        int r;
 
        assert(ret);
 
        log_info("Preparing to populate %s filesystem.", p->format);
 
        r = var_tmp_dir(&vt);
        if (r < 0)
                return log_error_errno(r, "Could not determine temporary directory: %m");
 
        r = tempfn_random_child(vt, "repart", &root);
        if (r < 0)
                return log_error_errno(r, "Failed to generate temporary directory: %m");
 
        r = mkdir(root, 0755);
        if (r < 0)
                return log_error_errno(errno, "Failed to create temporary directory: %m");
 
        /* Nothing below touches its atime (adding an entry to a directory only moves mtime), so stamp here. */
        usec_t ts = parse_source_date_epoch();
        if (ts != USEC_INFINITY) {
                _cleanup_close_ int rfd = -EBADF;
                struct timespec tspec;
 
                rfd = open(root, O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW);
                if (rfd < 0)
                        return log_error_errno(errno, "Failed to open temporary directory: %m");
 
                timespec_store(&tspec, ts);
                if (futimens(rfd, (const struct timespec[2]) { tspec, tspec }) < 0)
                        return log_error_errno(errno, "Failed to set timestamp of temporary directory: %m");
        }
 
        r = do_copy_files(context, p, root);
        if (r < 0)
                return r;
 
        r = do_make_directories(p, root);
        if (r < 0)
                return r;
 
        r = do_make_symlinks(p, root);
        if (r < 0)
                return r;
 
        r = do_make_validatefs_xattrs(p, root);
        if (r < 0)
                return r;
 
        log_info("Ready to populate %s filesystem.", p->format);
 
        *ret = TAKE_PTR(root);
        return 0;
}
 
static int partition_populate_filesystem(Context *context, Partition *p, const char *node) {
        int r;
 
        assert(p);
        assert(node);
 
        log_info("Populating %s filesystem.", p->format);
 
        /* We copy in a child process, since we have to mount the fs for that, and we don't want that fs to
         * appear in the host namespace. Hence we fork a child that has its own file system namespace and
         * detached mount propagation. */
 
        (void) dlopen_libmount(LOG_DEBUG);
 
        r = pidref_safe_fork(
                        "(sd-copy)",
                        FORK_DEATHSIG_SIGTERM|FORK_LOG|FORK_WAIT|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE,
                        /* ret= */ NULL);
        if (r < 0)
                return r;
        if (r == 0) {
                static const char fs[] = "/run/systemd/mount-root";
                /* This is a child process with its own mount namespace and propagation to host turned off */
 
                r = mkdir_p(fs, 0700);
                if (r < 0) {
                        log_error_errno(r, "Failed to create mount point: %m");
                        _exit(EXIT_FAILURE);
                }
 
                if (mount_nofollow_verbose(LOG_ERR, node, fs, p->format, MS_NOATIME|MS_NODEV|MS_NOEXEC|MS_NOSUID, NULL) < 0)
                        _exit(EXIT_FAILURE);
 
                if (do_copy_files(context, p, fs) < 0)
                        _exit(EXIT_FAILURE);
 
                if (do_make_directories(p, fs) < 0)
                        _exit(EXIT_FAILURE);
 
                if (do_make_symlinks(p, fs) < 0)
                        _exit(EXIT_FAILURE);
 
                if (do_make_validatefs_xattrs(p, fs) < 0)
                        _exit(EXIT_FAILURE);
 
                if (make_subvolumes_read_only(p, fs) < 0)
                        _exit(EXIT_FAILURE);
 
                if (set_default_subvolume(p, fs) < 0)
                        _exit(EXIT_FAILURE);
 
                r = syncfs_path(AT_FDCWD, fs);
                if (r < 0) {
                        log_error_errno(r, "Failed to synchronize written files: %m");
                        _exit(EXIT_FAILURE);
                }
 
                _exit(EXIT_SUCCESS);
        }
 
        log_info("Successfully populated %s filesystem.", p->format);
        return 0;
}
 
static int append_btrfs_subvols(char ***l, OrderedHashmap *subvolumes, const char *default_subvolume) {
        Subvolume *subvolume;
        int r;
 
        assert(l);
 
        ORDERED_HASHMAP_FOREACH(subvolume, subvolumes) {
                _cleanup_free_ char *s = NULL;
 
                if (streq_ptr(subvolume->path, default_subvolume) && !strextend(&s, "default"))
                        return log_oom();
 
                if (FLAGS_SET(subvolume->flags, BTRFS_SUBVOL_RO) && !strextend_with_separator(&s, "-", "ro"))
                        return log_oom();
 
                if (!strextend_with_separator(&s, ":", subvolume->path))
                        return log_oom();
 
                r = strv_extend_many(l, "--subvol", s);
                if (r < 0)
                        return log_oom();
        }
 
        return 0;
}
 
static int append_btrfs_inode_flags(char ***l, OrderedHashmap *subvolumes) {
        Subvolume *subvolume;
        int r;
 
        assert(l);
 
        ORDERED_HASHMAP_FOREACH(subvolume, subvolumes) {
                if (!FLAGS_SET(subvolume->flags, BTRFS_SUBVOL_NODATACOW))
                        continue;
 
                _cleanup_free_ char *s = strjoin("nodatacow:", subvolume->path);
                if (!s)
                        return log_oom();
 
                r = strv_extend_many(l, "--inode-flags", s);
                if (r < 0)
                        return log_oom();
        }
 
        return 0;
}
 
static int finalize_extra_mkfs_options(const Partition *p, const char *root, char ***ret) {
        _cleanup_strv_free_ char **sv = NULL;
        int r;
 
        assert(p);
        assert(ret);
 
        r = mkfs_options_from_env("REPART", p->format, &sv);
        if (r < 0)
                return log_error_errno(r,
                                       "Failed to determine mkfs command line options for '%s': %m",
                                       p->format);
 
        if (partition_needs_populate(p) && root && streq(p->format, "btrfs")) {
                r = append_btrfs_subvols(&sv, p->subvolumes, p->default_subvolume);
                if (r < 0)
                        return r;
 
                r = append_btrfs_inode_flags(&sv, p->subvolumes);
                if (r < 0)
                        return r;
 
                if (p->suppressing_supplement) {
                        r = append_btrfs_subvols(&sv, p->supplemented_by->subvolumes, NULL);
                        if (r < 0)
                                return r;
 
                        r = append_btrfs_inode_flags(&sv, p->supplemented_by->subvolumes);
                        if (r < 0)
                                return r;
                }
 
                if (p->minimize != MINIMIZE_OFF && strv_extend(&sv, "--shrink") < 0)
                        return log_oom();
        }
 
        *ret = TAKE_PTR(sv);
        return 0;
}
 
static int context_block_device_replace(Context *context) {
        int r;
 
        assert(context);
 
        LIST_FOREACH(partitions, p, context->partitions) {
                _cleanup_(partition_target_freep) PartitionTarget *t = NULL;
 
                if (p->dropped)
                        continue;
 
                if (PARTITION_EXISTS(p))
                        continue;
 
                if (!p->btrfs_replaced)
                        continue;
 
                if (partition_defer(context, p))
                        continue;
 
                assert(!p->btrfs_replaced->done);
 
                (void) context_notify(context, PROGRESS_REPLACING_DEVICE, p->definition_path, UINT_MAX);
 
                assert(p->offset != UINT64_MAX);
                assert(p->new_size != UINT64_MAX);
 
                r = partition_target_prepare(context, p,
                                             p->new_size,
                                             /* need_path= */ true,
                                             &t);
                if (r < 0)
                        return r;
 
                if (p->encrypt != ENCRYPT_OFF) {
                        r = partition_encrypt(context, p, t, /* offline= */ false, /* temporary= */ false);
                        if (r < 0)
                                return log_error_errno(r, "Failed to encrypt device: %m");
                }
 
                log_info("Replacing partition %" PRIu64 ".", p->partno);
 
                /* btrfs_replace calls a synchronous ioctl and will return when replace is finished */
                r = btrfs_replace(p->btrfs_replaced->mountpoint_fd, p->btrfs_replaced->devid, partition_target_path(t));
                if (r < 0)
                        return log_error_errno(r, "Failed to replace btrfs device on partition %" PRIu64 ": %m", p->partno);
 
                p->btrfs_replaced->done = true;
 
                if (t->decrypted)
                        t->decrypted->keep = true;
 
                log_info("Successfully replaced partition %" PRIu64 ".", p->partno);
        }
 
        return 0;
}
 
static void context_btrfs_replace_resize(Context *context) {
        int r;
 
        assert(context);
 
        LIST_FOREACH(partitions, p, context->partitions) {
                if (!p->btrfs_replaced)
                        continue;
 
                if (!p->btrfs_replaced->done)
                        continue;
 
                r = btrfs_resize_max(p->btrfs_replaced->mountpoint_fd, p->btrfs_replaced->devid);
                if (r < 0)
                        log_warning_errno(r, "Could not resize btrfs filesystem moved to partition %" PRIu64 ", proceeding without resizing: %m", p->partno);
                else
                        log_info("Successfully resized partition %" PRIu64 ".", p->partno);
        }
}
 
static void context_btrfs_replace_back(Context *context) {
        int r;
 
        assert(context);
 
        LIST_FOREACH(partitions, p, context->partitions) {
                if (!p->btrfs_replaced)
                        continue;
 
                if (!p->btrfs_replaced->done)
                        continue;
 
                r = btrfs_replace(p->btrfs_replaced->mountpoint_fd, p->btrfs_replaced->devid, p->btrfs_replaced->source_path);
                if (r < 0)
                        log_warning_errno(r, "Could not move back btrfs filesystem from partition %" PRIu64 ", leaving it on new device: %m", p->partno);
        }
}
 
static int check_mkfs(const Context *context) {
        int r;
 
        assert(context);
 
        LIST_FOREACH(partitions, p, context->partitions) {
                if (p->dropped)
                        continue;
 
                if (PARTITION_EXISTS(p)) /* Never format existing partitions */
                        continue;
 
                if (!p->format)
                        continue;
 
                if (partition_defer(context, p))
                        continue;
 
                /* For offline signing case */
                if (!set_isempty(arg_verity_settings) && partition_designator_is_verity_sig(p->type.designator))
                        continue;
 
                /* Minimized partitions will use the copy blocks logic so skip those here. */
                if (p->copy_blocks_fd >= 0)
                        continue;
 
                /* We don't yet quite know if have_root= will be true, so just pass -1 which
                 * means "not sure". */
                r = mkfs_find_or_warn(p->format, /* have_root= */ -1, /* ret= */ NULL);
                if (r < 0)
                        return r;
        }
 
        return 0;
}
 
static int context_mkfs(Context *context) {
        int r;
 
        assert(context);
 
        /* Make a file system */
 
        LIST_FOREACH(partitions, p, context->partitions) {
                _cleanup_(rm_rf_physical_and_freep) char *root = NULL;
                _cleanup_(partition_target_freep) PartitionTarget *t = NULL;
                _cleanup_strv_free_ char **extra_mkfs_options = NULL;
 
                if (p->dropped)
                        continue;
 
                if (PARTITION_EXISTS(p)) /* Never format existing partitions */
                        continue;
 
                if (!p->format)
                        continue;
 
                if (partition_defer(context, p))
                        continue;
 
                /* For offline signing case */
                if (!set_isempty(arg_verity_settings) && partition_designator_is_verity_sig(p->type.designator))
                        return partition_format_verity_sig(context, p);
 
                /* Minimized partitions will use the copy blocks logic so skip those here. */
                if (p->copy_blocks_fd >= 0)
                        continue;
 
                (void) context_notify(context, PROGRESS_FORMATTING_PARTITION, p->definition_path, UINT_MAX);
 
                assert(p->offset != UINT64_MAX);
                assert(p->new_size != UINT64_MAX);
                assert(p->new_size >= (p->encrypt != ENCRYPT_OFF ? LUKS2_METADATA_KEEP_FREE : 0));
 
                /* If we're doing encryption, keep free space at the end which is required
                 * for cryptsetup's offline encryption. */
                r = partition_target_prepare(context, p,
                                             p->new_size - (p->encrypt != ENCRYPT_OFF ? LUKS2_METADATA_KEEP_FREE : 0),
                                             /* need_path= */ true,
                                             &t);
                if (r < 0)
                        return r;
 
                if (p->encrypt != ENCRYPT_OFF && (t->loop || t->block_partition)) {
                        r = partition_target_grow(t, p->new_size);
                        if (r < 0)
                                return r;
 
                        r = partition_encrypt(context, p, t, /* offline= */ false, /* temporary= */ true);
                        if (r < 0)
                                return log_error_errno(r, "Failed to encrypt device: %m");
                }
 
                log_info("Formatting future partition %" PRIu64 ".", p->partno);
 
                /* If we're not writing to a loop device or if we're populating a read-only filesystem, we
                 * have to populate using the filesystem's mkfs's --root= (or equivalent) option. To do that,
                 * we need to set up the final directory tree beforehand. */
 
                if (partition_needs_populate(p) &&
                    ((!t->loop && !t->block_partition) || fstype_is_ro(p->format) || (streq_ptr(p->format, "btrfs") && p->compression))) {
                        if (!mkfs_supports_root_option(p->format))
                                return log_error_errno(SYNTHETIC_ERRNO(ENODEV),
                                                        "Loop device or block partition access is required to populate %s filesystems.",
                                                        p->format);
 
                        r = partition_populate_directory(context, p, &root);
                        if (r < 0)
                                return r;
                }
 
                r = finalize_extra_mkfs_options(p, root, &extra_mkfs_options);
                if (r < 0)
                        return r;
 
                r = make_filesystem(
                                partition_target_path(t),
                                p->format,
                                strempty(p->new_label),
                                root,
                                p->fs_uuid,
                                partition_mkfs_flags(p),
                                partition_fs_sector_size(context, p),
                                p->compression,
                                p->compression_level,
                                extra_mkfs_options);
                if (r < 0)
                        return r;
 
                /* The mkfs binary we invoked might have removed our temporary file when we're not operating
                 * on a loop device, so open the file again to make sure our file descriptor points to actual
                 * new file. */
 
                if (t->fd >= 0 && t->path && !t->loop && !t->block_partition) {
                        safe_close(t->fd);
                        t->fd = open(t->path, O_RDWR|O_CLOEXEC);
                        if (t->fd < 0)
                                return log_error_errno(errno, "Failed to reopen temporary file: %m");
                }
 
                log_info("Successfully formatted future partition %" PRIu64 ".", p->partno);
 
                /* If we're writing to a loop device or BLKPG partition, we can now mount the empty filesystem and populate it. */
                if (partition_needs_populate(p) && !root) {
                        assert(t->loop || t->block_partition);
 
                        r = partition_populate_filesystem(context, p, partition_target_path(t));
                        if (r < 0)
                                return r;
                }
 
                if (p->encrypt != ENCRYPT_OFF && !t->loop && !t->block_partition) {
                        r = partition_target_grow(t, p->new_size);
                        if (r < 0)
                                return r;
 
                        r = partition_encrypt(context, p, t, /* offline= */ true, /* temporary= */ true);
                        if (r < 0)
                                return log_error_errno(r, "Failed to encrypt device: %m");
                }
 
                /* Note that we always sync explicitly here, since mkfs.fat doesn't do that on its own, and
                 * if we don't sync before detaching a block device the in-flight sectors possibly won't hit
                 * the disk. */
 
                r = partition_target_sync(context, p, t);
                if (r < 0)
                        return r;
 
                if (p->siblings[VERITY_HASH] && !partition_defer(context, p->siblings[VERITY_HASH])) {
                        /* The verity hash must cover the partition contents as stored on disk, i.e. the
                         * ciphertext if the partition is encrypted, hence tear down the dm-crypt device
                         * first. */
                        partition_target_drop_decrypted(t);
 
                        r = partition_format_verity_hash(context, p->siblings[VERITY_HASH],
                                                         /* node= */ NULL, partition_target_path(t));
                        if (r < 0)
                                return r;
                }
 
                if (p->siblings[VERITY_SIG] && !partition_defer(context, p->siblings[VERITY_SIG])) {
                        r = partition_format_verity_sig(context, p->siblings[VERITY_SIG]);
                        if (r < 0)
                                return r;
                }
        }
 
        return 0;
}
 
static int partition_acquire_uuid(Context *context, Partition *p, sd_id128_t *ret) {
        struct {
                sd_id128_t type_uuid;
                uint64_t counter;
        } _packed_ plaintext = {};
        union {
                uint8_t md[SHA256_DIGEST_SIZE];
                sd_id128_t id;
        } result;
 
        uint64_t k = 0;
        int r;
 
        assert(context);
        assert(p);
        assert(ret);
 
        /* Calculate a good UUID for the indicated partition. We want a certain degree of reproducibility,
         * hence we won't generate the UUIDs randomly. Instead we use a cryptographic hash (precisely:
         * HMAC-SHA256) to derive them from a single seed. The seed is generally the machine ID of the
         * installation we are processing, but if random behaviour is desired can be random, too. We use the
         * seed value as key for the HMAC (since the machine ID is something we generally don't want to leak)
         * and the partition type as plaintext. The partition type is suffixed with a counter (only for the
         * second and later partition of the same type) if we have more than one partition of the same
         * time. Or in other words:
         *
         * With:
         *     SEED := /etc/machine-id
         *
         * If first partition instance of type TYPE_UUID:
         *     PARTITION_UUID := HMAC-SHA256(SEED, TYPE_UUID)
         *
         * For all later partition instances of type TYPE_UUID with INSTANCE being the LE64 encoded instance number:
         *     PARTITION_UUID := HMAC-SHA256(SEED, TYPE_UUID || INSTANCE)
         */
 
        LIST_FOREACH(partitions, q, context->partitions) {
                if (p == q)
                        break;
 
                if (!sd_id128_equal(p->type.uuid, q->type.uuid))
                        continue;
 
                k++;
        }
 
        plaintext.type_uuid = p->type.uuid;
        plaintext.counter = htole64(k);
 
        hmac_sha256(context->seed.bytes, sizeof(context->seed.bytes),
                    &plaintext,
                    k == 0 ? sizeof(sd_id128_t) : sizeof(plaintext),
                    result.md);
 
        /* Take the first half, mark it as v4 UUID */
        assert_cc(sizeof(result.md) == sizeof(result.id) * 2);
        result.id = id128_make_v4_uuid(result.id);
 
        /* Ensure this partition UUID is actually unique, and there's no remaining partition from an earlier run? */
        LIST_FOREACH(partitions, q, context->partitions) {
                if (p == q)
                        continue;
 
                if (sd_id128_in_set(result.id, q->current_uuid, q->new_uuid)) {
                        log_warning("Partition UUID calculated from seed for partition %" PRIu64 " already used, reverting to randomized UUID.", p->partno);
 
                        r = sd_id128_randomize(&result.id);
                        if (r < 0)
                                return log_error_errno(r, "Failed to generate randomized UUID: %m");
 
                        break;
                }
        }
 
        *ret = result.id;
        return 0;
}
 
static int partition_acquire_label(Context *context, Partition *p, char **ret) {
        _cleanup_free_ char *label = NULL;
        const char *prefix;
        unsigned k = 1;
 
        assert(context);
        assert(p);
        assert(ret);
 
        prefix = gpt_partition_type_uuid_to_string(p->type.uuid);
        if (!prefix)
                prefix = "linux";
 
        for (;;) {
                const char *ll = label ?: prefix;
                bool retry = false;
 
                LIST_FOREACH(partitions, q, context->partitions) {
                        if (p == q)
                                break;
 
                        if (streq_ptr(ll, q->current_label) ||
                            streq_ptr(ll, q->new_label)) {
                                retry = true;
                                break;
                        }
                }
 
                if (!retry)
                        break;
 
                label = mfree(label);
                if (asprintf(&label, "%s-%u", prefix, ++k) < 0)
                        return log_oom();
        }
 
        if (!label) {
                label = strdup(prefix);
                if (!label)
                        return log_oom();
        }
 
        *ret = TAKE_PTR(label);
        return 0;
}
 
static int context_acquire_partition_uuids_and_labels(Context *context) {
        int r;
 
        assert(context);
 
        LIST_FOREACH(partitions, p, context->partitions) {
                sd_id128_t uuid;
 
                /* Never touch foreign partitions, their UUID and label are set when loading them. */
                if (PARTITION_IS_FOREIGN(p))
                        continue;
 
                (void) context_notify(context, PROGRESS_ACQUIRING_PARTITION_LABELS, p->definition_path, UINT_MAX);
 
                if (!sd_id128_is_null(p->current_uuid))
                        p->new_uuid = uuid = p->current_uuid; /* Never change initialized UUIDs */
                else if (p->new_uuid_is_set)
                        uuid = p->new_uuid;
                else {
                        /* Not explicitly set by user! */
                        r = partition_acquire_uuid(context, p, &uuid);
                        if (r < 0)
                                return r;
 
                        /* The final verity hash/data UUIDs can only be determined after formatting the
                         * verity hash partition. However, we still want to use the generated partition UUID
                         * to derive other UUIDs to keep things unique and reproducible, so we always
                         * generate a UUID if none is set, but we only use it as the actual partition UUID if
                         * verity is not configured. */
                        if (!IN_SET(p->verity, VERITY_DATA, VERITY_HASH)) {
                                p->new_uuid = uuid;
                                p->new_uuid_is_set = true;
                        }
                }
 
                /* Calculate the UUID for the file system as HMAC-SHA256 of the string "file-system-uuid",
                 * keyed off the partition UUID. */
                r = derive_uuid(uuid, "file-system-uuid", &p->fs_uuid);
                if (r < 0)
                        return r;
 
                if (p->encrypt != ENCRYPT_OFF) {
                        r = derive_uuid(uuid, "luks-uuid", &p->luks_uuid);
                        if (r < 0)
                                return r;
                }
 
                /* Derive the verity salt and verity superblock UUID from the seed to keep them reproducible */
                if (p->verity == VERITY_HASH) {
                        derive_salt(context->seed, "verity-salt", p->verity_salt);
 
                        r = derive_uuid(context->seed, "verity-uuid", &p->verity_uuid);
                        if (r < 0)
                                return log_error_errno(r, "Failed to acquire verity uuid: %m");
                }
 
                if (!isempty(p->current_label)) {
                        /* never change initialized labels */
                        r = free_and_strdup_warn(&p->new_label, p->current_label);
                        if (r < 0)
                                return r;
                } else if (!p->new_label) {
                        /* Not explicitly set by user! */
 
                        r = partition_acquire_label(context, p, &p->new_label);
                        if (r < 0)
                                return r;
                }
        }
 
        return 0;
}
 
static int set_gpt_flags(struct fdisk_partition *q, uint64_t flags) {
        _cleanup_free_ char *a = NULL;
        int r;
 
        BIT_FOREACH(i, flags) {
                r = strextendf_with_separator(&a, ",", "%i", i);
                if (r < 0)
                        return r;
        }
 
        return sym_fdisk_partition_set_attrs(q, strempty(a));
}
 
static uint64_t partition_merge_flags(Partition *p) {
        uint64_t f;
 
        assert(p);
 
        f = p->gpt_flags;
 
        if (p->no_auto >= 0) {
                if (gpt_partition_type_knows_no_auto(p->type))
                        SET_FLAG(f, SD_GPT_FLAG_NO_AUTO, p->no_auto);
                else {
                        char buffer[SD_ID128_UUID_STRING_MAX];
                        log_warning("Configured NoAuto=%s for partition type '%s' that doesn't support it, ignoring.",
                                    yes_no(p->no_auto),
                                    gpt_partition_type_uuid_to_string_harder(p->type.uuid, buffer));
                }
        }
 
        if (p->read_only >= 0) {
                if (gpt_partition_type_knows_read_only(p->type))
                        SET_FLAG(f, SD_GPT_FLAG_READ_ONLY, p->read_only);
                else {
                        char buffer[SD_ID128_UUID_STRING_MAX];
                        log_warning("Configured ReadOnly=%s for partition type '%s' that doesn't support it, ignoring.",
                                    yes_no(p->read_only),
                                    gpt_partition_type_uuid_to_string_harder(p->type.uuid, buffer));
                }
        }
 
        if (p->growfs >= 0) {
                if (gpt_partition_type_knows_growfs(p->type))
                        SET_FLAG(f, SD_GPT_FLAG_GROWFS, p->growfs);
                else {
                        char buffer[SD_ID128_UUID_STRING_MAX];
                        log_warning("Configured GrowFileSystem=%s for partition type '%s' that doesn't support it, ignoring.",
                                    yes_no(p->growfs),