HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/home/homework-luks.c

162,356 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: d4ce674c3601e23183894548a8204dc282786674

Lines 2001–3000 of 4,048

                return log_error_errno(r, "Failed to determine disk label UUID: %m");
 
        r = sym_fdisk_get_partition(c, 0, &q);
        if (r < 0)
                return log_error_errno(r, "Failed to read created partition metadata: %m");
 
        assert(sym_fdisk_partition_has_start(q));
        offset = sym_fdisk_partition_get_start(q);
        if (offset > UINT64_MAX / fdisk_sector_size)
                return log_error_errno(SYNTHETIC_ERRNO(ERANGE), "Partition offset too large.");
 
        assert(sym_fdisk_partition_has_size(q));
        size = sym_fdisk_partition_get_size(q);
        if (size > UINT64_MAX / fdisk_sector_size)
                return log_error_errno(SYNTHETIC_ERRNO(ERANGE), "Partition size too large.");
 
        *ret_offset = offset * fdisk_sector_size;
        *ret_size = size * fdisk_sector_size;
        *ret_disk_uuid = disk_uuid;
 
        return 0;
}
 
static bool supported_fs_size(const char *fstype, uint64_t host_size) {
        uint64_t m;
 
        m = minimal_size_by_fs_name(fstype);
        if (m == UINT64_MAX)
                return false;
 
        return host_size >= m;
}
 
static int wait_for_devlink(const char *path) {
        _cleanup_close_ int inotify_fd = -EBADF;
        usec_t until;
        int r;
 
        /* let's wait for a device link to show up in /dev, with a timeout. This is good to do since we
         * return a /dev/disk/by-uuid/… link to our callers and they likely want to access it right-away,
         * hence let's wait until udev has caught up with our changes, and wait for the symlink to be
         * created. */
 
        until = usec_add(now(CLOCK_MONOTONIC), 45 * USEC_PER_SEC);
 
        for (;;) {
                _cleanup_free_ char *dn = NULL;
                usec_t w;
 
                r = access_nofollow(path, F_OK);
                if (r >= 0)
                        return 0; /* Found it */
                if (r != -ENOENT)
                        return log_error_errno(r, "Failed to determine whether %s exists: %m", path);
 
                if (inotify_fd < 0) {
                        /* We need to wait for the device symlink to show up, let's create an inotify watch for it */
                        inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
                        if (inotify_fd < 0)
                                return log_error_errno(errno, "Failed to allocate inotify fd: %m");
                }
 
                r = path_extract_directory(path, &dn);
                if (r < 0)
                        return log_error_errno(r, "Failed to extract directory from device node path '%s': %m", path);
                for (;;) {
                        _cleanup_free_ char *ndn = NULL;
 
                        log_info("Watching %s", dn);
 
                        if (inotify_add_watch(inotify_fd, dn, IN_CREATE|IN_MOVED_TO|IN_ONLYDIR|IN_DELETE_SELF|IN_MOVE_SELF) < 0) {
                                if (errno != ENOENT)
                                        return log_error_errno(errno, "Failed to add watch on %s: %m", dn);
                        } else
                                break;
 
                        r = path_extract_directory(dn, &ndn);
                        if (r == -EADDRNOTAVAIL) /* Arrived at the top? */
                                break;
                        if (r < 0)
                                return log_error_errno(r, "Failed to extract directory from device node path '%s': %m", dn);
 
                        free_and_replace(dn, ndn);
                }
 
                w = now(CLOCK_MONOTONIC);
                if (w >= until)
                        return log_error_errno(SYNTHETIC_ERRNO(ETIMEDOUT), "Device link %s still hasn't shown up, giving up.", path);
 
                r = fd_wait_for_event(inotify_fd, POLLIN, until - w);
                if (ERRNO_IS_NEG_TRANSIENT(r))
                        continue;
                if (r < 0)
                        return log_error_errno(r, "Failed to watch inotify: %m");
 
                (void) flush_fd(inotify_fd);
        }
}
 
