HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/home/homed-manager.c

86,158 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 6dc0d82d7dca55da6726e4e1cd82945faa02caf0

Lines 1001–2000 of 2,238

        if (!m->scan_slash_home)
                return 0;
 
        d = opendir(get_home_root());
        if (!d)
                return log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_ERR, errno,
                                      "Failed to open %s: %m", get_home_root());
 
        FOREACH_DIRENT(de, d, return log_error_errno(errno, "Failed to read %s directory: %m", get_home_root()))
                (void) manager_assess_image(m, dirfd(d), get_home_root(), de->d_name);
 
        return 0;
}
 
static int manager_connect_bus(Manager *m) {
        _cleanup_free_ char *b = NULL;
        const char *suffix, *busname;
        int r;
 
        assert(m);
        assert(!m->bus);
 
        r = sd_bus_default_system(&m->bus);
        if (r < 0)
                return log_error_errno(r, "Failed to connect to system bus: %m");
 
        r = bus_add_implementation(m->bus, &manager_object, m);
        if (r < 0)
                return r;
 
        r = bus_log_control_api_register(m->bus);
        if (r < 0)
                return r;
 
        suffix = getenv("SYSTEMD_HOME_DEBUG_SUFFIX");
        if (suffix) {
                b = strjoin("org.freedesktop.home1.", suffix);
                if (!b)
                        return log_oom();
                busname = b;
        } else
                busname = "org.freedesktop.home1";
 
        r = sd_bus_request_name_async(m->bus, NULL, busname, 0, NULL, NULL);
        if (r < 0)
                return log_error_errno(r, "Failed to request name: %m");
 
        r = sd_bus_attach_event(m->bus, m->event, SD_EVENT_PRIORITY_NORMAL);
        if (r < 0)
                return log_error_errno(r, "Failed to attach bus to event loop: %m");
 
        (void) sd_bus_set_exit_on_disconnect(m->bus, true);
 
        return 0;
}
 
static int manager_bind_varlink(Manager *m) {
        _cleanup_free_ char *p = NULL;
        const char *suffix, *socket_path;
        int r;
 
        assert(m);
        assert(!m->varlink_server);
 
        r = varlink_server_new(
                        &m->varlink_server,
                        SD_VARLINK_SERVER_ACCOUNT_UID|SD_VARLINK_SERVER_INHERIT_USERDATA|SD_VARLINK_SERVER_INPUT_SENSITIVE,
                        m);
        if (r < 0)
                return log_error_errno(r, "Failed to allocate varlink server: %m");
 
        r = sd_varlink_server_add_interface_many(
                        m->varlink_server,
                        &vl_interface_io_systemd_UserDatabase,
                        &vl_interface_io_systemd_service);
        if (r < 0)
                return log_error_errno(r, "Failed to add UserDatabase interface to varlink server: %m");
 
        r = sd_varlink_server_bind_method_many(
                        m->varlink_server,
                        "io.systemd.UserDatabase.GetUserRecord",  vl_method_get_user_record,
                        "io.systemd.UserDatabase.GetGroupRecord", vl_method_get_group_record,
                        "io.systemd.UserDatabase.GetMemberships", vl_method_get_memberships,
                        "io.systemd.service.Ping",                varlink_method_ping,
                        "io.systemd.service.SetLogLevel",         varlink_method_set_log_level,
                        "io.systemd.service.GetLogLevel",         varlink_method_get_log_level,
                        "io.systemd.service.GetEnvironment",      varlink_method_get_environment);
        if (r < 0)
                return log_error_errno(r, "Failed to register varlink methods: %m");
 
        /* To make things easier to debug, when working from a homed managed home directory, let's optionally
         * use a different varlink socket name */
        suffix = getenv("SYSTEMD_HOME_DEBUG_SUFFIX");
        if (suffix) {
                p = strjoin("/run/systemd/userdb/io.systemd.Home.", suffix);
                if (!p)
                        return log_oom();
                socket_path = p;
        } else
                socket_path = "/run/systemd/userdb/io.systemd.Home";
 
        r = sd_varlink_server_listen_address(m->varlink_server, socket_path, 0666 | SD_VARLINK_SERVER_MODE_MKDIR_0755);
        if (r < 0)
                return log_error_errno(r, "Failed to bind to varlink socket '%s': %m", socket_path);
 
        /* Reduce the noise routed to us: advertise that only look-ups for non-system users in the 16bit
         * range are routed to us (excluding 'nobody', i.e. 0xfffe) */
        char text[DECIMAL_STR_MAX(uid_t) + 1 + DECIMAL_STR_MAX(gid_t) + 1];
        xsprintf(text, UID_FMT "-" UID_FMT, (uid_t) (SYSTEM_UID_MAX + 1), UID_NOBODY - 1);
        FOREACH_STRING(xattr, "user.userdb.uid", "user.userdb.gid")
                (void) xsetxattr(AT_FDCWD, socket_path, /* at_flags= */ 0, xattr, text);
 
        r = sd_varlink_server_attach_event(m->varlink_server, m->event, SD_EVENT_PRIORITY_NORMAL);
        if (r < 0)
                return log_error_errno(r, "Failed to attach varlink connection to event loop: %m");
 
        assert(!m->userdb_service);
        r = path_extract_filename(socket_path, &m->userdb_service);
        if (r < 0)
                return log_error_errno(r, "Failed to extract filename from socket path '%s': %m", socket_path);
 
        /* Avoid recursion */
        if (setenv("SYSTEMD_BYPASS_USERDB", m->userdb_service, 1) < 0)
                return log_error_errno(errno, "Failed to set $SYSTEMD_BYPASS_USERDB: %m");
 
        return 0;
}
 
