HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/home/homed-home.c

129,052 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 12d83b8f6fbc3ea7861f40de99c2ab85b02f6207

Lines 1–1000 of 3,443

/* SPDX-License-Identifier: LGPL-2.1-or-later */
 
#include <sys/vfs.h>
#include <unistd.h>
 
#include "sd-bus.h"
#include "sd-json.h"
 
#include "blockdev-util.h"
#include "btrfs-util.h"
#include "build-path.h"
#include "bus-common-errors.h"
#include "bus-locator.h"
#include "device-util.h"
#include "env-util.h"
#include "errno-list.h"
#include "errno-util.h"
#include "event-util.h"
#include "fd-util.h"
#include "fileio.h"
#include "filesystems.h"
#include "format-util.h"
#include "glyph-util.h"
#include "home-util.h"
#include "homed-home.h"
#include "homed-home-bus.h"
#include "homed-manager.h"
#include "homed-operation.h"
#include "json-util.h"
#include "log.h"
#include "memfd-util.h"
#include "mkdir.h"
#include "ordered-set.h"
#include "parse-util.h"
#include "path-util.h"
#include "process-util.h"
#include "quota-util.h"
#include "resize-fs.h"
#include "rm-rf.h"
#include "signal-util.h"
#include "stat-util.h"
#include "string-table.h"
#include "strv.h"
#include "time-util.h"
#include "uid-classification.h"
#include "user-record.h"
#include "user-record-password-quality.h"
#include "user-record-sign.h"
#include "user-record-util.h"
#include "user-util.h"
 
#define HOME_USERS_MAX 500
#define PENDING_OPERATIONS_MAX 100
 
assert_cc(HOME_UID_MIN <= HOME_UID_MAX);
assert_cc(HOME_USERS_MAX <= (HOME_UID_MAX - HOME_UID_MIN + 1));
 
static int home_start_work(
                Home *h,
                const char *verb,
                UserRecord *hr,
                UserRecord *secret,
                Hashmap *blobs,
                uint64_t flags);
 
DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(operation_hash_ops, void, trivial_hash_func, trivial_compare_func, Operation, operation_unref);
 
static int suitable_home_record(UserRecord *hr) {
        int r;
 
        assert(hr);
 
        if (!hr->user_name)
                return -EUNATCH;
 
        /* We are a bit more restrictive with what we accept as homed-managed user than what we accept in
         * home records in general. Let's enforce the stricter rule here. */
        if (!suitable_user_name(hr->user_name))
                return -EINVAL;
        if (!uid_is_valid(hr->uid))
                return -EINVAL;
 
        /* Insist we are outside of the dynamic and system range */
        if (uid_is_system(hr->uid) || gid_is_system(user_record_gid(hr)) ||
            uid_is_dynamic(hr->uid) || gid_is_dynamic(user_record_gid(hr)) ||
            uid_is_greeter(hr->uid))
                return -EADDRNOTAVAIL;
 
        /* Insist that GID and UID match */
        if (user_record_gid(hr) != (gid_t) hr->uid)
                return -EBADSLT;
 
        /* Similar for the realm */
        if (hr->realm) {
                r = suitable_realm(hr->realm);
                if (r < 0)
                        return r;
                if (r == 0)
                        return -EINVAL;
        }
 
        return 0;
}
 