static int calculate_initial_image_size(UserRecord *h, int image_fd, const char *fstype, uint64_t *ret) {
        uint64_t upper_boundary, lower_boundary;
        struct statfs sfs;
 
        assert(h);
        assert(image_fd >= 0);
        assert(ret);
 
        if (fstatfs(image_fd, &sfs) < 0)
                return log_error_errno(errno, "statfs() on image failed: %m");
 
        upper_boundary = DISK_SIZE_ROUND_DOWN((uint64_t) sfs.f_bsize * sfs.f_bavail);
 
        if (h->disk_size != UINT64_MAX)
                *ret = MIN(DISK_SIZE_ROUND_DOWN(h->disk_size), upper_boundary);
        else if (h->disk_size_relative == UINT64_MAX) {
 
                if (upper_boundary > UINT64_MAX / USER_DISK_SIZE_DEFAULT_PERCENT)
                        return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW), "Disk size too large.");
 
                *ret = DISK_SIZE_ROUND_DOWN(upper_boundary * USER_DISK_SIZE_DEFAULT_PERCENT / 100);
 
                log_info("Sizing home to %u%% of available disk space, which is %s.",
                         USER_DISK_SIZE_DEFAULT_PERCENT,
                         FORMAT_BYTES(*ret));
        } else {
                *ret = DISK_SIZE_ROUND_DOWN((uint64_t) ((double) upper_boundary * (double) CLAMP(h->disk_size_relative, 0U, UINT32_MAX) / (double) UINT32_MAX));
 
                log_info("Sizing home to %" PRIu64 ".%01" PRIu64 "%% of available disk space, which is %s.",
                         (h->disk_size_relative * 100) / UINT32_MAX,
                         ((h->disk_size_relative * 1000) / UINT32_MAX) % 10,
                         FORMAT_BYTES(*ret));
        }
 
        lower_boundary = minimal_size_by_fs_name(fstype);
        if (lower_boundary != UINT64_MAX) {
                assert(GPT_LUKS2_OVERHEAD < UINT64_MAX - lower_boundary);
                lower_boundary += GPT_LUKS2_OVERHEAD;
        }
        if (lower_boundary == UINT64_MAX || lower_boundary < USER_DISK_SIZE_MIN)
                lower_boundary = USER_DISK_SIZE_MIN;
 
        if (*ret < lower_boundary)
                *ret = lower_boundary;
 
        return 0;
}
 
static int home_truncate(
                UserRecord *h,
                int fd,
                uint64_t size) {
 
        bool trunc;
        int r;
 
        assert(h);
        assert(fd >= 0);
 
        trunc = user_record_luks_discard(h);
        if (!trunc) {
                r = fallocate(fd, 0, 0, size);
                if (r < 0 && ERRNO_IS_NOT_SUPPORTED(errno)) {
                        /* Some file systems do not support fallocate(), let's gracefully degrade
                         * (ZFS, reiserfs, …) and fall back to truncation */
                        log_notice_errno(errno, "Backing file system does not support fallocate(), falling back to ftruncate(), i.e. implicitly using non-discard mode.");
                        trunc = true;
                }
        }
 
        if (trunc)
                r = ftruncate(fd, size);
 
        if (r < 0) {
                if (ERRNO_IS_DISK_SPACE(errno)) {
                        log_debug_errno(errno, "Not enough disk space to allocate home of size %s.", FORMAT_BYTES(size));
                        return -ENOSPC; /* make recognizable */
                }
 
                return log_error_errno(errno, "Failed to truncate home image: %m");
        }
 
        return !trunc; /* Return == 0 if we managed to truncate, > 0 if we managed to allocate */
}
 