static int on_notify_socket(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
        Manager *m = ASSERT_PTR(userdata);
        int r;
 
        assert(s);
 
        _cleanup_(fdset_free_asyncp) FDSet *passed_fds = NULL;
        _cleanup_(pidref_done) PidRef sender = PIDREF_NULL;
        _cleanup_strv_free_ char **l = NULL;
        r = notify_recv_with_fds_strv(fd, &l, /* ret_ucred= */ NULL, &sender, &passed_fds);
        if (r == -EAGAIN)
                return 0;
        if (r < 0)
                return r;
 
        if (fdset_size(passed_fds) > 1) {
                log_warning("Received notify datagram with multiple fds, ignoring.");
                return 0;
        }
 
        Home *h = hashmap_get(m->homes_by_worker_pid, &sender);
        if (!h) {
                log_warning("Received notify datagram of unknown process, ignoring.");
                return 0;
        }
 
        home_process_notify(h, l, fdset_steal_first(passed_fds));
        return 0;
}
 
static int manager_listen_notify(Manager *m) {
        int r;
 
        assert(m);
        assert(!m->notify_socket_path);
 
        r = notify_socket_prepare_full(
                        m->event,
                        SD_EVENT_PRIORITY_NORMAL - 5, /* Make sure we process sd_notify() before child exit for
                                                       * any worker, so that we always know the error number
                                                       * of a client before it exits. */
                        on_notify_socket,
                        m,
                        /* accept_fds= */ true,
                        &m->notify_socket_path,
                        /* ret_event_source= */ NULL);
        if (r < 0)
                return log_error_errno(r, "Failed to prepare notify socket: %m");
 
        return 0;
}
 
static int manager_add_device(Manager *m, sd_device *d) {
        _cleanup_free_ char *user_name = NULL, *realm = NULL, *node = NULL;
        const char *tabletype, *parttype, *partname, *partuuid, *sysfs;
        sd_id128_t id;
        int r;
 
        assert(m);
        assert(d);
 
        r = sd_device_get_syspath(d, &sysfs);
        if (r < 0)
                return log_error_errno(r, "Failed to acquire sysfs path of device: %m");
 
        r = sd_device_get_property_value(d, "ID_PART_TABLE_TYPE", &tabletype);
        if (r == -ENOENT)
                return 0;
        if (r < 0)
                return log_error_errno(r, "Failed to acquire ID_PART_TABLE_TYPE device property, ignoring: %m");
 
        if (!streq(tabletype, "gpt")) {
                log_debug("Found partition (%s) on non-GPT table, ignoring.", sysfs);
                return 0;
        }
 
        r = sd_device_get_property_value(d, "ID_PART_ENTRY_TYPE", &parttype);
        if (r == -ENOENT)
                return 0;
        if (r < 0)
                return log_error_errno(r, "Failed to acquire ID_PART_ENTRY_TYPE device property, ignoring: %m");
        if (sd_id128_string_equal(parttype, SD_GPT_USER_HOME) <= 0) {
                log_debug("Found partition (%s) we don't care about, ignoring.", sysfs);
                return 0;
        }
 
        r = sd_device_get_property_value(d, "ID_PART_ENTRY_NAME", &partname);
        if (r < 0)
                return log_warning_errno(r, "Failed to acquire ID_PART_ENTRY_NAME device property, ignoring: %m");
 
        r = split_user_name_realm(partname, &user_name, &realm);
        if (r == -EINVAL)
                return log_warning_errno(r, "Found partition with correct partition type but a non-parsable partition name '%s', ignoring.", partname);
        if (r < 0)
                return log_error_errno(r, "Failed to validate partition name '%s': %m", partname);
 
        r = sd_device_get_property_value(d, "ID_FS_UUID", &partuuid);
        if (r < 0)
                return log_warning_errno(r, "Failed to acquire ID_FS_UUID device property, ignoring: %m");
 
        r = sd_id128_from_string(partuuid, &id);
        if (r < 0)
                return log_warning_errno(r, "Failed to parse ID_FS_UUID field '%s', ignoring: %m", partuuid);
 
        if (asprintf(&node, "/dev/disk/by-uuid/" SD_ID128_UUID_FORMAT_STR, SD_ID128_FORMAT_VAL(id)) < 0)
                return log_oom();
 
        return manager_add_home_by_image(m, user_name, realm, node, sysfs, USER_LUKS, UID_INVALID);
}
 