int home_new(Manager *m, UserRecord *hr, const char *sysfs, Home **ret) {
        _cleanup_(home_freep) Home *home = NULL;
        _cleanup_free_ char *nm = NULL, *ns = NULL, *blob = NULL;
        _cleanup_strv_free_ char **aliases = NULL;
        int r;
 
        assert(m);
        assert(hr);
 
        r = suitable_home_record(hr);
        if (r < 0)
                return r;
 
        if (hashmap_contains(m->homes_by_name, hr->user_name))
                return -EBUSY;
 
        STRV_FOREACH(a, hr->aliases)
                if (hashmap_contains(m->homes_by_name, *a))
                        return -EBUSY;
 
        if (hashmap_contains(m->homes_by_uid, UID_TO_PTR(hr->uid)))
                return -EBUSY;
 
        if (sysfs && hashmap_contains(m->homes_by_sysfs, sysfs))
                return -EBUSY;
 
        if (hashmap_size(m->homes_by_uid) >= HOME_USERS_MAX)
                return -EUSERS;
 
        nm = strdup(hr->user_name);
        if (!nm)
                return -ENOMEM;
 
        if (!strv_isempty(hr->aliases)) {
                aliases = strv_copy(hr->aliases);
                if (!aliases)
                        return -ENOMEM;
        }
 
        if (sysfs) {
                ns = strdup(sysfs);
                if (!ns)
                        return -ENOMEM;
        }
 
        home = new(Home, 1);
        if (!home)
                return -ENOMEM;
 
        *home = (Home) {
                .manager = m,
                .user_name = TAKE_PTR(nm),
                .aliases = TAKE_PTR(aliases),
                .uid = hr->uid,
                .state = _HOME_STATE_INVALID,
                .worker_pid = PIDREF_NULL,
                .worker_stdout_fd = -EBADF,
                .sysfs = TAKE_PTR(ns),
                .signed_locally = -1,
                .pin_fd = -EBADF,
                .luks_lock_fd = -EBADF,
        };
 
        r = hashmap_put(m->homes_by_name, home->user_name, home);
        if (r < 0)
                return r;
 
        STRV_FOREACH(a, home->aliases) {
                r = hashmap_put(m->homes_by_name, *a, home);
                if (r < 0)
                        return r;
        }
 
        r = hashmap_put(m->homes_by_uid, UID_TO_PTR(home->uid), home);
        if (r < 0)
                return r;
 
        if (home->sysfs) {
                r = hashmap_put(m->homes_by_sysfs, home->sysfs, home);
                if (r < 0)
                        return r;
        }
 
        r = user_record_clone(hr, USER_RECORD_LOAD_MASK_SECRET|USER_RECORD_PERMISSIVE, &home->record);
        if (r < 0)
                return r;
 
        blob = path_join(home_system_blob_dir(), hr->user_name);
        if (!blob)
                return -ENOMEM;
        r = mkdir_safe(blob, 0755, 0, 0, MKDIR_IGNORE_EXISTING);
        if (r < 0)
                log_warning_errno(r, "Failed to create blob dir for user '%s': %m", home->user_name);
 
        (void) bus_manager_emit_auto_login_changed(m);
        (void) bus_home_emit_change(home);
        (void) manager_schedule_rebalance(m, /* immediately= */ false);
 
        if (ret)
                *ret = TAKE_PTR(home);
        else
                TAKE_PTR(home);
 
        return 0;
}
 
Home *home_free(Home *h) {
 
        if (!h)
                return NULL;
 
        if (h->manager) {
                (void) bus_home_emit_remove(h);
                (void) bus_manager_emit_auto_login_changed(h->manager);
 
                if (h->user_name)
                        (void) hashmap_remove_value(h->manager->homes_by_name, h->user_name, h);
 
                STRV_FOREACH(a, h->aliases)
                        (void) hashmap_remove_value(h->manager->homes_by_name, *a, h);
 
                if (uid_is_valid(h->uid))
                        (void) hashmap_remove_value(h->manager->homes_by_uid, UID_TO_PTR(h->uid), h);
 
                if (h->sysfs)
                        (void) hashmap_remove_value(h->manager->homes_by_sysfs, h->sysfs, h);
 
                if (pidref_is_set(&h->worker_pid))
                        (void) hashmap_remove_value(h->manager->homes_by_worker_pid, &h->worker_pid, h);
 
                if (h->manager->gc_focus == h)
                        h->manager->gc_focus = NULL;
 
                (void) manager_schedule_rebalance(h->manager, /* immediately= */ false);
        }
 
        user_record_unref(h->record);
        user_record_unref(h->secret);
 
        pidref_done_sigkill_wait(&h->worker_pid);
        h->worker_event_source = sd_event_source_disable_unref(h->worker_event_source);
        safe_close(h->worker_stdout_fd);
        free(h->user_name);
        strv_free(h->aliases);
        free(h->sysfs);
 
        h->ref_event_source_please_suspend = sd_event_source_disable_unref(h->ref_event_source_please_suspend);
        h->ref_event_source_dont_suspend = sd_event_source_disable_unref(h->ref_event_source_dont_suspend);
 
        h->pending_operations = ordered_set_free(h->pending_operations);
        h->pending_event_source = sd_event_source_disable_unref(h->pending_event_source);
        h->deferred_change_event_source = sd_event_source_disable_unref(h->deferred_change_event_source);
 
        h->current_operation = operation_unref(h->current_operation);
 
        safe_close(h->pin_fd);
        safe_close(h->luks_lock_fd);
 
        h->retry_deactivate_event_source = sd_event_source_disable_unref(h->retry_deactivate_event_source);
 
        return mfree(h);
}
 