int home_create_luks(
                UserRecord *h,
                HomeSetup *setup,
                const PasswordCache *cache,
                char **effective_passwords,
                UserRecord **ret_home) {
 
        _cleanup_free_ char *subdir = NULL, *disk_uuid_path = NULL;
        uint64_t encrypted_size, image_sector_size, luks_sector_size,
                host_size = 0, partition_offset = 0, partition_size = 0; /* Unnecessary initialization to appease gcc */
        _cleanup_(user_record_unrefp) UserRecord *new_home = NULL;
        sd_id128_t partition_uuid, fs_uuid, luks_uuid, disk_uuid;
        _cleanup_close_ int mount_fd = -EBADF;
        const char *fstype, *ip;
        struct statfs sfs;
        struct stat st;
        int r;
        _cleanup_strv_free_ char **extra_mkfs_options = NULL;
 
        assert(h);
        assert(h->storage < 0 || h->storage == USER_LUKS);
        assert(setup);
        assert(!setup->temporary_image_path);
        assert(setup->image_fd < 0);
        assert(ret_home);
 
        r = dlopen_fdisk(LOG_DEBUG);
        if (r < 0)
                return r;
 
        r = dlopen_cryptsetup(LOG_DEBUG);
        if (r < 0)
                return r;
 
        assert_se(ip = user_record_image_path(h));
 
        fstype = user_record_file_system_type(h);
        if (!supported_fstype(fstype))
                return log_error_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT), "Unsupported file system type: %s", fstype);
 
        r = mkfs_exists(fstype);
        if (r < 0)
                return log_error_errno(r, "Failed to check if mkfs binary for %s exists: %m", fstype);
        if (r == 0) {
                if (h->file_system_type || streq(fstype, "ext4") || !supported_fstype("ext4"))
                        return log_error_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT), "mkfs binary for file system type %s does not exist.", fstype);
 
                /* If the record does not explicitly declare a file system to use, and the compiled-in
                 * default does not actually exist, than do an automatic fallback onto ext4, as the baseline
                 * fs of Linux. We won't search for a working fs type here beyond ext4, i.e. nothing fancier
                 * than a single, conservative fallback to baseline. This should be useful in minimal
                 * environments where mkfs.btrfs or so are not made available, but mkfs.ext4 as Linux' most
                 * boring, most basic fs is. */
                log_info("Formatting tool for compiled-in default file system %s not available, falling back to ext4 instead.", fstype);
                fstype = "ext4";
        }
 
        if (sd_id128_is_null(h->partition_uuid)) {
                r = sd_id128_randomize(&partition_uuid);
                if (r < 0)
                        return log_error_errno(r, "Failed to acquire partition UUID: %m");
        } else
                partition_uuid = h->partition_uuid;
 
        if (sd_id128_is_null(h->luks_uuid)) {
                r = sd_id128_randomize(&luks_uuid);
                if (r < 0)
                        return log_error_errno(r, "Failed to acquire LUKS UUID: %m");
        } else
                luks_uuid = h->luks_uuid;
 
        if (sd_id128_is_null(h->file_system_uuid)) {
                r = sd_id128_randomize(&fs_uuid);
                if (r < 0)
                        return log_error_errno(r, "Failed to acquire file system UUID: %m");
        } else
                fs_uuid = h->file_system_uuid;
 
        r = make_dm_names(h, setup);
        if (r < 0)
                return r;
 
        r = access(setup->dm_node, F_OK);
        if (r < 0) {
                if (errno != ENOENT)
                        return log_error_errno(errno, "Failed to determine whether %s exists: %m", setup->dm_node);
        } else
                return log_error_errno(SYNTHETIC_ERRNO(EEXIST), "Device mapper device %s already exists, refusing.", setup->dm_node);
 
        if (path_startswith(ip, "/dev/")) {
                _cleanup_free_ char *sysfs = NULL;
                uint64_t block_device_size;
 
                /* Let's place the home directory on a real device, i.e. a USB stick or such */
 
                setup->image_fd = open_image_file(h, ip, &st);
                if (setup->image_fd < 0)
                        return setup->image_fd;
 
                r = stat_verify_block(&st);
                if (r < 0)
                        return log_error_errno(r, "Device is not a block device, refusing.");
 
                if (asprintf(&sysfs, "/sys/dev/block/" DEVNUM_FORMAT_STR "/partition", DEVNUM_FORMAT_VAL(st.st_rdev)) < 0)
                        return log_oom();
                if (access(sysfs, F_OK) < 0) {
                        if (errno != ENOENT)
                                return log_error_errno(errno, "Failed to check whether %s exists: %m", sysfs);
                } else
                        return log_error_errno(SYNTHETIC_ERRNO(ENOTBLK), "Operating on partitions is currently not supported, sorry. Please specify a top-level block device.");
 
                if (flock(setup->image_fd, LOCK_EX) < 0) /* make sure udev doesn't read from it while we operate on the device */
                        return log_error_errno(errno, "Failed to lock block device %s: %m", ip);
 
                r = blockdev_get_device_size(setup->image_fd, &block_device_size);
                if (r < 0)
                        return log_error_errno(r, "Failed to read block device size: %m");
 
                if (h->disk_size == UINT64_MAX) {
 
                        /* If a relative disk size is requested, apply it relative to the block device size */
                        if (h->disk_size_relative < UINT32_MAX)
                                host_size = CLAMP(DISK_SIZE_ROUND_DOWN(block_device_size * h->disk_size_relative / UINT32_MAX),
                                                  USER_DISK_SIZE_MIN, USER_DISK_SIZE_MAX);
                        else
                                host_size = block_device_size; /* Otherwise, take the full device */
 
                } else if (h->disk_size > block_device_size)
                        return log_error_errno(SYNTHETIC_ERRNO(EMSGSIZE), "Selected disk size larger than backing block device, refusing.");
                else
                        host_size = DISK_SIZE_ROUND_DOWN(h->disk_size);
 
                if (!supported_fs_size(fstype, LESS_BY(host_size, GPT_LUKS2_OVERHEAD)))
                        return log_error_errno(SYNTHETIC_ERRNO(ERANGE),
                                               "Selected file system size too small for %s.", fstype);
 
                /* After creation we should reference this partition by its UUID instead of the block
                 * device. That's preferable since the user might have specified a device node such as
                 * /dev/sdb to us, which might look very different when replugged. */
                if (asprintf(&disk_uuid_path, "/dev/disk/by-uuid/" SD_ID128_UUID_FORMAT_STR, SD_ID128_FORMAT_VAL(luks_uuid)) < 0)
                        return log_oom();
 
                if (user_record_luks_discard(h) || user_record_luks_offline_discard(h)) {
                        /* If we want online or offline discard, discard once before we start using things. */
 
                        if (ioctl(setup->image_fd, BLKDISCARD, (uint64_t[]) { 0, block_device_size }) < 0)
                                log_full_errno(errno == EOPNOTSUPP ? LOG_DEBUG : LOG_WARNING, errno,
                                               "Failed to issue full-device BLKDISCARD on device, ignoring: %m");
                        else
                                log_info("Full device discard completed.");
                }
        } else {
                _cleanup_free_ char *t = NULL;
 
                r = mkdir_parents(ip, 0755);
                if (r < 0)
                        return log_error_errno(r, "Failed to create parent directory of %s: %m", ip);
 
                r = tempfn_random(ip, "homework", &t);
                if (r < 0)
                        return log_error_errno(r, "Failed to derive temporary file name for %s: %m", ip);
 
                setup->image_fd = open(t, O_RDWR|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
                if (setup->image_fd < 0)
                        return log_error_errno(errno, "Failed to create home image %s: %m", t);
 
                setup->temporary_image_path = TAKE_PTR(t);
 
                r = chattr_full(setup->image_fd, NULL, FS_NOCOW_FL|FS_NOCOMP_FL, FS_NOCOW_FL|FS_NOCOMP_FL, NULL, NULL, CHATTR_FALLBACK_BITWISE);
                if (r < 0 && r != -ENOANO) /* ENOANO → some bits didn't work; which we skip logging about because chattr_full() already debug logs about those flags */
                        log_full_errno(ERRNO_IS_IOCTL_NOT_SUPPORTED(r) ? LOG_DEBUG : LOG_WARNING, r,
                                       "Failed to set file attributes on %s, ignoring: %m", setup->temporary_image_path);
 
                r = calculate_initial_image_size(h, setup->image_fd, fstype, &host_size);
                if (r < 0)
                        return r;
 
                r = resize_image_loop(h, setup, 0, host_size, &host_size);
                if (r < 0)
                        return r;
 
                log_info("Allocating image file completed.");
        }
 
        if (h->luks_sector_size == UINT64_MAX) {
                /* If sector size is not specified, select UINT32_MAX, i.e. auto-probe */
                image_sector_size = UINT32_MAX;
                /* Let cryptsetup decide if the sector size is not specified in home record */
                luks_sector_size = 0;
        } else {
                if (S_ISBLK(st.st_mode)) {
                        /* For physical block devices always use the actual device logical
                         * sector size. Else the partition will not be discoverable by kernel. */
                        image_sector_size = UINT32_MAX;
                        luks_sector_size = user_record_luks_sector_size(h);
                } else
                        image_sector_size = luks_sector_size = user_record_luks_sector_size(h);
        }
        r = make_partition_table(
                        setup->image_fd,
                        image_sector_size,
                        user_record_user_name_and_realm(h),
                        partition_uuid,
                        &partition_offset,
                        &partition_size,
                        &disk_uuid);
        if (r < 0)
                return r;
 
        log_info("Writing of partition table completed.");
 
        if (fstat(setup->image_fd, &st) < 0)
                return log_error_errno(errno, "Failed to fstat home image: %m");
 
        /* Ensure we don't create a loop device over block device as it leads to huge overhead for discard operations
         * if the device does not support discard_zeroes_data */
        if (S_ISBLK(st.st_mode)) {
                _cleanup_free_ char *partition_path = NULL;
                assert(!sd_id128_is_null(partition_uuid));
                if (asprintf(&partition_path, "/dev/disk/by-partuuid/" SD_ID128_UUID_FORMAT_STR, SD_ID128_FORMAT_VAL(partition_uuid)) < 0)
                        return log_oom();
 
                /* Release the lock, so that udev can find the partition */
                setup->image_fd = safe_close(setup->image_fd);
                (void) wait_for_devlink(partition_path);
                setup->image_fd = open_image_file(h, ip, &st);
                if (setup->image_fd < 0)
                        return setup->image_fd;
 
                r = loop_device_open_from_path(
                                partition_path,
                                O_RDWR,
                                LOCK_EX,
                                &setup->loop);
                if (r < 0)
                        return log_error_errno(r, "Failed to open newly written partition device: %s", partition_path);
        } else {
                r = loop_device_make(
                                setup->image_fd,
                                O_RDWR,
                                partition_offset,
                                partition_size,
                                image_sector_size,
                                0,
                                LOCK_EX,
                                &setup->loop);
                if (r == -ENOENT) /* this means /dev/loop-control doesn't exist, i.e. we are in a container
                                   * or similar and loopback bock devices are not available, return a
                                   * recognizable error in this case. */
                        return log_error_errno(SYNTHETIC_ERRNO(ENOLINK), "Loopback block device support is not available on this system.");
                if (r < 0)
                        return log_error_errno(r, "Failed to set up loopback device for %s: %m", setup->temporary_image_path);
        }
 
        log_info("Setting up loopback device %s completed.", setup->loop->node ?: ip);
 
        r = luks_format(setup->loop->node,
                        setup->dm_name,
                        luks_uuid,
                        user_record_user_name_and_realm(h),
                        cache,
                        effective_passwords,
                        user_record_luks_discard(h) || user_record_luks_offline_discard(h),
                        luks_sector_size,
                        h,
                        &setup->crypt_device);
        if (r < 0)
                return r;
 
        setup->undo_dm = true;
 
        r = block_get_size_by_path(setup->dm_node, &encrypted_size);
        if (r < 0)
                return log_error_errno(r, "Failed to get encrypted block device size: %m");
 
        log_info("Setting up LUKS device %s completed.", setup->dm_node);
 
        r = mkfs_options_from_env("HOME", fstype, &extra_mkfs_options);
        if (r < 0)
                return log_error_errno(r, "Failed to determine mkfs command line options for '%s': %m", fstype);
 
        r = make_filesystem(setup->dm_node,
                            fstype,
                            user_record_user_name_and_realm(h),
                            /* root= */ NULL,
                            fs_uuid,
                            (user_record_luks_discard(h) ? MKFS_DISCARD : 0) | MKFS_QUIET,
                            /* sector_size= */ 0,
                            /* compression= */ NULL,
                            /* compression_level= */ NULL,
                            extra_mkfs_options);
        if (r < 0)
                return r;
 
        log_info("Formatting file system completed.");
 
        r = home_unshare_and_mount(setup->dm_node, fstype, user_record_luks_discard(h), user_record_mount_flags(h), h->luks_extra_mount_options);
        if (r < 0)
                return r;
 
        setup->undo_mount = true;
 
        subdir = path_join(HOME_RUNTIME_WORK_DIR, user_record_user_name_and_realm(h));
        if (!subdir)
                return log_oom();
 
        /* Prefer using a btrfs subvolume if we can, fall back to directory otherwise */
        r = btrfs_subvol_make_fallback(AT_FDCWD, subdir, 0700);
        if (r < 0)
                return log_error_errno(r, "Failed to create user directory in mounted image file: %m");
 
        setup->root_fd = open(subdir, O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOFOLLOW);
        if (setup->root_fd < 0)
                return log_error_errno(errno, "Failed to open user directory in mounted image file: %m");
 
        (void) home_shift_uid(setup->root_fd, NULL, UID_NOBODY, h->uid, &mount_fd);
 
        if (mount_fd >= 0) {
                /* If we have established a new mount, then we can use that as new root fd to our home directory. */
                safe_close(setup->root_fd);
 
                setup->root_fd = fd_reopen(mount_fd, O_RDONLY|O_CLOEXEC|O_DIRECTORY);
                if (setup->root_fd < 0)
                        return log_error_errno(setup->root_fd, "Unable to convert mount fd into proper directory fd: %m");
 
                mount_fd = safe_close(mount_fd);
        }
 
        r = home_populate(h, setup->root_fd);
        if (r < 0)
                return r;
 
        r = home_sync_and_statfs(setup->root_fd, &sfs);
        if (r < 0)
                return r;
 
        r = user_record_clone(h, USER_RECORD_LOAD_MASK_SECRET|USER_RECORD_LOG|USER_RECORD_PERMISSIVE, &new_home);
        if (r < 0)
                return log_error_errno(r, "Failed to clone record: %m");
 
        r = user_record_add_binding(
                        new_home,
                        USER_LUKS,
                        disk_uuid_path ?: ip,
                        partition_uuid,
                        luks_uuid,
                        fs_uuid,
                        sym_crypt_get_cipher(setup->crypt_device),
                        sym_crypt_get_cipher_mode(setup->crypt_device),
                        luks_volume_key_size_convert(setup->crypt_device),
                        fstype,
                        NULL,
                        h->uid,
                        (gid_t) h->uid);
        if (r < 0)
                return log_error_errno(r, "Failed to add binding to record: %m");
 
        if (user_record_luks_offline_discard(h)) {
                r = run_fitrim(setup->root_fd);
                if (r < 0)
                        return r;
        }
 
        setup->root_fd = safe_close(setup->root_fd);
 
        r = home_setup_undo_mount(setup, LOG_ERR);
        if (r < 0)
                return r;
 
        r = home_setup_undo_dm(setup, LOG_ERR);
        if (r < 0)
                return r;
 
        setup->loop = loop_device_unref(setup->loop);
 
        if (!user_record_luks_offline_discard(h)) {
                r = run_fallocate(setup->image_fd, NULL /* refresh stat() data */);
                if (r < 0)
                        return r;
        }
 
        /* Sync everything to disk before we move things into place under the final name. */
        if (fsync(setup->image_fd) < 0)
                return log_error_errno(errno, "Failed to synchronize image to disk: %m");
 
        if (disk_uuid_path)
                /* Reread partition table if this is a block device */
                (void) reread_partition_table_fd(setup->image_fd, /* flags= */ 0);
        else {
                assert(setup->temporary_image_path);
 
                if (rename(setup->temporary_image_path, ip) < 0)
                        return log_error_errno(errno, "Failed to rename image file: %m");
 
                setup->temporary_image_path = mfree(setup->temporary_image_path);
 
                /* If we operate on a file, sync the containing directory too. */
                r = fsync_directory_of_file(setup->image_fd);
                if (r < 0)
                        return log_error_errno(r, "Failed to synchronize directory of image file to disk: %m");
 
                log_info("Moved image file into place.");
        }
 
        /* Let's close the image fd now. If we are operating on a real block device this will release the BSD
         * lock that ensures udev doesn't interfere with what we are doing */
        setup->image_fd = safe_close(setup->image_fd);
 
        if (disk_uuid_path)
                (void) wait_for_devlink(disk_uuid_path);
 
        log_info("Creation completed.");
 
        print_size_summary(host_size, encrypted_size, &sfs);
 
        log_debug("GPT + LUKS2 overhead is %" PRIu64 " (expected %" PRIu64 ")", host_size - encrypted_size, GPT_LUKS2_OVERHEAD);
 
        *ret_home = TAKE_PTR(new_home);
        return 0;
}
 