static int manager_on_device(sd_device_monitor *monitor, sd_device *d, void *userdata) {
        Manager *m = ASSERT_PTR(userdata);
        int r;
 
        assert(d);
 
        if (device_for_action(d, SD_DEVICE_REMOVE)) {
                const char *sysfs;
                Home *h;
 
                r = sd_device_get_syspath(d, &sysfs);
                if (r < 0) {
                        log_warning_errno(r, "Failed to acquire sysfs path from device: %m");
                        return 0;
                }
 
                log_info("block device %s has been removed.", sysfs);
 
                /* Let's see if we previously synthesized a home record from this device, if so, let's just
                 * revalidate that. Otherwise let's revalidate them all, but asynchronously. */
                h = hashmap_get(m->homes_by_sysfs, sysfs);
                if (h)
                        manager_revalidate_image(m, h);
                else
                        manager_enqueue_gc(m, NULL);
        } else
                (void) manager_add_device(m, d);
 
        (void) bus_manager_emit_auto_login_changed(m);
        return 0;
}
 
static int manager_watch_devices(Manager *m) {
        int r;
 
        assert(m);
        assert(!m->device_monitor);
 
        r = sd_device_monitor_new(&m->device_monitor);
        if (r < 0)
                return log_error_errno(r, "Failed to allocate device monitor: %m");
 
        r = sd_device_monitor_filter_add_match_subsystem_devtype(m->device_monitor, "block", NULL);
        if (r < 0)
                return log_error_errno(r, "Failed to configure device monitor match: %m");
 
        r = sd_device_monitor_attach_event(m->device_monitor, m->event);
        if (r < 0)
                return log_error_errno(r, "Failed to attach device monitor to event loop: %m");
 
        r = sd_device_monitor_start(m->device_monitor, manager_on_device, m);
        if (r < 0)
                return log_error_errno(r, "Failed to start device monitor: %m");
 
        return 0;
}
 
static int manager_enumerate_devices(Manager *m) {
        _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
        int r;
 
        assert(m);
 
        r = sd_device_enumerator_new(&e);
        if (r < 0)
                return r;
 
        r = sd_device_enumerator_add_match_subsystem(e, "block", true);
        if (r < 0)
                return r;
 
        FOREACH_DEVICE(e, d) {
                if (device_is_processed(d) <= 0)
                        continue;
                (void) manager_add_device(m, d);
        }
 
        return 0;
}
 
static int manager_load_key_pair(Manager *m) {
        _cleanup_fclose_ FILE *f = NULL;
        struct stat st;
        int r;
 
        assert(m);
 
        if (m->private_key) {
                sym_EVP_PKEY_free(m->private_key);
                m->private_key = NULL;
        }
 
        r = search_and_fopen_nulstr("local.private", "re", NULL, KEY_PATHS_NULSTR, &f, NULL);
        if (r == -ENOENT)
                return 0;
        if (r < 0)
                return log_error_errno(r, "Failed to read private key file: %m");
 
        if (fstat(fileno(f), &st) < 0)
                return log_error_errno(errno, "Failed to stat private key file: %m");
 
        r = stat_verify_regular(&st);
        if (r < 0)
                return log_error_errno(r, "Private key file is not regular: %m");
 
        if (st.st_uid != 0 || (st.st_mode & 0077) != 0)
                return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Private key file is readable by more than the root user");
 
        m->private_key = sym_PEM_read_PrivateKey(f, NULL, NULL, NULL);
        if (!m->private_key)
                return log_openssl_errors(LOG_ERR, "Failed to load private key pair");
 
        log_info("Successfully loaded private key pair.");
 
        return 1;
}
 