int home_set_record(Home *h, UserRecord *hr) {
        _cleanup_(user_record_unrefp) UserRecord *new_hr = NULL;
        Home *other;
        int r;
 
        assert(h);
        assert(h->user_name);
        assert(h->record);
        assert(hr);
 
        if (user_record_equal(h->record, hr))
                return 0;
 
        r = suitable_home_record(hr);
        if (r < 0)
                return r;
 
        if (!user_record_compatible(h->record, hr))
                return -EREMCHG;
 
        /* For now do not allow changing list of aliases */
        if (!strv_equal_ignore_order(h->aliases, hr->aliases))
                return -EREMCHG;
 
        if (!FLAGS_SET(hr->mask, USER_RECORD_REGULAR) ||
            FLAGS_SET(hr->mask, USER_RECORD_SECRET))
                return -EINVAL;
 
        if (FLAGS_SET(h->record->mask, USER_RECORD_STATUS)) {
                _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
 
                /* Hmm, the existing record has status fields? If so, copy them over */
 
                v = sd_json_variant_ref(hr->json);
                r = sd_json_variant_set_field(&v, "status", sd_json_variant_by_key(h->record->json, "status"));
                if (r < 0)
                        return r;
 
                new_hr = user_record_new();
                if (!new_hr)
                        return -ENOMEM;
 
                r = user_record_load(new_hr, v, USER_RECORD_LOAD_REFUSE_SECRET|USER_RECORD_PERMISSIVE);
                if (r < 0)
                        return r;
 
                hr = new_hr;
        }
 
        other = hashmap_get(h->manager->homes_by_uid, UID_TO_PTR(hr->uid));
        if (other && other != h)
                return -EBUSY;
 
        if (h->uid != hr->uid) {
                r = hashmap_remove_and_replace(h->manager->homes_by_uid, UID_TO_PTR(h->uid), UID_TO_PTR(hr->uid), h);
                if (r < 0)
                        return r;
        }
 
        user_record_unref(h->record);
        h->record = user_record_ref(hr);
        h->uid = h->record->uid;
 
        /* The updated record might have a different autologin setting, trigger a PropertiesChanged event for it */
        (void) bus_manager_emit_auto_login_changed(h->manager);
        (void) bus_home_emit_change(h);
 
        return 0;
}
 
int home_save_record(Home *h) {
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
        _cleanup_free_ char *text = NULL;
        const char *fn;
        int r;
 
        assert(h);
 
        v = sd_json_variant_ref(h->record->json);
        r = sd_json_variant_normalize(&v);
        if (r < 0)
                log_warning_errno(r, "User record could not be normalized.");
 
        r = sd_json_variant_format(v, SD_JSON_FORMAT_PRETTY|SD_JSON_FORMAT_NEWLINE, &text);
        if (r < 0)
                return r;
 
        (void) mkdir("/var/lib/systemd/", 0755);
        (void) mkdir(home_record_dir(), 0700);
 
        fn = strjoina(home_record_dir(), "/", h->user_name, ".identity");
 
        r = write_string_file(fn, text, WRITE_STRING_FILE_ATOMIC|WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_MODE_0600|WRITE_STRING_FILE_SYNC);
        if (r < 0)
                return r;
 
        return 0;
}
 
int home_unlink_record(Home *h) {
        _cleanup_free_ char *blob = NULL;
        const char *fn;
        int r;
 
        assert(h);
 
        fn = strjoina(home_record_dir(), "/", h->user_name, ".identity");
        if (unlink(fn) < 0 && errno != ENOENT)
                return -errno;
 
        fn = strjoina("/run/systemd/home/", h->user_name, ".ref");
        if (unlink(fn) < 0 && errno != ENOENT)
                return -errno;
 
        blob = path_join(home_system_blob_dir(), h->user_name);
        if (!blob)
                return -ENOMEM;
        r = rm_rf(blob, REMOVE_ROOT|REMOVE_PHYSICAL|REMOVE_MISSING_OK);
        if (r < 0)
                return r;
 
        return 0;
}
 
static void home_unpin(Home *h) {
        assert(h);
 
        if (h->pin_fd < 0)
                return;
 
        h->pin_fd = safe_close(h->pin_fd);
        log_debug("Successfully closed pin fd on home for %s.", h->user_name);
}
 
static void home_pin(Home *h) {
        const char *path;
 
        assert(h);
 
        if (h->pin_fd >= 0) /* Already pinned? */
                return;
 
        path = user_record_home_directory(h->record);
        if (!path) {
                log_warning("No home directory path to pin for %s, ignoring.", h->user_name);
                return;
        }
 
        h->pin_fd = open(path, O_PATH|O_DIRECTORY|O_CLOEXEC);
        if (h->pin_fd < 0) {
                log_warning_errno(errno, "Couldn't open home directory '%s' for pinning, ignoring: %m", path);
                return;
        }
 
        log_debug("Successfully pinned home directory '%s'.", path);
}
 
static void home_update_pin_fd(Home *h, HomeState state) {
        assert(h);
 
        if (state < 0)
                state = home_get_state(h);
 
        return HOME_STATE_SHALL_PIN(state) ? home_pin(h) : home_unpin(h);
}
 