int home_get_state_luks(UserRecord *h, HomeSetup *setup) {
        int r;
 
        assert(h);
        assert(setup);
 
        r = make_dm_names(h, setup);
        if (r < 0)
                return r;
 
        r = access(setup->dm_node, F_OK);
        if (r < 0 && errno != ENOENT)
                return log_error_errno(errno, "Failed to determine whether %s exists: %m", setup->dm_node);
 
        return r >= 0;
}
 
enum {
        CAN_RESIZE_ONLINE,
        CAN_RESIZE_OFFLINE,
};
 
static int can_resize_fs(int fd, uint64_t old_size, uint64_t new_size) {
        struct statfs sfs;
 
        assert(fd >= 0);
 
        /* Filter out bogus requests early */
        if (old_size == 0 || old_size == UINT64_MAX ||
            new_size == 0 || new_size == UINT64_MAX)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid resize parameters.");
 
        if ((old_size & 511) != 0 || (new_size & 511) != 0)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Resize parameters not multiple of 512.");
 
        if (fstatfs(fd, &sfs) < 0)
                return log_error_errno(errno, "Failed to fstatfs() file system: %m");
 
        if (is_fs_type(&sfs, BTRFS_SUPER_MAGIC)) {
 
                if (new_size < BTRFS_MINIMAL_SIZE)
                        return log_error_errno(SYNTHETIC_ERRNO(ERANGE), "New file system size too small for btrfs (needs to be 256M at least.");
 
                /* btrfs can grow and shrink online */
 
        } else if (is_fs_type(&sfs, XFS_SUPER_MAGIC)) {
 
                if (new_size < XFS_MINIMAL_SIZE)
                        return log_error_errno(SYNTHETIC_ERRNO(ERANGE), "New file system size too small for xfs (needs to be 14M at least).");
 
                /* XFS can grow, but not shrink */
                if (new_size < old_size)
                        return log_error_errno(SYNTHETIC_ERRNO(EMSGSIZE), "Shrinking this type of file system is not supported.");
 
        } else if (is_fs_type(&sfs, EXT4_SUPER_MAGIC)) {
 
                if (new_size < EXT4_MINIMAL_SIZE)
                        return log_error_errno(SYNTHETIC_ERRNO(ERANGE), "New file system size too small for ext4 (needs to be 1M at least).");
 
                /* ext4 can grow online, and shrink offline */
                if (new_size < old_size)
                        return CAN_RESIZE_OFFLINE;
 
        } else
                return log_error_errno(SYNTHETIC_ERRNO(ESOCKTNOSUPPORT), "Resizing this type of file system is not supported.");
 
        return CAN_RESIZE_ONLINE;
}
 