static int manager_generate_key_pair(Manager *m) {
        _cleanup_(EVP_PKEY_CTX_freep) EVP_PKEY_CTX *ctx = NULL;
        _cleanup_(unlink_and_freep) char *temp_public = NULL, *temp_private = NULL;
        _cleanup_fclose_ FILE *fpublic = NULL, *fprivate = NULL;
        int r;
 
        if (m->private_key) {
                sym_EVP_PKEY_free(m->private_key);
                m->private_key = NULL;
        }
 
        ctx = sym_EVP_PKEY_CTX_new_id(EVP_PKEY_ED25519, NULL);
        if (!ctx)
                return log_openssl_errors(LOG_ERR, "Failed to allocate Ed25519 key generation context.");
 
        if (sym_EVP_PKEY_keygen_init(ctx) <= 0)
                return log_openssl_errors(LOG_ERR, "Failed to initialize Ed25519 key generation context.");
 
        log_info("Generating key pair for signing local user identity records.");
 
        if (sym_EVP_PKEY_keygen(ctx, &m->private_key) <= 0)
                return log_openssl_errors(LOG_ERR, "Failed to generate Ed25519 key pair");
 
        log_info("Successfully created Ed25519 key pair.");
 
        (void) mkdir_p("/var/lib/systemd/home", 0755);
 
        /* Write out public key (note that we only do that as a help to the user, we don't make use of this ever */
        r = fopen_temporary("/var/lib/systemd/home/local.public", &fpublic, &temp_public);
        if (r < 0)
                return log_error_errno(r, "Failed to open key file for writing: %m");
 
        if (sym_PEM_write_PUBKEY(fpublic, m->private_key) <= 0)
                return log_openssl_errors(LOG_ERR, "Failed to write public key.");
 
        (void) fchmod(fileno(fpublic), 0444); /* Make public key world readable */
 
        r = fflush_sync_and_check(fpublic);
        if (r < 0)
                return log_error_errno(r, "Failed to write private key: %m");
 
        fpublic = safe_fclose(fpublic);
 
        /* Write out the private key (this actually writes out both private and public, OpenSSL is confusing) */
        r = fopen_temporary("/var/lib/systemd/home/local.private", &fprivate, &temp_private);
        if (r < 0)
                return log_error_errno(r, "Failed to open key file for writing: %m");
 
        if (sym_PEM_write_PrivateKey(fprivate, m->private_key, NULL, NULL, 0, NULL, NULL) <= 0)
                return log_openssl_errors(LOG_ERR, "Failed to write private key pair.");
 
        (void) fchmod(fileno(fprivate), 0400); /* Make private key root readable */
 
        r = fflush_sync_and_check(fprivate);
        if (r < 0)
                return log_error_errno(r, "Failed to write private key: %m");
 
        fprivate = safe_fclose(fprivate);
 
        /* Both are written now, move them into place */
 
        if (rename(temp_public, "/var/lib/systemd/home/local.public") < 0)
                return log_error_errno(errno, "Failed to move public key file into place: %m");
        temp_public = mfree(temp_public);
 
        r = RET_NERRNO(rename(temp_private, "/var/lib/systemd/home/local.private"));
        if (r < 0) {
                (void) unlink("/var/lib/systemd/home/local.public"); /* try to remove the file we already created */
                return log_error_errno(r, "Failed to move private key file into place: %m");
        }
        temp_private = mfree(temp_private);
 
        r = fsync_path_at(AT_FDCWD, "/var/lib/systemd/home/");
        if (r < 0)
                log_warning_errno(r, "Failed to sync /var/lib/systemd/home/, ignoring: %m");
 
        return 1;
}
 
int manager_acquire_key_pair(Manager *m) {
        int r;
 
        assert(m);
 
        /* Already there? */
        if (m->private_key)
                return 1;
 
        /* First try to load key off disk */
        r = manager_load_key_pair(m);
        if (r != 0)
                return r;
 
        /* Didn't work, generate a new one */
        return manager_generate_key_pair(m);
}
 
int manager_sign_user_record(Manager *m, UserRecord *u, UserRecord **ret, sd_bus_error *error) {
        int r;
 
        assert(m);
        assert(u);
        assert(ret);
 
        r = manager_acquire_key_pair(m);
        if (r < 0)
                return r;
        if (r == 0)
                return sd_bus_error_set(error, BUS_ERROR_NO_PRIVATE_KEY, "Can't sign without local key.");
 
        return user_record_sign(u, m->private_key, ret);
}
 
/* dlopen_libcrypto() must have been called before populating this hashmap. */
DEFINE_HASH_OPS_FULL(public_key_hash_ops, char, string_hash_func, string_compare_func, free, EVP_PKEY, sym_EVP_PKEY_free);
 