static void home_maybe_close_luks_lock_fd(Home *h, HomeState state) {
        assert(h);
 
        if (h->luks_lock_fd < 0)
                return;
 
        if (state < 0)
                state = home_get_state(h);
 
        /* Keep the lock as long as the home dir is active or has some operation going */
        if (HOME_STATE_IS_EXECUTING_OPERATION(state) || HOME_STATE_IS_ACTIVE(state) || state == HOME_LOCKED)
                return;
 
        h->luks_lock_fd = safe_close(h->luks_lock_fd);
        log_debug("Successfully closed LUKS backing file lock for %s.", h->user_name);
}
 
static void home_maybe_stop_retry_deactivate(Home *h, HomeState state) {
        assert(h);
 
        /* Free the deactivation retry event source if we won't need it anymore. Specifically, we'll free the
         * event source whenever the home directory is already deactivated (and we thus where successful) or
         * if we start executing an operation that indicates that the home directory is going to be used or
         * operated on again. Also, if the home is referenced again stop the timer. */
 
        if (HOME_STATE_MAY_RETRY_DEACTIVATE(state) && !home_is_referenced(h))
                return;
 
        h->retry_deactivate_event_source = sd_event_source_disable_unref(h->retry_deactivate_event_source);
}
 
static int home_deactivate_internal(Home *h, bool force, sd_bus_error *error);
static void home_start_retry_deactivate(Home *h);
 
static int home_on_retry_deactivate(sd_event_source *s, uint64_t usec, void *userdata) {
        Home *h = ASSERT_PTR(userdata);
        HomeState state;
 
        assert(s);
 
        /* 15s after the last attempt to deactivate the home directory passed. Let's try it one more time. */
 
        h->retry_deactivate_event_source = sd_event_source_disable_unref(h->retry_deactivate_event_source);
 
        state = home_get_state(h);
        if (!HOME_STATE_MAY_RETRY_DEACTIVATE(state))
                return 0;
 
        if (IN_SET(state, HOME_ACTIVE, HOME_LINGERING)) {
                log_info("Again trying to deactivate home directory.");
 
                /* If we are not executing any operation, let's start deactivating now. Note that this will
                 * restart our timer again, we are gonna be called again if this doesn't work. */
                (void) home_deactivate_internal(h, /* force= */ false, NULL);
        } else
                /* if we are executing an operation (specifically, area already running a deactivation
                 * operation), then simply reque the timer, so that we retry again. */
                home_start_retry_deactivate(h);
 
        return 0;
}
 
static void home_start_retry_deactivate(Home *h) {
        int r;
 
        assert(h);
        assert(h->manager);
 
        /* Already allocated? */
        if (h->retry_deactivate_event_source)
                return;
 
        /* If the home directory is being used now don't start the timer */
        if (home_is_referenced(h))
                return;
 
        r = sd_event_add_time_relative(
                        h->manager->event,
                        &h->retry_deactivate_event_source,
                        CLOCK_MONOTONIC,
                        HOME_RETRY_DEACTIVATE_USEC,
                        1*USEC_PER_MINUTE,
                        home_on_retry_deactivate,
                        h);
        if (r < 0)
                return (void) log_warning_errno(r, "Failed to install retry-deactivate event source, ignoring: %m");
 
        (void) sd_event_source_set_description(h->retry_deactivate_event_source, "retry-deactivate");
}
 
static void home_set_state(Home *h, HomeState state) {
        HomeState old_state, new_state;
 
        assert(h);
 
        old_state = home_get_state(h);
        h->state = state;
        new_state = home_get_state(h); /* Query the new state, since the 'state' variable might be set to -1,
                                        * in which case we synthesize an high-level state on demand */
 
        log_info("%s: changing state %s %s %s", h->user_name,
                 home_state_to_string(old_state),
                 glyph(GLYPH_ARROW_RIGHT),
                 home_state_to_string(new_state));
 
        home_update_pin_fd(h, new_state);
        home_maybe_close_luks_lock_fd(h, new_state);
        home_maybe_stop_retry_deactivate(h, new_state);
 
        if (HOME_STATE_IS_EXECUTING_OPERATION(old_state) && !HOME_STATE_IS_EXECUTING_OPERATION(new_state)) {
                /* If we just finished executing some operation, process the queue of pending operations. And
                 * enqueue it for GC too. */
 
                home_schedule_operation(h, NULL, NULL);
                manager_reschedule_rebalance(h->manager);
                manager_enqueue_gc(h->manager, h);
        }
}
 