static int ext4_offline_resize_fs(
                HomeSetup *setup,
                uint64_t new_size,
                bool discard,
                unsigned long flags,
                const char *extra_mount_options) {
 
        _cleanup_free_ char *size_str = NULL;
        bool re_open = false, re_mount = false;
        _cleanup_(pidref_done) PidRef fsck_pidref = PIDREF_NULL;
        int r, exit_status;
 
        assert(setup);
        assert(setup->dm_node);
 
        /* First, unmount the file system */
        if (setup->root_fd >= 0) {
                setup->root_fd = safe_close(setup->root_fd);
                re_open = true;
        }
 
        if (setup->undo_mount) {
                r = home_setup_undo_mount(setup, LOG_ERR);
                if (r < 0)
                        return r;
 
                re_mount = true;
        }
 
        log_info("Temporary unmounting of file system completed.");
 
        /* resize2fs requires that the file system is force checked first, do so. */
        r = pidref_safe_fork(
                        "(e2fsck)",
                        FORK_RESET_SIGNALS|FORK_RLIMIT_NOFILE_SAFE|FORK_DEATHSIG_SIGTERM|FORK_LOG|FORK_STDOUT_TO_STDERR|FORK_CLOSE_ALL_FDS,
                        &fsck_pidref);
        if (r < 0)
                return r;
        if (r == 0) {
                /* Child */
                execlp("e2fsck", "e2fsck", "-fp", setup->dm_node, NULL);
                log_open();
                log_error_errno(errno, "Failed to execute e2fsck: %m");
                _exit(EXIT_FAILURE);
        }
 
        exit_status = pidref_wait_for_terminate_and_check("e2fsck", &fsck_pidref, WAIT_LOG_ABNORMAL);
        if (exit_status < 0)
                return exit_status;
        if ((exit_status & ~FSCK_ERROR_CORRECTED) != 0) {
                log_warning("e2fsck failed with exit status %i.", exit_status);
 
                if ((exit_status & (FSCK_SYSTEM_SHOULD_REBOOT|FSCK_ERRORS_LEFT_UNCORRECTED)) != 0)
                        return log_error_errno(SYNTHETIC_ERRNO(EIO), "File system is corrupted, refusing.");
 
                log_warning("Ignoring fsck error.");
        }
 
        log_info("Forced file system check completed.");
 
        /* We use 512 sectors here, because resize2fs doesn't do byte sizes */
        if (asprintf(&size_str, "%" PRIu64 "s", new_size / 512) < 0)
                return log_oom();
 
        /* Resize the thing */
        r = pidref_safe_fork(
                        "(e2resize)",
                        FORK_RESET_SIGNALS|FORK_RLIMIT_NOFILE_SAFE|FORK_DEATHSIG_SIGTERM|FORK_LOG|FORK_WAIT|FORK_STDOUT_TO_STDERR|FORK_CLOSE_ALL_FDS,
                        /* ret= */ NULL);
        if (r < 0)
                return r;
        if (r == 0) {
                /* Child */
                execlp("resize2fs", "resize2fs", setup->dm_node, size_str, NULL);
                log_open();
                log_error_errno(errno, "Failed to execute resize2fs: %m");
                _exit(EXIT_FAILURE);
        }
 
        log_info("Offline file system resize completed.");
 
        /* Re-establish mounts and reopen the directory */
        if (re_mount) {
                r = home_mount_node(setup->dm_node, "ext4", discard, flags, extra_mount_options);
                if (r < 0)
                        return r;
 
                setup->undo_mount = true;
        }
 
        if (re_open) {
                setup->root_fd = open(HOME_RUNTIME_WORK_DIR, O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOFOLLOW);
                if (setup->root_fd < 0)
                        return log_error_errno(errno, "Failed to reopen file system: %m");
        }
 
        log_info("File system mounted again.");
 
        return 0;
}
 
