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 9001–10000 of 11,995

 
        r = blkid_partition_get_type_id128(pp, &pt_parsed);
        if (r < 0) {
                log_debug_errno(r, "Failed to read partition type UUID of partition %u:%u: %m",
                                major(partition_devno), minor(partition_devno));
                return false;
        }
 
        if (!sd_id128_equal(pt_parsed, partition_type.uuid)) {
                log_debug("Partition %u:%u has non-matching partition type " SD_ID128_FORMAT_STR " (needed: " SD_ID128_FORMAT_STR "), ignoring.",
                          major(partition_devno), minor(partition_devno),
                          SD_ID128_FORMAT_VAL(pt_parsed), SD_ID128_FORMAT_VAL(partition_type.uuid));
                return false;
        }
 
        r = blkid_partition_get_uuid_id128(pp, &u);
        if (r == -ENXIO) {
                log_debug_errno(r, "Partition " DEVNUM_FORMAT_STR " has no UUID.", DEVNUM_FORMAT_VAL(partition_devno));
                return false;
        }
        if (r < 0) {
                log_debug_errno(r, "Failed to read partition UUID of " DEVNUM_FORMAT_STR ": %m", DEVNUM_FORMAT_VAL(partition_devno));
                return false;
        }
 
        log_debug("Automatically found partition " DEVNUM_FORMAT_STR " of right type " SD_ID128_FORMAT_STR ".",
                  DEVNUM_FORMAT_VAL(partition_devno),
                  SD_ID128_FORMAT_VAL(pt_parsed));
 
        if (ret_uuid)
                *ret_uuid = u;
 
        return true;
#else
        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
                               "Cannot check partition type UUID and device location, libblkid support is not compiled in.");
#endif
}
 
static int resolve_copy_blocks_auto_candidate_harder(
                dev_t start_devno,
                GptPartitionType partition_type,
                dev_t restrict_devno,
                dev_t *ret_found_devno,
                sd_id128_t *ret_uuid) {
 
        _cleanup_(sd_device_unrefp) sd_device *d = NULL, *nd = NULL;
        int r;
 
        /* A wrapper around resolve_copy_blocks_auto_candidate(), but looks for verity/verity-sig associated
         * partitions, too. i.e. if the input is a data or verity partition, will try to find the
         * verity/verity-sig partition for it, based on udev metadata. */
 
        const char *property;
        if (partition_designator_is_verity_hash(partition_type.designator))
                property = "ID_DISSECT_PART_VERITY_DEVICE";
        else if (partition_designator_is_verity_sig(partition_type.designator))
                property = "ID_DISSECT_PART_VERITY_SIG_DEVICE";
        else
                goto not_found;
 
        r = sd_device_new_from_devnum(&d, 'b', start_devno);
        if (r < 0)
                return log_error_errno(r, "Failed to allocate device object for " DEVNUM_FORMAT_STR ": %m", DEVNUM_FORMAT_VAL(start_devno));
 
        const char *node;
        r = sd_device_get_property_value(d, property, &node);
        if (r == -ENOENT) {
                log_debug_errno(r, "Property %s not set on " DEVNUM_FORMAT_STR ", skipping.", property, DEVNUM_FORMAT_VAL(start_devno));
                goto not_found;
        }
        if (r < 0)
                return log_error_errno(r, "Failed to read property %s from device " DEVNUM_FORMAT_STR ": %m", property, DEVNUM_FORMAT_VAL(start_devno));
 
        r = sd_device_new_from_devname(&nd, node);
        if (ERRNO_IS_NEG_DEVICE_ABSENT(r)) {
                log_debug_errno(r, "Device %s referenced in %s property not found, skipping: %m", node, property);
                goto not_found;
        }
        if (r < 0)
                return log_error_errno(r, "Failed to allocate device object for '%s': %m", node);
 
        r = device_in_subsystem(nd, "block");
        if (r < 0)
                return log_error_errno(r, "Failed to determine if '%s' is a block device: %m", node);
        if (r == 0) {
                log_debug("Device referenced by %s property of %s does not refer to block device, refusing.", property, node);
                goto not_found;
        }
 
        dev_t found_devno = 0;
        r = sd_device_get_devnum(nd, &found_devno);
        if (r < 0)
                return log_error_errno(r, "Failed to get device number for '%s': %m", node);
 
        r = resolve_copy_blocks_auto_candidate(found_devno, partition_type, restrict_devno, ret_uuid);
        if (r < 0)
                return r;
        if (r == 0)
                goto not_found;
 
        if (ret_found_devno)
                *ret_found_devno = found_devno;
 
        return 1;
 
not_found:
        if (ret_found_devno)
                *ret_found_devno = 0;
        if (ret_uuid)
                *ret_uuid = SD_ID128_NULL;
 
        return 0;
}
 
