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 1–1000 of 2,238

/* SPDX-License-Identifier: LGPL-2.1-or-later */
 
#include <grp.h>
#include <linux/fscrypt.h>
#include <linux/magic.h>
#include <pwd.h>
#include <sys/inotify.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <unistd.h>
 
#include "sd-bus.h"
#include "sd-event.h"
#include "sd-gpt.h"
#include "sd-id128.h"
 
#include "alloc-util.h"
#include "btrfs-util.h"
#include "bus-common-errors.h"
#include "bus-error.h"
#include "bus-log-control-api.h"
#include "bus-object.h"
#include "clean-ipc.h"
#include "common-signal.h"
#include "conf-files.h"
#include "crypto-util.h"
#include "device-util.h"
#include "dirent-util.h"
#include "errno-util.h"
#include "fd-util.h"
#include "fdset.h"
#include "fileio.h"
#include "format-util.h"
#include "fs-util.h"
#include "glyph-util.h"
#include "home-util.h"
#include "homed-conf.h"
#include "homed-home.h"
#include "homed-manager.h"
#include "homed-manager-bus.h"
#include "homed-operation.h"
#include "homed-varlink.h"
#include "logarithm.h"
#include "mkdir.h"
#include "notify-recv.h"
#include "ordered-set.h"
#include "quota-util.h"
#include "random-util.h"
#include "resize-fs.h"
#include "rm-rf.h"
#include "set.h"
#include "siphash24.h"
#include "sort-util.h"
#include "stat-util.h"
#include "string-util.h"
#include "strv.h"
#include "sync-util.h"
#include "time-util.h"
#include "tmpfile-util.h"
#include "udev-util.h"
#include "user-record.h"
#include "user-record-sign.h"
#include "user-record-util.h"
#include "user-util.h"
#include "varlink-io.systemd.UserDatabase.h"
#include "varlink-io.systemd.service.h"
#include "varlink-util.h"
#include "xattr-util.h"
 
/* Where to look for private/public keys that are used to sign the user records. We are not using
 * CONF_PATHS_NULSTR() here since we want to insert /var/lib/systemd/home/ in the middle. And we insert that
 * since we want to auto-generate a persistent private/public key pair if we need to. */
#define KEY_PATHS_NULSTR                        \
        "/etc/systemd/home/\0"                  \
        "/run/systemd/home/\0"                  \
        "/var/lib/systemd/home/\0"              \
        "/usr/local/lib/systemd/home/\0"        \
        "/usr/lib/systemd/home/\0"
 
static bool uid_is_home(uid_t uid) {
        return uid >= HOME_UID_MIN && uid <= HOME_UID_MAX;
}
/* Takes a value generated randomly or by hashing and turns it into a UID in the right range */
 
#define UID_CLAMP_INTO_HOME_RANGE(rnd) (((uid_t) (rnd) % (HOME_UID_MAX - HOME_UID_MIN + 1)) + HOME_UID_MIN)
 
DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(homes_by_uid_hash_ops, void, trivial_hash_func, trivial_compare_func, Home, home_free);
DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(homes_by_worker_pid_hash_ops, PidRef, pidref_hash_func, pidref_compare_func, Home, home_free);
DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(homes_by_sysfs_hash_ops, char, path_hash_func, path_compare, Home, home_free);
 
static int on_home_inotify(sd_event_source *s, const struct inotify_event *event, void *userdata);
static int manager_gc_images(Manager *m);
static int manager_gc_blob(Manager *m);
static int manager_enumerate_images(Manager *m);
static int manager_assess_image(Manager *m, int dir_fd, const char *dir_path, const char *dentry_name);
static void manager_revalidate_image(Manager *m, Home *h);
 
static void manager_watch_home(Manager *m) {
        struct statfs sfs;
        int r;
 
        assert(m);
 
        m->inotify_event_source = sd_event_source_disable_unref(m->inotify_event_source);
        m->scan_slash_home = false;
 
        if (statfs(get_home_root(), &sfs) < 0) {
                log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_WARNING, errno,
                               "Failed to statfs() %s directory, disabling automatic scanning.", get_home_root());
                return;
        }
 
        if (is_network_fs(&sfs)) {
                log_info("%s is a network file system, disabling automatic scanning.", get_home_root());
                return;
        }
 
        if (is_fs_type(&sfs, AUTOFS_SUPER_MAGIC)) {
                log_info("%s is on autofs, disabling automatic scanning.", get_home_root());
                return;
        }
 
        m->scan_slash_home = true;
 
        r = sd_event_add_inotify(m->event, &m->inotify_event_source, get_home_root(),
                                 IN_CREATE|IN_CLOSE_WRITE|IN_DELETE_SELF|IN_MOVE_SELF|IN_ONLYDIR|IN_MOVED_TO|IN_MOVED_FROM|IN_DELETE,
                                 on_home_inotify, m);
        if (r < 0)
                log_full_errno(r == -ENOENT ? LOG_DEBUG : LOG_WARNING, r,
                               "Failed to create inotify watch on %s, ignoring.", get_home_root());
 
        (void) sd_event_source_set_description(m->inotify_event_source, "home-inotify");
 
        log_info("Watching %s.", get_home_root());
}
 