static int manager_load_public_key_one(Manager *m, const char *path) {
        _cleanup_(EVP_PKEY_freep) EVP_PKEY *pkey = NULL;
        _cleanup_fclose_ FILE *f = NULL;
        _cleanup_free_ char *fn = NULL;
        struct stat st;
        int r;
 
        assert(m);
 
        r = path_extract_filename(path, &fn);
        if (r < 0)
                return log_error_errno(r, "Failed to extract filename of path '%s': %m", path);
 
        if (streq(fn, "local.public")) /* we already loaded the private key, which includes the public one */
                return 0;
 
        f = fopen(path, "re");
        if (!f) {
                if (errno == ENOENT)
                        return 0;
 
                return log_error_errno(errno, "Failed to open public key %s: %m", path);
        }
 
        if (fstat(fileno(f), &st) < 0)
                return log_error_errno(errno, "Failed to stat public key %s: %m", path);
 
        r = stat_verify_regular(&st);
        if (r < 0)
                return log_error_errno(r, "Public key file %s is not a regular file: %m", path);
 
        if (st.st_uid != 0 || (st.st_mode & 0022) != 0)
                return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Public key file %s is writable by more than the root user, refusing.", path);
 
        pkey = sym_PEM_read_PUBKEY(f, &pkey, NULL, NULL);
        if (!pkey)
                return log_openssl_errors(LOG_ERR, "Failed to parse public key file %s.", path);
 
        r = hashmap_ensure_put(&m->public_keys, &public_key_hash_ops, fn, pkey);
        if (r < 0)
                return log_error_errno(r, "Failed to add public key to set: %m");
 
        TAKE_PTR(fn);
        TAKE_PTR(pkey);
 
        return 0;
}
 
static int manager_load_public_keys(Manager *m) {
        _cleanup_strv_free_ char **files = NULL;
        int r;
 
        assert(m);
 
        m->public_keys = hashmap_free(m->public_keys);
 
        r = conf_files_list_nulstr(
                        &files,
                        ".public",
                        NULL,
                        CONF_FILES_REGULAR|CONF_FILES_FILTER_MASKED|CONF_FILES_WARN,
                        KEY_PATHS_NULSTR);
        if (r < 0)
                return log_error_errno(r, "Failed to assemble list of public key directories: %m");
 
        STRV_FOREACH(i, files)
                (void) manager_load_public_key_one(m, *i);
 
        return 0;
}
 
int manager_startup(Manager *m) {
        int r;
 
        assert(m);
 
        r = dlopen_libcrypto(LOG_ERR);
        if (r < 0)
                return r;
 
        r = manager_listen_notify(m);
        if (r < 0)
                return r;
 
        r = manager_connect_bus(m);
        if (r < 0)
                return r;
 
        r = manager_bind_varlink(m);
        if (r < 0)
                return r;
 
        r = manager_load_key_pair(m); /* only try to load it, don't generate any */
        if (r < 0)
                return r;
 
        r = manager_load_public_keys(m);
        if (r < 0)
                return r;
 
        manager_watch_home(m);
        (void) manager_watch_devices(m);
 
        (void) manager_enumerate_records(m);
        (void) manager_enumerate_images(m);
        (void) manager_enumerate_devices(m);
 
        /* Let's clean up home directories whose devices got removed while we were not running */
        (void) manager_enqueue_gc(m, NULL);
 
        /* Let's clean up blob directories for home dirs that no longer exist */
        (void) manager_gc_blob(m);
 
        return 0;
}
 
