chiark / gitweb /
logind: change TasksMax= value for user logins to 33%
[elogind.git] / src / login / logind.c
index b97ba6d..b976981 100644 (file)
@@ -1,5 +1,3 @@
-/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
-
 /***
   This file is part of systemd.
 
 ***/
 
 #include <errno.h>
-#include <libudev.h>
 #include <fcntl.h>
 #include <string.h>
 #include <unistd.h>
-#include <linux/vt.h>
-#include <sys/timerfd.h>
 
+#if 0 /// elogind needs the systems udev header
+#include "libudev.h"
+#else
+#include <libudev.h>
+#endif // 0
 #include "sd-daemon.h"
-#include "strv.h"
-#include "conf-parser.h"
-#include "mkdir.h"
-#include "bus-util.h"
+
+#include "alloc-util.h"
 #include "bus-error.h"
+#include "bus-util.h"
+#include "conf-parser.h"
+#include "def.h"
+#include "dirent-util.h"
+#include "fd-util.h"
+#include "formats-util.h"
 #include "logind.h"
+#include "selinux-util.h"
+#include "signal-util.h"
+#include "strv.h"
 #include "udev-util.h"
 
-Manager *manager_new(void) {
-        Manager *m;
-        int r;
+/// additional includes elogind needs
+#include "cgroup.h"       // From src/core/
+#include "label.h"
+#include "mount-setup.h"  // From src/core
+#include "musl_missing.h"
 
-        m = new0(Manager, 1);
-        if (!m)
-                return NULL;
+static void manager_free(Manager *m);
 
-        m->console_active_fd = -1;
-        m->reserve_vt_fd = -1;
+static void manager_reset_config(Manager *m) {
 
+#ifdef ENABLE_DEBUG_ELOGIND
+        int dbg_cnt;
+#endif // ENABLE_DEBUG_ELOGIND
+
+#if 0 /// elogind does not support autospawning of vts
         m->n_autovts = 6;
         m->reserve_vt = 6;
+#endif // 0
+        m->remove_ipc = true;
         m->inhibit_delay_max = 5 * USEC_PER_SEC;
         m->handle_power_key = HANDLE_POWEROFF;
         m->handle_suspend_key = HANDLE_SUSPEND;
         m->handle_hibernate_key = HANDLE_HIBERNATE;
         m->handle_lid_switch = HANDLE_SUSPEND;
+        m->handle_lid_switch_docked = HANDLE_IGNORE;
+        m->power_key_ignore_inhibited = false;
+        m->suspend_key_ignore_inhibited = false;
+        m->hibernate_key_ignore_inhibited = false;
         m->lid_switch_ignore_inhibited = true;
 
+        m->holdoff_timeout_usec = 30 * USEC_PER_SEC;
+
         m->idle_action_usec = 30 * USEC_PER_MINUTE;
         m->idle_action = HANDLE_IGNORE;
+
+        m->runtime_dir_size = physical_memory_scale(10U, 100U); /* 10% */
+        m->user_tasks_max = system_tasks_max_scale(33U, 100U); /* 33% */
+        m->sessions_max = 8192;
+        m->inhibitors_max = 8192;
+
+        m->kill_user_processes = KILL_USER_PROCESSES;
+
+        m->kill_only_users = strv_free(m->kill_only_users);
+        m->kill_exclude_users = strv_free(m->kill_exclude_users);
+
+        /* Set default Sleep config if not already set by logind.conf */
+        if (!m->suspend_state)
+                m->suspend_state = strv_new("mem", "standby", "freeze", NULL);
+        if (!m->hibernate_mode)
+                m->hibernate_mode = strv_new("platform", "shutdown", NULL);
+        if (!m->hibernate_state)
+                m->hibernate_state = strv_new("disk", NULL);
+        if (!m->hybrid_sleep_mode)
+                m->hybrid_sleep_mode = strv_new("suspend", "platform", "shutdown", NULL);
+        if (!m->hybrid_sleep_state)
+                m->hybrid_sleep_state = strv_new("disk", NULL);
+
+#ifdef ENABLE_DEBUG_ELOGIND
+        dbg_cnt = -1;
+        while (m->suspend_mode && m->suspend_mode[++dbg_cnt])
+                log_debug_elogind("suspend_mode[%d] = %s",
+                                  dbg_cnt, m->suspend_mode[dbg_cnt]);
+        dbg_cnt = -1;
+        while (m->suspend_state[++dbg_cnt])
+                log_debug_elogind("suspend_state[%d] = %s",
+                                  dbg_cnt, m->suspend_state[dbg_cnt]);
+        dbg_cnt = -1;
+        while (m->hibernate_mode[++dbg_cnt])
+                log_debug_elogind("hibernate_mode[%d] = %s",
+                                  dbg_cnt, m->hibernate_mode[dbg_cnt]);
+        dbg_cnt = -1;
+        while (m->hibernate_state[++dbg_cnt])
+                log_debug_elogind("hibernate_state[%d] = %s",
+                                  dbg_cnt, m->hibernate_state[dbg_cnt]);
+        dbg_cnt = -1;
+        while (m->hybrid_sleep_mode[++dbg_cnt])
+                log_debug_elogind("hybrid_sleep_mode[%d] = %s",
+                                  dbg_cnt, m->hybrid_sleep_mode[dbg_cnt]);
+        dbg_cnt = -1;
+        while (m->hybrid_sleep_state[++dbg_cnt])
+                log_debug_elogind("hybrid_sleep_state[%d] = %s",
+                                  dbg_cnt, m->hybrid_sleep_state[dbg_cnt]);
+#endif // ENABLE_DEBUG_ELOGIND
+}
+
+static Manager *manager_new(void) {
+        Manager *m;
+        int r;
+
+        m = new0(Manager, 1);
+        if (!m)
+                return NULL;
+
+        m->pin_cgroupfs_fd = -1;
+        m->console_active_fd = -1;
+#if 0 /// UNNEEDED by elogind
+        m->reserve_vt_fd = -1;
+#endif // 0
+
         m->idle_action_not_before_usec = now(CLOCK_MONOTONIC);
 
-        m->devices = hashmap_new(string_hash_func, string_compare_func);
-        m->seats = hashmap_new(string_hash_func, string_compare_func);
-        m->sessions = hashmap_new(string_hash_func, string_compare_func);
-        m->users = hashmap_new(trivial_hash_func, trivial_compare_func);
-        m->inhibitors = hashmap_new(string_hash_func, string_compare_func);
-        m->buttons = hashmap_new(string_hash_func, string_compare_func);
+        m->devices = hashmap_new(&string_hash_ops);
+        m->seats = hashmap_new(&string_hash_ops);
+        m->sessions = hashmap_new(&string_hash_ops);
+        m->users = hashmap_new(NULL);
+        m->inhibitors = hashmap_new(&string_hash_ops);
+        m->buttons = hashmap_new(&string_hash_ops);
 
-        m->user_units = hashmap_new(string_hash_func, string_compare_func);
-        m->session_units = hashmap_new(string_hash_func, string_compare_func);
+        m->user_units = hashmap_new(&string_hash_ops);
+        m->session_units = hashmap_new(&string_hash_ops);
 
-        m->busnames = set_new(string_hash_func, string_compare_func);
+        m->test_run   = false;
 
-        if (!m->devices || !m->seats || !m->sessions || !m->users || !m->inhibitors || !m->buttons || !m->busnames ||
-            !m->user_units || !m->session_units ||
-            !m->busnames) {
-                manager_free(m);
-                return NULL;
-        }
+        if (!m->devices || !m->seats || !m->sessions || !m->users || !m->inhibitors || !m->buttons || !m->user_units || !m->session_units)
+                goto fail;
 
-        m->kill_exclude_users = strv_new("root", NULL);
-        if (!m->kill_exclude_users) {
-                manager_free(m);
-                return NULL;
+        /* If elogind should be its own controller, mount its cgroup */
+        if (streq(SYSTEMD_CGROUP_CONTROLLER, "name=elogind")) {
+                r = mount_setup(true);
+                if (r < 0)
+                        goto fail;
         }
 
+        /* Make cgroups */
+        r = manager_setup_cgroup(m);
+        if (r < 0)
+                goto fail;
+
+        m->suspend_mode       = NULL;
+        m->suspend_state      = NULL;
+        m->hibernate_mode     = NULL;
+        m->hibernate_state    = NULL;
+        m->hybrid_sleep_mode  = NULL;
+        m->hybrid_sleep_state = NULL;
+
         m->udev = udev_new();
-        if (!m->udev) {
-                manager_free(m);
-                return NULL;
-        }
+        if (!m->udev)
+                goto fail;
 
         r = sd_event_default(&m->event);
-        if (r < 0) {
-                manager_free(m);
-                return NULL;
-        }
+        if (r < 0)
+                goto fail;
 
         sd_event_set_watchdog(m->event, true);
 
+        manager_reset_config(m);
+
         return m;
+
+fail:
+        manager_free(m);
+        return NULL;
 }
 
-void manager_free(Manager *m) {
+static void manager_free(Manager *m) {
         Session *session;
         User *u;
         Device *d;
@@ -140,43 +235,59 @@ void manager_free(Manager *m) {
         hashmap_free(m->user_units);
         hashmap_free(m->session_units);
 
-        set_free_free(m->busnames);
-
         sd_event_source_unref(m->idle_action_event_source);
+        sd_event_source_unref(m->inhibit_timeout_source);
+        sd_event_source_unref(m->scheduled_shutdown_timeout_source);
+        sd_event_source_unref(m->nologin_timeout_source);
+        sd_event_source_unref(m->wall_message_timeout_source);
 
         sd_event_source_unref(m->console_active_event_source);
         sd_event_source_unref(m->udev_seat_event_source);
         sd_event_source_unref(m->udev_device_event_source);
         sd_event_source_unref(m->udev_vcsa_event_source);
         sd_event_source_unref(m->udev_button_event_source);
+        sd_event_source_unref(m->lid_switch_ignore_event_source);
+
+        safe_close(m->console_active_fd);
 
-        if (m->console_active_fd >= 0)
-                close_nointr_nofail(m->console_active_fd);
+        udev_monitor_unref(m->udev_seat_monitor);
+        udev_monitor_unref(m->udev_device_monitor);
+        udev_monitor_unref(m->udev_vcsa_monitor);
+        udev_monitor_unref(m->udev_button_monitor);
 
-        if (m->udev_seat_monitor)
-                udev_monitor_unref(m->udev_seat_monitor);
-        if (m->udev_device_monitor)
-                udev_monitor_unref(m->udev_device_monitor);
-        if (m->udev_vcsa_monitor)
-                udev_monitor_unref(m->udev_vcsa_monitor);
-        if (m->udev_button_monitor)
-                udev_monitor_unref(m->udev_button_monitor);
+        udev_unref(m->udev);
 
-        if (m->udev)
-                udev_unref(m->udev);
+        if (m->unlink_nologin)
+                (void) unlink("/run/nologin");
 
-        bus_verify_polkit_async_registry_free(m->bus, m->polkit_registry);
+        bus_verify_polkit_async_registry_free(m->polkit_registry);
 
         sd_bus_unref(m->bus);
         sd_event_unref(m->event);
 
-        if (m->reserve_vt_fd >= 0)
-                close_nointr_nofail(m->reserve_vt_fd);
+#if 0 /// elogind does not support autospawning of vts
+        safe_close(m->reserve_vt_fd);
+#endif // 0
+
+        manager_shutdown_cgroup(m, true);
 
         strv_free(m->kill_only_users);
         strv_free(m->kill_exclude_users);
 
+        free(m->scheduled_shutdown_type);
+        free(m->scheduled_shutdown_tty);
+        free(m->wall_message);
+
+        strv_free(m->suspend_mode);
+        strv_free(m->suspend_state);
+        strv_free(m->hibernate_mode);
+        strv_free(m->hibernate_state);
+        strv_free(m->hybrid_sleep_mode);
+        strv_free(m->hybrid_sleep_state);
+
+#if 0 /// UNNEEDED by elogind
         free(m->action_job);
+#endif // 0
         free(m);
 }
 
@@ -198,6 +309,10 @@ static int manager_enumerate_devices(Manager *m) {
         if (r < 0)
                 return r;
 
+        r = udev_enumerate_add_match_is_initialized(e);
+        if (r < 0)
+                return r;
+
         r = udev_enumerate_scan_devices(e);
         if (r < 0)
                 return r;
@@ -211,9 +326,6 @@ static int manager_enumerate_devices(Manager *m) {
                 if (!d)
                         return -ENOMEM;
 
-                if (!udev_device_get_is_initialized(d))
-                        continue;
-
                 k = manager_process_seat_device(m, d);
                 if (k < 0)
                         r = k;
@@ -234,7 +346,8 @@ static int manager_enumerate_buttons(Manager *m) {
         if (m->handle_power_key == HANDLE_IGNORE &&
             m->handle_suspend_key == HANDLE_IGNORE &&
             m->handle_hibernate_key == HANDLE_IGNORE &&
-            m->handle_lid_switch == HANDLE_IGNORE)
+            m->handle_lid_switch == HANDLE_IGNORE &&
+            m->handle_lid_switch_docked == HANDLE_IGNORE)
                 return 0;
 
         e = udev_enumerate_new(m->udev);
@@ -249,6 +362,10 @@ static int manager_enumerate_buttons(Manager *m) {
         if (r < 0)
                 return r;
 
+        r = udev_enumerate_add_match_is_initialized(e);
+        if (r < 0)
+                return r;
+
         r = udev_enumerate_scan_devices(e);
         if (r < 0)
                 return r;
@@ -262,9 +379,6 @@ static int manager_enumerate_buttons(Manager *m) {
                 if (!d)
                         return -ENOMEM;
 
-                if (!udev_device_get_is_initialized(d))
-                        continue;
-
                 k = manager_process_button_device(m, d);
                 if (k < 0)
                         r = k;
@@ -289,8 +403,7 @@ static int manager_enumerate_seats(Manager *m) {
                 if (errno == ENOENT)
                         return 0;
 
-                log_error("Failed to open /run/systemd/seats: %m");
-                return -errno;
+                return log_error_errno(errno, "Failed to open /run/systemd/seats: %m");
         }
 
         FOREACH_DIRENT(de, d, return -errno) {
@@ -326,8 +439,7 @@ static int manager_enumerate_linger_users(Manager *m) {
                 if (errno == ENOENT)
                         return 0;
 
-                log_error("Failed to open /var/lib/systemd/linger/: %m");
-                return -errno;
+                return log_error_errno(errno, "Failed to open /var/lib/systemd/linger/: %m");
         }
 
         FOREACH_DIRENT(de, d, return -errno) {
@@ -338,7 +450,7 @@ static int manager_enumerate_linger_users(Manager *m) {
 
                 k = manager_add_user_by_name(m, de->d_name, NULL);
                 if (k < 0) {
-                        log_notice("Couldn't add lingering user %s: %s", de->d_name, strerror(-k));
+                        log_notice_errno(k, "Couldn't add lingering user %s: %m", de->d_name);
                         r = k;
                 }
         }
@@ -362,8 +474,7 @@ static int manager_enumerate_users(Manager *m) {
                 if (errno == ENOENT)
                         return 0;
 
-                log_error("Failed to open /run/systemd/users: %m");
-                return -errno;
+                return log_error_errno(errno, "Failed to open /run/systemd/users: %m");
         }
 
         FOREACH_DIRENT(de, d, return -errno) {
@@ -374,7 +485,7 @@ static int manager_enumerate_users(Manager *m) {
 
                 k = manager_add_user_by_name(m, de->d_name, &u);
                 if (k < 0) {
-                        log_error("Failed to add user by file name %s: %s", de->d_name, strerror(-k));
+                        log_error_errno(k, "Failed to add user by file name %s: %m", de->d_name);
 
                         r = k;
                         continue;
@@ -403,8 +514,7 @@ static int manager_enumerate_sessions(Manager *m) {
                 if (errno == ENOENT)
                         return 0;
 
-                log_error("Failed to open /run/systemd/sessions: %m");
-                return -errno;
+                return log_error_errno(errno, "Failed to open /run/systemd/sessions: %m");
         }
 
         FOREACH_DIRENT(de, d, return -errno) {
@@ -422,7 +532,7 @@ static int manager_enumerate_sessions(Manager *m) {
 
                 k = manager_add_session(m, de->d_name, &s);
                 if (k < 0) {
-                        log_error("Failed to add session by file name %s: %s", de->d_name, strerror(-k));
+                        log_error_errno(k, "Failed to add session by file name %s: %m", de->d_name);
 
                         r = k;
                         continue;
@@ -450,8 +560,7 @@ static int manager_enumerate_inhibitors(Manager *m) {
                 if (errno == ENOENT)
                         return 0;
 
-                log_error("Failed to open /run/systemd/inhibit: %m");
-                return -errno;
+                return log_error_errno(errno, "Failed to open /run/systemd/inhibit: %m");
         }
 
         FOREACH_DIRENT(de, d, return -errno) {
@@ -463,7 +572,7 @@ static int manager_enumerate_inhibitors(Manager *m) {
 
                 k = manager_add_inhibitor(m, de->d_name, &i);
                 if (k < 0) {
-                        log_notice("Couldn't add inhibitor %s: %s", de->d_name, strerror(-k));
+                        log_notice_errno(k, "Couldn't add inhibitor %s: %m", de->d_name);
                         r = k;
                         continue;
                 }
@@ -504,6 +613,7 @@ static int manager_dispatch_device_udev(sd_event_source *s, int fd, uint32_t rev
         return 0;
 }
 
+#if 0 /// UNNEEDED by elogind
 static int manager_dispatch_vcsa_udev(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
         _cleanup_udev_device_unref_ struct udev_device *d = NULL;
         Manager *m = userdata;
@@ -525,6 +635,7 @@ static int manager_dispatch_vcsa_udev(sd_event_source *s, int fd, uint32_t reven
 
         return 0;
 }
+#endif // 0
 
 static int manager_dispatch_button_udev(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
         _cleanup_udev_device_unref_ struct udev_device *d = NULL;
@@ -551,6 +662,7 @@ static int manager_dispatch_console(sd_event_source *s, int fd, uint32_t revents
         return 0;
 }
 
+#if 0 /// UNNEEDED by elogind
 static int manager_reserve_vt(Manager *m) {
         _cleanup_free_ char *p = NULL;
 
@@ -567,126 +679,146 @@ static int manager_reserve_vt(Manager *m) {
 
                 /* Don't complain on VT-less systems */
                 if (errno != ENOENT)
-                        log_warning("Failed to pin reserved VT: %m");
+                        log_warning_errno(errno, "Failed to pin reserved VT: %m");
                 return -errno;
         }
 
         return 0;
 }
+#endif // 0
 
-static int manager_connect_bus(Manager *m) {
-        _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
+static int signal_agent_released(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+        _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
+        Manager *m = userdata;
+        const char *cgroup;
+        Session *s;
+        uid_t sender_uid;
         int r;
 
+        assert(message);
         assert(m);
-        assert(!m->bus);
 
-        r = sd_bus_default_system(&m->bus);
-        if (r < 0) {
-                log_error("Failed to connect to system bus: %s", strerror(-r));
+        /* only accept org.freedesktop.systemd1.Agent from UID=0 */
+        r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_EUID, &creds);
+        if (r < 0)
                 return r;
-        }
 
-        r = sd_bus_add_object_vtable(m->bus, "/org/freedesktop/login1", "org.freedesktop.login1.Manager", manager_vtable, m);
-        if (r < 0) {
-                log_error("Failed to add manager object vtable: %s", strerror(-r));
-                return r;
-        }
+        r = sd_bus_creds_get_euid(creds, &sender_uid);
+        if (r < 0 || sender_uid != 0)
+                return 0;
 
-        r = sd_bus_add_fallback_vtable(m->bus, "/org/freedesktop/login1/seat", "org.freedesktop.login1.Seat", seat_vtable, seat_object_find, m);
+        /* parse 'cgroup-empty' notification */
+        r = sd_bus_message_read(message, "s", &cgroup);
         if (r < 0) {
-                log_error("Failed to add seat object vtable: %s", strerror(-r));
-                return r;
+                bus_log_parse_error(r);
+                return 0;
         }
 
-        r = sd_bus_add_node_enumerator(m->bus, "/org/freedesktop/login1/seat", seat_node_enumerator, m);
-        if (r < 0) {
-                log_error("Failed to add seat enumerator: %s", strerror(-r));
-                return r;
-        }
+        s = hashmap_get(m->sessions, cgroup);
 
-        r = sd_bus_add_fallback_vtable(m->bus, "/org/freedesktop/login1/session", "org.freedesktop.login1.Session", session_vtable, session_object_find, m);
-        if (r < 0) {
-                log_error("Failed to add session object vtable: %s", strerror(-r));
-                return r;
+        if (!s) {
+                log_warning("Session not found: %s", cgroup);
+                return 0;
         }
 
-        r = sd_bus_add_node_enumerator(m->bus, "/org/freedesktop/login1/session", session_node_enumerator, m);
-        if (r < 0) {
-                log_error("Failed to add session enumerator: %s", strerror(-r));
-                return r;
-        }
+        session_finalize(s);
+        session_free(s);
 
-        r = sd_bus_add_fallback_vtable(m->bus, "/org/freedesktop/login1/user", "org.freedesktop.login1.User", user_vtable, user_object_find, m);
-        if (r < 0) {
-                log_error("Failed to add user object vtable: %s", strerror(-r));
-                return r;
-        }
+        return 0;
+}
 
-        r = sd_bus_add_node_enumerator(m->bus, "/org/freedesktop/login1/user", user_node_enumerator, m);
-        if (r < 0) {
-                log_error("Failed to add user enumerator: %s", strerror(-r));
-                return r;
-        }
+static int manager_connect_bus(Manager *m) {
+        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+        int r;
 
-        r = sd_bus_add_match(m->bus,
-                             "type='signal',"
-                             "sender='org.freedesktop.DBus',"
-                             "interface='org.freedesktop.DBus',"
-                             "member='NameOwnerChanged',"
-                             "path='/org/freedesktop/DBus'",
-                             match_name_owner_changed, m);
-        if (r < 0) {
-                log_error("Failed to add match for NameOwnerChanged: %s", strerror(-r));
-                return 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 = sd_bus_add_object_vtable(m->bus, NULL, "/org/freedesktop/login1", "org.freedesktop.login1.Manager", manager_vtable, m);
+        if (r < 0)
+                return log_error_errno(r, "Failed to add manager object vtable: %m");
+
+        /* elogind relies on signals from its release agent */
+        r = sd_bus_add_match(
+                        m->bus,
+                        NULL,
+                        "type='signal',"
+                        "interface='org.freedesktop.elogind.Agent',"
+                        "member='Released',"
+                        "path='/org/freedesktop/elogind/agent'",
+                        signal_agent_released, m);
+
+        r = sd_bus_add_fallback_vtable(m->bus, NULL, "/org/freedesktop/login1/seat", "org.freedesktop.login1.Seat", seat_vtable, seat_object_find, m);
+        if (r < 0)
+                return log_error_errno(r, "Failed to add seat object vtable: %m");
+
+        r = sd_bus_add_node_enumerator(m->bus, NULL, "/org/freedesktop/login1/seat", seat_node_enumerator, m);
+        if (r < 0)
+                return log_error_errno(r, "Failed to add seat enumerator: %m");
+
+        r = sd_bus_add_fallback_vtable(m->bus, NULL, "/org/freedesktop/login1/session", "org.freedesktop.login1.Session", session_vtable, session_object_find, m);
+        if (r < 0)
+                return log_error_errno(r, "Failed to add session object vtable: %m");
+
+        r = sd_bus_add_node_enumerator(m->bus, NULL, "/org/freedesktop/login1/session", session_node_enumerator, m);
+        if (r < 0)
+                return log_error_errno(r, "Failed to add session enumerator: %m");
+
+        r = sd_bus_add_fallback_vtable(m->bus, NULL, "/org/freedesktop/login1/user", "org.freedesktop.login1.User", user_vtable, user_object_find, m);
+        if (r < 0)
+                return log_error_errno(r, "Failed to add user object vtable: %m");
+
+        r = sd_bus_add_node_enumerator(m->bus, NULL, "/org/freedesktop/login1/user", user_node_enumerator, m);
+        if (r < 0)
+                return log_error_errno(r, "Failed to add user enumerator: %m");
+
+#if 0 /// elogind does not support systemd as PID 1
         r = sd_bus_add_match(m->bus,
+                             NULL,
                              "type='signal',"
                              "sender='org.freedesktop.systemd1',"
                              "interface='org.freedesktop.systemd1.Manager',"
                              "member='JobRemoved',"
                              "path='/org/freedesktop/systemd1'",
                              match_job_removed, m);
-        if (r < 0) {
-                log_error("Failed to add match for JobRemoved: %s", strerror(-r));
-                return r;
-        }
+        if (r < 0)
+                return log_error_errno(r, "Failed to add match for JobRemoved: %m");
 
         r = sd_bus_add_match(m->bus,
+                             NULL,
                              "type='signal',"
                              "sender='org.freedesktop.systemd1',"
                              "interface='org.freedesktop.systemd1.Manager',"
                              "member='UnitRemoved',"
                              "path='/org/freedesktop/systemd1'",
                              match_unit_removed, m);
-        if (r < 0) {
-                log_error("Failed to add match for UnitRemoved: %s", strerror(-r));
-                return r;
-        }
+        if (r < 0)
+                return log_error_errno(r, "Failed to add match for UnitRemoved: %m");
 
         r = sd_bus_add_match(m->bus,
+                             NULL,
                              "type='signal',"
                              "sender='org.freedesktop.systemd1',"
                              "interface='org.freedesktop.DBus.Properties',"
                              "member='PropertiesChanged'",
                              match_properties_changed, m);
-        if (r < 0) {
-                log_error("Failed to add match for PropertiesChanged: %s", strerror(-r));
-                return r;
-        }
+        if (r < 0)
+                return log_error_errno(r, "Failed to add match for PropertiesChanged: %m");
 
         r = sd_bus_add_match(m->bus,
+                             NULL,
                              "type='signal',"
                              "sender='org.freedesktop.systemd1',"
                              "interface='org.freedesktop.systemd1.Manager',"
                              "member='Reloading',"
                              "path='/org/freedesktop/systemd1'",
                              match_reloading, m);
-        if (r < 0) {
-                log_error("Failed to add match for Reloading: %s", strerror(-r));
-                return r;
-        }
+        if (r < 0)
+                return log_error_errno(r, "Failed to add match for Reloading: %m");
 
         r = sd_bus_call_method(
                         m->bus,
@@ -700,17 +832,55 @@ static int manager_connect_bus(Manager *m) {
                 log_error("Failed to enable subscription: %s", bus_error_message(&error, r));
                 return r;
         }
+#endif // 0
 
         r = sd_bus_request_name(m->bus, "org.freedesktop.login1", 0);
-        if (r < 0) {
-                log_error("Failed to register name: %s", strerror(-r));
-                return r;
+        if (r < 0)
+                return log_error_errno(r, "Failed to register 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");
+
+        return 0;
+}
+
+static int manager_vt_switch(sd_event_source *src, const struct signalfd_siginfo *si, void *data) {
+        Manager *m = data;
+        Session *active, *iter;
+
+        /*
+         * We got a VT-switch signal and we have to acknowledge it immediately.
+         * Preferably, we'd just use m->seat0->active->vtfd, but unfortunately,
+         * old user-space might run multiple sessions on a single VT, *sigh*.
+         * Therefore, we have to iterate all sessions and find one with a vtfd
+         * on the requested VT.
+         * As only VTs with active controllers have VT_PROCESS set, our current
+         * notion of the active VT might be wrong (for instance if the switch
+         * happens while we setup VT_PROCESS). Therefore, read the current VT
+         * first and then use s->active->vtnr as reference. Note that this is
+         * not racy, as no further VT-switch can happen as long as we're in
+         * synchronous VT_PROCESS mode.
+         */
+
+        assert(m->seat0);
+        seat_read_active_vt(m->seat0);
+
+        active = m->seat0->active;
+        if (!active || active->vtnr < 1) {
+                log_warning("Received VT_PROCESS signal without a registered session on that VT.");
+                return 0;
         }
 
-        r = sd_bus_attach_event(m->bus, m->event, 0);
-        if (r < 0) {
-                log_error("Failed to attach bus to event loop: %s", strerror(-r));
-                return r;
+        if (active->vtfd >= 0) {
+                session_leave_vt(active);
+        } else {
+                LIST_FOREACH(sessions_by_seat, iter, m->seat0->sessions) {
+                        if (iter->vtnr == active->vtnr && iter->vtfd >= 0) {
+                                session_leave_vt(iter);
+                                break;
+                        }
+                }
         }
 
         return 0;
@@ -736,16 +906,34 @@ static int manager_connect_console(Manager *m) {
                 if (errno == ENOENT)
                         return 0;
 
-                log_error("Failed to open /sys/class/tty/tty0/active: %m");
-                return -errno;
+                return log_error_errno(errno, "Failed to open /sys/class/tty/tty0/active: %m");
         }
 
-        r = sd_event_add_io(m->event, m->console_active_fd, 0, manager_dispatch_console, m, &m->console_active_event_source);
+        r = sd_event_add_io(m->event, &m->console_active_event_source, m->console_active_fd, 0, manager_dispatch_console, m);
         if (r < 0) {
                 log_error("Failed to watch foreground console");
                 return r;
         }
 
+        /*
+         * SIGRTMIN is used as global VT-release signal, SIGRTMIN + 1 is used
+         * as VT-acquire signal. We ignore any acquire-events (yes, we still
+         * have to provide a valid signal-number for it!) and acknowledge all
+         * release events immediately.
+         */
+
+        if (SIGRTMIN + 1 > SIGRTMAX) {
+                log_error("Not enough real-time signals available: %u-%u", SIGRTMIN, SIGRTMAX);
+                return -EINVAL;
+        }
+
+        assert_se(ignore_signals(SIGRTMIN + 1, -1) >= 0);
+        assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGRTMIN, -1) >= 0);
+
+        r = sd_event_add_signal(m->event, NULL, SIGRTMIN, manager_vt_switch, m);
+        if (r < 0)
+                return r;
+
         return 0;
 }
 
@@ -770,7 +958,7 @@ static int manager_connect_udev(Manager *m) {
         if (r < 0)
                 return r;
 
-        r = sd_event_add_io(m->event, udev_monitor_get_fd(m->udev_seat_monitor), EPOLLIN, manager_dispatch_seat_udev, m, &m->udev_seat_event_source);
+        r = sd_event_add_io(m->event, &m->udev_seat_event_source, udev_monitor_get_fd(m->udev_seat_monitor), EPOLLIN, manager_dispatch_seat_udev, m);
         if (r < 0)
                 return r;
 
@@ -794,7 +982,7 @@ static int manager_connect_udev(Manager *m) {
         if (r < 0)
                 return r;
 
-        r = sd_event_add_io(m->event, udev_monitor_get_fd(m->udev_device_monitor), EPOLLIN, manager_dispatch_device_udev, m, &m->udev_device_event_source);
+        r = sd_event_add_io(m->event, &m->udev_device_event_source, udev_monitor_get_fd(m->udev_device_monitor), EPOLLIN, manager_dispatch_device_udev, m);
         if (r < 0)
                 return r;
 
@@ -802,7 +990,8 @@ static int manager_connect_udev(Manager *m) {
         if (m->handle_power_key != HANDLE_IGNORE ||
             m->handle_suspend_key != HANDLE_IGNORE ||
             m->handle_hibernate_key != HANDLE_IGNORE ||
-            m->handle_lid_switch != HANDLE_IGNORE) {
+            m->handle_lid_switch != HANDLE_IGNORE ||
+            m->handle_lid_switch_docked != HANDLE_IGNORE) {
 
                 m->udev_button_monitor = udev_monitor_new_from_netlink(m->udev, "udev");
                 if (!m->udev_button_monitor)
@@ -820,12 +1009,13 @@ static int manager_connect_udev(Manager *m) {
                 if (r < 0)
                         return r;
 
-                r = sd_event_add_io(m->event, udev_monitor_get_fd(m->udev_button_monitor), EPOLLIN, manager_dispatch_button_udev, m, &m->udev_button_event_source);
+                r = sd_event_add_io(m->event, &m->udev_button_event_source, udev_monitor_get_fd(m->udev_button_monitor), EPOLLIN, manager_dispatch_button_udev, m);
                 if (r < 0)
                         return r;
         }
 
         /* Don't bother watching VCSA devices, if nobody cares */
+#if 0 /// elogind does not support autospawning of vts
         if (m->n_autovts > 0 && m->console_active_fd >= 0) {
 
                 m->udev_vcsa_monitor = udev_monitor_new_from_netlink(m->udev, "udev");
@@ -840,15 +1030,16 @@ static int manager_connect_udev(Manager *m) {
                 if (r < 0)
                         return r;
 
-                r = sd_event_add_io(m->event, udev_monitor_get_fd(m->udev_vcsa_monitor), EPOLLIN, manager_dispatch_vcsa_udev, m, &m->udev_vcsa_event_source);
+                r = sd_event_add_io(m->event, &m->udev_vcsa_event_source, udev_monitor_get_fd(m->udev_vcsa_monitor), EPOLLIN, manager_dispatch_vcsa_udev, m);
                 if (r < 0)
                         return r;
         }
+#endif // 0
 
         return 0;
 }
 
-void manager_gc(Manager *m, bool drop_not_started) {
+static void manager_gc(Manager *m, bool drop_not_started) {
         Seat *seat;
         Session *session;
         User *user;
@@ -860,7 +1051,7 @@ void manager_gc(Manager *m, bool drop_not_started) {
                 seat->in_gc_queue = false;
 
                 if (!seat_check_gc(seat, drop_not_started)) {
-                        seat_stop(seat);
+                        seat_stop(seat, false);
                         seat_free(seat);
                 }
         }
@@ -869,8 +1060,15 @@ void manager_gc(Manager *m, bool drop_not_started) {
                 LIST_REMOVE(gc_queue, m->session_gc_queue, session);
                 session->in_gc_queue = false;
 
+                /* First, if we are not closing yet, initiate stopping */
+                if (!session_check_gc(session, drop_not_started) &&
+                    session_get_state(session) != SESSION_CLOSING)
+                        session_stop(session, false);
+
+                /* Normally, this should make the session referenced
+                 * again, if it doesn't then let's get rid of it
+                 * immediately */
                 if (!session_check_gc(session, drop_not_started)) {
-                        session_stop(session);
                         session_finalize(session);
                         session_free(session);
                 }
@@ -880,8 +1078,12 @@ void manager_gc(Manager *m, bool drop_not_started) {
                 LIST_REMOVE(gc_queue, m->user_gc_queue, user);
                 user->in_gc_queue = false;
 
+                /* First step: queue stop jobs */
+                if (!user_check_gc(user, drop_not_started))
+                        user_stop(user, false);
+
+                /* Second step: finalize user */
                 if (!user_check_gc(user, drop_not_started)) {
-                        user_stop(user);
                         user_finalize(user);
                         user_free(user);
                 }
@@ -923,44 +1125,85 @@ static int manager_dispatch_idle_action(sd_event_source *s, uint64_t t, void *us
 
         if (!m->idle_action_event_source) {
 
-                r = sd_event_add_monotonic(m->event, elapse, USEC_PER_SEC*30, manager_dispatch_idle_action, m, &m->idle_action_event_source);
-                if (r < 0) {
-                        log_error("Failed to add idle event source: %s", strerror(-r));
-                        return r;
-                }
+                r = sd_event_add_time(
+                                m->event,
+                                &m->idle_action_event_source,
+                                CLOCK_MONOTONIC,
+                                elapse, USEC_PER_SEC*30,
+                                manager_dispatch_idle_action, m);
+                if (r < 0)
+                        return log_error_errno(r, "Failed to add idle event source: %m");
 
                 r = sd_event_source_set_priority(m->idle_action_event_source, SD_EVENT_PRIORITY_IDLE+10);
-                if (r < 0) {
-                        log_error("Failed to set idle event source priority: %s", strerror(-r));
-                        return r;
-                }
+                if (r < 0)
+                        return log_error_errno(r, "Failed to set idle event source priority: %m");
         } else {
                 r = sd_event_source_set_time(m->idle_action_event_source, elapse);
-                if (r < 0) {
-                        log_error("Failed to set idle event timer: %s", strerror(-r));
-                        return r;
-                }
+                if (r < 0)
+                        return log_error_errno(r, "Failed to set idle event timer: %m");
 
                 r = sd_event_source_set_enabled(m->idle_action_event_source, SD_EVENT_ONESHOT);
-                if (r < 0) {
-                        log_error("Failed to enable idle event timer: %s", strerror(-r));
-                        return r;
-                }
+                if (r < 0)
+                        return log_error_errno(r, "Failed to enable idle event timer: %m");
         }
 
         return 0;
 }
 
-int manager_startup(Manager *m) {
+static int manager_parse_config_file(Manager *m) {
+#if 0 /// elogind parses its own config file
+        assert(m);
+
+        return config_parse_many(PKGSYSCONFDIR "/logind.conf",
+                                 CONF_PATHS_NULSTR("systemd/logind.conf.d"),
+                                 "Login\0",
+                                 config_item_perf_lookup, logind_gperf_lookup,
+                                 false, m);
+#else
+         const char* logind_conf = getenv("ELOGIND_CONF_FILE");
+
+         assert(m);
+
+         if (!logind_conf)
+                 logind_conf = PKGSYSCONFDIR "/logind.conf";
+
+         return config_parse(NULL, logind_conf, NULL, "Login\0Sleep\0",
+                             config_item_perf_lookup, logind_gperf_lookup,
+                             false, false, true, m);
+#endif // 0
+}
+
+static int manager_dispatch_reload_signal(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
+        Manager *m = userdata;
+        int r;
+
+        manager_reset_config(m);
+        r = manager_parse_config_file(m);
+        if (r < 0)
+                log_warning_errno(r, "Failed to parse config file, using defaults: %m");
+        else
+                log_info("Config file reloaded.");
+
+        return 0;
+}
+
+static int manager_startup(Manager *m) {
         int r;
         Seat *seat;
         Session *session;
         User *user;
+        Button *button;
         Inhibitor *inhibitor;
         Iterator i;
 
         assert(m);
 
+        assert_se(sigprocmask_many(SIG_SETMASK, NULL, SIGHUP, -1) >= 0);
+
+        r = sd_event_add_signal(m->event, NULL, SIGHUP, manager_dispatch_reload_signal, m);
+        if (r < 0)
+                return log_error_errno(r, "Failed to register SIGHUP handler: %m");
+
         /* Connect to console */
         r = manager_connect_console(m);
         if (r < 0)
@@ -968,10 +1211,8 @@ int manager_startup(Manager *m) {
 
         /* Connect to udev */
         r = manager_connect_udev(m);
-        if (r < 0) {
-                log_error("Failed to create udev watchers: %s", strerror(-r));
-                return r;
-        }
+        if (r < 0)
+                return log_error_errno(r, "Failed to create udev watchers: %m");
 
         /* Connect to the bus */
         r = manager_connect_bus(m);
@@ -980,41 +1221,45 @@ int manager_startup(Manager *m) {
 
         /* Instantiate magic seat 0 */
         r = manager_add_seat(m, "seat0", &m->seat0);
-        if (r < 0) {
-                log_error("Failed to add seat0: %s", strerror(-r));
-                return r;
-        }
+        if (r < 0)
+                return log_error_errno(r, "Failed to add seat0: %m");
+
+        r = manager_set_lid_switch_ignore(m, 0 + m->holdoff_timeout_usec);
+        if (r < 0)
+                log_warning_errno(r, "Failed to set up lid switch ignore event source: %m");
 
         /* Deserialize state */
         r = manager_enumerate_devices(m);
         if (r < 0)
-                log_warning("Device enumeration failed: %s", strerror(-r));
+                log_warning_errno(r, "Device enumeration failed: %m");
 
         r = manager_enumerate_seats(m);
         if (r < 0)
-                log_warning("Seat enumeration failed: %s", strerror(-r));
+                log_warning_errno(r, "Seat enumeration failed: %m");
 
         r = manager_enumerate_users(m);
         if (r < 0)
-                log_warning("User enumeration failed: %s", strerror(-r));
+                log_warning_errno(r, "User enumeration failed: %m");
 
         r = manager_enumerate_sessions(m);
         if (r < 0)
-                log_warning("Session enumeration failed: %s", strerror(-r));
+                log_warning_errno(r, "Session enumeration failed: %m");
 
         r = manager_enumerate_inhibitors(m);
         if (r < 0)
-                log_warning("Inhibitor enumeration failed: %s", strerror(-r));
+                log_warning_errno(r, "Inhibitor enumeration failed: %m");
 
         r = manager_enumerate_buttons(m);
         if (r < 0)
-                log_warning("Button enumeration failed: %s", strerror(-r));
+                log_warning_errno(r, "Button enumeration failed: %m");
 
         /* Remove stale objects before we start them */
         manager_gc(m, false);
 
         /* Reserve the special reserved VT */
+#if 0 /// elogind does not support autospawning of vts
         manager_reserve_vt(m);
+#endif // 0
 
         /* And start everything */
         HASHMAP_FOREACH(seat, m->seats, i)
@@ -1029,39 +1274,20 @@ int manager_startup(Manager *m) {
         HASHMAP_FOREACH(inhibitor, m->inhibitors, i)
                 inhibitor_start(inhibitor);
 
+        HASHMAP_FOREACH(button, m->buttons, i)
+                button_check_switches(button);
+
         manager_dispatch_idle_action(NULL, 0, m);
 
         return 0;
 }
 
-static int manager_recheck_buttons(Manager *m) {
-        Iterator i;
-        Button *b;
-        int r = 0;
-
-        assert(m);
-
-        HASHMAP_FOREACH(b, m->buttons, i) {
-                int q;
-
-                q = button_recheck(b);
-                if (q > 0)
-                        return 1;
-                if (q < 0)
-                        r = q;
-        }
-
-        return r;
-}
-
-int manager_run(Manager *m) {
+static int manager_run(Manager *m) {
         int r;
 
         assert(m);
 
         for (;;) {
-                usec_t us = (uint64_t) -1;
-
                 r = sd_event_get_state(m->event);
                 if (r < 0)
                         return r;
@@ -1070,62 +1296,32 @@ int manager_run(Manager *m) {
 
                 manager_gc(m, true);
 
-                if (manager_dispatch_delayed(m) > 0)
-                        continue;
-
-                if (manager_recheck_buttons(m) > 0)
+                r = manager_dispatch_delayed(m, false);
+                if (r < 0)
+                        return r;
+                if (r > 0)
                         continue;
 
-                if (m->action_what != 0 && !m->action_job) {
-                        usec_t x, y;
-
-                        x = now(CLOCK_MONOTONIC);
-                        y = m->action_timestamp + m->inhibit_delay_max;
-
-                        us = x >= y ? 0 : y - x;
-                }
-
-                r = sd_event_run(m->event, us);
+                r = sd_event_run(m->event, (uint64_t) -1);
                 if (r < 0)
                         return r;
         }
-
-        return 0;
-}
-
-static int manager_parse_config_file(Manager *m) {
-        static const char fn[] = "/etc/systemd/logind.conf";
-        _cleanup_fclose_ FILE *f = NULL;
-        int r;
-
-        assert(m);
-
-        f = fopen(fn, "re");
-        if (!f) {
-                if (errno == ENOENT)
-                        return 0;
-
-                log_warning("Failed to open configuration file %s: %m", fn);
-                return -errno;
-        }
-
-        r = config_parse(NULL, fn, f, "Login\0", config_item_perf_lookup,
-                         (void*) logind_gperf_lookup, false, false, m);
-        if (r < 0)
-                log_warning("Failed to parse configuration file: %s", strerror(-r));
-
-        return r;
 }
 
 int main(int argc, char *argv[]) {
         Manager *m = NULL;
         int r;
 
+        elogind_set_program_name(argv[0]);
         log_set_target(LOG_TARGET_AUTO);
         log_set_facility(LOG_AUTH);
         log_parse_environment();
         log_open();
 
+#ifdef ENABLE_DEBUG_ELOGIND
+        log_set_max_level(LOG_DEBUG);
+#endif // ENABLE_DEBUG_ELOGIND
+
         umask(0022);
 
         if (argc != 1) {
@@ -1134,14 +1330,38 @@ int main(int argc, char *argv[]) {
                 goto finish;
         }
 
+        r = mac_selinux_init();
+        if (r < 0) {
+                log_error_errno(r, "Could not initialize labelling: %m");
+                goto finish;
+        }
+
         /* Always create the directories people can create inotify
          * watches in. Note that some applications might check for the
          * existence of /run/systemd/seats/ to determine whether
          * logind is available, so please always make sure this check
          * stays in. */
+#if 0 /// elogind can not rely on systemd to help, so we need a bit more effort than this
         mkdir_label("/run/systemd/seats", 0755);
         mkdir_label("/run/systemd/users", 0755);
         mkdir_label("/run/systemd/sessions", 0755);
+#else
+        r = mkdir_label("/run/systemd", 0755);
+        if ( (r < 0) && (-EEXIST != r) )
+                return log_error_errno(r, "Failed to create /run/systemd : %m");
+        r = mkdir_label("/run/systemd/seats", 0755);
+        if ( r < 0 && (-EEXIST != r) )
+                return log_error_errno(r, "Failed to create /run/systemd/seats : %m");
+        r = mkdir_label("/run/systemd/users", 0755);
+        if ( r < 0 && (-EEXIST != r) )
+                return log_error_errno(r, "Failed to create /run/systemd/users : %m");
+        r = mkdir_label("/run/systemd/sessions", 0755);
+        if ( r < 0 && (-EEXIST != r) )
+                return log_error_errno(r, "Failed to create /run/systemd/sessions : %m");
+        r = mkdir_label("/run/systemd/machines", 0755);
+        if ( r < 0 && (-EEXIST != r) )
+                return log_error_errno(r, "Failed to create /run/systemd/machines : %m");
+#endif // 0
 
         m = manager_new();
         if (!m) {
@@ -1153,11 +1373,11 @@ int main(int argc, char *argv[]) {
 
         r = manager_startup(m);
         if (r < 0) {
-                log_error("Failed to fully start up daemon: %s", strerror(-r));
+                log_error_errno(r, "Failed to fully start up daemon: %m");
                 goto finish;
         }
 
-        log_debug("systemd-logind running as pid %lu", (unsigned long) getpid());
+        log_debug("elogind running as pid "PID_FMT, getpid());
 
         sd_notify(false,
                   "READY=1\n"
@@ -1165,10 +1385,11 @@ int main(int argc, char *argv[]) {
 
         r = manager_run(m);
 
-        log_debug("systemd-logind stopped as pid %lu", (unsigned long) getpid());
+        log_debug("elogind stopped as pid "PID_FMT, getpid());
 
 finish:
         sd_notify(false,
+                  "STOPPING=1\n"
                   "STATUS=Shutting down...");
 
         if (m)