static int on_home_inotify(sd_event_source *s, const struct inotify_event *event, void *userdata) {
        _cleanup_free_ char *j = NULL;
        Manager *m = ASSERT_PTR(userdata);
        const char *e, *n;
 
        assert(event);
 
        if ((event->mask & (IN_Q_OVERFLOW|IN_MOVE_SELF|IN_DELETE_SELF|IN_IGNORED|IN_UNMOUNT)) != 0) {
 
                if (FLAGS_SET(event->mask, IN_Q_OVERFLOW))
                        log_debug("%s inotify queue overflow, rescanning.", get_home_root());
                else if (FLAGS_SET(event->mask, IN_MOVE_SELF))
                        log_info("%s moved or renamed, recreating watch and rescanning.", get_home_root());
                else if (FLAGS_SET(event->mask, IN_DELETE_SELF))
                        log_info("%s deleted, recreating watch and rescanning.", get_home_root());
                else if (FLAGS_SET(event->mask, IN_UNMOUNT))
                        log_info("%s unmounted, recreating watch and rescanning.", get_home_root());
                else if (FLAGS_SET(event->mask, IN_IGNORED))
                        log_info("%s watch invalidated, recreating watch and rescanning.", get_home_root());
 
                manager_watch_home(m);
                (void) manager_gc_images(m);
                (void) manager_enumerate_images(m);
                (void) bus_manager_emit_auto_login_changed(m);
                return 0;
        }
 
        /* For the other inotify events, let's ignore all events for file names that don't match our
         * expectations */
        if (isempty(event->name))
                return 0;
        e = endswith(event->name, FLAGS_SET(event->mask, IN_ISDIR) ? ".homedir" : ".home");
        if (!e)
                return 0;
 
        n = strndupa_safe(event->name, e - event->name);
        if (!suitable_user_name(n))
                return 0;
 
        j = path_join(get_home_root(), event->name);
        if (!j)
                return log_oom();
 
        if ((event->mask & (IN_CREATE|IN_CLOSE_WRITE|IN_MOVED_TO)) != 0) {
                if (FLAGS_SET(event->mask, IN_CREATE))
                        log_debug("%s has been created, having a look.", j);
                else if (FLAGS_SET(event->mask, IN_CLOSE_WRITE))
                        log_debug("%s has been modified, having a look.", j);
                else if (FLAGS_SET(event->mask, IN_MOVED_TO))
                        log_debug("%s has been moved in, having a look.", j);
 
                (void) manager_assess_image(m, /* dir_fd= */ -EBADF, get_home_root(), event->name);
                (void) bus_manager_emit_auto_login_changed(m);
        }
 
        if ((event->mask & (IN_DELETE | IN_CLOSE_WRITE | IN_MOVED_FROM)) != 0) {
                Home *h;
 
                if (FLAGS_SET(event->mask, IN_DELETE))
                        log_debug("%s has been deleted, revalidating.", j);
                else if (FLAGS_SET(event->mask, IN_CLOSE_WRITE))
                        log_debug("%s has been closed after writing, revalidating.", j);
                else if (FLAGS_SET(event->mask, IN_MOVED_FROM))
                        log_debug("%s has been moved away, revalidating.", j);
 
                h = hashmap_get(m->homes_by_name, n);
                if (h && streq(h->user_name, n)) {
                        manager_revalidate_image(m, h);
                        (void) bus_manager_emit_auto_login_changed(m);
                }
        }
 
        return 0;
}
 
static int sigusr1_handler(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
        Manager *m = ASSERT_PTR(userdata);
        assert(s);
 
        /* If clients send use SIGUSR1 we'll explicitly rescan for home directories. This is useful in some
         * cases where inotify isn't good enough, for example if /home/ is overmunted. */
        manager_watch_home(m);
        (void) manager_gc_images(m);
        (void) manager_enumerate_images(m);
        (void) bus_manager_emit_auto_login_changed(m);
 
        return 0;
}
 