void manager_revalidate_image(Manager *m, Home *h) {
        int r;
 
        assert(m);
        assert(h);
 
        /* Frees an automatically discovered image, if it's synthetic and its image disappeared. Unmounts any
         * image if it's mounted but its image vanished. */
 
        if (h->current_operation || !ordered_set_isempty(h->pending_operations))
                return;
 
        if (h->state == HOME_UNFIXATED) {
                r = user_record_test_image_path(h->record);
                if (r < 0)
                        log_warning_errno(r, "Can't determine if image of %s exists, freeing unfixated user: %m", h->user_name);
                else if (r == USER_TEST_ABSENT)
                        log_info("Image for %s disappeared, freeing unfixated user.", h->user_name);
                else
                        return;
 
                home_free(h);
 
        } else if (h->state < 0) {
 
                r = user_record_test_home_directory(h->record);
                if (r < 0) {
                        log_warning_errno(r, "Unable to determine state of home directory, ignoring: %m");
                        return;
                }
 
                if (r == USER_TEST_MOUNTED) {
                        r = user_record_test_image_path(h->record);
                        if (r < 0) {
                                log_warning_errno(r, "Unable to determine state of image path, ignoring: %m");
                                return;
                        }
 
                        if (r == USER_TEST_ABSENT) {
                                _cleanup_(operation_unrefp) Operation *o = NULL;
 
                                log_notice("Backing image disappeared while home directory %s was mounted, unmounting it forcibly.", h->user_name);
                                /* Wowza, the thing is mounted, but the device is gone? Act on it. */
 
                                r = home_killall(h);
                                if (r < 0)
                                        log_warning_errno(r, "Failed to kill processes of user %s, ignoring: %m", h->user_name);
 
                                /* We enqueue the operation here, after all the home directory might
                                 * currently already run some operation, and we can deactivate it only after
                                 * that's complete. */
                                o = operation_new(OPERATION_DEACTIVATE_FORCE, NULL);
                                if (!o) {
                                        log_oom();
                                        return;
                                }
 
                                r = home_schedule_operation(h, o, NULL);
                                if (r < 0)
                                        log_warning_errno(r, "Failed to enqueue forced home directory %s deactivation, ignoring: %m", h->user_name);
                        }
                }
        }
}
 
int manager_gc_images(Manager *m) {
        Home *h;
 
        assert_se(m);
 
        if (m->gc_focus) {
                /* Focus on a specific home */
 
                h = TAKE_PTR(m->gc_focus);
                manager_revalidate_image(m, h);
        } else {
                /* Gc all */
 
                HASHMAP_FOREACH(h, m->homes_by_uid)
                        manager_revalidate_image(m, h);
        }
 
        return 0;
}
 
static int manager_gc_blob(Manager *m) {
        _cleanup_closedir_ DIR *d = NULL;
        int r;
 
        assert(m);
 
        d = opendir(home_system_blob_dir());
        if (!d) {
                if (errno == ENOENT)
                        return 0;
                return log_error_errno(errno, "Failed to open %s: %m", home_system_blob_dir());
        }
 
        FOREACH_DIRENT(de, d, return log_error_errno(errno, "Failed to read system blob directory: %m")) {
                Home *found = hashmap_get(m->homes_by_name, de->d_name);
                if (!found || !streq(found->user_name, de->d_name)) {
                        r = rm_rf_at(dirfd(d), de->d_name, REMOVE_ROOT|REMOVE_PHYSICAL|REMOVE_SUBVOLUME);
                        if (r < 0)
                                log_warning_errno(r, "Failed to delete blob dir for missing user '%s', ignoring: %m", de->d_name);
                }
        }
 
        return 0;
}
 
static int on_deferred_rescan(sd_event_source *s, void *userdata) {
        Manager *m = ASSERT_PTR(userdata);
 
        m->deferred_rescan_event_source = sd_event_source_disable_unref(m->deferred_rescan_event_source);
 
        manager_enumerate_devices(m);
        manager_enumerate_images(m);
        return 0;
}
 
int manager_enqueue_rescan(Manager *m) {
        int r;
 
        assert(m);
 
        if (m->deferred_rescan_event_source)
                return 0;
 
        if (!m->event)
                return 0;
 
        if (IN_SET(sd_event_get_state(m->event), SD_EVENT_FINISHED, SD_EVENT_EXITING))
                return 0;
 
        r = sd_event_add_defer(m->event, &m->deferred_rescan_event_source, on_deferred_rescan, m);
        if (r < 0)
                return log_error_errno(r, "Failed to allocate rescan event source: %m");
 
        r = sd_event_source_set_priority(m->deferred_rescan_event_source, SD_EVENT_PRIORITY_IDLE+1);
        if (r < 0)
                log_warning_errno(r, "Failed to tweak priority of event source, ignoring: %m");
 
        (void) sd_event_source_set_description(m->deferred_rescan_event_source, "deferred-rescan");
        return 1;
}
 
static int on_deferred_gc(sd_event_source *s, void *userdata) {
        Manager *m = ASSERT_PTR(userdata);
 
        m->deferred_gc_event_source = sd_event_source_disable_unref(m->deferred_gc_event_source);
 
        manager_gc_images(m);
        return 0;
}
 