static int find_backing_devno(
                const char *path,
                const char *root,
                dev_t *ret) {
 
        _cleanup_free_ char *resolved = NULL;
        int r;
 
        assert(path);
 
        r = chase(path, root, CHASE_PREFIX_ROOT, &resolved, NULL);
        if (r < 0)
                return r;
 
        r = path_is_mount_point(resolved);
        if (r < 0)
                return r;
        if (r == 0) /* Not a mount point, then it's not a partition of its own, let's not automatically use it. */
                return -ENOENT;
 
        r = get_block_device(resolved, ret);
        if (r < 0)
                return r;
        if (r == 0) /* Not backed by physical file system, we can't use this */
                return -ENOENT;
 
        return 0;
}
 
static int resolve_copy_blocks_auto(
                GptPartitionType type,
                const char *root,
                dev_t restrict_devno,
                dev_t *ret_devno,
                sd_id128_t *ret_uuid) {
 
        const char *try1 = NULL, *try2 = NULL;
        char p[SYS_BLOCK_PATH_MAX("/slaves")];
        _cleanup_closedir_ DIR *d = NULL;
        sd_id128_t found_uuid = SD_ID128_NULL;
        dev_t devno, found = 0;
        int r;
 
        /* Enforce some security restrictions: CopyBlocks=auto should not be an avenue to get outside of the
         * --root=/--image= confinement. Specifically, refuse CopyBlocks= in combination with --root= at all,
         * and restrict block device references in the --image= case to loopback block device we set up.
         *
         * restrict_devno contain the dev_t of the loop back device we operate on in case of --image=, and
         * thus declares which device (and its partition subdevices) we shall limit access to. If
         * restrict_devno is zero no device probing access shall be allowed at all (used for --root=) and if
         * it is (dev_t) -1 then free access shall be allowed (if neither switch is used). */
 
        if (restrict_devno == 0)
                return log_error_errno(SYNTHETIC_ERRNO(EPERM),
                                       "Automatic discovery of backing block devices not permitted in --root= mode, refusing.");
 
        /* Handles CopyBlocks=auto, and finds the right source partition to copy from. We look for matching
         * partitions in the host, using the appropriate directory as key and ensuring that the partition
         * type matches. */
 
        switch (type.designator) {
 
        case PARTITION_ROOT:
        case PARTITION_ROOT_VERITY:
        case PARTITION_ROOT_VERITY_SIG:
                try1 = "/";
                break;
 
        case PARTITION_USR:
        case PARTITION_USR_VERITY:
        case PARTITION_USR_VERITY_SIG:
                try1 = "/usr/";
                break;
 
        case PARTITION_ESP:
                try1 = "/efi/";
                try2 = "/boot/";
                break;
 
        case PARTITION_XBOOTLDR:
                try1 = "/boot/";
                break;
 
        default:
                return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
                                       "Partition type %s not supported from automatic source block device discovery.",
                                       strna(partition_designator_to_string(type.designator)));
        }
 
        r = find_backing_devno(try1, root, &devno);
        if (r == -ENOENT && try2)
                r = find_backing_devno(try2, root, &devno);
        if (r < 0)
                return log_error_errno(r, "Failed to resolve automatic CopyBlocks= path for partition type %s, sorry: %m",
                                       partition_designator_to_string(type.designator));
 
        xsprintf_sys_block_path(p, "/slaves", devno);
        d = opendir(p);
        if (d) {
                struct dirent *de;
 
                for (;;) {
                        _cleanup_free_ char *q = NULL, *t = NULL;
                        sd_id128_t u;
                        dev_t sl;
 
                        errno = 0;
                        de = readdir_no_dot(d);
                        if (!de) {
                                if (errno != 0)
                                        return log_error_errno(errno, "Failed to read directory '%s': %m", p);
 
                                break;
                        }
 
                        if (!IN_SET(de->d_type, DT_LNK, DT_UNKNOWN))
                                continue;
 
                        q = path_join(p, de->d_name, "/dev");
                        if (!q)
                                return log_oom();
 
                        r = read_one_line_file(q, &t);
                        if (r < 0)
                                return log_error_errno(r, "Failed to read %s: %m", q);
 
                        r = parse_devnum(t, &sl);
                        if (r < 0) {
                                log_debug_errno(r, "Failed to parse %s, ignoring: %m", q);
                                continue;
                        }
                        if (major(sl) == 0) {
                                log_debug("Device backing %s is special, ignoring.", q);
                                continue;
                        }
 
                        r = resolve_copy_blocks_auto_candidate(sl, type, restrict_devno, &u);
                        if (r < 0)
                                return r;
                        if (r > 0) {
                                /* We found a matching one! */
                                if (found != 0 && found != sl)
                                        return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ),
                                                               "Multiple matching partitions found for partition type %s, refusing.",
                                                               partition_designator_to_string(type.designator));
 
                                found = sl;
                                found_uuid = u;
                        }
 
                        dev_t harder_devno = 0;
                        r = resolve_copy_blocks_auto_candidate_harder(sl, type, restrict_devno, &harder_devno, &u);
                        if (r < 0)
                                return r;
                        if (r > 0) {
                                /* We found a matching one! */
                                if (found != 0 && found != harder_devno)
                                        return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ),
                                                               "Multiple matching partitions found, refusing.");
 
                                found = harder_devno;
                                found_uuid = u;
                        }
                }
        } else if (errno != ENOENT)
                return log_error_errno(errno, "Failed to open %s: %m", p);
        else {
                r = resolve_copy_blocks_auto_candidate(devno, type, restrict_devno, &found_uuid);
                if (r < 0)
                        return r;
                if (r > 0)
                        found = devno;
        }
 
        if (found == 0)
                return log_error_errno(SYNTHETIC_ERRNO(ENXIO),
                                       "Unable to automatically discover suitable partition to copy blocks from for partition type %s.",
                                       partition_designator_to_string(type.designator));
 
        if (ret_devno)
                *ret_devno = found;
 
        if (ret_uuid)
                *ret_uuid = found_uuid;
 
        return 0;
}
 