int manager_new(Manager **ret) {
        _cleanup_(manager_freep) Manager *m = NULL;
        int r;
 
        assert(ret);
 
        m = new(Manager, 1);
        if (!m)
                return -ENOMEM;
 
        *m = (Manager) {
                .default_storage = _USER_STORAGE_INVALID,
                .rebalance_interval_usec = 2 * USEC_PER_MINUTE, /* initially, rebalance every 2min */
        };
 
        r = manager_parse_config_file(m);
        if (r < 0)
                return r;
 
        r = sd_event_default(&m->event);
        if (r < 0)
                return r;
 
        r = sd_event_set_signal_exit(m->event, true);
        if (r < 0)
                return r;
 
        r = sd_event_add_memory_pressure(m->event, /* ret= */ NULL, /* callback= */ NULL, /* userdata= */ NULL);
        if (r < 0)
                log_full_errno(ERRNO_IS_NOT_SUPPORTED(r) || ERRNO_IS_PRIVILEGE(r) || (r == -EHOSTDOWN) ? LOG_DEBUG : LOG_WARNING, r,
                               "Failed to allocate memory pressure watch, ignoring: %m");
 
        r = sd_event_add_signal(m->event, /* ret= */ NULL, (SIGRTMIN+18)|SD_EVENT_SIGNAL_PROCMASK, sigrtmin18_handler, /* userdata= */ NULL);
        if (r < 0)
                return r;
 
        r = sd_event_add_signal(m->event, /* ret= */ NULL, SIGUSR1|SD_EVENT_SIGNAL_PROCMASK, sigusr1_handler, m);
        if (r < 0)
                return r;
 
        (void) sd_event_set_watchdog(m->event, true);
 
        m->homes_by_uid = hashmap_new(&homes_by_uid_hash_ops);
        if (!m->homes_by_uid)
                return -ENOMEM;
 
        m->homes_by_name = hashmap_new(&string_hash_ops);
        if (!m->homes_by_name)
                return -ENOMEM;
 
        m->homes_by_worker_pid = hashmap_new(&homes_by_worker_pid_hash_ops);
        if (!m->homes_by_worker_pid)
                return -ENOMEM;
 
        m->homes_by_sysfs = hashmap_new(&homes_by_sysfs_hash_ops);
        if (!m->homes_by_sysfs)
                return -ENOMEM;
 
        *ret = TAKE_PTR(m);
        return 0;
}
 
Manager* manager_free(Manager *m) {
        Home *h;
 
        assert(m);
 
        HASHMAP_FOREACH(h, m->homes_by_worker_pid)
                (void) home_wait_for_worker(h);
 
        m->bus = sd_bus_flush_close_unref(m->bus);
        m->polkit_registry = hashmap_free(m->polkit_registry);
 
        m->device_monitor = sd_device_monitor_unref(m->device_monitor);
 
        m->inotify_event_source = sd_event_source_unref(m->inotify_event_source);
        m->notify_socket_path = mfree(m->notify_socket_path);
        m->deferred_rescan_event_source = sd_event_source_unref(m->deferred_rescan_event_source);
        m->deferred_gc_event_source = sd_event_source_unref(m->deferred_gc_event_source);
        m->deferred_auto_login_event_source = sd_event_source_unref(m->deferred_auto_login_event_source);
        m->rebalance_event_source = sd_event_source_unref(m->rebalance_event_source);
 
        m->event = sd_event_unref(m->event);
 
        m->homes_by_uid = hashmap_free(m->homes_by_uid);
        m->homes_by_name = hashmap_free(m->homes_by_name);
        m->homes_by_worker_pid = hashmap_free(m->homes_by_worker_pid);
        m->homes_by_sysfs = hashmap_free(m->homes_by_sysfs);
 
        if (m->private_key)
                sym_EVP_PKEY_free(m->private_key);
 
        hashmap_free(m->public_keys);
 
        sd_varlink_server_unref(m->varlink_server);
        free(m->userdb_service);
 
        free(m->default_file_system_type);
 
        return mfree(m);
}
 