static int home_parse_worker_stdout(int _fd, UserRecord **ret) {
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
        _cleanup_close_ int fd = ASSERT_FD(TAKE_FD(_fd)); /* take possession, even on failure */
        _cleanup_(user_record_unrefp) UserRecord *hr = NULL;
        _cleanup_fclose_ FILE *f = NULL;
        struct stat st;
        int r;
 
        assert(ret);
 
        if (fstat(fd, &st) < 0)
                return log_error_errno(errno, "Failed to stat stdout fd: %m");
 
        assert(S_ISREG(st.st_mode));
 
        if (st.st_size == 0) { /* empty record */
                *ret = NULL;
                return 0;
        }
 
        f = take_fdopen(&fd, "r");
        if (!f)
                return log_error_errno(errno, "Failed to reopen memfd: %m");
 
        if (DEBUG_LOGGING) {
                if (fseek(f, 0, SEEK_SET) < 0)
                        return log_error_errno(errno, "Failed to seek to beginning of memfd: %m");
 
                _cleanup_free_ char *text = NULL;
                r = read_full_stream(f, &text, NULL);
                if (r < 0)
                        return log_error_errno(r, "Failed to read from client: %m");
 
                log_debug("Got from worker: %s", text);
        }
 
        unsigned line = 0, column = 0;
        r = sd_json_parse_file(f, "stdout", SD_JSON_PARSE_MUST_BE_OBJECT|SD_JSON_PARSE_SENSITIVE|SD_JSON_PARSE_SEEK0, &v, &line, &column);
        if (r < 0)
                return log_error_errno(r, "Failed to parse identity at %u:%u: %m", line, column);
 
        hr = user_record_new();
        if (!hr)
                return log_oom();
 
        r = user_record_load(hr, v, USER_RECORD_LOAD_REFUSE_SECRET|USER_RECORD_PERMISSIVE);
        if (r < 0)
                return log_error_errno(r, "Failed to load home record identity: %m");
 
        *ret = TAKE_PTR(hr);
        return 1;
}
 
static int home_verify_user_record(Home *h, UserRecord *hr, bool *ret_signed_locally, sd_bus_error *ret_error) {
        int is_signed;
 
        assert(h);
        assert(hr);
        assert(ret_signed_locally);
 
        is_signed = manager_verify_user_record(h->manager, hr);
        switch (is_signed) {
 
        case USER_RECORD_SIGNED_EXCLUSIVE:
                log_info("Home %s is signed exclusively by our key, accepting.", hr->user_name);
                *ret_signed_locally = true;
                return 0;
 
        case USER_RECORD_SIGNED:
                log_info("Home %s is signed by our key (and others), accepting.", hr->user_name);
                *ret_signed_locally = false;
                return 0;
 
        case USER_RECORD_FOREIGN:
                log_info("Home %s is signed by foreign key we like, accepting.", hr->user_name);
                *ret_signed_locally = false;
                return 0;
 
        case USER_RECORD_UNSIGNED:
                sd_bus_error_setf(ret_error, BUS_ERROR_BAD_SIGNATURE, "User record %s is not signed at all, refusing.", hr->user_name);
                return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Home %s contains user record that is not signed at all, refusing.", hr->user_name);
 
        case -ENOKEY:
                sd_bus_error_setf(ret_error, BUS_ERROR_BAD_SIGNATURE, "User record %s is not signed by any known key, refusing.", hr->user_name);
                return log_error_errno(is_signed, "Home %s contains user record that is not signed by any known key, refusing.", hr->user_name);
 
        default:
                assert(is_signed < 0);
                return log_error_errno(is_signed, "Failed to verify signature on user record for %s, refusing fixation: %m", hr->user_name);
        }
}
 