static int context_open_copy_block_paths(
                Context *context,
                dev_t restrict_devno) {
 
        int r;
 
        assert(context);
 
        LIST_FOREACH(partitions, p, context->partitions) {
                _cleanup_close_ int source_fd = -EBADF;
                _cleanup_free_ char *opened = NULL;
                sd_id128_t uuid = SD_ID128_NULL;
                uint64_t size;
                struct stat st;
 
                if (p->copy_blocks_fd >= 0)
                        continue;
 
                assert(p->copy_blocks_size == UINT64_MAX);
 
                if (PARTITION_EXISTS(p)) /* Never copy over partitions that already exist! */
                        continue;
 
                if (p->copy_blocks_path) {
 
                        source_fd = chase_and_open(p->copy_blocks_path, p->copy_blocks_root, CHASE_PREFIX_ROOT, O_RDONLY|O_CLOEXEC|O_NONBLOCK, &opened);
                        if (source_fd < 0)
                                return log_error_errno(source_fd, "Failed to open '%s': %m", p->copy_blocks_path);
 
                        if (fstat(source_fd, &st) < 0)
                                return log_error_errno(errno, "Failed to stat block copy file '%s': %m", opened);
 
                        if (!S_ISREG(st.st_mode) && restrict_devno != (dev_t) -1)
                                return log_error_errno(SYNTHETIC_ERRNO(EPERM),
                                                       "Copying from block device node is not permitted in --image=/--root= mode, refusing.");
 
                } else if (p->copy_blocks_auto) {
                        dev_t devno = 0;  /* Fake initialization to appease gcc. */
 
                        r = resolve_copy_blocks_auto(p->type, p->copy_blocks_root, restrict_devno, &devno, &uuid);
                        if (r < 0)
                                return r;
                        assert(devno != 0);
 
                        source_fd = r = device_open_from_devnum(S_IFBLK, devno, O_RDONLY|O_CLOEXEC|O_NONBLOCK, &opened);
                        if (r < 0)
                                return log_error_errno(r, "Failed to open automatically determined source block copy device " DEVNUM_FORMAT_STR ": %m",
                                                       DEVNUM_FORMAT_VAL(devno));
 
                        if (fstat(source_fd, &st) < 0)
                                return log_error_errno(errno, "Failed to stat block copy file '%s': %m", opened);
                } else
                        continue;
 
                (void) context_notify(context, PROGRESS_OPENING_COPY_BLOCK_SOURCES, p->definition_path, UINT_MAX);
 
                if (S_ISDIR(st.st_mode)) {
                        _cleanup_free_ char *bdev = NULL;
                        dev_t devt;
 
                        /* If the file is a directory, automatically find the backing block device */
 
                        if (major(st.st_dev) != 0)
                                devt = st.st_dev;
                        else {
                                /* Special support for btrfs */
                                r = btrfs_get_block_device_fd(source_fd, &devt);
                                if (r == -EUCLEAN)
                                        return btrfs_log_dev_root(LOG_ERR, r, opened);
                                if (r < 0)
                                        return log_error_errno(r, "Unable to determine backing block device of '%s': %m", opened);
                        }
 
                        safe_close(source_fd);
 
                        source_fd = r = device_open_from_devnum(S_IFBLK, devt, O_RDONLY|O_CLOEXEC|O_NONBLOCK, &bdev);
                        if (r < 0)
                                return log_error_errno(r, "Failed to open block device backing '%s': %m", opened);
 
                        if (fstat(source_fd, &st) < 0)
                                return log_error_errno(errno, "Failed to stat block device '%s': %m", bdev);
                }
 
                if (S_ISREG(st.st_mode))
                        size = st.st_size;
                else if (S_ISBLK(st.st_mode)) {
                        r = blockdev_get_device_size(source_fd, &size);
                        if (r < 0)
                                return log_error_errno(r, "Failed to determine size of block device to copy from: %m");
                } else if (S_ISCHR(st.st_mode))
                        size = UINT64_MAX;
                else
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Specified path to copy blocks from '%s' is not a regular file, block device or directory, refusing.", opened);
 
                if (size != UINT64_MAX) {
                        if (size <= 0)
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "File to copy bytes from '%s' has zero size, refusing.", opened);
                        if (size % 512 != 0)
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "File to copy bytes from '%s' has size that is not multiple of 512, refusing.", opened);
                }
 
                p->copy_blocks_fd = TAKE_FD(source_fd);
                p->copy_blocks_size = size;
 
                free_and_replace(p->copy_blocks_path, opened);
 
                /* When copying from an existing partition copy that partitions UUID if none is configured explicitly */
                if (!p->new_uuid_is_set && !sd_id128_is_null(uuid)) {
                        p->new_uuid = uuid;
                        p->new_uuid_is_set = true;
                }
        }
 
        return 0;
}
 