int manager_verify_user_record(Manager *m, UserRecord *hr) {
        EVP_PKEY *pkey;
        int r;
 
        assert(m);
        assert(hr);
 
        if (!m->private_key && hashmap_isempty(m->public_keys)) {
                r = user_record_has_signature(hr);
                if (r < 0)
                        return r;
 
                return r ? -ENOKEY : USER_RECORD_UNSIGNED;
        }
 
        /* Is it our own? */
        if (m->private_key) {
                r = user_record_verify(hr, m->private_key);
                switch (r) {
 
                case USER_RECORD_FOREIGN:
                        /* This record is not signed by this key, but let's see below */
                        break;
 
                case USER_RECORD_SIGNED:               /* Signed by us, but also by others, let's propagate that */
                case USER_RECORD_SIGNED_EXCLUSIVE:     /* Signed by us, and nothing else, ditto */
                case USER_RECORD_UNSIGNED:             /* Not signed at all, ditto  */
                default:
                        return r;
                }
        }
 
        HASHMAP_FOREACH(pkey, m->public_keys) {
                r = user_record_verify(hr, pkey);
                switch (r) {
 
                case USER_RECORD_FOREIGN:
                        /* This record is not signed by this key, but let's see our other keys */
                        break;
 
                case USER_RECORD_SIGNED:            /* It's signed by this key we are happy with, but which is not our own. */
                case USER_RECORD_SIGNED_EXCLUSIVE:
                        return USER_RECORD_FOREIGN;
 
                case USER_RECORD_UNSIGNED: /* It's not signed at all */
                default:
                        return r;
                }
        }
 
        return -ENOKEY;
}
 
static int manager_add_home_by_record(
                Manager *m,
                const char *name,
                int dir_fd,
                const char *fname) {
 
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
        _cleanup_(user_record_unrefp) UserRecord *hr = NULL;
        int r, is_signed;
        struct stat st;
        Home *h;
 
        assert(m);
        assert(name);
        assert(fname);
 
        if (fstatat(dir_fd, fname, &st, 0) < 0)
                return log_error_errno(errno, "Failed to stat identity record %s: %m", fname);
 
        if (!S_ISREG(st.st_mode)) {
                log_debug("Identity record file %s is not a regular file, ignoring.", fname);
                return 0;
        }
 
        if (st.st_size == 0)
                goto unlink_this_file;
 
        unsigned line = 0, column = 0;
        r = sd_json_parse_file_at(/* f= */ NULL, dir_fd, fname, SD_JSON_PARSE_MUST_BE_OBJECT|SD_JSON_PARSE_SENSITIVE, &v, &line, &column);
        if (r < 0)
                return log_error_errno(r, "Failed to parse identity record at %s:%u:%u: %m", fname, line, column);
 
        if (sd_json_variant_is_blank_object(v))
                goto unlink_this_file;
 
        hr = user_record_new();
        if (!hr)
                return log_oom();
 
        r = user_record_load(hr, v, USER_RECORD_LOAD_REFUSE_SECRET|USER_RECORD_LOG|USER_RECORD_PERMISSIVE);
        if (r < 0)
                return r;
 
        if (!streq_ptr(hr->user_name, name))
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Identity's user name %s does not match file name %s, refusing.",
                                       hr->user_name, name);
 
        is_signed = manager_verify_user_record(m, hr);
        switch (is_signed) {
 
        case -ENOKEY:
                return log_warning_errno(is_signed, "User record %s is not signed by any accepted key, ignoring.", fname);
        case USER_RECORD_UNSIGNED:
                return log_warning_errno(SYNTHETIC_ERRNO(EPERM), "User record %s is not signed at all, ignoring.", fname);
        case USER_RECORD_SIGNED:
                log_info("User record %s is signed by us (and others), accepting.", fname);
                break;
        case USER_RECORD_SIGNED_EXCLUSIVE:
                log_info("User record %s is signed only by us, accepting.", fname);
                break;
        case USER_RECORD_FOREIGN:
                log_info("User record %s is signed by registered key from others, accepting.", fname);
                break;
        default:
                assert(is_signed < 0);
                return log_error_errno(is_signed, "Failed to verify signature of user record in %s: %m", fname);
        }
 
        h = hashmap_get(m->homes_by_name, name);
        if (h) {
                r = home_set_record(h, hr);
                if (r < 0)
                        return log_error_errno(r, "Failed to update home record for %s: %m", name);
 
                /* If we acquired a record now for a previously unallocated entry, then reset the state. This
                 * makes sure home_get_state() will check for the availability of the image file dynamically
                 * in order to detect to distinguish HOME_INACTIVE and HOME_ABSENT. */
                if (h->state == HOME_UNFIXATED)
                        h->state = _HOME_STATE_INVALID;
        } else {
                r = home_new(m, hr, NULL, &h);
                if (r < 0)
                        return log_error_errno(r, "Failed to allocate new home object: %m");
 
                log_info("Added registered home for user %s.", hr->user_name);
        }
 
        /* Only entries we exclusively signed are writable to us, hence remember the result */
        h->signed_locally = is_signed == USER_RECORD_SIGNED_EXCLUSIVE;
 
        return 1;
 