static int convert_worker_errno(Home *h, int e, sd_bus_error *error) {
        /* Converts the error numbers the worker process returned into somewhat sensible dbus errors */
 
        switch (e) {
 
        case -EMSGSIZE:
                return sd_bus_error_set(error, BUS_ERROR_BAD_HOME_SIZE, "File systems of this type cannot be shrunk");
        case -ETXTBSY:
                return sd_bus_error_set(error, BUS_ERROR_BAD_HOME_SIZE, "File systems of this type can only be shrunk offline");
        case -ERANGE:
                return sd_bus_error_set(error, BUS_ERROR_BAD_HOME_SIZE, "File system size too small");
        case -ENOLINK:
                return sd_bus_error_set(error, SD_BUS_ERROR_NOT_SUPPORTED, "System does not support selected storage backend");
        case -EPROTONOSUPPORT:
                return sd_bus_error_set(error, SD_BUS_ERROR_NOT_SUPPORTED, "System does not support selected file system");
        case -ENOTTY:
                return sd_bus_error_set(error, SD_BUS_ERROR_NOT_SUPPORTED, "Operation not supported on storage backend");
        case -ESOCKTNOSUPPORT:
                return sd_bus_error_set(error, SD_BUS_ERROR_NOT_SUPPORTED, "Operation not supported on file system");
        case -ENOKEY:
                return sd_bus_error_setf(error, BUS_ERROR_BAD_PASSWORD, "Password for home %s is incorrect or not sufficient for authentication.", h->user_name);
        case -EBADSLT:
                return sd_bus_error_setf(error, BUS_ERROR_BAD_PASSWORD_AND_NO_TOKEN, "Password for home %s is incorrect or not sufficient, and configured security token not found either.", h->user_name);
        case -EREMOTEIO:
                return sd_bus_error_setf(error, BUS_ERROR_BAD_RECOVERY_KEY, "Recovery key for home %s is incorrect or not sufficient for authentication.", h->user_name);
        case -ENOANO:
                return sd_bus_error_set(error, BUS_ERROR_TOKEN_PIN_NEEDED, "PIN for security token required.");
        case -ERFKILL:
                return sd_bus_error_set(error, BUS_ERROR_TOKEN_PROTECTED_AUTHENTICATION_PATH_NEEDED, "Security token requires protected authentication path.");
        case -EMEDIUMTYPE:
                return sd_bus_error_set(error, BUS_ERROR_TOKEN_USER_PRESENCE_NEEDED, "Security token requires presence confirmation.");
        case -ENOCSI:
                return sd_bus_error_set(error, BUS_ERROR_TOKEN_USER_VERIFICATION_NEEDED, "Security token requires user verification.");
        case -ENOSTR:
                return sd_bus_error_set(error, BUS_ERROR_TOKEN_ACTION_TIMEOUT, "Token action timeout. (User was supposed to verify presence or similar, by interacting with the token, and didn't do that in time.)");
        case -EOWNERDEAD:
                return sd_bus_error_set(error, BUS_ERROR_TOKEN_PIN_LOCKED, "PIN of security token locked.");
        case -ENOLCK:
                return sd_bus_error_set(error, BUS_ERROR_TOKEN_BAD_PIN, "Bad PIN of security token.");
        case -ETOOMANYREFS:
                return sd_bus_error_set(error, BUS_ERROR_TOKEN_BAD_PIN_FEW_TRIES_LEFT, "Bad PIN of security token, and only a few tries left.");
        case -EUCLEAN:
                return sd_bus_error_set(error, BUS_ERROR_TOKEN_BAD_PIN_ONE_TRY_LEFT, "Bad PIN of security token, and only one try left.");
        case -EBUSY:
                return sd_bus_error_setf(error, BUS_ERROR_HOME_BUSY, "Home %s is currently being used, or an operation on home %s is currently being executed.", h->user_name, h->user_name);
        case -ENOEXEC:
                return sd_bus_error_setf(error, BUS_ERROR_HOME_NOT_ACTIVE, "Home %s is currently not active", h->user_name);
        case -ENOSPC:
                return sd_bus_error_setf(error, BUS_ERROR_NO_DISK_SPACE, "Not enough disk space for home %s", h->user_name);
        case -EKEYREVOKED:
                return sd_bus_error_setf(error, BUS_ERROR_HOME_CANT_AUTHENTICATE, "Home %s has no password or other authentication mechanism defined.", h->user_name);
        case -EADDRINUSE:
                return sd_bus_error_setf(error, BUS_ERROR_HOME_IN_USE, "Home %s is currently being used elsewhere.", h->user_name);
        case -ENETUNREACH:
                return sd_bus_error_setf(error, BUS_ERROR_HOME_ABSENT, "Backing storage for %s currently absent.", h->user_name);
        }
 
        return 0;
}
 
static void home_count_bad_authentication(Home *h, int error, bool save) {
        int r;
 
        assert(h);
 
        if (!IN_SET(error,
                    -ENOKEY,       /* Password incorrect */
                    -EBADSLT,      /* Password incorrect and no token */
                    -EREMOTEIO))   /* Recovery key incorrect */
                return;
 
        r = user_record_bad_authentication(h->record);
        if (r < 0) {
                log_warning_errno(r, "Failed to increase bad authentication counter, ignoring: %m");
                return;
        }
 
        if (save) {
                r = home_save_record(h);
                if (r < 0)
                        log_warning_errno(r, "Failed to write home record to disk, ignoring: %m");
        }
}
 