static int prepare_resize_partition(
                int fd,
                uint64_t partition_offset,
                uint64_t old_partition_size,
                sd_id128_t *ret_disk_uuid,
                struct fdisk_table **ret_table,
                struct fdisk_partition **ret_partition) {
 
        _cleanup_(fdisk_unref_contextp) struct fdisk_context *c = NULL;
        _cleanup_(fdisk_unref_tablep) struct fdisk_table *t = NULL;
        struct fdisk_partition *found = NULL;
        sd_id128_t disk_uuid;
        size_t n_partitions;
        int r;
 
        assert(fd >= 0);
        assert(ret_disk_uuid);
        assert(ret_table);
        assert(ret_partition);
 
        assert((partition_offset & 511) == 0);
        assert((old_partition_size & 511) == 0);
        assert(UINT64_MAX - old_partition_size >= partition_offset);
 
        if (partition_offset == 0) {
                /* If the offset is at the beginning we assume no partition table, let's exit early. */
                log_debug("Not rewriting partition table, operating on naked device.");
                *ret_disk_uuid = SD_ID128_NULL;
                *ret_table = NULL;
                *ret_partition = NULL;
                return 0;
        }
 
        r = fdisk_new_context_at(fd, /* path= */ NULL, /* read_only= */ false, UINT32_MAX, &c);
        if (r < 0)
                return log_error_errno(r, "Failed to open device: %m");
 
        if (!sym_fdisk_is_labeltype(c, FDISK_DISKLABEL_GPT))
                return log_error_errno(SYNTHETIC_ERRNO(ENOMEDIUM), "Disk has no GPT partition table.");
 
        r = fdisk_get_disklabel_id_as_id128(c, &disk_uuid);
        if (r < 0)
                return log_error_errno(r, "Failed to acquire disk UUID: %m");
 
        r = sym_fdisk_get_partitions(c, &t);
        if (r < 0)
                return log_error_errno(r, "Failed to acquire partition table: %m");
 
        n_partitions = sym_fdisk_table_get_nents(t);
        for (size_t i = 0; i < n_partitions; i++)  {
                struct fdisk_partition *p;
                uint64_t fdisk_sector_size;
 
                p = sym_fdisk_table_get_partition(t, i);
                if (!p)
                        return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to read partition metadata.");
 
                if (sym_fdisk_partition_is_used(p) <= 0)
                        continue;
                if (sym_fdisk_partition_has_start(p) <= 0 ||
                        sym_fdisk_partition_has_size(p) <= 0 ||
                        sym_fdisk_partition_has_end(p) <= 0)
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Found partition without a size.");
 
                fdisk_sector_size = sym_fdisk_get_sector_size(c);
                assert(fdisk_sector_size > 0);
                if (sym_fdisk_partition_get_start(p) == partition_offset / fdisk_sector_size &&
                    sym_fdisk_partition_get_size(p) == old_partition_size / fdisk_sector_size) {
 
                        if (found)
                                return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ), "Partition found twice, refusing.");
 
                        found = p;
                } else if (sym_fdisk_partition_get_end(p) > partition_offset / fdisk_sector_size)
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Can't extend, not last partition in image.");
        }
 
        if (!found)
                return log_error_errno(SYNTHETIC_ERRNO(ENOPKG), "Failed to find matching partition to resize.");
 
        *ret_disk_uuid = disk_uuid;
        *ret_table = TAKE_PTR(t);
        *ret_partition = found;
 
        return 1;
}
 