unlink_this_file:
        /* If this is an empty file, then let's just remove it. An empty file is not useful in any case, and
         * apparently xfs likes to leave empty files around when not unmounted cleanly (see
         * https://github.com/systemd/systemd/issues/15178 for example). Note that we don't delete non-empty
         * files even if they are invalid, because that's just too risky, we might delete data the user still
         * needs. But empty files are never useful, hence let's just remove them. */
 
        if (unlinkat(dir_fd, fname, 0) < 0)
                return log_error_errno(errno, "Failed to remove empty user record file %s: %m", fname);
 
        log_notice("Discovered empty user record file %s/%s, removed automatically.", home_record_dir(), fname);
        return 0;
}
 
static int manager_enumerate_records(Manager *m) {
        _cleanup_closedir_ DIR *d = NULL;
 
        assert(m);
 
        d = opendir(home_record_dir());
        if (!d)
                return log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_ERR, errno,
                                      "Failed to open %s: %m", home_record_dir());
 
        FOREACH_DIRENT(de, d, return log_error_errno(errno, "Failed to read record directory: %m")) {
                _cleanup_free_ char *n = NULL;
                const char *e;
 
                if (!dirent_is_file(de))
                        continue;
 
                e = endswith(de->d_name, ".identity");
                if (!e)
                        continue;
 
                n = strndup(de->d_name, e - de->d_name);
                if (!n)
                        return log_oom();
 
                if (!suitable_user_name(n))
                        continue;
 
                (void) manager_add_home_by_record(m, n, dirfd(d), de->d_name);
        }
 
        return 0;
}
 
static int search_quota(uid_t uid, const char *exclude_quota_path) {
        struct stat exclude_st = {};
        dev_t previous_devno = 0;
        int r;
 
        /* Checks whether the specified UID owns any files on the files system, but ignore any file system
         * backing the specified file. The file is used when operating on home directories, where it's OK if
         * the UID of them already owns files. */
 
        if (exclude_quota_path && stat(exclude_quota_path, &exclude_st) < 0) {
                if (errno != ENOENT)
                        return log_warning_errno(errno, "Failed to stat %s, ignoring: %m", exclude_quota_path);
        }
 
        /* Check a few usual suspects where regular users might own files. Note that this is by no means
         * comprehensive, but should cover most cases. Note that in an ideal world every user would be
         * registered in NSS and avoid our own UID range, but for all other cases, it's a good idea to be
         * paranoid and check quota if we can. */
        FOREACH_STRING(where, get_home_root(), "/tmp/", "/var/", "/var/mail/", "/var/tmp/", "/var/spool/") {
                struct dqblk req;
                struct stat st;
 
                _cleanup_close_ int fd = open(where, O_RDONLY|O_CLOEXEC|O_DIRECTORY);
                if (fd < 0) {
                        log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_ERR, errno,
                                       "Failed to open '%s', ignoring: %m", where);
                        continue;
                }
 
                if (fstat(fd, &st) < 0) {
                        log_error_errno(errno, "Failed to stat '%s', ignoring: %m", where);
                        continue;
                }
 
                if (st.st_dev == exclude_st.st_dev) { /* If an exclude path is specified, then ignore quota
                                                       * reported on the same block device as that path. */
                        log_debug("Directory %s is where the home directory is located, not checking quota for UID use.", where);
                        continue;
                }
 
                if (st.st_dev == previous_devno) { /* Does this directory have the same devno as the previous
                                                    * one we tested? If so, there's no point in testing this
                                                    * again. */
                        log_debug("Directory %s is on same device as previous tested directory, not checking quota for UID use a second time.", where);
                        continue;
                }
 
                previous_devno = st.st_dev;
 
                r = quotactl_fd_with_fallback(fd, QCMD_FIXED(Q_GETQUOTA, USRQUOTA), uid, &req);
                if (r < 0) {
                        if (ERRNO_IS_NOT_SUPPORTED(r))
                                log_debug_errno(r, "No UID quota support on %s, ignoring.", where);
                        else if (r == -ESRCH)
                                log_debug_errno(r, "UID quota not enabled on %s (for user " UID_FMT "), ignoring.", where, uid);
                        else if (ERRNO_IS_PRIVILEGE(r))
                                log_debug_errno(r, "UID quota support for %s prohibited, ignoring.", where);
                        else
                                log_warning_errno(r, "Failed to query quota on %s, ignoring: %m", where);
 
                        continue;
                }
 
                if ((FLAGS_SET(req.dqb_valid, QIF_SPACE) && req.dqb_curspace > 0) ||
                    (FLAGS_SET(req.dqb_valid, QIF_INODES) && req.dqb_curinodes > 0)) {
                        log_debug("Quota reports UID " UID_FMT " occupies disk space on %s.", uid, where);
                        return 1;
                }
        }
 
        return 0;
}
 