static void home_fixate_finish(Home *h, int ret, UserRecord *hr) {
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
        _cleanup_(user_record_unrefp) UserRecord *secret = NULL;
        bool signed_locally;
        int r;
 
        assert(h);
        assert(IN_SET(h->state, HOME_FIXATING, HOME_FIXATING_FOR_ACTIVATION, HOME_FIXATING_FOR_ACQUIRE));
 
        secret = TAKE_PTR(h->secret); /* Take possession */
 
        if (ret < 0) {
                home_count_bad_authentication(h, ret, /* save= */ false);
 
                (void) convert_worker_errno(h, ret, &error);
                r = log_error_errno(ret, "Fixation failed: %m");
                goto fail;
        }
        if (!hr) {
                r = log_error_errno(SYNTHETIC_ERRNO(EIO), "Did not receive user record from worker process, fixation failed.");
                goto fail;
        }
 
        r = home_verify_user_record(h, hr, &signed_locally, &error);
        if (r < 0)
                goto fail;
 
        r = home_set_record(h, hr);
        if (r < 0) {
                log_error_errno(r, "Failed to update home record: %m");
                goto fail;
        }
 
        h->signed_locally = signed_locally;
 
        /* When we finished fixating (and don't follow-up with activation), let's count this as good authentication */
        if (h->state == HOME_FIXATING) {
                r = user_record_good_authentication(h->record);
                if (r < 0)
                        log_warning_errno(r, "Failed to increase good authentication counter, ignoring: %m");
        }
 
        r = home_save_record(h);
        if (r < 0)
                log_warning_errno(r, "Failed to write home record to disk, ignoring: %m");
 
        if (IN_SET(h->state, HOME_FIXATING_FOR_ACTIVATION, HOME_FIXATING_FOR_ACQUIRE)) {
 
                r = home_start_work(h, "activate", h->record, secret, NULL, 0);
                if (r < 0) {
                        h->current_operation = operation_result_unref(h->current_operation, r, NULL);
                        home_set_state(h, _HOME_STATE_INVALID);
                } else
                        home_set_state(h, h->state == HOME_FIXATING_FOR_ACTIVATION ? HOME_ACTIVATING : HOME_ACTIVATING_FOR_ACQUIRE);
 
                return;
        }
 
        log_debug("Fixation of %s completed.", h->user_name);
 
        h->current_operation = operation_result_unref(h->current_operation, 0, NULL);
 
        /* Reset the state to "invalid", which makes home_get_state() test if the image exists and returns
         * HOME_ABSENT vs. HOME_INACTIVE as necessary. */
        home_set_state(h, _HOME_STATE_INVALID);
        (void) manager_schedule_rebalance(h->manager, /* immediately= */ false);
        return;
 
fail:
        /* If fixation fails, we stay in unfixated state! */
        h->current_operation = operation_result_unref(h->current_operation, r, &error);
        home_set_state(h, HOME_UNFIXATED);
}
 
static bool error_is_bad_password(int ret) {
        /* Tests for the various cases of bad passwords. We generally don't want to log so loudly about
         * these, since everyone types in a bad password now and then. Moreover we usually try to start out
         * with an empty set of passwords, so the first authentication will frequently fail, if not token is
         * inserted. */
 
        return IN_SET(ret,
                      -ENOKEY,       /* Bad password, or insufficient */
                      -EBADSLT,      /* Bad password, and no token */
                      -EREMOTEIO,    /* Bad recovery key */
                      -ENOANO,       /* PIN for security token needed */
                      -ERFKILL,      /* "Protected Authentication Path" for token needed */
                      -EMEDIUMTYPE,  /* Presence confirmation on token needed */
                      -ENOCSI,       /* User verification on token needed */
                      -ENOSTR,       /* Token action timeout */
                      -EOWNERDEAD,   /* PIN locked of security token */
                      -ENOLCK,       /* Bad PIN of security token */
                      -ETOOMANYREFS, /* Bad PIN and few tries left */
                      -EUCLEAN);     /* Bad PIN and one try left */
}
 
static void home_activate_finish(Home *h, int ret, UserRecord *hr) {
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
        int r;
 
        assert(h);
        assert(IN_SET(h->state, HOME_ACTIVATING, HOME_ACTIVATING_FOR_ACQUIRE));
 
        if (ret < 0) {
                home_count_bad_authentication(h, ret, /* save= */ true);
 
                (void) convert_worker_errno(h, ret, &error);
                r = log_full_errno(error_is_bad_password(ret) ? LOG_NOTICE : LOG_ERR,
                                   ret, "Activation failed: %s", bus_error_message(&error, ret));
                goto finish;
        }
 
        if (hr) {
                bool signed_locally;
 
                r = home_verify_user_record(h, hr, &signed_locally, &error);
                if (r < 0)
                        goto finish;
 
                r = home_set_record(h, hr);
                if (r < 0) {
                        log_error_errno(r, "Failed to update home record, ignoring: %m");
                        goto finish;
                }
 
                h->signed_locally = signed_locally;
 
                r = user_record_good_authentication(h->record);
                if (r < 0)
                        log_warning_errno(r, "Failed to increase good authentication counter, ignoring: %m");
 
                r = home_save_record(h);
                if (r < 0)
                        log_warning_errno(r, "Failed to write home record to disk, ignoring: %m");
        }
 
        log_debug("Activation of %s completed.", h->user_name);
        r = 0;
 
finish:
        h->current_operation = operation_result_unref(h->current_operation, r, &error);
        home_set_state(h, _HOME_STATE_INVALID);
 
        if (r >= 0)
                (void) manager_schedule_rebalance(h->manager, /* immediately= */ true);
}
 