int manager_enqueue_gc(Manager *m, Home *focus) {
        int r;
 
        assert(m);
 
        /* This enqueues a request to GC dead homes. It may be called with focus=NULL in which case all homes
         * will be scanned, or with the parameter set, in which case only that home is checked. */
 
        if (!m->event)
                return 0;
 
        if (IN_SET(sd_event_get_state(m->event), SD_EVENT_FINISHED, SD_EVENT_EXITING))
                return 0;
 
        /* If a focus home is specified, then remember to focus just on this home. Otherwise invalidate any
         * focus that might be set to look at all homes. */
 
        if (m->deferred_gc_event_source) {
                if (m->gc_focus != focus) /* not the same focus, then look at everything */
                        m->gc_focus = NULL;
 
                return 0;
        } else
                m->gc_focus = focus; /* start focused */
 
        r = sd_event_add_defer(m->event, &m->deferred_gc_event_source, on_deferred_gc, m);
        if (r < 0)
                return log_error_errno(r, "Failed to allocate GC event source: %m");
 
        r = sd_event_source_set_priority(m->deferred_gc_event_source, SD_EVENT_PRIORITY_IDLE);
        if (r < 0)
                log_warning_errno(r, "Failed to tweak priority of event source, ignoring: %m");
 
        (void) sd_event_source_set_description(m->deferred_gc_event_source, "deferred-gc");
        return 1;
}
 
static bool manager_shall_rebalance(Manager *m) {
        Home *h;
 
        assert(m);
 
        if (IN_SET(m->rebalance_state, REBALANCE_PENDING, REBALANCE_SHRINKING, REBALANCE_GROWING))
                return true;
 
        HASHMAP_FOREACH(h, m->homes_by_uid)
                if (home_shall_rebalance(h))
                        return true;
 
        return false;
}
 
static int home_cmp(Home *const*a, Home *const*b) {
        int r;
 
        assert(a);
        assert(*a);
        assert(b);
        assert(*b);
 
        /* Order user records by their weight (and by their name, to make things stable). We put the records
         * with the highest weight last, since we distribute space from the beginning and round down, hence
         * later entries tend to get slightly more than earlier entries. */
 
        r = CMP(user_record_rebalance_weight((*a)->record), user_record_rebalance_weight((*b)->record));
        if (r != 0)
                return r;
 
        return strcmp((*a)->user_name, (*b)->user_name);
}
 