static int manager_acquire_uid(
                Manager *m,
                uid_t start_uid,
                const char *user_name,
                const char *exclude_quota_path,
                uid_t *ret) {
 
        static const uint8_t hash_key[] = {
                0xa3, 0xb8, 0x82, 0x69, 0x9a, 0x71, 0xf7, 0xa9,
                0xe0, 0x7c, 0xf6, 0xf1, 0x21, 0x69, 0xd2, 0x1e
        };
 
        enum {
                PHASE_SUGGESTED,
                PHASE_HASHED,
                PHASE_RANDOM
        } phase = PHASE_SUGGESTED;
 
        unsigned n_tries = 100;
        int r;
 
        assert(m);
        assert(ret);
 
        for (;;) {
                _cleanup_free_ struct passwd *pw = NULL;
                _cleanup_free_ struct group *gr = NULL;
                uid_t candidate;
                Home *other;
 
                if (--n_tries <= 0)
                        return -EBUSY;
 
                switch (phase) {
 
                case PHASE_SUGGESTED:
                        phase = PHASE_HASHED;
 
                        if (!uid_is_home(start_uid))
                                continue;
 
                        candidate = start_uid;
                        break;
 
                case PHASE_HASHED:
                        phase = PHASE_RANDOM;
 
                        if (!user_name)
                                continue;
 
                        candidate = UID_CLAMP_INTO_HOME_RANGE(siphash24(user_name, strlen(user_name), hash_key));
                        break;
 
                case PHASE_RANDOM:
                        random_bytes(&candidate, sizeof(candidate));
                        candidate = UID_CLAMP_INTO_HOME_RANGE(candidate);
                        break;
 
                default:
                        assert_not_reached();
                }
 
                other = hashmap_get(m->homes_by_uid, UID_TO_PTR(candidate));
                if (other) {
                        log_debug("Candidate UID " UID_FMT " already used by another home directory (%s), let's try another.",
                                  candidate, other->user_name);
                        continue;
                }
 
                r = getpwuid_malloc(candidate, &pw);
                if (r >= 0) {
                        log_debug("Candidate UID " UID_FMT " already registered by another user in NSS (%s), let's try another.",
                                  candidate, pw->pw_name);
                        continue;
                }
                if (r != -ESRCH) {
                        log_debug_errno(r, "Failed to check if an NSS user is already registered for candidate UID " UID_FMT ", assuming there might be: %m", candidate);
                        continue;
                }
 
                r = getgrgid_malloc((gid_t) candidate, &gr);
                if (r >= 0) {
                        log_debug("Candidate UID " UID_FMT " already registered by another group in NSS (%s), let's try another.",
                                  candidate, gr->gr_name);
                        continue;
                }
                if (r != -ESRCH) {
                        log_debug_errno(r, "Failed to check if an NSS group is already registered for candidate UID " UID_FMT ", assuming there might be: %m", candidate);
                        continue;
                }
 
                r = search_ipc(candidate, (gid_t) candidate);
                if (r < 0)
                        continue;
                if (r > 0) {
                        log_debug("Candidate UID " UID_FMT " already owns IPC objects, let's try another.", candidate);
                        continue;
                }
 
                r = search_quota(candidate, exclude_quota_path);
                if (r != 0)
                        continue;
 
                *ret = candidate;
                return 0;
        }
}
 