static void home_deactivate_finish(Home *h, int ret, UserRecord *hr) {
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
        int r;
 
        assert(h);
        assert(h->state == HOME_DEACTIVATING);
        assert(!hr); /* We don't expect a record on this operation */
 
        if (ret < 0) {
                (void) convert_worker_errno(h, ret, &error);
                r = log_error_errno(ret, "Deactivation of %s failed: %m", h->user_name);
                goto finish;
        }
 
        log_debug("Deactivation of %s completed.", h->user_name);
        r = 0;
 
finish:
        h->current_operation = operation_result_unref(h->current_operation, r, &error);
        home_set_state(h, _HOME_STATE_INVALID);
 
        if (r >= 0)
                (void) manager_schedule_rebalance(h->manager, /* immediately= */ true);
}
 
static void home_remove_finish(Home *h, int ret, UserRecord *hr) {
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
        Manager *m;
        int r;
 
        assert(h);
        assert(h->state == HOME_REMOVING);
        assert(!hr); /* We don't expect a record on this operation */
 
        m = h->manager;
 
        if (ret < 0 && ret != -EALREADY) {
                (void) convert_worker_errno(h, ret, &error);
                r = log_error_errno(ret, "Removing %s failed: %m", h->user_name);
                goto fail;
        }
 
        /* For a couple of storage types we can't delete the actual data storage when called (such as LUKS on
         * partitions like USB sticks, or so). Sometimes these storage locations are among those we normally
         * automatically discover in /home or in udev. When such a home is deleted let's hence issue a rescan
         * after completion, so that "unfixated" entries are rediscovered.  */
        (void) manager_enqueue_rescan(m);
 
        /* The image is now removed from disk. Now also remove our stored record */
        r = home_unlink_record(h);
        if (r < 0) {
                log_error_errno(r, "Removing record file failed: %m");
                goto fail;
        }
 
        log_debug("Removal of %s completed.", h->user_name);
        h->current_operation = operation_result_unref(h->current_operation, 0, NULL);
 
        /* Unload this record from memory too now. */
        h = home_free(h);
 
        (void) manager_schedule_rebalance(m, /* immediately= */ true);
        return;
 
fail:
        h->current_operation = operation_result_unref(h->current_operation, r, &error);
        home_set_state(h, _HOME_STATE_INVALID);
}
 
static void home_create_finish(Home *h, int ret, UserRecord *hr) {
        int r;
 
        assert(h);
        assert(h->state == HOME_CREATING);
 
        if (ret < 0) {
                _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
 
                (void) convert_worker_errno(h, ret, &error);
                log_error_errno(ret, "Operation on %s failed: %m", h->user_name);
                h->current_operation = operation_result_unref(h->current_operation, ret, &error);
 
                if (h->unregister_on_failure) {
                        (void) home_unlink_record(h);
                        h = home_free(h);
                        return;
                }
 
                home_set_state(h, _HOME_STATE_INVALID);
                return;
        }
 
        if (hr) {
                r = home_set_record(h, hr);
                if (r < 0)
                        log_warning_errno(r, "Failed to update home record, ignoring: %m");
        }
 
        r = home_save_record(h);
        if (r < 0)
                log_warning_errno(r, "Failed to save record to disk, ignoring: %m");
 
        log_debug("Creation of %s completed.", h->user_name);
 
        h->current_operation = operation_result_unref(h->current_operation, 0, NULL);
        home_set_state(h, _HOME_STATE_INVALID);
 
        (void) manager_schedule_rebalance(h->manager, /* immediately= */ true);
}
 
static void home_change_finish(Home *h, int ret, UserRecord *hr) {
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
        uint64_t flags;
        int r;
 
        assert(h);
 
        flags = h->current_operation ? h->current_operation->call_flags : 0;
 
        if (ret < 0) {
                home_count_bad_authentication(h, ret, /* save= */ true);
 
                (void) convert_worker_errno(h, ret, &error);
                r = log_full_errno(error_is_bad_password(ret) ? LOG_NOTICE : LOG_ERR,
                                   ret, "Change operation failed: %s", bus_error_message(&error, ret));
                goto finish;