static int manager_rebalance_calculate(Manager *m) {
        uint64_t weight_sum, free_sum, usage_sum = 0, min_free = UINT64_MAX;
        _cleanup_free_ Home **array = NULL;
        bool relevant = false;
        struct statfs sfs;
        int c = 0, r;
        Home *h;
 
        assert(m);
 
        if (statfs(get_home_root(), &sfs) < 0)
                return log_error_errno(errno, "Failed to statfs() /home: %m");
 
        free_sum = (uint64_t) sfs.f_bsize * sfs.f_bavail; /* This much free space is available on the
                                                           * underlying pool directory */
 
        weight_sum = REBALANCE_WEIGHT_BACKING; /* Grant the underlying pool directory a fixed weight of 20
                                                * (home dirs get 100 by default, i.e. 5x more). This weight
                                                * is not configurable, the per-home weights are. */
 
        HASHMAP_FOREACH(h, m->homes_by_uid) {
                statfs_f_type_t fstype;
                h->rebalance_pending = false; /* First, reset the flag, we only want it to be true for the
                                               * homes that qualify for rebalancing */
 
                if (!home_shall_rebalance(h)) /* Only look at actual candidates */
                        continue;
 
                if (home_is_busy(h))
                        return -EBUSY; /* Let's not rebalance if there's a busy home directory. */
 
                r = home_get_disk_status(
                                h,
                                &h->rebalance_size,
                                &h->rebalance_usage,
                                &h->rebalance_free,
                                NULL,
                                NULL,
                                &fstype,
                                NULL);
                if (r < 0) {
                        log_warning_errno(r, "Failed to get free space of home '%s', ignoring.", h->user_name);
                        continue;
                }
 
                if (h->rebalance_free > UINT64_MAX - free_sum)
                        return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW), "Rebalance free overflow");
                free_sum += h->rebalance_free;
 
                if (h->rebalance_usage > UINT64_MAX - usage_sum)
                        return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW), "Rebalance usage overflow");
                usage_sum += h->rebalance_usage;
 
                h->rebalance_weight = user_record_rebalance_weight(h->record);
                if (h->rebalance_weight > UINT64_MAX - weight_sum)
                        return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW), "Rebalance weight overflow");
                weight_sum += h->rebalance_weight;
 
                h->rebalance_min = minimal_size_by_fs_magic(fstype);
 
                if (!GREEDY_REALLOC(array, c+1))
                        return log_oom();
 
                array[c++] = h;
        }
 
        if (c == 0) {
                log_debug("No homes to rebalance.");
                return 0;
        }
 
        assert(weight_sum > 0);
 
        log_debug("Disk space usage by all home directories to rebalance: %s — available disk space: %s",
                  FORMAT_BYTES(usage_sum), FORMAT_BYTES(free_sum));
 
        /* Bring the home directories in a well-defined order, so that we distribute space in a reproducible
         * way for the same parameters. */
        typesafe_qsort(array, c, home_cmp);
 
        for (int i = 0; i < c; i++) {
                uint64_t new_free;
                double d;
 
                h = array[i];
 
                assert(h->rebalance_free <= free_sum);
                assert(h->rebalance_usage <= usage_sum);
                assert(h->rebalance_weight <= weight_sum);
 
                d = free_sum / 4096.0 * h->rebalance_weight / weight_sum; /* Calculate new space for this home in units of 4K */
 
                /* Convert from units of 4K back to bytes */
                if (d >= UINT64_MAX / 4096)
                        new_free = UINT64_MAX;
                else
                        new_free = (uint64_t) d * 4096;
 
                /* Subtract the weight and assigned space from the sums now, to distribute the rounding noise
                 * to the remaining home dirs */
                free_sum = LESS_BY(free_sum, new_free);
                weight_sum = LESS_BY(weight_sum, h->rebalance_weight);
 
                /* Keep track of home directory with the least amount of space left: we want to schedule the
                 * next rebalance more quickly if this is low */
                if (new_free < min_free)
                        min_free = new_free;
 
                if (new_free > UINT64_MAX - h->rebalance_usage)
                        h->rebalance_goal = UINT64_MAX-1; /* maximum size */
                else {
                        h->rebalance_goal = h->rebalance_usage + new_free;
 
                        if (h->rebalance_min != UINT64_MAX && h->rebalance_goal < h->rebalance_min)
                                h->rebalance_goal = h->rebalance_min;
                }
 
                /* Skip over this home if the state doesn't match the operation */
                if ((m->rebalance_state == REBALANCE_SHRINKING && h->rebalance_goal > h->rebalance_size) ||
                    (m->rebalance_state == REBALANCE_GROWING && h->rebalance_goal < h->rebalance_size))
                        h->rebalance_pending = false;
                else {
                        log_debug("Rebalancing home directory '%s' %s %s %s.", h->user_name,
                                  FORMAT_BYTES(h->rebalance_size),
                                  glyph(GLYPH_ARROW_RIGHT),
                                  FORMAT_BYTES(h->rebalance_goal));
                        h->rebalance_pending = true;
                }
 
                if (ABS_DIFF(h->rebalance_size, h->rebalance_goal) * 100.0 / h->rebalance_size >= 5.0)
                        relevant = true;
        }
 
        /* Scale next rebalancing interval based on the least amount of space of any of the home
         * directories. We pick a time in the range 1min … 15min, scaled by floor(log2(min_free)),
         * so that: 10M → ~0.6min, 100M → ~2.3min, 1G → ~4.0min, 10G → ~6.3min, 100G → ~8.1min */
        m->rebalance_interval_usec = (usec_t) CLAMP((LESS_BY(log2u64(min_free), 22u)*15*USEC_PER_MINUTE)/26,
                                                    1 * USEC_PER_MINUTE,
                                                    15 * USEC_PER_MINUTE);
 
        log_debug("Rebalancing interval set to %s.", FORMAT_TIMESPAN(m->rebalance_interval_usec, USEC_PER_MSEC));
 
        /* Let's suppress small resizes, growing/shrinking file systems isn't free after all */
        if (!relevant) {
                log_debug("Skipping rebalancing, since all calculated size changes are below ±5%%.");
                return 0;
        }
 
        return c;
}
 
static int manager_rebalance_apply(Manager *m) {
        int c = 0, r;
        Home *h;
 
        assert(m);
 
        HASHMAP_FOREACH(h, m->homes_by_uid) {
                _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
 
                if (!h->rebalance_pending)
                        continue;
 
                h->rebalance_pending = false;
 
                r = home_resize(h, h->rebalance_goal, /* secret= */ NULL, &error);
                if (r < 0)
                        log_warning_errno(r, "Failed to resize home '%s' for rebalancing, ignoring: %s",
                                          h->user_name, bus_error_message(&error, r));
                else
                        c++;
        }
 
        return c;
}
 
static void manager_rebalance_reply_messages(Manager *m) {
        int r;
 
        assert(m);
 
        for (;;) {
                _cleanup_(sd_bus_message_unrefp) sd_bus_message *msg =
                        set_steal_first(m->rebalance_pending_method_calls);
 
                if (!msg)
                        break;