static int manager_add_home_by_image(
                Manager *m,
                const char *user_name,
                const char *realm,
                const char *image_path,
                const char *sysfs,
                UserStorage storage,
                uid_t start_uid) {
 
        _cleanup_(user_record_unrefp) UserRecord *hr = NULL;
        uid_t uid;
        Home *h;
        int r;
 
        assert(m);
 
        assert(m);
        assert(user_name);
        assert(image_path);
        assert(storage >= 0);
        assert(storage < _USER_STORAGE_MAX);
 
        h = hashmap_get(m->homes_by_name, user_name);
        if (h) {
                bool same;
 
                if (!streq(h->user_name, user_name)) {
                        log_debug("Found an image for user %s which already is an alias for another user, skipping.", user_name);
                        return 0; /* Ignore images that would synthesize a user that conflicts with an alias of another user */
                }
 
                if (h->state != HOME_UNFIXATED) {
                        log_debug("Found an image for user %s which already has a record, skipping.", user_name);
                        return 0; /* ignore images that synthesize a user we already have a record for */
                }
 
                same = user_record_storage(h->record) == storage;
                if (same) {
                        if (h->sysfs && sysfs)
                                same = path_equal(h->sysfs, sysfs);
                        else if (!!h->sysfs != !!sysfs)
                                same = false;
                        else {
                                const char *p;
 
                                p = user_record_image_path(h->record);
                                same = p && path_equal(p, image_path);
                        }
                }
 
                if (!same) {
                        log_debug("Found multiple images for user '%s', ignoring image '%s'.", user_name, image_path);
                        return 0;
                }
        } else {
                /* Check NSS, in case there's another user or group by this name */
                if (getpwnam_malloc(user_name, /* ret= */ NULL) >= 0 || getgrnam_malloc(user_name, /* ret= */ NULL) >= 0) {
                        log_debug("Found an existing user or group by name '%s', ignoring image '%s'.", user_name, image_path);
                        return 0;
                }
        }
 
        if (h && uid_is_valid(h->uid))
                uid = h->uid;
        else {
                r = manager_acquire_uid(m, start_uid, user_name,
                                        IN_SET(storage, USER_SUBVOLUME, USER_DIRECTORY, USER_FSCRYPT) ? image_path : NULL,
                                        &uid);
                if (r < 0)
                        return log_warning_errno(r, "Failed to acquire unused UID for %s: %m", user_name);
        }
 
        hr = user_record_new();
        if (!hr)
                return log_oom();
 
        r = user_record_synthesize(hr, user_name, realm, image_path, storage, uid, (gid_t) uid);
        if (r < 0)
                return log_error_errno(r, "Failed to synthesize home record for %s (image %s): %m", user_name, image_path);
 
        if (h) {
                r = home_set_record(h, hr);
                if (r < 0)
                        return log_error_errno(r, "Failed to update home record for %s: %m", user_name);
        } else {
                r = home_new(m, hr, sysfs, &h);
                if (r < 0)
                        return log_error_errno(r, "Failed to allocate new home object: %m");
 
                h->state = HOME_UNFIXATED;
 
                log_info("Discovered new home for user %s through image %s.", user_name, image_path);
        }
 
        return 1;
}
 
int manager_augment_record_with_uid(
                Manager *m,
                UserRecord *hr) {
 
        const char *exclude_quota_path = NULL;
        uid_t start_uid = UID_INVALID, uid;
        int r;
 
        assert(m);
        assert(hr);
 
        if (uid_is_valid(hr->uid))
                return 0;
 
        if (IN_SET(hr->storage, USER_CLASSIC, USER_SUBVOLUME, USER_DIRECTORY, USER_FSCRYPT)) {
                const char * ip;
 
                ip = user_record_image_path(hr);
                if (ip) {
                        struct stat st;
 
                        if (stat(ip, &st) < 0) {
                                if (errno != ENOENT)
                                        log_warning_errno(errno, "Failed to stat(%s): %m", ip);
                        }  else if (uid_is_home(st.st_uid)) {
                                start_uid = st.st_uid;
                                exclude_quota_path = ip;
                        }
                }
        }
 
        r = manager_acquire_uid(m, start_uid, hr->user_name, exclude_quota_path, &uid);
        if (r < 0)
                return r;
 
        log_debug("Acquired new UID " UID_FMT " for %s.", uid, hr->user_name);
 
        r = user_record_add_binding(
                        hr,
                        _USER_STORAGE_INVALID,
                        NULL,
                        SD_ID128_NULL,
                        SD_ID128_NULL,
                        SD_ID128_NULL,
                        NULL,
                        NULL,
                        UINT64_MAX,
                        NULL,
                        NULL,
                        uid,
                        (gid_t) uid);
        if (r < 0)
                return r;
 
        return 1;
}
 