static int context_open_btrfs_filesystems(Context *context) {
        int r;
 
        assert(context);
 
        LIST_FOREACH(partitions, p, context->partitions) {
                _cleanup_(btrfs_replacement_freep) BtrfsReplacement *replacement = NULL;
 
                if (p->dropped)
                        continue;
 
                if (PARTITION_EXISTS(p))
                        continue;
 
                if (!p->block_device_replace)
                        continue;
 
                if (partition_defer(context, p))
                        continue;
 
                (void) context_notify(context, PROGRESS_OPENING_BLOCK_DEVICE_REPLACE_SOURCES, p->definition_path, UINT_MAX);
 
                replacement = new(BtrfsReplacement, 1);
                if (!replacement)
                        return log_oom();
 
                *replacement = (BtrfsReplacement) {
                        .mountpoint_fd = -EBADF,
                        .source_fd = -EBADF,
                };
 
                replacement->mountpoint_fd = xopenat(AT_FDCWD, p->block_device_replace, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
                if (replacement->mountpoint_fd < 0)
                        return log_error_errno(replacement->mountpoint_fd, "Failed to open mountpoint %s for btrfs filesystem: %m", p->block_device_replace);
 
                r = fd_is_fs_type(replacement->mountpoint_fd, BTRFS_SUPER_MAGIC);
                if (r < 0)
                        return log_error_errno(r, "Failed to check filesystem for mountpoint %s: %m", p->block_device_replace);
                if (r == 0)
                        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Mountpoint %s is not a btrfs filesystem", p->block_device_replace);
 
                r = btrfs_get_block_device_at_full(replacement->mountpoint_fd, "", &replacement->devid, &replacement->source_path, /* ret= */ NULL);
                if (r < 0)
                        return log_error_errno(r, "Failed to find device id for btrfs filesystem: %m");
                if (r == 0)
                        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Btrfs filesystem has multiple devices.");
 
                /* We need to keep the source device open otherwise, it might be collected. */
                replacement->source_fd = open(replacement->source_path, O_RDONLY|O_CLOEXEC);
                if (replacement->source_fd < 0)
                        return log_error_errno(errno, "Failed to open source device %s: %m", replacement->source_path);
 
                r = fd_verify_block(replacement->source_fd);
                if (r < 0)
                        return log_error_errno(r, "Device %s is not a block device: %m", replacement->source_path);
 
                r = blockdev_get_device_size(replacement->source_fd, &replacement->source_size);
                if (r < 0)
                        return log_error_errno(r, "Failed to get device size %s: %m", replacement->source_path);
 
                p->btrfs_replaced = TAKE_PTR(replacement);
        }
 
        return 0;
}
 
static int fd_apparent_size(int fd, uint64_t *ret) {
        off_t initial = 0;
        uint64_t size = 0;
 
        assert(fd >= 0);
        assert(ret);
 
        initial = lseek(fd, 0, SEEK_CUR);
        if (initial < 0)
                return log_error_errno(errno, "Failed to get file offset: %m");
 
        for (off_t off = 0;;) {
                off_t r;
 
                r = lseek(fd, off, SEEK_DATA);
                if (r < 0 && errno == ENXIO)
                        /* If errno == ENXIO, that means we've reached the final hole of the file and
                         * that hole isn't followed by more data. */
                        break;
                if (r < 0)
                        return log_error_errno(errno, "Failed to seek data in file from offset %"PRIi64": %m", off);
 
                off = r; /* Set the offset to the start of the data segment. */
 
                /* After copying a potential hole, find the end of the data segment by looking for
                 * the next hole. If we get ENXIO, we're at EOF. */
                r = lseek(fd, off, SEEK_HOLE);
                if (r < 0) {
                        if (errno == ENXIO)
                                break;
                        return log_error_errno(errno, "Failed to seek hole in file from offset %"PRIi64": %m", off);
                }
 
                size += r - off;
                off = r;
        }
 
        if (lseek(fd, initial, SEEK_SET) < 0)
                return log_error_errno(errno, "Failed to reset file offset: %m");
 
        *ret = size;
 
        return 0;
}
 
static bool need_fstab_one(const Partition *p) {
        assert(p);
 
        if (p->dropped)
                return false;
 
        if (!p->format)
                return false;
 
        if (p->n_mountpoints == 0)
                return false;
 
        return true;
}
 
static bool need_fstab(const Context *context) {
        assert(context);
 
        LIST_FOREACH(partitions, p, context->partitions)
                if (need_fstab_one(p))
                        return true;
 
        return false;
}
 
static int make_by_uuid_symlink_path(const Partition *p, char **ret) {
        _cleanup_free_ char *what = NULL;
 
        assert(p);
        assert(ret);
 
        if (streq_ptr(p->format, "vfat")) {
                if (asprintf(&what, "UUID=%04X-%04X",
                             ((uint32_t) p->fs_uuid.bytes[0] << 8) |
                             ((uint32_t) p->fs_uuid.bytes[1] << 0),
                             ((uint32_t) p->fs_uuid.bytes[2] << 8) |
                             ((uint32_t) p->fs_uuid.bytes[3])) < 0) /* Take first 32 bytes of UUID */
                        return log_oom();
        } else {
                what = strjoin("UUID=", SD_ID128_TO_UUID_STRING(p->fs_uuid));
                if (!what)
                        return log_oom();
        }
 
        *ret = TAKE_PTR(what);
        return 0;
}
 
static int context_fstab(Context *context) {
        _cleanup_(unlink_and_freep) char *t = NULL;
        _cleanup_fclose_ FILE *f = NULL;
        _cleanup_free_ char *path = NULL, *c = NULL;
        int r;
 
        assert(context);
 
        if (!arg_generate_fstab)
                return false;
 
        if (!need_fstab(context)) {
                log_notice("MountPoint= is not specified for any eligible partitions, not generating %s",
                           arg_generate_fstab);
                return 0;
        }
 
        if (arg_dry_run) {
                log_notice("Running in dry run mode, not generating %s", arg_generate_fstab);
                return 0;
        }
 
        path = path_join(arg_copy_source, arg_generate_fstab);
        if (!path)
                return log_oom();
 
        r = fopen_tmpfile_linkable(path, O_WRONLY|O_CLOEXEC, &t, &f);
        if (r < 0)
                return log_error_errno(r, "Failed to open temporary file for %s: %m", path);
 
        fputs(AUTOMATIC_FSTAB_HEADER_START "\n", f);
 
        LIST_FOREACH(partitions, p, context->partitions) {
                _cleanup_free_ char *what = NULL;
 
                if (!need_fstab_one(p))
                        continue;
 
                r = make_by_uuid_symlink_path(p, &what);
                if (r < 0)
                        return r;
 
                FOREACH_ARRAY(mountpoint, p->mountpoints, p->n_mountpoints) {
                        _cleanup_free_ char *options = NULL;
 
                        r = partition_pick_mount_options(
                                        p->type.designator,
                                        p->format,
                                        /* rw= */ true,
                                        /* discard= */ !IN_SET(p->type.designator, PARTITION_ESP, PARTITION_XBOOTLDR),
                                        &options,
                                        NULL);
                        if (r < 0)
                                return r;
 
                        if (!strextend_with_separator(&options, ",", mountpoint->options))
                                return log_oom();
 
                        fprintf(f, "%s %s %s %s 0 %i\n",
                                what,
                                mountpoint->where,
                                p->format,
                                options,
                                p->type.designator == PARTITION_ROOT ? 1 : 2);
                }
        }
 
        fputs(AUTOMATIC_FSTAB_HEADER_END "\n", f);
 
        switch (arg_append_fstab) {
        case APPEND_AUTO: {
                r = read_full_file(path, &c, NULL);
                if (r == -ENOENT) {
                        log_debug("File fstab not found in %s", path);
                        break;
                }
                if (r < 0)
                        return log_error_errno(r, "Failed to open %s: %m", path);
 
                const char *acs, *ace;
                acs = find_line(c, AUTOMATIC_FSTAB_HEADER_START);
                if (acs) {
                        fwrite(c, 1, acs - c, f);
                        ace = find_line_after(acs, AUTOMATIC_FSTAB_HEADER_END);
                        if (ace)
                                fputs(ace, f);
                } else
                        fputs(c, f);
                break;
        }
        case APPEND_NO:
        case APPEND_REPLACE:
                break;
        default:
                assert_not_reached();
        }
 
        r = fchmod_umask(fileno(f), 0666);
        if (r < 0)
                return log_error_errno(r, "Failed to adjust access mode of generated fstab file: %m");
 
        r = flink_tmpfile(f, t, path, IN_SET(arg_append_fstab, APPEND_AUTO, APPEND_REPLACE) ? LINK_TMPFILE_REPLACE : 0);
        if (r < 0)
                return log_error_errno(r, "Failed to link temporary file to %s: %m", path);
 
        t = mfree(t);
 
        log_info("%s written.", path);
 
        return 0;
}
 
static bool need_crypttab_one(const Partition *p) {
        assert(p);
 
        if (p->dropped)
                return false;
 
        if (p->encrypt == ENCRYPT_OFF)
                return false;
 
        if (!p->encrypted_volume)
                return false;
 
        return true;
}
 
static bool need_crypttab(Context *context) {
        assert(context);
 
        LIST_FOREACH(partitions, p, context->partitions)
                if (need_crypttab_one(p))
                        return true;
 
        return false;
}
 
static int context_crypttab(Context *context, bool late) {
        _cleanup_(unlink_and_freep) char *t = NULL;
        _cleanup_fclose_ FILE *f = NULL;
        _cleanup_free_ char *path = NULL;
        int r;
 
        assert(context);
 
        if (!arg_generate_crypttab)
                return false;
 
        if (!need_crypttab(context)) {
                log_notice("EncryptedVolume= is not specified for any eligible partitions, not generating %s",
                           arg_generate_crypttab);
                return 0;
        }
 
        if (arg_dry_run) {
                log_notice("Running in dry run mode, not generating %s", arg_generate_crypttab);
                return 0;
        }
 
        path = path_join(arg_copy_source, arg_generate_crypttab);
        if (!path)
                return log_oom();
 
        r = fopen_tmpfile_linkable(path, O_WRONLY|O_CLOEXEC, &t, &f);
        if (r < 0)
                return log_error_errno(r, "Failed to open temporary file for %s: %m", path);
 
        fprintf(f, "# Automatically generated by systemd-repart\n\n");
 
        LIST_FOREACH(partitions, p, context->partitions) {
                _cleanup_free_ char *volume = NULL;
 
                if (!need_crypttab_one(p))
                        continue;
 
                if (!p->encrypted_volume->name && asprintf(&volume, "luks-%s", SD_ID128_TO_UUID_STRING(p->luks_uuid)) < 0)
                        return log_oom();
 
                fprintf(f, "%s UUID=%s %s %s\n",
                        p->encrypted_volume->name ?: volume,
                        SD_ID128_TO_UUID_STRING(p->luks_uuid),
                        isempty(p->encrypted_volume->keyfile) ? "-" : p->encrypted_volume->keyfile,
                        strempty(p->encrypted_volume->options));
        }
 
        r = flink_tmpfile(f, t, path, late ? LINK_TMPFILE_REPLACE : 0);
        if (r < 0)
                return log_error_errno(r, "Failed to link temporary file to %s: %m", path);
 
        t = mfree(t);
 
        log_info("%s written.", path);
 
        return 0;
}
 
/* update block sizes for verity siblings, calculate hash partition size if requested */
static int context_update_verity_size(Context *context) {
        int r;
 
        assert(context);
 
        LIST_FOREACH(partitions, p, context->partitions) {
                Partition *dp;
 
                if (p->verity != VERITY_HASH)
                        continue;
 
                if (p->dropped)
                        continue;
 
                if (PARTITION_EXISTS(p)) /* Never format existing partitions */
                        continue;
 
                assert_se(dp = p->siblings[VERITY_DATA]);
 
                if (p->verity_data_block_size == UINT64_MAX)
                        p->verity_data_block_size = partition_fs_sector_size(context, p);
 
                if (p->verity_hash_block_size == UINT64_MAX)
                        p->verity_hash_block_size = partition_fs_sector_size(context, p);
 
                uint64_t sz;
                if (dp->size_max != UINT64_MAX) {
                        r = calculate_verity_hash_size(
                                        dp->size_max,
                                        p->verity_hash_block_size,
                                        p->verity_data_block_size,
                                        &sz);
                        if (r < 0)
                                return log_error_errno(r, "Failed to calculate size of dm-verity hash partition: %m");
 
                        if (sz > p->size_min || sz > p->size_max)
                                log_warning("The dm-verity hash partition %s may be too small for a data partition "
                                            "with SizeMaxBytes=%s. The hash partition would require %s for a data "
                                            "partition of specified max size. Consider increasing the size of the "
                                            "hash partition, or decreasing SizeMaxBytes= of the data partition.",
                                            p->definition_path, FORMAT_BYTES(dp->size_max), FORMAT_BYTES(sz));
                        else if (p->size_min == UINT64_MAX) {
                                log_debug("Derived size %s of verity hash partition %s from verity data partition %s.",
                                                FORMAT_BYTES(sz), p->definition_path, dp->definition_path);
 
                                p->size_min = sz;
                        }
                }
        }
 
        return 0;
}
 
static int context_minimize(Context *context) {
        const char *vt = NULL;
        unsigned attrs = 0;
        int r;
 
        assert(context);
 
        if (context->backing_fd >= 0) {
                r = read_attr_fd(context->backing_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);
        }
 
        LIST_FOREACH(partitions, p, context->partitions) {
                _cleanup_(rm_rf_physical_and_freep) char *root = NULL;
                _cleanup_(unlink_and_freep) char *temp = NULL;
                _cleanup_(loop_device_unrefp) LoopDevice *d = NULL;
                _cleanup_strv_free_ char **extra_mkfs_options = NULL;
                _cleanup_close_ int fd = -EBADF;
                _cleanup_free_ char *hint = NULL;
                sd_id128_t fs_uuid;
                struct stat st;
                uint64_t fsz;
 
                if (p->dropped)
                        continue;
 
                if (PARTITION_EXISTS(p)) /* Never format existing partitions */
                        continue;
 
                if (!p->format)
                        continue;
 
                bool is_btrfs = streq(p->format, "btrfs");
 
                if (p->copy_blocks_fd >= 0)
                        continue;
 
                if (p->minimize == MINIMIZE_OFF)
                        continue;
 
                if (!partition_needs_populate(p))
                        continue;
 
                (void) context_notify(context, PROGRESS_MINIMIZING, p->definition_path, UINT_MAX);
 
                assert(!p->copy_blocks_path);
 
                (void) partition_hint(p, context->node, &hint);
 
                log_info("Pre-populating %s filesystem of partition %s to calculate minimal partition size",
                         p->format, strna(hint));
 
                if (!vt) {
                        r = var_tmp_dir(&vt);
                        if (r < 0)
                                return log_error_errno(r, "Could not determine temporary directory: %m");
                }
 
                r = tempfn_random_child(vt, "repart", &temp);
                if (r < 0)
                        return log_error_errno(r, "Failed to generate temporary file path: %m");
 
                fd = xopenat_full(
                                AT_FDCWD,
                                temp,
                                O_CREAT|O_EXCL|O_CLOEXEC|O_RDWR|O_NOCTTY,
                                attrs & FS_NOCOW_FL ? XO_NOCOW : 0,
                                0600);
                if (fd < 0)
                        return log_error_errno(fd, "Failed to open temporary file %s: %m", temp);
 
                if (fstype_is_ro(p->format) || is_btrfs)
                        /* Read-only filesystems and btrfs (with mkfs.btrfs --shrink) produce a minimal
                         * filesystem in one pass, so we can use the real UUID directly. */
                        fs_uuid = p->fs_uuid;
                else {
                        /* This may seem huge but it will be created sparse so it doesn't take up any space
                         * on disk until written to. */
                        if (ftruncate(fd, 1024ULL * 1024ULL * 1024ULL * 1024ULL) < 0)
                                return log_error_errno(errno, "Failed to truncate temporary file to %s: %m",
                                                       FORMAT_BYTES(1024ULL * 1024ULL * 1024ULL * 1024ULL));
 
                        if (arg_offline <= 0) {
                                r = loop_device_make(fd, O_RDWR, 0, UINT64_MAX, context->sector_size, 0, LOCK_EX, &d);
                                if (r < 0 && loop_device_error_is_fatal(p, r))
                                        return log_error_errno(r, "Failed to make loopback device of %s: %m", temp);
                        }
 
                        /* We're going to populate this filesystem twice so use a random UUID the first time
                         * to avoid UUID conflicts. */
                        r = sd_id128_randomize(&fs_uuid);
                        if (r < 0)
                                return r;
                }
 
                if (!d || fstype_is_ro(p->format)) {
                        if (!mkfs_supports_root_option(p->format))
                                return log_error_errno(SYNTHETIC_ERRNO(ENODEV),
                                                       "Loop device 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(
                                d ? d->node : temp,
                                p->format,
                                strempty(p->new_label),
                                root,
                                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;
 
                /* Read-only filesystems are minimal from the first try because they create and size the
                 * loopback file for us. Similarly, mkfs.btrfs --shrink populates the filesystem from the
                 * root directory and then shrinks the backing file to the minimal size. */
                if (fstype_is_ro(p->format) || is_btrfs) {
                        fd = safe_close(fd);
 
                        fd = open(temp, O_RDONLY|O_CLOEXEC|O_NONBLOCK);
                        if (fd < 0)
                                return log_error_errno(errno, "Failed to open temporary file %s: %m", temp);
 
                        if (fstat(fd, &st) < 0)
                                return log_error_errno(errno, "Failed to stat temporary file: %m");
 
                        if ((uint64_t) st.st_size > partition_max_size(context, p))
                                return log_error_errno(SYNTHETIC_ERRNO(E2BIG),
                                                       "Minimal partition size of %s filesystem of partition %s exceeds configured maximum size (%s > %s)",
                                                       p->format, strna(hint), FORMAT_BYTES(st.st_size), FORMAT_BYTES(partition_max_size(context, p)));
 
                        log_info("Minimal partition size of %s filesystem of partition %s is %s",
                                 p->format, strna(hint), FORMAT_BYTES(st.st_size));
 
                        p->copy_blocks_path = TAKE_PTR(temp);
                        p->copy_blocks_path_is_our_file = true;
                        p->copy_blocks_fd = TAKE_FD(fd);
                        p->copy_blocks_size = st.st_size;
                        continue;
                }
 
                if (!root) {
                        assert(d);
 
                        r = partition_populate_filesystem(context, p, d->node);
                        if (r < 0)
                                return r;
                }
 
                /* Other filesystems need to be provided with a pre-sized loopback file and will adapt to
                 * fully occupy it. Because we gave the filesystem a 1T sparse file, we need to shrink the
                 * filesystem down to a reasonable size again to fit it in the disk image. Let's populate the
                 * filesystem again, but this time, instead of providing the filesystem with a 1T sparse
                 * loopback file, let's size the loopback file based on the actual data used by the
                 * filesystem in the sparse file after the first attempt. This should be a good guess of the
                 * minimal amount of space needed in the filesystem to fit all the required data.
                 */
                r = fd_apparent_size(fd, &fsz);
                if (r < 0)
                        return r;