static int get_maximum_partition_size(
                int fd,
                struct fdisk_partition *p,
                uint64_t *ret_maximum_partition_size) {
 
        _cleanup_(fdisk_unref_contextp) struct fdisk_context *c = NULL;
        uint64_t start_lba, start, last_lba, end, fdisk_sector_size;
        int r;
 
        assert(fd >= 0);
        assert(p);
        assert(ret_maximum_partition_size);
 
        r = fdisk_new_context_at(fd, /* path= */ NULL, /* read_only= */ true, /* sector_size= */ UINT32_MAX, &c);
        if (r < 0)
                return log_error_errno(r, "Failed to create fdisk context: %m");
 
        /* Get the probed sector size by fdisk */
        fdisk_sector_size = sym_fdisk_get_sector_size(c);
        start_lba = sym_fdisk_partition_get_start(p);
        assert(start_lba <= UINT64_MAX / fdisk_sector_size);
        start = start_lba * fdisk_sector_size;
 
        last_lba = sym_fdisk_get_last_lba(c); /* One sector before boundary where usable space ends */
        assert(last_lba < UINT64_MAX / fdisk_sector_size);
        end = DISK_SIZE_ROUND_DOWN((last_lba + 1) * fdisk_sector_size);
 
        if (start > end)
                return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Last LBA is before partition start.");
 
        *ret_maximum_partition_size = DISK_SIZE_ROUND_DOWN(end - start);
 
        return 1;
}
 