static int manager_assess_image(
                Manager *m,
                int dir_fd,
                const char *dir_path,
                const char *dentry_name) {
 
        const char *luks_suffix, *directory_suffix;
        _cleanup_free_ char *path = NULL;
        struct stat st;
        int r;
 
        assert(m);
        assert(dir_path);
        assert(dentry_name);
 
        /* Maybe registers the specified .home or .homedir as a home we manage. Returns:
         *
         * -EMEDIUMTYPE: Not a dir with .homedir suffix or a file with .home suffix */
 
        luks_suffix = endswith(dentry_name, ".home");
        if (luks_suffix)
                directory_suffix = NULL;
        else
                directory_suffix = endswith(dentry_name, ".homedir");
 
        /* Early filter out: by name */
        if (!luks_suffix && !directory_suffix)
                return -EMEDIUMTYPE;
 
        path = path_join(dir_path, dentry_name);
        if (!path)
                return log_oom();
 
        /* Follow symlinks here, to allow people to link in stuff to make them available locally. */
        if (dir_fd >= 0)
                r = fstatat(dir_fd, dentry_name, &st, 0);
        else
                r = stat(path, &st);
        if (r < 0)
                return log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_WARNING, errno,
                                      "Failed to stat() directory entry '%s', ignoring: %m", dentry_name);
 
        if (S_ISREG(st.st_mode)) {
                _cleanup_free_ char *n = NULL, *user_name = NULL, *realm = NULL;
 
                if (!luks_suffix)
                        return -EMEDIUMTYPE;
 
                n = strndup(dentry_name, luks_suffix - dentry_name);
                if (!n)
                        return log_oom();
 
                r = split_user_name_realm(n, &user_name, &realm);
                if (r == -EINVAL) /* Not the right format: ignore */
                        return -EMEDIUMTYPE;
                if (r < 0)
                        return log_error_errno(r, "Failed to split image name into user name/realm: %m");
 
                return manager_add_home_by_image(m, user_name, realm, path, NULL, USER_LUKS, UID_INVALID);
        }
 
        if (S_ISDIR(st.st_mode)) {
                _cleanup_free_ char *n = NULL, *user_name = NULL, *realm = NULL;
                _cleanup_close_ int fd = -EBADF;
                UserStorage storage;
 
                if (!directory_suffix)
                        return -EMEDIUMTYPE;
 
                n = strndup(dentry_name, directory_suffix - dentry_name);
                if (!n)
                        return log_oom();
 
                r = split_user_name_realm(n, &user_name, &realm);
                if (r == -EINVAL) /* Not the right format: ignore */
                        return -EMEDIUMTYPE;
                if (r < 0)
                        return log_error_errno(r, "Failed to split image name into user name/realm: %m");
 
                if (dir_fd >= 0)
                        fd = openat(dir_fd, dentry_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC);
                else
                        fd = open(path, O_DIRECTORY|O_RDONLY|O_CLOEXEC);
                if (fd < 0)
                        return log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_WARNING, errno,
                                              "Failed to open directory '%s', ignoring: %m", path);
 
                if (fstat(fd, &st) < 0)
                        return log_warning_errno(errno, "Failed to fstat() %s, ignoring: %m", path);
 
                assert(S_ISDIR(st.st_mode)); /* Must hold, we used O_DIRECTORY above */
 
                r = btrfs_is_subvol_fd(fd);
                if (r < 0)
                        return log_warning_errno(r, "Failed to determine whether %s is a btrfs subvolume: %m", path);
                if (r > 0)
                        storage = USER_SUBVOLUME;
                else {
                        struct fscrypt_policy policy;
 
                        if (ioctl(fd, FS_IOC_GET_ENCRYPTION_POLICY, &policy) < 0) {
 
                                if (errno == ENODATA)
                                        log_debug_errno(errno, "Determined %s is not fscrypt encrypted.", path);
                                else if (ERRNO_IS_NOT_SUPPORTED(errno))
                                        log_debug_errno(errno, "Determined %s is not fscrypt encrypted because kernel or file system doesn't support it.", path);
                                else
                                        log_debug_errno(errno, "FS_IOC_GET_ENCRYPTION_POLICY failed with unexpected error code on %s, ignoring: %m", path);
 
                                storage = USER_DIRECTORY;
                        } else
                                storage = USER_FSCRYPT;
                }
 
                return manager_add_home_by_image(m, user_name, realm, path, NULL, storage, st.st_uid);
        }
 
        return -EMEDIUMTYPE;
}
 
int manager_adopt_home(Manager *m, const char *path) {
        int r;
 
        assert(m);
        assert(path);
 
        _cleanup_free_ char *fn = NULL;
        r = path_extract_filename(path, &fn);
        if (r < 0)
                return r;
 
        _cleanup_free_ char *dir = NULL;
        r = path_extract_directory(path, &dir);
        if (r < 0)
                return r;
 
        return manager_assess_image(m, /* dir_fd= */ -EBADF, dir, fn);
}
 
int manager_enumerate_images(Manager *m) {
        _cleanup_closedir_ DIR *d = NULL;
 
        assert(m);