static int apply_resize_partition(
                int fd,
                sd_id128_t disk_uuids,
                struct fdisk_table *t,
                struct fdisk_partition *p,
                size_t new_partition_size) {
 
        _cleanup_(fdisk_unref_contextp) struct fdisk_context *c = NULL;
        uint32_t ssz;
        int r;
 
        assert(fd >= 0);
        assert(!t == !p);
 
        if (!t) /* no partition table to apply, exit early */
                return 0;
 
        assert(p);
 
        r = probe_sector_size(fd, &ssz);
        if (r < 0)
                return log_error_errno(r, "Failed to determine current sector size: %m");
 
        r = fdisk_new_context_at(fd, /* path= */ NULL, /* read_only= */ false, ssz, &c);
        if (r < 0)
                return log_error_errno(r, "Failed to open device: %m");
 
        /* Before writing our partition patch the final size in */
        r = sym_fdisk_partition_size_explicit(p, 1);
        if (r < 0)
                return log_error_errno(r, "Failed to enable explicit partition size: %m");
 
        r = sym_fdisk_partition_set_size(p, new_partition_size / ssz);
        if (r < 0)
                return log_error_errno(r, "Failed to change partition size: %m");
 
        r = sym_fdisk_create_disklabel(c, "gpt");
        if (r < 0)
                return log_error_errno(r, "Failed to create GPT disk label: %m");
 
        r = sym_fdisk_apply_table(c, t);
        if (r < 0)
                return log_error_errno(r, "Failed to apply partition table: %m");
 
        r = fdisk_set_disklabel_id_as_id128(c, disk_uuids);
        if (r < 0)
                return log_error_errno(r, "Failed to change disklabel ID: %m");
 
        r = sym_fdisk_write_disklabel(c);
        if (r < 0)
                return log_error_errno(r, "Failed to write disk label: %m");
 
        return 1;
}
 
/* Always keep at least 16M free, so that we can safely log in and update the user record while doing so */
#define HOME_MIN_FREE (16U*1024U*1024U)
 
static int get_smallest_fs_size(int fd, uint64_t *ret) {
        uint64_t minsz, needed;
        struct statfs sfs;
 
        assert(fd >= 0);
        assert(ret);
 
        /* Determines the minimal disk size we might be able to shrink the file system referenced by the fd to. */
 
        if (syncfs(fd) < 0) /* let's sync before we query the size, so that the values returned are accurate */
                return log_error_errno(errno, "Failed to synchronize home file system: %m");
 
        if (fstatfs(fd, &sfs) < 0)
                return log_error_errno(errno, "Failed to statfs() home file system: %m");
 
        /* Let's determine the minimal file system size of the used fstype */
        minsz = minimal_size_by_fs_magic(sfs.f_type);
        if (minsz == UINT64_MAX)
                return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Don't know minimum file system size of file system type '%s' of home directory.", fs_type_to_string(sfs.f_type));
 
        if (minsz < USER_DISK_SIZE_MIN)
                minsz = USER_DISK_SIZE_MIN;
 
        if (sfs.f_bfree > sfs.f_blocks)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Detected amount of free blocks is greater than the total amount of file system blocks. Refusing.");
 
        /* Calculate how much disk space is currently in use. */
        needed = sfs.f_blocks - sfs.f_bfree;
        if (needed > UINT64_MAX / sfs.f_bsize)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "File system size out of range.");
 
        needed *= sfs.f_bsize;
 
        /* Add some safety margin of free space we'll always keep */
        if (needed > UINT64_MAX - HOME_MIN_FREE) /* Check for overflow */
                needed = UINT64_MAX;
        else
                needed += HOME_MIN_FREE;
 
        *ret = DISK_SIZE_ROUND_UP(MAX(needed, minsz));
        return 0;
}
 
static int get_largest_image_size(int fd, const struct stat *st, uint64_t *ret) {
        uint64_t used, avail, sum;