[systemd-commits] 11 commits - configure.ac .gitignore Makefile.am src/libsystemd src/libsystemd-terminal src/login src/shared src/test src/udev

David Herrmann dvdhrm at kemper.freedesktop.org
Wed Aug 27 09:47:14 PDT 2014


 .gitignore                                 |    1 
 Makefile.am                                |   29 
 configure.ac                               |    7 
 src/libsystemd-terminal/evcat.c            |  499 +++++++++
 src/libsystemd-terminal/idev-evdev.c       |  938 ++++++++++++++++++
 src/libsystemd-terminal/idev-internal.h    |  184 +++
 src/libsystemd-terminal/idev-keyboard.c    |  846 ++++++++++++++++
 src/libsystemd-terminal/idev.c             |  693 +++++++++++++
 src/libsystemd-terminal/idev.h             |  202 +++
 src/libsystemd-terminal/sysview-internal.h |  140 ++
 src/libsystemd-terminal/sysview.c          | 1471 +++++++++++++++++++++++++++++
 src/libsystemd-terminal/sysview.h          |  151 ++
 src/libsystemd/sd-bus/bus-util.c           |   93 +
 src/libsystemd/sd-bus/bus-util.h           |    8 
 src/login/logind-session.c                 |    6 
 src/shared/macro.h                         |   15 
 src/shared/util.c                          |    2 
 src/shared/util.h                          |    1 
 src/test/test-util.c                       |   19 
 src/udev/udevadm.c                         |    2 
 20 files changed, 5271 insertions(+), 36 deletions(-)

New commits:
commit 8e9371905c743cf997b2e8fa7fe3238f81f741fe
Author: David Herrmann <dh.herrmann at gmail.com>
Date:   Wed Aug 27 18:38:01 2014 +0200

    terminal: add systemd-evcat input debugging tool
    
    Like systemd-subterm, this new systemd-evcat tool should only be used to
    debug libsystemd-terminal. systemd-evcat attaches to the running session
    and pushes all evdev devices attached to the current session into an
    idev-session. All events of the created idev-devices are then printed to
    stdout for input-event debugging.

diff --git a/.gitignore b/.gitignore
index 8aed0b9..f865087 100644
--- a/.gitignore
+++ b/.gitignore
@@ -69,6 +69,7 @@
 /systemd-detect-virt
 /systemd-efi-boot-generator
 /systemd-escape
+/systemd-evcat
 /systemd-firstboot
 /systemd-fsck
 /systemd-fstab-generator
diff --git a/Makefile.am b/Makefile.am
index 35a4c44..e091feb 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -2954,6 +2954,7 @@ noinst_LTLIBRARIES += \
 	libsystemd-terminal.la
 
 noinst_PROGRAMS += \
+	systemd-evcat \
 	systemd-subterm
 
 unifontdatadir=$(datadir)/unifont
@@ -2995,6 +2996,19 @@ libsystemd_terminal_la_LIBADD = \
 	libsystemd-shared.la \
 	$(TERMINAL_LIBS)
 
+systemd_evcat_CFLAGS = \
+	$(AM_CFLAGS) \
+	$(TERMINAL_CFLAGS)
+
+systemd_evcat_SOURCES = \
+	src/libsystemd-terminal/evcat.c
+
+systemd_evcat_LDADD = \
+	libsystemd-terminal.la \
+	libsystemd-internal.la \
+	libsystemd-shared.la \
+	$(TERMINAL_LIBS)
+
 systemd_subterm_SOURCES = \
 	src/libsystemd-terminal/subterm.c
 
diff --git a/src/libsystemd-terminal/evcat.c b/src/libsystemd-terminal/evcat.c
new file mode 100644
index 0000000..590a30d
--- /dev/null
+++ b/src/libsystemd-terminal/evcat.c
@@ -0,0 +1,499 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+  This file is part of systemd.
+
+  Copyright (C) 2014 David Herrmann <dh.herrmann at gmail.com>
+
+  systemd is free software; you can redistribute it and/or modify it
+  under the terms of the GNU Lesser General Public License as published by
+  the Free Software Foundation; either version 2.1 of the License, or
+  (at your option) any later version.
+
+  systemd is distributed in the hope that it will be useful, but
+  WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+  Lesser General Public License for more details.
+
+  You should have received a copy of the GNU Lesser General Public License
+  along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+/*
+ * Event Catenation
+ * The evcat tool catenates input events of all requested devices and prints
+ * them to standard-output. It's only meant for debugging of input-related
+ * problems.
+ */
+
+#include <assert.h>
+#include <errno.h>
+#include <getopt.h>
+#include <libevdev/libevdev.h>
+#include <linux/kd.h>
+#include <linux/vt.h>
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/stat.h>
+#include <systemd/sd-bus.h>
+#include <systemd/sd-event.h>
+#include <systemd/sd-login.h>
+#include <termios.h>
+#include <unistd.h>
+#include <xkbcommon/xkbcommon.h>
+#include "build.h"
+#include "bus-util.h"
+#include "event-util.h"
+#include "idev.h"
+#include "macro.h"
+#include "sysview.h"
+#include "term-internal.h"
+#include "util.h"
+
+typedef struct Evcat Evcat;
+
+struct Evcat {
+        char *session;
+        char *seat;
+        sd_event *event;
+        sd_bus *bus;
+        sysview_context *sysview;
+        idev_context *idev;
+        idev_session *idev_session;
+
+        bool managed : 1;
+};
+
+static Evcat *evcat_free(Evcat *e) {
+        if (!e)
+                return NULL;
+
+        e->idev_session = idev_session_free(e->idev_session);
+        e->idev = idev_context_unref(e->idev);
+        e->sysview = sysview_context_free(e->sysview);
+        e->bus = sd_bus_unref(e->bus);
+        e->event = sd_event_unref(e->event);
+        free(e->seat);
+        free(e->session);
+        free(e);
+
+        tcflush(0, TCIOFLUSH);
+
+        return NULL;
+}
+
+DEFINE_TRIVIAL_CLEANUP_FUNC(Evcat*, evcat_free);
+
+static bool is_managed(const char *session) {
+        unsigned int vtnr;
+        struct stat st;
+        long mode;
+        int r;
+
+        /* Using logind's Controller API is highly fragile if there is already
+         * a session controller running. If it is registered as controller
+         * itself, TakeControl will simply fail. But if its a legacy controller
+         * that does not use logind's controller API, we must never register
+         * our own controller. Otherwise, we really mess up the VT. Therefore,
+         * only run in managed mode if there's no-one else. */
+
+        if (geteuid() == 0)
+                return false;
+
+        if (!isatty(1))
+                return false;
+
+        if (!session)
+                return false;
+
+        r = sd_session_get_vt(session, &vtnr);
+        if (r < 0 || vtnr < 1 || vtnr > 63)
+                return false;
+
+        mode = 0;
+        r = ioctl(1, KDGETMODE, &mode);
+        if (r < 0 || mode != KD_TEXT)
+                return false;
+
+        r = fstat(1, &st);
+        if (r < 0 || minor(st.st_rdev) != vtnr)
+                return false;
+
+        return true;
+}
+
+static int evcat_new(Evcat **out) {
+        _cleanup_(evcat_freep) Evcat *e = NULL;
+        int r;
+
+        assert(out);
+
+        e = new0(Evcat, 1);
+        if (!e)
+                return log_oom();
+
+        r = sd_pid_get_session(getpid(), &e->session);
+        if (r < 0) {
+                log_error("Cannot retrieve logind session: %s", strerror(-r));
+                return r;
+        }
+
+        r = sd_session_get_seat(e->session, &e->seat);
+        if (r < 0) {
+                log_error("Cannot retrieve seat of logind session: %s", strerror(-r));
+                return r;
+        }
+
+        e->managed = is_managed(e->session);
+
+        r = sd_event_default(&e->event);
+        if (r < 0)
+                return r;
+
+        r = sd_bus_open_system(&e->bus);
+        if (r < 0)
+                return r;
+
+        r = sd_bus_attach_event(e->bus, e->event, SD_EVENT_PRIORITY_NORMAL);
+        if (r < 0)
+                return r;
+
+        r = sigprocmask_many(SIG_BLOCK, SIGTERM, SIGINT, -1);
+        if (r < 0)
+                return r;
+
+        r = sd_event_add_signal(e->event, NULL, SIGTERM, NULL, NULL);
+        if (r < 0)
+                return r;
+
+        r = sd_event_add_signal(e->event, NULL, SIGINT, NULL, NULL);
+        if (r < 0)
+                return r;
+
+        r = sysview_context_new(&e->sysview,
+                                SYSVIEW_CONTEXT_SCAN_LOGIND |
+                                SYSVIEW_CONTEXT_SCAN_EVDEV,
+                                e->event,
+                                e->bus,
+                                NULL);
+        if (r < 0)
+                return r;
+
+        r = idev_context_new(&e->idev, e->event, e->bus);
+        if (r < 0)
+                return r;
+
+        *out = e;
+        e = NULL;
+        return 0;
+}
+
+static void kdata_print(idev_data *data) {
+        idev_data_keyboard *k = &data->keyboard;
+        char buf[128];
+        uint32_t i, c;
+        int cwidth;
+
+        /* Key-press state: UP/DOWN/REPEAT */
+        printf(" %-6s", k->value == 0 ? "UP" :
+                        k->value == 1 ? "DOWN" :
+                        "REPEAT");
+
+        /* Keycode that triggered the event */
+        printf(" | %5u", (unsigned)k->keycode);
+
+        /* Well-known name of the keycode */
+        printf(" | %-20s", libevdev_event_code_get_name(EV_KEY, k->keycode) ? : "<unknown>");
+
+        /* Well-known modifiers */
+        printf(" | %-5s", (k->mods & IDEV_KBDMOD_SHIFT) ? "SHIFT" : "");
+        printf(" %-4s", (k->mods & IDEV_KBDMOD_CTRL) ? "CTRL" : "");
+        printf(" %-3s", (k->mods & IDEV_KBDMOD_ALT) ? "ALT" : "");
+        printf(" %-5s", (k->mods & IDEV_KBDMOD_LINUX) ? "LINUX" : "");
+        printf(" %-4s", (k->mods & IDEV_KBDMOD_CAPS) ? "CAPS" : "");
+
+        /* Resolved symbols */
+        printf(" |");
+        for (i = 0; i < k->n_syms; ++i) {
+                buf[0] = 0;
+                xkb_keysym_get_name(k->keysyms[i], buf, sizeof(buf));
+
+                if (is_locale_utf8()) {
+                        c = k->codepoints[i];
+                        if (c < 0x110000 && c > 0x20 && (c < 0x7f || c > 0x9f)) {
+                                /* "%4lc" doesn't work well, so hard-code it */
+                                cwidth = mk_wcwidth(c);
+                                while (cwidth++ < 2)
+                                        printf(" ");
+
+                                printf(" '%lc':", (wchar_t)c);
+                        } else {
+                                printf("      ");
+                        }
+                }
+
+                printf(" XKB_KEY_%-30s", buf);
+        }
+
+        printf("\n");
+}
+
+static bool kdata_is_exit(idev_data *data) {
+        idev_data_keyboard *k = &data->keyboard;
+
+        if (k->value != 1)
+                return false;
+        if (k->n_syms != 1)
+                return false;
+
+        return k->codepoints[0] == 'q';
+}
+
+static int evcat_idev_fn(idev_session *session, void *userdata, idev_event *ev) {
+        Evcat *e = userdata;
+
+        switch (ev->type) {
+        case IDEV_EVENT_DEVICE_ADD:
+                idev_device_enable(ev->device_add.device);
+                break;
+        case IDEV_EVENT_DEVICE_REMOVE:
+                idev_device_disable(ev->device_remove.device);
+                break;
+        case IDEV_EVENT_DEVICE_DATA:
+                switch (ev->device_data.data.type) {
+                case IDEV_DATA_KEYBOARD:
+                        if (kdata_is_exit(&ev->device_data.data))
+                                sd_event_exit(e->event, 0);
+                        else
+                                kdata_print(&ev->device_data.data);
+
+                        break;
+                }
+
+                break;
+        }
+
+        return 0;
+}
+
+static int evcat_sysview_fn(sysview_context *c, void *userdata, sysview_event *ev) {
+        unsigned int flags, type;
+        Evcat *e = userdata;
+        sysview_device *d;
+        const char *name;
+        int r;
+
+        switch (ev->type) {
+        case SYSVIEW_EVENT_SESSION_FILTER:
+                if (streq_ptr(e->session, ev->session_filter.id))
+                        return 1;
+
+                break;
+        case SYSVIEW_EVENT_SESSION_ADD:
+                assert(!e->idev_session);
+
+                name = sysview_session_get_name(ev->session_add.session);
+                flags = 0;
+
+                if (e->managed)
+                        flags |= IDEV_SESSION_MANAGED;
+
+                r = idev_session_new(&e->idev_session,
+                                     e->idev,
+                                     flags,
+                                     name,
+                                     evcat_idev_fn,
+                                     e);
+                if (r < 0) {
+                        log_error("Cannot create idev session: %s", strerror(-r));
+                        return r;
+                }
+
+                idev_session_enable(e->idev_session);
+
+                if (e->managed) {
+                        r = sysview_session_take_control(ev->session_add.session);
+                        if (r < 0) {
+                                log_error("Cannot request session control: %s", strerror(-r));
+                                return r;
+                        }
+                }
+
+                break;
+        case SYSVIEW_EVENT_SESSION_REMOVE:
+                idev_session_disable(e->idev_session);
+                e->idev_session = idev_session_free(e->idev_session);
+                sd_event_exit(e->event, 0);
+                break;
+        case SYSVIEW_EVENT_SESSION_ATTACH:
+                d = ev->session_attach.device;
+                type = sysview_device_get_type(d);
+                if (type == SYSVIEW_DEVICE_EVDEV) {
+                        r = idev_session_add_evdev(e->idev_session, sysview_device_get_ud(d));
+                        if (r < 0) {
+                                log_error("Cannot add evdev device to idev: %s", strerror(-r));
+                                return r;
+                        }
+                }
+
+                break;
+        case SYSVIEW_EVENT_SESSION_DETACH:
+                d = ev->session_detach.device;
+                type = sysview_device_get_type(d);
+                if (type == SYSVIEW_DEVICE_EVDEV) {
+                        r = idev_session_remove_evdev(e->idev_session, sysview_device_get_ud(d));
+                        if (r < 0) {
+                                log_error("Cannot remove evdev device from idev: %s", strerror(-r));
+                                return r;
+                        }
+                }
+
+                break;
+        case SYSVIEW_EVENT_SESSION_CONTROL:
+                r = ev->session_control.error;
+                if (r < 0) {
+                        log_error("Cannot acquire session control: %s", strerror(-r));
+                        return r;
+                }
+
+                r = ioctl(1, KDSKBMODE, K_UNICODE);
+                if (r < 0) {
+                        log_error("Cannot set K_UNICODE on stdout: %m");
+                        return -errno;
+                }
+
+                r = ioctl(1, KDSETMODE, KD_TEXT);
+                if (r < 0) {
+                        log_error("Cannot set KD_TEXT on stdout: %m");
+                        return -errno;
+                }
+
+                printf("\n");
+
+                break;
+        }
+
+        return 0;
+}
+
+static int evcat_run(Evcat *e) {
+        struct termios in_attr, saved_attr;
+        int r;
+
+        assert(e);
+
+        if (!e->managed && geteuid() > 0)
+                log_warning("You run in unmanaged mode without being root. This is likely to produce no output..");
+
+        printf("evcat - Read and catenate events from selected input devices\n"
+               "        Running on seat '%s' in user-session '%s'\n"
+               "        Exit by pressing ^C or 'q'\n\n",
+               e->seat ? : "seat0", e->session ? : "<none>");
+
+        r = sysview_context_start(e->sysview, evcat_sysview_fn, e);
+        if (r < 0)
+                goto out;
+
+        r = tcgetattr(0, &in_attr);
+        if (r < 0) {
+                r = -errno;
+                goto out;
+        }
+
+        saved_attr = in_attr;
+        in_attr.c_lflag &= ~ECHO;
+
+        r = tcsetattr(0, TCSANOW, &in_attr);
+        if (r < 0) {
+                r = -errno;
+                goto out;
+        }
+
+        r = sd_event_loop(e->event);
+        tcsetattr(0, TCSANOW, &saved_attr);
+        printf("exiting..\n");
+
+out:
+        sysview_context_stop(e->sysview);
+        return r;
+}
+
+static int help(void) {
+        printf("%s [OPTIONS...]\n\n"
+               "Read and catenate events from selected input devices.\n\n"
+               "  -h --help               Show this help\n"
+               "     --version            Show package version\n"
+               , program_invocation_short_name);
+
+        return 0;
+}
+
+static int parse_argv(int argc, char *argv[]) {
+        enum {
+                ARG_VERSION = 0x100,
+        };
+        static const struct option options[] = {
+                { "help",       no_argument,    NULL, 'h'               },
+                { "version",    no_argument,    NULL, ARG_VERSION       },
+                {},
+        };
+        int c;
+
+        assert(argc >= 0);
+        assert(argv);
+
+        while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
+                switch (c) {
+                case 'h':
+                        help();
+                        return 0;
+
+                case ARG_VERSION:
+                        puts(PACKAGE_STRING);
+                        puts(SYSTEMD_FEATURES);
+                        return 0;
+
+                case '?':
+                        return -EINVAL;
+
+                default:
+                        assert_not_reached("Unhandled option");
+                }
+
+        if (argc > optind) {
+                log_error("Too many arguments");
+                return -EINVAL;
+        }
+
+        return 1;
+}
+
+int main(int argc, char *argv[]) {
+        _cleanup_(evcat_freep) Evcat *e = NULL;
+        int r;
+
+        log_set_target(LOG_TARGET_AUTO);
+        log_parse_environment();
+        log_open();
+
+        setlocale(LC_ALL, "");
+        if (!is_locale_utf8())
+                log_warning("Locale is not set to UTF-8. Codepoints will not be printed!");
+
+        r = parse_argv(argc, argv);
+        if (r <= 0)
+                goto finish;
+
+        r = evcat_new(&e);
+        if (r < 0)
+                goto finish;
+
+        r = evcat_run(e);
+
+finish:
+        return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+}

commit e06cc7b07465369fb7c01c9778b84cf82c82fdcf
Author: David Herrmann <dh.herrmann at gmail.com>
Date:   Wed Aug 27 18:34:55 2014 +0200

    terminal: add xkb-based keyboard devices to idev
    
    The idev-keyboard object provides keyboard devices to the idev interface.
    It uses libxkbcommon to provide proper keymap support.
    
    So far, the keyboard implementation is pretty straightforward with one
    keyboard device per matching evdev element. We feed everything into the
    system keymap and provide proper high-level keyboard events to the
    application. Compose-features and IM need to be added later.

diff --git a/Makefile.am b/Makefile.am
index b51c522..35a4c44 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -2976,6 +2976,7 @@ libsystemd_terminal_la_SOURCES = \
 	src/libsystemd-terminal/idev-internal.h \
 	src/libsystemd-terminal/idev.c \
 	src/libsystemd-terminal/idev-evdev.c \
+	src/libsystemd-terminal/idev-keyboard.c \
 	src/libsystemd-terminal/sysview.h \
 	src/libsystemd-terminal/sysview-internal.h \
 	src/libsystemd-terminal/sysview.c \
diff --git a/configure.ac b/configure.ac
index 3900c40..a25ad3f 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1066,7 +1066,7 @@ AM_CONDITIONAL(ENABLE_MULTI_SEAT_X, [test "$have_multi_seat_x" = "yes"])
 have_terminal=no
 AC_ARG_ENABLE(terminal, AS_HELP_STRING([--enable-terminal], [enable terminal support]))
 if test "x$enable_terminal" = "xyes"; then
-        PKG_CHECK_MODULES([TERMINAL], [ libevdev >= 1.2 ], [have_terminal=yes])
+        PKG_CHECK_MODULES([TERMINAL], [ libevdev >= 1.2 xkbcommon >= 0.4 ], [have_terminal=yes])
         AS_IF([test "x$have_terminal" != xyes -a "x$enable_terminal" = xyes],
               [AC_MSG_ERROR([*** terminal support requested but required dependencies not available])],
               [test "x$have_terminal" = xyes],
diff --git a/src/libsystemd-terminal/idev-internal.h b/src/libsystemd-terminal/idev-internal.h
index 3301ebf..c416f4f 100644
--- a/src/libsystemd-terminal/idev-internal.h
+++ b/src/libsystemd-terminal/idev-internal.h
@@ -28,6 +28,7 @@
 #include <stdlib.h>
 #include <systemd/sd-bus.h>
 #include <systemd/sd-event.h>
+#include <xkbcommon/xkbcommon.h>
 #include "hashmap.h"
 #include "idev.h"
 #include "list.h"
@@ -47,6 +48,14 @@ idev_element *idev_find_evdev(idev_session *s, dev_t devnum);
 int idev_evdev_new(idev_element **out, idev_session *s, struct udev_device *ud);
 
 /*
+ * Keyboard Devices
+ */
+
+bool idev_is_keyboard(idev_device *d);
+idev_device *idev_find_keyboard(idev_session *s, const char *name);
+int idev_keyboard_new(idev_device **out, idev_session *s, const char *name);
+
+/*
  * Element Links
  */
 
diff --git a/src/libsystemd-terminal/idev-keyboard.c b/src/libsystemd-terminal/idev-keyboard.c
new file mode 100644
index 0000000..647aade
--- /dev/null
+++ b/src/libsystemd-terminal/idev-keyboard.c
@@ -0,0 +1,846 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+  This file is part of systemd.
+
+  Copyright (C) 2014 David Herrmann <dh.herrmann at gmail.com>
+
+  systemd is free software; you can redistribute it and/or modify it
+  under the terms of the GNU Lesser General Public License as published by
+  the Free Software Foundation; either version 2.1 of the License, or
+  (at your option) any later version.
+
+  systemd is distributed in the hope that it will be useful, but
+  WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+  Lesser General Public License for more details.
+
+  You should have received a copy of the GNU Lesser General Public License
+  along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <inttypes.h>
+#include <stdbool.h>
+#include <stdlib.h>
+#include <systemd/sd-bus.h>
+#include <systemd/sd-event.h>
+#include <xkbcommon/xkbcommon.h>
+#include "bus-util.h"
+#include "hashmap.h"
+#include "idev.h"
+#include "idev-internal.h"
+#include "macro.h"
+#include "util.h"
+
+typedef struct kbdmap kbdmap;
+typedef struct kbdctx kbdctx;
+typedef struct idev_keyboard idev_keyboard;
+
+struct kbdmap {
+        unsigned long ref;
+        struct xkb_keymap *xkb_keymap;
+        xkb_mod_index_t modmap[IDEV_KBDMOD_CNT];
+        xkb_led_index_t ledmap[IDEV_KBDLED_CNT];
+};
+
+struct kbdctx {
+        unsigned long ref;
+        idev_context *context;
+        struct xkb_context *xkb_context;
+        struct kbdmap *kbdmap;
+
+        sd_bus_slot *slot_locale_props_changed;
+        sd_bus_slot *slot_locale_get_all;
+
+        char *locale_x11_model;
+        char *locale_x11_layout;
+        char *locale_x11_variant;
+        char *locale_x11_options;
+        char *last_x11_model;
+        char *last_x11_layout;
+        char *last_x11_variant;
+        char *last_x11_options;
+};
+
+struct idev_keyboard {
+        idev_device device;
+        kbdctx *kbdctx;
+        kbdmap *kbdmap;
+
+        struct xkb_state *xkb_state;
+
+        usec_t repeat_delay;
+        usec_t repeat_rate;
+        sd_event_source *repeat_timer;
+
+        uint32_t n_syms;
+        idev_data evdata;
+        idev_data repdata;
+
+        bool repeating : 1;
+};
+
+#define keyboard_from_device(_d) container_of((_d), idev_keyboard, device)
+
+#define KBDCTX_KEY "keyboard.context"           /* hashmap key for global kbdctx */
+#define KBDXKB_SHIFT (8)                        /* xkb shifts evdev key-codes by 8 */
+#define KBDKEY_UP (0)                           /* KEY UP event value */
+#define KBDKEY_DOWN (1)                         /* KEY DOWN event value */
+#define KBDKEY_REPEAT (2)                       /* KEY REPEAT event value */
+
+static const idev_device_vtable keyboard_vtable;
+
+static int keyboard_update_kbdmap(idev_keyboard *k);
+
+/*
+ * Keyboard Keymaps
+ */
+
+static const char * const kbdmap_modmap[IDEV_KBDMOD_CNT] = {
+        [IDEV_KBDMOD_IDX_SHIFT]                 = XKB_MOD_NAME_SHIFT,
+        [IDEV_KBDMOD_IDX_CTRL]                  = XKB_MOD_NAME_CTRL,
+        [IDEV_KBDMOD_IDX_ALT]                   = XKB_MOD_NAME_ALT,
+        [IDEV_KBDMOD_IDX_LINUX]                 = XKB_MOD_NAME_LOGO,
+        [IDEV_KBDMOD_IDX_CAPS]                  = XKB_MOD_NAME_CAPS,
+};
+
+static const char * const kbdmap_ledmap[IDEV_KBDLED_CNT] = {
+        [IDEV_KBDLED_IDX_NUM]                   = XKB_LED_NAME_NUM,
+        [IDEV_KBDLED_IDX_CAPS]                  = XKB_LED_NAME_CAPS,
+        [IDEV_KBDLED_IDX_SCROLL]                = XKB_LED_NAME_SCROLL,
+};
+
+static kbdmap *kbdmap_ref(kbdmap *km) {
+        assert_return(km, NULL);
+        assert_return(km->ref > 0, NULL);
+
+        ++km->ref;
+        return km;
+}
+
+static kbdmap *kbdmap_unref(kbdmap *km) {
+        if (!km)
+                return NULL;
+
+        assert_return(km->ref > 0, NULL);
+
+        if (--km->ref > 0)
+                return NULL;
+
+        xkb_keymap_unref(km->xkb_keymap);
+        free(km);
+
+        return 0;
+}
+
+DEFINE_TRIVIAL_CLEANUP_FUNC(kbdmap*, kbdmap_unref);
+
+static int kbdmap_new_from_names(kbdmap **out,
+                                 kbdctx *kc,
+                                 const char *model,
+                                 const char *layout,
+                                 const char *variant,
+                                 const char *options) {
+        _cleanup_(kbdmap_unrefp) kbdmap *km = NULL;
+        struct xkb_rule_names rmlvo = { };
+        unsigned int i;
+
+        assert_return(out, -EINVAL);
+
+        km = new0(kbdmap, 1);
+        if (!km)
+                return -ENOMEM;
+
+        km->ref = 1;
+
+        rmlvo.rules = "evdev";
+        rmlvo.model = model;
+        rmlvo.layout = layout;
+        rmlvo.variant = variant;
+        rmlvo.options = options;
+
+        errno = 0;
+        km->xkb_keymap = xkb_keymap_new_from_names(kc->xkb_context, &rmlvo, 0);
+        if (!km->xkb_keymap)
+                return errno > 0 ? -errno : -EFAULT;
+
+        for (i = 0; i < IDEV_KBDMOD_CNT; ++i) {
+                const char *t = kbdmap_modmap[i];
+
+                if (t)
+                        km->modmap[i] = xkb_keymap_mod_get_index(km->xkb_keymap, t);
+                else
+                        km->modmap[i] = XKB_MOD_INVALID;
+        }
+
+        for (i = 0; i < IDEV_KBDLED_CNT; ++i) {
+                const char *t = kbdmap_ledmap[i];
+
+                if (t)
+                        km->ledmap[i] = xkb_keymap_led_get_index(km->xkb_keymap, t);
+                else
+                        km->ledmap[i] = XKB_LED_INVALID;
+        }
+
+        *out = km;
+        km = NULL;
+        return 0;
+}
+
+/*
+ * Keyboard Context
+ */
+
+static void move_str(char **dest, char **src) {
+        free(*dest);
+        *dest = *src;
+        *src = NULL;
+}
+
+static int kbdctx_refresh_keymap(kbdctx *kc) {
+        idev_session *s;
+        idev_device *d;
+        Iterator i, j;
+        kbdmap *km;
+        int r;
+
+        if (kc->kbdmap &&
+            streq_ptr(kc->locale_x11_model, kc->last_x11_model) &&
+            streq_ptr(kc->locale_x11_layout, kc->last_x11_layout) &&
+            streq_ptr(kc->locale_x11_variant, kc->last_x11_variant) &&
+            streq_ptr(kc->locale_x11_options, kc->last_x11_options))
+                return 0 ;
+
+        move_str(&kc->last_x11_model, &kc->locale_x11_model);
+        move_str(&kc->last_x11_layout, &kc->locale_x11_layout);
+        move_str(&kc->last_x11_variant, &kc->locale_x11_variant);
+        move_str(&kc->last_x11_options, &kc->locale_x11_options);
+
+        log_debug("idev-keyboard: new default keymap: [%s / %s / %s / %s]",
+                  kc->last_x11_model, kc->last_x11_layout, kc->last_x11_variant, kc->last_x11_options);
+
+        /* TODO: add a fallback keymap that's compiled-in */
+        r = kbdmap_new_from_names(&km, kc, kc->last_x11_model, kc->last_x11_layout,
+                                  kc->last_x11_variant, kc->last_x11_options);
+        if (r < 0) {
+                log_debug("idev-keyboard: cannot create keymap from locale1: %s",
+                          strerror(-r));
+                return r;
+        }
+
+        kbdmap_unref(kc->kbdmap);
+        kc->kbdmap = km;
+
+        HASHMAP_FOREACH(s, kc->context->session_map, i)
+                HASHMAP_FOREACH(d, s->device_map, j)
+                        if (idev_is_keyboard(d))
+                                keyboard_update_kbdmap(keyboard_from_device(d));
+
+        return 0;
+}
+
+static const struct bus_properties_map kbdctx_locale_map[] = {
+        { "X11Model",   "s",    NULL, offsetof(kbdctx, locale_x11_model) },
+        { "X11Layout",  "s",    NULL, offsetof(kbdctx, locale_x11_layout) },
+        { "X11Variant", "s",    NULL, offsetof(kbdctx, locale_x11_variant) },
+        { "X11Options", "s",    NULL, offsetof(kbdctx, locale_x11_options) },
+};
+
+static int kbdctx_locale_get_all_fn(sd_bus *bus,
+                                    sd_bus_message *m,
+                                    void *userdata,
+                                    sd_bus_error *ret_err) {
+        kbdctx *kc = userdata;
+        int r;
+
+        kc->slot_locale_get_all = sd_bus_slot_unref(kc->slot_locale_get_all);
+
+        if (sd_bus_message_is_method_error(m, NULL)) {
+                const sd_bus_error *error = sd_bus_message_get_error(m);
+
+                log_debug("idev-keyboard: GetAll() on locale1 failed: %s: %s",
+                          error->name, error->message);
+                return 0;
+        }
+
+        r = bus_message_map_all_properties(bus, m, kbdctx_locale_map, kc);
+        if (r < 0) {
+                log_debug("idev-keyboard: erroneous GetAll() reply from locale1");
+                return 0;
+        }
+
+        kbdctx_refresh_keymap(kc);
+        return 0;
+}
+
+static int kbdctx_query_locale(kbdctx *kc) {
+        _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
+        int r;
+
+        kc->slot_locale_get_all = sd_bus_slot_unref(kc->slot_locale_get_all);
+
+        r = sd_bus_message_new_method_call(kc->context->sysbus,
+                                           &m,
+                                           "org.freedesktop.locale1",
+                                           "/org/freedesktop/locale1",
+                                           "org.freedesktop.DBus.Properties",
+                                           "GetAll");
+        if (r < 0)
+                goto error;
+
+        r = sd_bus_message_append(m, "s", "org.freedesktop.locale1");
+        if (r < 0)
+                goto error;
+
+        r = sd_bus_call_async(kc->context->sysbus,
+                              &kc->slot_locale_get_all,
+                              m,
+                              kbdctx_locale_get_all_fn,
+                              kc,
+                              0);
+        if (r < 0)
+                goto error;
+
+        return 0;
+
+error:
+        log_debug("idev-keyboard: cannot send GetAll to locale1: %s", strerror(-r));
+        return r;
+}
+
+static int kbdctx_locale_props_changed_fn(sd_bus *bus,
+                                          sd_bus_message *signal,
+                                          void *userdata,
+                                          sd_bus_error *ret_err) {
+        _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
+        kbdctx *kc = userdata;
+        int r;
+
+        kc->slot_locale_get_all = sd_bus_slot_unref(kc->slot_locale_get_all);
+
+        r = bus_message_map_properties_changed(bus, signal, kbdctx_locale_map, kc);
+        if (r < 0) {
+                log_debug("idev-keyboard: cannot handle PropertiesChanged from locale1: %s", strerror(-r));
+                return r;
+        }
+
+        if (r > 0) {
+                r = kbdctx_query_locale(kc);
+                if (r < 0)
+                        return r;
+        }
+
+        kbdctx_refresh_keymap(kc);
+        return 0;
+}
+
+static int kbdctx_setup_bus(kbdctx *kc) {
+        int r;
+
+        r = sd_bus_add_match(kc->context->sysbus,
+                             &kc->slot_locale_props_changed,
+                             "type='signal',"
+                             "sender='org.freedesktop.locale1',"
+                             "interface='org.freedesktop.DBus.Properties',"
+                             "member='PropertiesChanged',"
+                             "path='/org/freedesktop/locale1'",
+                             kbdctx_locale_props_changed_fn,
+                             kc);
+        if (r < 0) {
+                log_debug("idev-keyboard: cannot setup locale1 link: %s", strerror(-r));
+                return r;
+        }
+
+        return kbdctx_query_locale(kc);
+}
+
+static kbdctx *kbdctx_ref(kbdctx *kc) {
+        assert_return(kc, NULL);
+        assert_return(kc->ref > 0, NULL);
+
+        ++kc->ref;
+        return kc;
+}
+
+static kbdctx *kbdctx_unref(kbdctx *kc) {
+        if (!kc)
+                return NULL;
+
+        assert_return(kc->ref > 0, NULL);
+
+        if (--kc->ref > 0)
+                return NULL;
+
+        free(kc->last_x11_options);
+        free(kc->last_x11_variant);
+        free(kc->last_x11_layout);
+        free(kc->last_x11_model);
+        free(kc->locale_x11_options);
+        free(kc->locale_x11_variant);
+        free(kc->locale_x11_layout);
+        free(kc->locale_x11_model);
+        kc->slot_locale_get_all = sd_bus_slot_unref(kc->slot_locale_get_all);
+        kc->slot_locale_props_changed = sd_bus_slot_unref(kc->slot_locale_props_changed);
+        kc->kbdmap = kbdmap_unref(kc->kbdmap);
+        xkb_context_unref(kc->xkb_context);
+        hashmap_remove_value(kc->context->data_map, KBDCTX_KEY, kc);
+        free(kc);
+
+        return NULL;
+}
+
+DEFINE_TRIVIAL_CLEANUP_FUNC(kbdctx*, kbdctx_unref);
+
+static int kbdctx_new(kbdctx **out, idev_context *c) {
+        _cleanup_(kbdctx_unrefp) kbdctx *kc = NULL;
+        int r;
+
+        assert_return(out, -EINVAL);
+        assert_return(c, -EINVAL);
+
+        kc = new0(kbdctx, 1);
+        if (!kc)
+                return -ENOMEM;
+
+        kc->ref = 1;
+        kc->context = c;
+
+        errno = 0;
+        kc->xkb_context = xkb_context_new(0);
+        if (!kc->xkb_context)
+                return errno > 0 ? -errno : -EFAULT;
+
+        r = kbdctx_refresh_keymap(kc);
+        if (r < 0)
+                return r;
+
+        if (c->sysbus) {
+                r = kbdctx_setup_bus(kc);
+                if (r < 0)
+                        return r;
+        }
+
+        r = hashmap_put(c->data_map, KBDCTX_KEY, kc);
+        if (r < 0)
+                return r;
+
+        *out = kc;
+        kc = NULL;
+        return 0;
+}
+
+static int get_kbdctx(idev_context *c, kbdctx **out) {
+        kbdctx *kc;
+
+        assert_return(c, -EINVAL);
+        assert_return(out, -EINVAL);
+
+        kc = hashmap_get(c->data_map, KBDCTX_KEY);
+        if (kc) {
+                *out = kbdctx_ref(kc);
+                return 0;
+        }
+
+        return kbdctx_new(out, c);
+}
+
+/*
+ * Keyboard Devices
+ */
+
+bool idev_is_keyboard(idev_device *d) {
+        return d && d->vtable == &keyboard_vtable;
+}
+
+idev_device *idev_find_keyboard(idev_session *s, const char *name) {
+        char *kname;
+
+        assert_return(s, NULL);
+        assert_return(name, NULL);
+
+        kname = strappenda("keyboard/", name);
+        return hashmap_get(s->device_map, kname);
+}
+
+static int keyboard_raise_data(idev_keyboard *k, idev_data *data) {
+        idev_device *d = &k->device;
+        int r;
+
+        r = idev_session_raise_device_data(d->session, d, data);
+        if (r < 0)
+                log_debug("idev-keyboard: %s/%s: error while raising data event: %s",
+                          d->session->name, d->name, strerror(-r));
+
+        return r;
+}
+
+static void keyboard_arm(idev_keyboard *k, usec_t usecs) {
+        int r;
+
+        if (usecs != 0) {
+                usecs += now(CLOCK_MONOTONIC);
+                r = sd_event_source_set_time(k->repeat_timer, usecs);
+                if (r >= 0)
+                        sd_event_source_set_enabled(k->repeat_timer, SD_EVENT_ONESHOT);
+        } else {
+                sd_event_source_set_enabled(k->repeat_timer, SD_EVENT_OFF);
+        }
+}
+
+static int keyboard_repeat_timer_fn(sd_event_source *source, uint64_t usec, void *userdata) {
+        idev_keyboard *k = userdata;
+
+        keyboard_arm(k, k->repeat_rate);
+        return keyboard_raise_data(k, &k->repdata);
+}
+
+int idev_keyboard_new(idev_device **out, idev_session *s, const char *name) {
+        _cleanup_(idev_device_freep) idev_device *d = NULL;
+        idev_keyboard *k;
+        char *kname;
+        int r;
+
+        assert_return(out, -EINVAL);
+        assert_return(s, -EINVAL);
+        assert_return(name, -EINVAL);
+
+        k = new0(idev_keyboard, 1);
+        if (!k)
+                return -ENOMEM;
+
+        d = &k->device;
+        k->device = IDEV_DEVICE_INIT(&keyboard_vtable, s);
+        k->repeat_delay = 250 * USEC_PER_MSEC;
+        k->repeat_rate = 30 * USEC_PER_MSEC;
+
+        /* TODO: add key-repeat configuration */
+
+        r = get_kbdctx(s->context, &k->kbdctx);
+        if (r < 0)
+                return r;
+
+        r = keyboard_update_kbdmap(k);
+        if (r < 0)
+                return r;
+
+        r = sd_event_add_time(s->context->event,
+                              &k->repeat_timer,
+                              CLOCK_MONOTONIC,
+                              0,
+                              10 * USEC_PER_MSEC,
+                              keyboard_repeat_timer_fn,
+                              k);
+        if (r < 0)
+                return r;
+
+        r = sd_event_source_set_enabled(k->repeat_timer, SD_EVENT_OFF);
+        if (r < 0)
+                return r;
+
+        kname = strappenda("keyboard/", name);
+        r = idev_device_add(d, kname);
+        if (r < 0)
+                return r;
+
+        if (out)
+                *out = d;
+        d = NULL;
+        return 0;
+}
+
+static void keyboard_free(idev_device *d) {
+        idev_keyboard *k = keyboard_from_device(d);
+
+        free(k->repdata.keyboard.codepoints);
+        free(k->repdata.keyboard.keysyms);
+        free(k->evdata.keyboard.codepoints);
+        free(k->evdata.keyboard.keysyms);
+        k->repeat_timer = sd_event_source_unref(k->repeat_timer);
+        k->kbdmap = kbdmap_unref(k->kbdmap);
+        k->kbdctx = kbdctx_unref(k->kbdctx);
+        free(k);
+}
+
+static int8_t guess_ascii(struct xkb_state *state, uint32_t code, uint32_t n_syms, const uint32_t *syms) {
+        xkb_layout_index_t n_lo, lo;
+        xkb_level_index_t lv;
+        struct xkb_keymap *keymap;
+        const xkb_keysym_t *s;
+        int num;
+
+        if (n_syms == 1 && syms[0] < 128)
+                return syms[0];
+
+        keymap = xkb_state_get_keymap(state);
+        n_lo = xkb_keymap_num_layouts_for_key(keymap, code + KBDXKB_SHIFT);
+
+        for (lo = 0; lo < n_lo; ++lo) {
+                lv = xkb_state_key_get_level(state, code + KBDXKB_SHIFT, lo);
+                num = xkb_keymap_key_get_syms_by_level(keymap, code + KBDXKB_SHIFT, lo, lv, &s);
+                if (num == 1 && s[0] < 128)
+                        return s[0];
+        }
+
+        return -1;
+}
+
+static int keyboard_fill(idev_keyboard *k,
+                         idev_data *dst,
+                         bool resync,
+                         uint16_t code,
+                         uint32_t value,
+                         uint32_t n_syms,
+                         const uint32_t *keysyms) {
+        idev_data_keyboard *kev;
+        uint32_t i;
+
+        assert(dst == &k->evdata || dst == &k->repdata);
+
+        if (n_syms > k->n_syms) {
+                uint32_t *t;
+
+                t = realloc(k->evdata.keyboard.keysyms, sizeof(*t) * n_syms);
+                if (!t)
+                        return -ENOMEM;
+                k->evdata.keyboard.keysyms = t;
+
+                t = realloc(k->evdata.keyboard.codepoints, sizeof(*t) * n_syms);
+                if (!t)
+                        return -ENOMEM;
+                k->evdata.keyboard.codepoints = t;
+
+                t = realloc(k->repdata.keyboard.keysyms, sizeof(*t) * n_syms);
+                if (!t)
+                        return -ENOMEM;
+                k->repdata.keyboard.keysyms = t;
+
+                t = realloc(k->repdata.keyboard.codepoints, sizeof(*t) * n_syms);
+                if (!t)
+                        return -ENOMEM;
+                k->repdata.keyboard.codepoints = t;
+
+                k->n_syms = n_syms;
+        }
+
+        dst->type = IDEV_DATA_KEYBOARD;
+        dst->resync = resync;
+        kev = &dst->keyboard;
+        kev->ascii = guess_ascii(k->xkb_state, code, n_syms, keysyms);
+        kev->value = value;
+        kev->keycode = code;
+        kev->mods = 0;
+        kev->consumed_mods = 0;
+        kev->n_syms = n_syms;
+        memcpy(kev->keysyms, keysyms, sizeof(*keysyms) * n_syms);
+
+        for (i = 0; i < n_syms; ++i) {
+                kev->codepoints[i] = xkb_keysym_to_utf32(keysyms[i]);
+                if (!kev->codepoints[i])
+                        kev->codepoints[i] = 0xffffffffUL;
+        }
+
+        for (i = 0; i < IDEV_KBDMOD_CNT; ++i) {
+                int r;
+
+                if (k->kbdmap->modmap[i] == XKB_MOD_INVALID)
+                        continue;
+
+                r = xkb_state_mod_index_is_active(k->xkb_state, k->kbdmap->modmap[i], XKB_STATE_MODS_EFFECTIVE);
+                if (r > 0)
+                        kev->mods |= 1 << i;
+
+                r = xkb_state_mod_index_is_consumed(k->xkb_state, code + KBDXKB_SHIFT, k->kbdmap->modmap[i]);
+                if (r > 0)
+                        kev->consumed_mods |= 1 << i;
+        }
+
+        return 0;
+}
+
+static void keyboard_repeat(idev_keyboard *k) {
+        idev_data *evdata = &k->evdata;
+        idev_data *repdata = &k->repdata;
+        idev_data_keyboard *evkbd = &evdata->keyboard;
+        idev_data_keyboard *repkbd = &repdata->keyboard;
+        const xkb_keysym_t *keysyms;
+        idev_device *d = &k->device;
+        bool repeats;
+        int r, num;
+
+        if (evdata->resync) {
+                /*
+                 * We received a re-sync event. During re-sync, any number of
+                 * key-events may have been lost and sync-events may be
+                 * re-ordered. Always disable key-repeat for those events. Any
+                 * following event will trigger it again.
+                 */
+
+                k->repeating = false;
+                keyboard_arm(k, 0);
+                return;
+        }
+
+        repeats = xkb_keymap_key_repeats(k->kbdmap->xkb_keymap, evkbd->keycode + KBDXKB_SHIFT);
+
+        if (k->repeating && repkbd->keycode == evkbd->keycode) {
+                /*
+                 * We received an event for the key we currently repeat. If it
+                 * was released, stop key-repeat. Otherwise, ignore the event.
+                 */
+
+                if (evkbd->value == KBDKEY_UP) {
+                        k->repeating = false;
+                        keyboard_arm(k, 0);
+                }
+        } else if (evkbd->value == KBDKEY_DOWN && repeats) {
+                /*
+                 * We received a key-down event for a key that repeats. The
+                 * previous condition caught keys we already repeat, so we know
+                 * this is a different key or no key-repeat is running. Start
+                 * new key-repeat.
+                 */
+
+                errno = 0;
+                num = xkb_state_key_get_syms(k->xkb_state, evkbd->keycode + KBDXKB_SHIFT, &keysyms);
+                if (num < 0)
+                        r = errno > 0 ? errno : -EFAULT;
+                else
+                        r = keyboard_fill(k, repdata, false, evkbd->keycode, KBDKEY_REPEAT, num, keysyms);
+
+                if (r < 0) {
+                        log_debug("idev-keyboard: %s/%s: cannot set key-repeat: %s",
+                                  d->session->name, d->name, strerror(-r));
+                        k->repeating = false;
+                        keyboard_arm(k, 0);
+                } else {
+                        k->repeating = true;
+                        keyboard_arm(k, k->repeat_delay);
+                }
+        } else if (k->repeating && !repeats) {
+                /*
+                 * We received an event for a key that does not repeat, but we
+                 * currently repeat a previously received key. The new key is
+                 * usually a modifier, but might be any kind of key. In this
+                 * case, we continue repeating the old key, but update the
+                 * symbols according to the new state.
+                 */
+
+                errno = 0;
+                num = xkb_state_key_get_syms(k->xkb_state, repkbd->keycode + KBDXKB_SHIFT, &keysyms);
+                if (num < 0)
+                        r = errno > 0 ? errno : -EFAULT;
+                else
+                        r = keyboard_fill(k, repdata, false, repkbd->keycode, KBDKEY_REPEAT, num, keysyms);
+
+                if (r < 0) {
+                        log_debug("idev-keyboard: %s/%s: cannot update key-repeat: %s",
+                                  d->session->name, d->name, strerror(-r));
+                        k->repeating = false;
+                        keyboard_arm(k, 0);
+                }
+        }
+}
+
+static int keyboard_feed_evdev(idev_keyboard *k, idev_data *data) {
+        struct input_event *ev = &data->evdev.event;
+        enum xkb_state_component compch;
+        const xkb_keysym_t *keysyms;
+        idev_device *d = &k->device;
+        int num, r;
+
+        if (ev->type != EV_KEY || ev->value > KBDKEY_DOWN)
+                return 0;
+
+        /* TODO: We should audit xkb-actions, whether they need @resync as
+         * flag. Most actions should just be executed, however, there might
+         * be actions that depend on modifier-orders. Those should be
+         * suppressed. */
+
+        num = xkb_state_key_get_syms(k->xkb_state, ev->code + KBDXKB_SHIFT, &keysyms);
+        compch = xkb_state_update_key(k->xkb_state, ev->code + KBDXKB_SHIFT, ev->value);
+
+        if (compch & XKB_STATE_LEDS) {
+                /* TODO: update LEDs */
+        }
+
+        if (num < 0)
+                goto error;
+
+        r = keyboard_fill(k, &k->evdata, data->resync, ev->code, ev->value, num, keysyms);
+        if (r < 0)
+                goto error;
+
+        keyboard_repeat(k);
+        return keyboard_raise_data(k, &k->evdata);
+
+error:
+        log_debug("idev-keyboard: %s/%s: cannot handle event: %s",
+                  d->session->name, d->name, strerror(-r));
+        k->repeating = false;
+        keyboard_arm(k, 0);
+        return 0;
+}
+
+static int keyboard_feed(idev_device *d, idev_data *data) {
+        idev_keyboard *k = keyboard_from_device(d);
+
+        switch (data->type) {
+        case IDEV_DATA_RESYNC:
+                /*
+                 * If the underlying device is re-synced, key-events might be
+                 * sent re-ordered. Thus, we don't know which key was pressed
+                 * last. Key-repeat might get confused, hence, disable it
+                 * during re-syncs. The first following event will enable it
+                 * again.
+                 */
+
+                k->repeating = false;
+                keyboard_arm(k, 0);
+                return 0;
+        case IDEV_DATA_EVDEV:
+                return keyboard_feed_evdev(k, data);
+        default:
+                return 0;
+        }
+}
+
+static int keyboard_update_kbdmap(idev_keyboard *k) {
+        idev_device *d = &k->device;
+        struct xkb_state *state;
+        kbdmap *km;
+        int r;
+
+        assert(k);
+
+        km = k->kbdctx->kbdmap;
+        if (km == k->kbdmap)
+                return 0;
+
+        errno = 0;
+        state = xkb_state_new(km->xkb_keymap);
+        if (!state) {
+                r = errno > 0 ? -errno : -EFAULT;
+                goto error;
+        }
+
+        kbdmap_unref(k->kbdmap);
+        k->kbdmap = kbdmap_ref(km);
+        xkb_state_unref(k->xkb_state);
+        k->xkb_state = state;
+
+        /* TODO: On state-change, we should trigger a resync so the whole
+         * event-state is flushed into the new xkb-state. libevdev currently
+         * does not support that, though. */
+
+        return 0;
+
+error:
+        log_debug("idev-keyboard: %s/%s: cannot adopt new keymap: %s",
+                  d->session->name, d->name, strerror(-r));
+        return r;
+}
+
+static const idev_device_vtable keyboard_vtable = {
+        .free                   = keyboard_free,
+        .feed                   = keyboard_feed,
+};
diff --git a/src/libsystemd-terminal/idev.c b/src/libsystemd-terminal/idev.c
index 2316a66..0ed518c 100644
--- a/src/libsystemd-terminal/idev.c
+++ b/src/libsystemd-terminal/idev.c
@@ -27,6 +27,7 @@
 #include <systemd/sd-bus.h>
 #include <systemd/sd-event.h>
 #include <systemd/sd-login.h>
+#include <xkbcommon/xkbcommon.h>
 #include "hashmap.h"
 #include "idev.h"
 #include "idev-internal.h"
@@ -525,10 +526,40 @@ void idev_session_disable(idev_session *s) {
         }
 }
 
+static int add_link(idev_element *e, idev_device *d) {
+        idev_link *l;
+
+        assert(e);
+        assert(d);
+
+        l = new0(idev_link, 1);
+        if (!l)
+                return -ENOMEM;
+
+        l->element = e;
+        l->device = d;
+        LIST_PREPEND(links_by_element, e->links, l);
+        LIST_PREPEND(links_by_device, d->links, l);
+        device_attach(d, l);
+
+        return 0;
+}
+
+static int guess_type(struct udev_device *d) {
+        const char *id_key;
+
+        id_key = udev_device_get_property_value(d, "ID_INPUT_KEY");
+        if (streq_ptr(id_key, "1"))
+                return IDEV_DEVICE_KEYBOARD;
+
+        return IDEV_DEVICE_CNT;
+}
+
 int idev_session_add_evdev(idev_session *s, struct udev_device *ud) {
         idev_element *e;
+        idev_device *d;
         dev_t devnum;
-        int r;
+        int r, type;
 
         assert_return(s, -EINVAL);
         assert_return(ud, -EINVAL);
@@ -549,7 +580,34 @@ int idev_session_add_evdev(idev_session *s, struct udev_device *ud) {
         if (r != 0)
                 return r;
 
-        return 0;
+        type = guess_type(ud);
+        if (type < 0)
+                return type;
+
+        switch (type) {
+        case IDEV_DEVICE_KEYBOARD:
+                d = idev_find_keyboard(s, e->name);
+                if (d) {
+                        log_debug("idev: %s: keyboard for new evdev element '%s' already available",
+                                  s->name, e->name);
+                        return 0;
+                }
+
+                r = idev_keyboard_new(&d, s, e->name);
+                if (r < 0)
+                        return r;
+
+                r = add_link(e, d);
+                if (r < 0) {
+                        idev_device_free(d);
+                        return r;
+                }
+
+                return session_add_device(s, d);
+        default:
+                /* unknown elements are silently ignored */
+                return 0;
+        }
 }
 
 int idev_session_remove_evdev(idev_session *s, struct udev_device *ud) {
diff --git a/src/libsystemd-terminal/idev.h b/src/libsystemd-terminal/idev.h
index c98fb1b..0ae044c 100644
--- a/src/libsystemd-terminal/idev.h
+++ b/src/libsystemd-terminal/idev.h
@@ -32,10 +32,12 @@
 #include <stdlib.h>
 #include <systemd/sd-bus.h>
 #include <systemd/sd-event.h>
+#include <xkbcommon/xkbcommon.h>
 #include "util.h"
 
 typedef struct idev_data                idev_data;
 typedef struct idev_data_evdev          idev_data_evdev;
+typedef struct idev_data_keyboard       idev_data_keyboard;
 
 typedef struct idev_event               idev_event;
 typedef struct idev_device              idev_device;
@@ -52,6 +54,7 @@ enum {
 };
 
 enum {
+        IDEV_DEVICE_KEYBOARD,
         IDEV_DEVICE_CNT
 };
 
@@ -64,12 +67,57 @@ struct idev_data_evdev {
 };
 
 /*
+ * Keyboard Devices
+ */
+
+struct xkb_state;
+
+enum {
+        IDEV_KBDMOD_IDX_SHIFT,
+        IDEV_KBDMOD_IDX_CTRL,
+        IDEV_KBDMOD_IDX_ALT,
+        IDEV_KBDMOD_IDX_LINUX,
+        IDEV_KBDMOD_IDX_CAPS,
+        IDEV_KBDMOD_CNT,
+
+        IDEV_KBDMOD_SHIFT               = 1 << IDEV_KBDMOD_IDX_SHIFT,
+        IDEV_KBDMOD_CTRL                = 1 << IDEV_KBDMOD_IDX_CTRL,
+        IDEV_KBDMOD_ALT                 = 1 << IDEV_KBDMOD_IDX_ALT,
+        IDEV_KBDMOD_LINUX               = 1 << IDEV_KBDMOD_IDX_LINUX,
+        IDEV_KBDMOD_CAPS                = 1 << IDEV_KBDMOD_IDX_CAPS,
+};
+
+enum {
+        IDEV_KBDLED_IDX_NUM,
+        IDEV_KBDLED_IDX_CAPS,
+        IDEV_KBDLED_IDX_SCROLL,
+        IDEV_KBDLED_CNT,
+
+        IDEV_KBDLED_NUM                 = 1 << IDEV_KBDLED_IDX_NUM,
+        IDEV_KBDLED_CAPS                = 1 << IDEV_KBDLED_IDX_CAPS,
+        IDEV_KBDLED_SCROLL              = 1 << IDEV_KBDLED_IDX_SCROLL,
+};
+
+struct idev_data_keyboard {
+        struct xkb_state *xkb_state;
+        int8_t ascii;
+        uint8_t value;
+        uint16_t keycode;
+        uint32_t mods;
+        uint32_t consumed_mods;
+        uint32_t n_syms;
+        uint32_t *keysyms;
+        uint32_t *codepoints;
+};
+
+/*
  * Data Packets
  */
 
 enum {
         IDEV_DATA_RESYNC,
         IDEV_DATA_EVDEV,
+        IDEV_DATA_KEYBOARD,
         IDEV_DATA_CNT
 };
 
@@ -79,6 +127,7 @@ struct idev_data {
 
         union {
                 idev_data_evdev evdev;
+                idev_data_keyboard keyboard;
         };
 };
 

commit c93e5a62ff599528c3bf2a8656825403aaebe093
Author: David Herrmann <dh.herrmann at gmail.com>
Date:   Wed Aug 27 18:31:34 2014 +0200

    terminal: add evdev elements to idev
    
    The evdev-element provides linux evdev interfaces as idev-elements. This
    way, all real input hardware devices on linux can be used with the idev
    interface.
    
    We use libevdev to interface with the kernel. It's a simple wrapper
    library around the kernel evdev API that takes care to resync devices
    after kernel-queue overflows, which is a rather non-trivial task.
    Furthermore, it's a well tested interface used by all other major input
    users (Xorg, weston, libinput, ...).
    Last but not least, it provides nice keycode to keyname lookup tables (and
    vice versa), which is really nice for debugging input problems.

diff --git a/Makefile.am b/Makefile.am
index 82f474e..b51c522 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -2968,12 +2968,14 @@ tests += \
 endif
 
 libsystemd_terminal_la_CFLAGS = \
-	$(AM_CFLAGS)
+	$(AM_CFLAGS) \
+	$(TERMINAL_CFLAGS)
 
 libsystemd_terminal_la_SOURCES = \
 	src/libsystemd-terminal/idev.h \
 	src/libsystemd-terminal/idev-internal.h \
 	src/libsystemd-terminal/idev.c \
+	src/libsystemd-terminal/idev-evdev.c \
 	src/libsystemd-terminal/sysview.h \
 	src/libsystemd-terminal/sysview-internal.h \
 	src/libsystemd-terminal/sysview.c \
@@ -2989,7 +2991,8 @@ libsystemd_terminal_la_SOURCES = \
 libsystemd_terminal_la_LIBADD = \
 	libudev-internal.la \
 	libsystemd-internal.la \
-	libsystemd-shared.la
+	libsystemd-shared.la \
+	$(TERMINAL_LIBS)
 
 systemd_subterm_SOURCES = \
 	src/libsystemd-terminal/subterm.c
diff --git a/configure.ac b/configure.ac
index 08a8a10..3900c40 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1066,8 +1066,11 @@ AM_CONDITIONAL(ENABLE_MULTI_SEAT_X, [test "$have_multi_seat_x" = "yes"])
 have_terminal=no
 AC_ARG_ENABLE(terminal, AS_HELP_STRING([--enable-terminal], [enable terminal support]))
 if test "x$enable_terminal" = "xyes"; then
-        AC_DEFINE(ENABLE_TERMINAL, 1, [Define if terminal support is to be enabled])
-        have_terminal=yes
+        PKG_CHECK_MODULES([TERMINAL], [ libevdev >= 1.2 ], [have_terminal=yes])
+        AS_IF([test "x$have_terminal" != xyes -a "x$enable_terminal" = xyes],
+              [AC_MSG_ERROR([*** terminal support requested but required dependencies not available])],
+              [test "x$have_terminal" = xyes],
+              [AC_DEFINE(ENABLE_TERMINAL, 1, [Define if terminal support is to be enabled])])
 fi
 AM_CONDITIONAL(ENABLE_TERMINAL, [test "x$have_terminal" = "xyes"])
 
diff --git a/src/libsystemd-terminal/idev-evdev.c b/src/libsystemd-terminal/idev-evdev.c
new file mode 100644
index 0000000..c93ede8
--- /dev/null
+++ b/src/libsystemd-terminal/idev-evdev.c
@@ -0,0 +1,938 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+  This file is part of systemd.
+
+  Copyright (C) 2014 David Herrmann <dh.herrmann at gmail.com>
+
+  systemd is free software; you can redistribute it and/or modify it
+  under the terms of the GNU Lesser General Public License as published by
+  the Free Software Foundation; either version 2.1 of the License, or
+  (at your option) any later version.
+
+  systemd is distributed in the hope that it will be useful, but
+  WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+  Lesser General Public License for more details.
+
+  You should have received a copy of the GNU Lesser General Public License
+  along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <fcntl.h>
+#include <inttypes.h>
+#include <libevdev/libevdev.h>
+#include <libudev.h>
+#include <stdbool.h>
+#include <stdlib.h>
+#include <systemd/sd-bus.h>
+#include <systemd/sd-event.h>
+#include <unistd.h>
+#include "bus-util.h"
+#include "hashmap.h"
+#include "idev.h"
+#include "idev-internal.h"
+#include "macro.h"
+#include "udev-util.h"
+#include "util.h"
+
+typedef struct idev_evdev idev_evdev;
+typedef struct unmanaged_evdev unmanaged_evdev;
+typedef struct managed_evdev managed_evdev;
+
+struct idev_evdev {
+        struct idev_element element;
+        struct libevdev *evdev;
+        int fd;
+        sd_event_source *fd_src;
+        sd_event_source *idle_src;
+
+        bool unsync : 1;                /* not in-sync with kernel */
+        bool resync : 1;                /* re-syncing with kernel */
+};
+
+struct unmanaged_evdev {
+        struct idev_evdev evdev;
+        char *devnode;
+};
+
+struct managed_evdev {
+        struct idev_evdev evdev;
+        dev_t devnum;
+
+        sd_bus_slot *slot_pause_device;
+        sd_bus_slot *slot_resume_device;
+        sd_bus_slot *slot_take_device;
+
+        bool requested : 1;             /* TakeDevice() was sent */
+        bool acquired : 1;              /* TakeDevice() was successful */
+};
+
+#define idev_evdev_from_element(_e) container_of((_e), idev_evdev, element)
+#define unmanaged_evdev_from_element(_e) \
+        container_of(idev_evdev_from_element(_e), unmanaged_evdev, evdev)
+#define managed_evdev_from_element(_e) \
+        container_of(idev_evdev_from_element(_e), managed_evdev, evdev)
+
+#define IDEV_EVDEV_INIT(_vtable, _session) ((idev_evdev){ \
+                .element = IDEV_ELEMENT_INIT((_vtable), (_session)), \
+                .fd = -1, \
+        })
+
+#define IDEV_EVDEV_NAME_MAX (8 + DECIMAL_STR_MAX(unsigned) * 2)
+
+static const idev_element_vtable unmanaged_evdev_vtable;
+static const idev_element_vtable managed_evdev_vtable;
+
+static int idev_evdev_resume(idev_evdev *evdev, int dev_fd);
+static void idev_evdev_pause(idev_evdev *evdev, bool release);
+
+/*
+ * Virtual Evdev Element
+ * The virtual evdev element is the base class of all other evdev elements. It
+ * uses libevdev to access the kernel evdev API. It supports asynchronous
+ * access revocation, re-syncing if events got dropped and more.
+ * This element cannot be used by itself. There must be a wrapper around it
+ * which opens a file-descriptor and passes it to the virtual evdev element.
+ */
+
+static void idev_evdev_name(char *out, dev_t devnum) {
+        /* @out must be at least of size IDEV_EVDEV_NAME_MAX */
+        sprintf(out, "evdev/%u:%u", major(devnum), minor(devnum));
+}
+
+static int idev_evdev_raise(idev_evdev *evdev, struct input_event *event) {
+        idev_data data = {
+                .type = IDEV_DATA_EVDEV,
+                .resync = evdev->resync,
+                .evdev = {
+                        .event = *event,
+                },
+        };
+
+        return idev_element_feed(&evdev->element, &data);
+}
+
+static void idev_evdev_hup(idev_evdev *evdev) {
+        /*
+         * On HUP, we close the current fd via idev_evdev_pause(). This drops
+         * the event-sources from the main-loop and effectively puts the
+         * element asleep. If the HUP is part of a hotplug-event, a following
+         * udev-notification will destroy the element. Otherwise, the HUP is
+         * either result of access-revokation or a serious error.
+         * For unmanaged devices, we should never receive HUP (except for
+         * unplug-events). But if we do, something went seriously wrong and we
+         * shouldn't try to be clever.
+         * Instead, we simply stay asleep and wait for the device to be
+         * disabled and then re-enabled (or closed and re-opened). This will
+         * re-open the device node and restart the device.
+         * For managed devices, a HUP usually means our device-access was
+         * revoked. In that case, we simply put the device asleep and wait for
+         * logind to notify us once the device is alive again. logind also
+         * passes us a new fd. Hence, we don't have to re-enable the device.
+         *
+         * Long story short: The only thing we have to do here, is close() the
+         * file-descriptor and remove it from the main-loop. Everything else is
+         * handled via additional events we receive.
+         */
+
+        idev_evdev_pause(evdev, true);
+}
+
+static int idev_evdev_io(idev_evdev *evdev) {
+        idev_element *e = &evdev->element;
+        struct input_event ev;
+        unsigned int flags;
+        int r, error = 0;
+
+        /*
+         * Read input-events via libevdev until the input-queue is drained. In
+         * case we're disabled, don't do anything. The input-queue might
+         * overflow, but we don't care as we have to resync after wake-up,
+         * anyway.
+         * TODO: libevdev should give us a hint how many events to read. We
+         * really want to avoid starvation, so we shouldn't read forever in
+         * case we cannot keep up with the kernel.
+         * TODO: Make sure libevdev always reports SYN_DROPPED to us, regardless
+         * whether any event was synced afterwards.
+         * TODO: Forward SYN_DROPPED to attached devices.
+         */
+
+        flags = LIBEVDEV_READ_FLAG_NORMAL;
+        while (e->enabled) {
+                if (evdev->unsync) {
+                        /* immediately resync, even if in sync right now */
+                        evdev->unsync = false;
+                        evdev->resync = false;
+                        flags = LIBEVDEV_READ_FLAG_NORMAL;
+                        r = libevdev_next_event(evdev->evdev, flags | LIBEVDEV_READ_FLAG_FORCE_SYNC, &ev);
+                        if (r < 0 && r != -EAGAIN) {
+                                r = 0;
+                                goto error;
+                        } else if (r != LIBEVDEV_READ_STATUS_SYNC) {
+                                log_debug("idev-evdev: %s/%s: cannot force resync: %d",
+                                          e->session->name, e->name, r);
+                        }
+                } else {
+                        r = libevdev_next_event(evdev->evdev, flags, &ev);
+                }
+
+                if (evdev->resync && r == -EAGAIN) {
+                        /* end of re-sync */
+                        evdev->resync = false;
+                        flags = LIBEVDEV_READ_FLAG_NORMAL;
+                } else if (r == -EAGAIN) {
+                        /* no data available */
+                        break;
+                } else if (r < 0) {
+                        /* read error */
+                        goto error;
+                } else if (r == LIBEVDEV_READ_STATUS_SYNC) {
+                        if (evdev->resync) {
+                                /* sync-event */
+                                r = idev_evdev_raise(evdev, &ev);
+                                if (r != 0) {
+                                        error = r;
+                                        break;
+                                }
+                        } else {
+                                /* start of sync */
+                                evdev->resync = true;
+                                flags = LIBEVDEV_READ_FLAG_SYNC;
+                        }
+                } else {
+                        /* normal event */
+                        r = idev_evdev_raise(evdev, &ev);
+                        if (r != 0) {
+                                error = r;
+                                break;
+                        }
+                }
+        }
+
+        if (error < 0)
+                log_debug("idev-evdev: %s/%s: error on data event: %s",
+                          e->session->name, e->name, strerror(-error));
+        return error;
+
+error:
+        idev_evdev_hup(evdev);
+        return r;
+}
+
+static int idev_evdev_event_fn(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
+        idev_evdev *evdev = userdata;
+
+        /* fetch data as long as EPOLLIN is signalled */
+        if (revents & EPOLLIN)
+                return idev_evdev_io(evdev);
+
+        if (revents & (EPOLLHUP | EPOLLERR))
+                idev_evdev_hup(evdev);
+
+        return 0;
+}
+
+static int idev_evdev_idle_fn(sd_event_source *s, void *userdata) {
+        idev_evdev *evdev = userdata;
+
+        /*
+         * The idle-event is raised whenever we have to re-sync the libevdev
+         * state from the kernel. We simply call into idev_evdev_io() which
+         * flushes the state and re-syncs it if @unsync is set.
+         * State has to be synced whenever our view of the kernel device is
+         * out of date. This is the case when we open the device, if the
+         * kernel's receive buffer overflows, or on other exceptional
+         * situations. Events during re-syncs must be forwarded to the upper
+         * layers so they can update their view of the device. However, such
+         * events must only be handled passively, as they might be out-of-order
+         * and/or re-ordered. Therefore, we mark them as 'sync' events.
+         */
+
+        if (!evdev->unsync)
+                return 0;
+
+        return idev_evdev_io(evdev);
+}
+
+static void idev_evdev_destroy(idev_evdev *evdev) {
+        assert(evdev);
+        assert(evdev->fd < 0);
+
+        libevdev_free(evdev->evdev);
+        evdev->evdev = NULL;
+}
+
+static void idev_evdev_enable(idev_evdev *evdev) {
+        assert(evdev);
+        assert(evdev->fd_src);
+        assert(evdev->idle_src);
+
+        sd_event_source_set_enabled(evdev->fd_src, SD_EVENT_ON);
+        sd_event_source_set_enabled(evdev->idle_src, SD_EVENT_ONESHOT);
+}
+
+static void idev_evdev_disable(idev_evdev *evdev) {
+        assert(evdev);
+        assert(evdev->fd_src);
+        assert(evdev->idle_src);
+
+        sd_event_source_set_enabled(evdev->fd_src, SD_EVENT_OFF);
+        sd_event_source_set_enabled(evdev->idle_src, SD_EVENT_OFF);
+}
+
+static int idev_evdev_resume(idev_evdev *evdev, int dev_fd) {
+        idev_element *e = &evdev->element;
+        _cleanup_close_ int fd = dev_fd;
+        int r, flags;
+
+        if (fd < 0 || evdev->fd == fd) {
+                fd = -1;
+                if (evdev->fd >= 0 && e->n_open > 0 && e->enabled)
+                        idev_evdev_enable(evdev);
+
+                return 0;
+        }
+
+        idev_evdev_pause(evdev, true);
+        log_debug("idev-evdev: %s/%s: resume", e->session->name, e->name);
+
+        r = fd_nonblock(fd, true);
+        if (r < 0)
+                return r;
+
+        r = fd_cloexec(fd, true);
+        if (r < 0)
+                return r;
+
+        flags = fcntl(fd, F_GETFL, 0);
+        if (flags < 0)
+                return r;
+
+        flags &= O_ACCMODE;
+        if (flags == O_WRONLY)
+                return -EACCES;
+
+        evdev->element.readable = true;
+        evdev->element.writable = true;
+        if (flags == O_RDONLY)
+                evdev->element.writable = false;
+        else if (flags == O_WRONLY)
+                evdev->element.readable = false;
+
+        /*
+         * TODO: We *MUST* re-sync the device so we get a delta of the changed
+         * state while we didn't read events from the device. This works just
+         * fine with libevdev_change_fd(), however, libevdev_new_from_fd() (or
+         * libevdev_set_fd()) don't pass us events for the initial device
+         * state. So even if we force a re-sync, we will not get the delta for
+         * the initial device state.
+         * We really need to fix libevdev to support that!
+         */
+        if (evdev->evdev)
+                r = libevdev_change_fd(evdev->evdev, fd);
+        else
+                r = libevdev_new_from_fd(fd, &evdev->evdev);
+
+        if (r < 0)
+                return r;
+
+        r = sd_event_add_io(e->session->context->event,
+                            &evdev->fd_src,
+                            fd,
+                            EPOLLHUP | EPOLLERR | EPOLLIN,
+                            idev_evdev_event_fn,
+                            evdev);
+        if (r < 0)
+                return r;
+
+        r = sd_event_add_defer(e->session->context->event,
+                               &evdev->idle_src,
+                               idev_evdev_idle_fn,
+                               evdev);
+        if (r < 0) {
+                evdev->fd_src = sd_event_source_unref(evdev->fd_src);
+                return r;
+        }
+
+        if (e->n_open < 1 || !e->enabled) {
+                sd_event_source_set_enabled(evdev->fd_src, SD_EVENT_OFF);
+                sd_event_source_set_enabled(evdev->idle_src, SD_EVENT_OFF);
+        }
+
+        evdev->unsync = true;
+        evdev->fd = fd;
+
+        fd = -1;
+        return 0;
+}
+
+static void idev_evdev_pause(idev_evdev *evdev, bool release) {
+        idev_element *e = &evdev->element;
+
+        if (evdev->fd < 0)
+                return;
+
+        log_debug("idev-evdev: %s/%s: pause", e->session->name, e->name);
+
+        if (release) {
+                evdev->idle_src = sd_event_source_unref(evdev->idle_src);
+                evdev->fd_src = sd_event_source_unref(evdev->fd_src);
+                evdev->fd = safe_close(evdev->fd);
+        } else {
+                idev_evdev_disable(evdev);
+        }
+}
+
+/*
+ * Unmanaged Evdev Element
+ * The unmanaged evdev element opens the evdev node for a given input device
+ * directly (/dev/input/eventX) and thus needs sufficient privileges. It opens
+ * the device only if we really require it and releases it as soon as we're
+ * disabled or closed.
+ * The unmanaged element can be used in all situations where you have direct
+ * access to input device nodes. Unlike managed evdev elements, it can be used
+ * outside of user sessions and in emergency situations where logind is not
+ * available.
+ */
+
+static void unmanaged_evdev_resume(idev_element *e) {
+        unmanaged_evdev *eu = unmanaged_evdev_from_element(e);
+        int r, fd;
+
+        /*
+         * Unmanaged devices can be acquired on-demand. Therefore, don't
+         * acquire it unless someone opened the device *and* we're enabled.
+         */
+        if (e->n_open < 1 || !e->enabled)
+                return;
+
+        fd = eu->evdev.fd;
+        if (fd < 0) {
+                fd = open(eu->devnode, O_RDWR | O_CLOEXEC | O_NOCTTY | O_NONBLOCK);
+                if (fd < 0) {
+                        if (errno != EACCES && errno != EPERM) {
+                                log_debug("idev-evdev: %s/%s: cannot open node %s: %m",
+                                          e->session->name, e->name, eu->devnode);
+                                return;
+                        }
+
+                        fd = open(eu->devnode, O_RDONLY | O_CLOEXEC | O_NOCTTY | O_NONBLOCK);
+                        if (fd < 0) {
+                                log_debug("idev-evdev: %s/%s: cannot open node %s: %m",
+                                          e->session->name, e->name, eu->devnode);
+                                return;
+                        }
+
+                        e->readable = true;
+                        e->writable = false;
+                } else {
+                        e->readable = true;
+                        e->writable = true;
+                }
+        }
+
+        r = idev_evdev_resume(&eu->evdev, fd);
+        if (r < 0)
+                log_debug("idev-evdev: %s/%s: cannot resume: %s",
+                          e->session->name, e->name, strerror(-r));
+}
+
+static void unmanaged_evdev_pause(idev_element *e) {
+        unmanaged_evdev *eu = unmanaged_evdev_from_element(e);
+
+        /*
+         * Release the device if the device is disabled or there is no-one who
+         * opened it. This guarantees we stay only available if we're opened
+         * *and* enabled.
+         */
+
+        idev_evdev_pause(&eu->evdev, true);
+}
+
+static int unmanaged_evdev_new(idev_element **out, idev_session *s, struct udev_device *ud) {
+        _cleanup_(idev_element_freep) idev_element *e = NULL;
+        char name[IDEV_EVDEV_NAME_MAX];
+        unmanaged_evdev *eu;
+        const char *devnode;
+        dev_t devnum;
+        int r;
+
+        assert_return(s, -EINVAL);
+        assert_return(ud, -EINVAL);
+
+        devnode = udev_device_get_devnode(ud);
+        devnum = udev_device_get_devnum(ud);
+        if (!devnode || devnum == 0)
+                return -ENODEV;
+
+        idev_evdev_name(name, devnum);
+
+        eu = new0(unmanaged_evdev, 1);
+        if (!eu)
+                return -ENOMEM;
+
+        e = &eu->evdev.element;
+        eu->evdev = IDEV_EVDEV_INIT(&unmanaged_evdev_vtable, s);
+
+        eu->devnode = strdup(devnode);
+        if (!eu->devnode)
+                return -ENOMEM;
+
+        r = idev_element_add(e, name);
+        if (r < 0)
+                return r;
+
+        if (out)
+                *out = e;
+        e = NULL;
+        return 0;
+}
+
+static void unmanaged_evdev_free(idev_element *e) {
+        unmanaged_evdev *eu = unmanaged_evdev_from_element(e);
+
+        idev_evdev_destroy(&eu->evdev);
+        free(eu->devnode);
+        free(eu);
+}
+
+static const idev_element_vtable unmanaged_evdev_vtable = {
+        .free                   = unmanaged_evdev_free,
+        .enable                 = unmanaged_evdev_resume,
+        .disable                = unmanaged_evdev_pause,
+        .open                   = unmanaged_evdev_resume,
+        .close                  = unmanaged_evdev_pause,
+};
+
+/*
+ * Managed Evdev Element
+ * The managed evdev element uses systemd-logind to acquire evdev devices. This
+ * means, we do not open the device node /dev/input/eventX directly. Instead,
+ * logind passes us a file-descriptor whenever our session is activated. Thus,
+ * we don't need access to the device node directly.
+ * Furthermore, whenever the session is put asleep, logind revokes the
+ * file-descriptor so we loose access to the device.
+ * Managed evdev elements should be preferred over unmanaged elements whenever
+ * you run inside a user session with exclusive device access.
+ */
+
+static int managed_evdev_take_device_fn(sd_bus *bus,
+                                        sd_bus_message *reply,
+                                        void *userdata,
+                                        sd_bus_error *ret_error) {
+        managed_evdev *em = userdata;
+        idev_element *e = &em->evdev.element;
+        idev_session *s = e->session;
+        int r, paused, fd;
+
+        em->slot_take_device = sd_bus_slot_unref(em->slot_take_device);
+
+        if (sd_bus_message_is_method_error(reply, NULL)) {
+                const sd_bus_error *error = sd_bus_message_get_error(reply);
+
+                log_debug("idev-evdev: %s/%s: TakeDevice failed: %s: %s",
+                          s->name, e->name, error->name, error->message);
+                return 0;
+        }
+
+        em->acquired = true;
+
+        r = sd_bus_message_read(reply, "hb", &fd, &paused);
+        if (r < 0) {
+                log_debug("idev-evdev: %s/%s: erroneous TakeDevice reply", s->name, e->name);
+                return 0;
+        }
+
+        /* If the device is paused, ignore it; we will get the next fd via
+         * ResumeDevice signals. */
+        if (paused)
+                return 0;
+
+        fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
+        if (fd < 0) {
+                log_debug("idev-evdev: %s/%s: cannot duplicate evdev fd: %m", s->name, e->name);
+                return 0;
+        }
+
+        r = idev_evdev_resume(&em->evdev, fd);
+        if (r < 0)
+                log_debug("idev-evdev: %s/%s: cannot resume: %s",
+                          s->name, e->name, strerror(-r));
+
+        return 0;
+}
+
+static void managed_evdev_resume(idev_element *e) {
+        _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
+        managed_evdev *em = managed_evdev_from_element(e);
+        idev_session *s = e->session;
+        idev_context *c = s->context;
+        int r;
+
+        /*
+         * Acquiring managed devices is heavy, so do it only once we're
+         * enabled *and* opened by someone.
+         */
+        if (e->n_open < 1 || !e->enabled)
+                return;
+
+        /* bail out if already pending */
+        if (em->requested)
+                return;
+
+        r = sd_bus_message_new_method_call(c->sysbus,
+                                           &m,
+                                           "org.freedesktop.login1",
+                                           s->path,
+                                           "org.freedesktop.login1.Session",
+                                           "TakeDevice");
+        if (r < 0)
+                goto error;
+
+        r = sd_bus_message_append(m, "uu", major(em->devnum), minor(em->devnum));
+        if (r < 0)
+                goto error;
+
+        r = sd_bus_call_async(c->sysbus,
+                              &em->slot_take_device,
+                              m,
+                              managed_evdev_take_device_fn,
+                              em,
+                              0);
+        if (r < 0)
+                goto error;
+
+        em->requested = true;
+        return;
+
+error:
+        log_debug("idev-evdev: %s/%s: cannot send TakeDevice request: %s",
+                  s->name, e->name, strerror(-r));
+}
+
+static void managed_evdev_pause(idev_element *e) {
+        _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
+        managed_evdev *em = managed_evdev_from_element(e);
+        idev_session *s = e->session;
+        idev_context *c = s->context;
+        int r;
+
+        /*
+         * Releasing managed devices is heavy. Once acquired, we get
+         * notifications for sleep/wake-up events, so there's no reason to
+         * release it if disabled but opened. However, if a device is closed,
+         * we release it immediately as we don't care for sleep/wake-up events
+         * then (even if we're actually enabled).
+         */
+
+        idev_evdev_pause(&em->evdev, false);
+
+        if (e->n_open > 0 || !em->requested)
+                return;
+
+        /*
+         * If TakeDevice() is pending or was successful, make sure to
+         * release the device again. We don't care for return-values,
+         * so send it without waiting or callbacks.
+         * If a failed TakeDevice() is pending, but someone else took
+         * the device on the same bus-connection, we might incorrectly
+         * release their device. This is an unlikely race, though.
+         * Furthermore, you really shouldn't have two users of the
+         * controller-API on the same session, on the same devices, *AND* on
+         * the same bus-connection. So we don't care for that race..
+         */
+
+        idev_evdev_pause(&em->evdev, true);
+        em->requested = false;
+
+        if (!em->acquired && !em->slot_take_device)
+                return;
+
+        em->slot_take_device = sd_bus_slot_unref(em->slot_take_device);
+        em->acquired = false;
+
+        r = sd_bus_message_new_method_call(c->sysbus,
+                                           &m,
+                                           "org.freedesktop.login1",
+                                           s->path,
+                                           "org.freedesktop.login1.Session",
+                                           "ReleaseDevice");
+        if (r >= 0) {
+                r = sd_bus_message_append(m, "uu", major(em->devnum), minor(em->devnum));
+                if (r >= 0)
+                        r = sd_bus_send(c->sysbus, m, NULL);
+        }
+
+        if (r < 0 && r != -ENOTCONN)
+                log_debug("idev-evdev: %s/%s: cannot send ReleaseDevice: %s",
+                          s->name, e->name, strerror(-r));
+}
+
+static int managed_evdev_pause_device_fn(sd_bus *bus,
+                                         sd_bus_message *signal,
+                                         void *userdata,
+                                         sd_bus_error *ret_error) {
+        managed_evdev *em = userdata;
+        idev_element *e = &em->evdev.element;
+        idev_session *s = e->session;
+        idev_context *c = s->context;
+        uint32_t major, minor;
+        const char *mode;
+        int r;
+
+        /*
+         * We get PauseDevice() signals from logind whenever a device we
+         * requested was, or is about to be, paused. Arguments are major/minor
+         * number of the device and the mode of the operation.
+         * In case the event is not about our device, we ignore it. Otherwise,
+         * we treat it as asynchronous access-revocation (as if we got HUP on
+         * the device fd). Note that we might have already treated the HUP
+         * event via EPOLLHUP, whichever comes first.
+         *
+         * @mode can be one of the following:
+         *   "pause": The device is about to be paused. We must react
+         *            immediately and respond with PauseDeviceComplete(). Once
+         *            we replied, logind will pause the device. Note that
+         *            logind might apply any kind of timeout and force pause
+         *            the device if we don't respond in a timely manner. In
+         *            this case, we will receive a second PauseDevice event
+         *            with @mode set to "force" (or similar).
+         *   "force": The device was disabled forecfully by logind. Access is
+         *            already revoked. This is just an asynchronous
+         *            notification so we can put the device asleep (in case
+         *            we didn't already notice the access revocation).
+         *    "gone": This is like "force" but is sent if the device was
+         *            paused due to a device-removal event.
+         *
+         * We always handle PauseDevice signals as "force" as we properly
+         * support asynchronous access revocation, anyway. But in case logind
+         * sent mode "pause", we also call PauseDeviceComplete() to immediately
+         * acknowledge the request.
+         */
+
+        r = sd_bus_message_read(signal, "uus", &major, &minor, &mode);
+        if (r < 0) {
+                log_debug("idev-evdev: %s/%s: erroneous PauseDevice signal",
+                          s->name, e->name);
+                return 0;
+        }
+
+        /* not our device? */
+        if (makedev(major, minor) != em->devnum)
+                return 0;
+
+        idev_evdev_pause(&em->evdev, true);
+
+        if (streq(mode, "pause")) {
+                _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
+
+                /*
+                 * Sending PauseDeviceComplete() is racy if logind triggers the
+                 * timeout. That is, if we take too long and logind pauses the
+                 * device by sending a forced PauseDevice, our
+                 * PauseDeviceComplete call will be stray. That's fine, though.
+                 * logind ignores such stray calls. Only if logind also sent a
+                 * further PauseDevice() signal, it might match our call
+                 * incorrectly to the newer PauseDevice(). That's fine, too, as
+                 * we handle that event asynchronously, anyway. Therefore,
+                 * whatever happens, we're fine. Yay!
+                 */
+
+                r = sd_bus_message_new_method_call(c->sysbus,
+                                                   &m,
+                                                   "org.freedesktop.login1",
+                                                   s->path,
+                                                   "org.freedesktop.login1.Session",
+                                                   "PauseDeviceComplete");
+                if (r >= 0) {
+                        r = sd_bus_message_append(m, "uu", major, minor);
+                        if (r >= 0)
+                                r = sd_bus_send(c->sysbus, m, NULL);
+                }
+
+                if (r < 0)
+                        log_debug("idev-evdev: %s/%s: cannot send PauseDeviceComplete: %s",
+                                  s->name, e->name, strerror(-r));
+        }
+
+        return 0;
+}
+
+static int managed_evdev_resume_device_fn(sd_bus *bus,
+                                          sd_bus_message *signal,
+                                          void *userdata,
+                                          sd_bus_error *ret_error) {
+        managed_evdev *em = userdata;
+        idev_element *e = &em->evdev.element;
+        idev_session *s = e->session;
+        uint32_t major, minor;
+        int r, fd;
+
+        /*
+         * We get ResumeDevice signals whenever logind resumed a previously
+         * paused device. The arguments contain the major/minor number of the
+         * related device and a new file-descriptor for the freshly opened
+         * device-node.
+         * If the signal is not about our device, we simply ignore it.
+         * Otherwise, we take the file-descriptor and immediately resume the
+         * device.
+         */
+
+        r = sd_bus_message_read(signal, "uuh", &major, &minor, &fd);
+        if (r < 0) {
+                log_debug("idev-evdev: %s/%s: erroneous ResumeDevice signal",
+                          s->name, e->name);
+                return 0;
+        }
+
+        /* not our device? */
+        if (makedev(major, minor) != em->devnum)
+                return 0;
+
+        fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
+        if (fd < 0) {
+                log_debug("idev-evdev: %s/%s: cannot duplicate evdev fd: %m",
+                          s->name, e->name);
+                return 0;
+        }
+
+        r = idev_evdev_resume(&em->evdev, fd);
+        if (r < 0)
+                log_debug("idev-evdev: %s/%s: cannot resume: %s",
+                          s->name, e->name, strerror(-r));
+
+        return 0;
+}
+
+static int managed_evdev_setup_bus(managed_evdev *em) {
+        idev_element *e = &em->evdev.element;
+        idev_session *s = e->session;
+        idev_context *c = s->context;
+        _cleanup_free_ char *match = NULL;
+        int r;
+
+        match = strjoin("type='signal',"
+                        "sender='org.freedesktop.login1',"
+                        "interface='org.freedesktop.login1.Session',"
+                        "member='PauseDevice',"
+                        "path='", s->path, "'",
+                        NULL);
+        if (!match)
+                return -ENOMEM;
+
+        r = sd_bus_add_match(c->sysbus,
+                             &em->slot_pause_device,
+                             match,
+                             managed_evdev_pause_device_fn,
+                             em);
+        if (r < 0)
+                return r;
+
+        free(match);
+        match = strjoin("type='signal',"
+                        "sender='org.freedesktop.login1',"
+                        "interface='org.freedesktop.login1.Session',"
+                        "member='ResumeDevice',"
+                        "path='", s->path, "'",
+                        NULL);
+        if (!match)
+                return -ENOMEM;
+
+        r = sd_bus_add_match(c->sysbus,
+                             &em->slot_resume_device,
+                             match,
+                             managed_evdev_resume_device_fn,
+                             em);
+        if (r < 0)
+                return r;
+
+        return 0;
+}
+
+static int managed_evdev_new(idev_element **out, idev_session *s, struct udev_device *ud) {
+        _cleanup_(idev_element_freep) idev_element *e = NULL;
+        char name[IDEV_EVDEV_NAME_MAX];
+        managed_evdev *em;
+        dev_t devnum;
+        int r;
+
+        assert_return(s, -EINVAL);
+        assert_return(s->context->sysbus, -EINVAL);
+        assert_return(s->managed, -EINVAL);
+        assert_return(s->context->sysbus, -EINVAL);
+        assert_return(ud, -EINVAL);
+
+        devnum = udev_device_get_devnum(ud);
+        if (devnum == 0)
+                return -ENODEV;
+
+        idev_evdev_name(name, devnum);
+
+        em = new0(managed_evdev, 1);
+        if (!em)
+                return -ENOMEM;
+
+        e = &em->evdev.element;
+        em->evdev = IDEV_EVDEV_INIT(&managed_evdev_vtable, s);
+        em->devnum = devnum;
+
+        r = managed_evdev_setup_bus(em);
+        if (r < 0)
+                return r;
+
+        r = idev_element_add(e, name);
+        if (r < 0)
+                return r;
+
+        if (out)
+                *out = e;
+        e = NULL;
+        return 0;
+}
+
+static void managed_evdev_free(idev_element *e) {
+        managed_evdev *em = managed_evdev_from_element(e);
+
+        em->slot_resume_device = sd_bus_slot_unref(em->slot_resume_device);
+        em->slot_pause_device = sd_bus_slot_unref(em->slot_pause_device);
+        idev_evdev_destroy(&em->evdev);
+        free(em);
+}
+
+static const idev_element_vtable managed_evdev_vtable = {
+        .free                   = managed_evdev_free,
+        .enable                 = managed_evdev_resume,
+        .disable                = managed_evdev_pause,
+        .open                   = managed_evdev_resume,
+        .close                  = managed_evdev_pause,
+};
+
+/*
+ * Generic Constructor
+ * Instead of relying on the caller to choose between managed and unmanaged
+ * evdev devices, the idev_evdev_new() constructor does that for you (by
+ * looking at s->managed).
+ */
+
+bool idev_is_evdev(idev_element *e) {
+        return e && (e->vtable == &unmanaged_evdev_vtable ||
+                     e->vtable == &managed_evdev_vtable);
+}
+
+idev_element *idev_find_evdev(idev_session *s, dev_t devnum) {
+        char name[IDEV_EVDEV_NAME_MAX];
+
+        assert_return(s, NULL);
+        assert_return(devnum != 0, NULL);
+
+        idev_evdev_name(name, devnum);
+        return idev_find_element(s, name);
+}
+
+int idev_evdev_new(idev_element **out, idev_session *s, struct udev_device *ud) {
+        assert_return(s, -EINVAL);
+        assert_return(ud, -EINVAL);
+
+        return s->managed ? managed_evdev_new(out, s, ud) : unmanaged_evdev_new(out, s, ud);
+}
diff --git a/src/libsystemd-terminal/idev-internal.h b/src/libsystemd-terminal/idev-internal.h
index bffefbb..3301ebf 100644
--- a/src/libsystemd-terminal/idev-internal.h
+++ b/src/libsystemd-terminal/idev-internal.h
@@ -22,6 +22,8 @@
 #pragma once
 
 #include <inttypes.h>
+#include <libudev.h>
+#include <linux/input.h>
 #include <stdbool.h>
 #include <stdlib.h>
 #include <systemd/sd-bus.h>
@@ -37,6 +39,14 @@ typedef struct idev_element             idev_element;
 typedef struct idev_element_vtable      idev_element_vtable;
 
 /*
+ * Evdev Elements
+ */
+
+bool idev_is_evdev(idev_element *e);
+idev_element *idev_find_evdev(idev_session *s, dev_t devnum);
+int idev_evdev_new(idev_element **out, idev_session *s, struct udev_device *ud);
+
+/*
  * Element Links
  */
 
diff --git a/src/libsystemd-terminal/idev.c b/src/libsystemd-terminal/idev.c
index 5e30807..2316a66 100644
--- a/src/libsystemd-terminal/idev.c
+++ b/src/libsystemd-terminal/idev.c
@@ -20,6 +20,8 @@
 ***/
 
 #include <inttypes.h>
+#include <libudev.h>
+#include <linux/input.h>
 #include <stdbool.h>
 #include <stdlib.h>
 #include <systemd/sd-bus.h>
@@ -31,6 +33,7 @@
 #include "login-shared.h"
 #include "macro.h"
 #include "set.h"
+#include "udev-util.h"
 #include "util.h"
 
 static void element_open(idev_element *e);
@@ -522,6 +525,51 @@ void idev_session_disable(idev_session *s) {
         }
 }
 
+int idev_session_add_evdev(idev_session *s, struct udev_device *ud) {
+        idev_element *e;
+        dev_t devnum;
+        int r;
+
+        assert_return(s, -EINVAL);
+        assert_return(ud, -EINVAL);
+
+        devnum = udev_device_get_devnum(ud);
+        if (devnum == 0)
+                return 0;
+
+        e = idev_find_evdev(s, devnum);
+        if (e)
+                return 0;
+
+        r = idev_evdev_new(&e, s, ud);
+        if (r < 0)
+                return r;
+
+        r = session_add_element(s, e);
+        if (r != 0)
+                return r;
+
+        return 0;
+}
+
+int idev_session_remove_evdev(idev_session *s, struct udev_device *ud) {
+        idev_element *e;
+        dev_t devnum;
+
+        assert(s);
+        assert(ud);
+
+        devnum = udev_device_get_devnum(ud);
+        if (devnum == 0)
+                return 0;
+
+        e = idev_find_evdev(s, devnum);
+        if (!e)
+                return 0;
+
+        return session_remove_element(s, e);
+}
+
 /*
  * Contexts
  */
diff --git a/src/libsystemd-terminal/idev.h b/src/libsystemd-terminal/idev.h
index 6f618f3..c98fb1b 100644
--- a/src/libsystemd-terminal/idev.h
+++ b/src/libsystemd-terminal/idev.h
@@ -26,6 +26,8 @@
 #pragma once
 
 #include <inttypes.h>
+#include <libudev.h>
+#include <linux/input.h>
 #include <stdbool.h>
 #include <stdlib.h>
 #include <systemd/sd-bus.h>
@@ -33,6 +35,7 @@
 #include "util.h"
 
 typedef struct idev_data                idev_data;
+typedef struct idev_data_evdev          idev_data_evdev;
 
 typedef struct idev_event               idev_event;
 typedef struct idev_device              idev_device;
@@ -44,6 +47,7 @@ typedef struct idev_context             idev_context;
  */
 
 enum {
+        IDEV_ELEMENT_EVDEV,
         IDEV_ELEMENT_CNT
 };
 
@@ -52,17 +56,30 @@ enum {
 };
 
 /*
+ * Evdev Elements
+ */
+
+struct idev_data_evdev {
+        struct input_event event;
+};
+
+/*
  * Data Packets
  */
 
 enum {
         IDEV_DATA_RESYNC,
+        IDEV_DATA_EVDEV,
         IDEV_DATA_CNT
 };
 
 struct idev_data {
         unsigned int type;
         bool resync : 1;
+
+        union {
+                idev_data_evdev evdev;
+        };
 };
 
 /*
@@ -122,6 +139,9 @@ bool idev_session_is_enabled(idev_session *s);
 void idev_session_enable(idev_session *s);
 void idev_session_disable(idev_session *s);
 
+int idev_session_add_evdev(idev_session *s, struct udev_device *ud);
+int idev_session_remove_evdev(idev_session *s, struct udev_device *ud);
+
 /*
  * Contexts
  */

commit e202fa31fb2d60084e7b2ab7976a81c138184d40
Author: David Herrmann <dh.herrmann at gmail.com>
Date:   Wed Aug 27 18:17:27 2014 +0200

    terminal: add input interface
    
    The idev-interface provides input drivers for all libsystemd-terminal
    based applications. It is split into 4 main objects:
        idev_context: The context object tracks global state of the input
                      interface. This will include data like system-keymaps,
                      xkb contexts and more.
        idev_session: A session serves as controller for a set of devices.
                      Each session on an idev-context is independent of each
                      other. The session is also the main notification object.
                      All events raised via idev are reported through the
                      session interface. Apart of that, the session is a
                      pretty dumb object that just contains devices.
        idev_element: Elements provide real hardware in the idev stack. For
                      each hardware device, one element is added. Elements
                      have no knowledge of higher-level device types, they
                      only provide raw input data to the upper levels. For
                      example, each evdev device is represented by a different
                      element in an idev session.
         idev_device: Devices are objects that the application deals with. An
                      application is usually not interested in elements (and
                      those are hidden to applications), instead, they want
                      high-level input devices like keyboard, touchpads, mice
                      and more. Device are the high-level interface provided
                      by idev. Each device might be fed by a set of elements.
                      Elements drive the device. If elements are removed,
                      devices are destroyed. If elements are added, suitable
                      devices are created.
    
    Applications should monitor the system for sessions and hardware devices.
    For each session they want to operate on, they create an idev_session
    object and add hardware to that object. The idev interface requires the
    application to monitor the system (preferably via sysview_*, but not
    required) for hardware devices. Whenever hardware is added to the idev
    session, new devices *might* be created. The relationship between hardware
    and high-level idev-devices is hidden in the idev-session and not exposed.
    
    Internally, the idev elements and devices are virtual objects. Each real
    hardware and device type inherits those virtual objects and provides real
    elements and devices. Those types will be added in follow-up commits.
    
    Data flow from hardware to the application is done via idev_*_feed()
    functions. Data flow from applications to hardware is done via
    idev_*_feedback() functions. Feedback is usually used for LEDs, FF and
    similar operations.

diff --git a/Makefile.am b/Makefile.am
index 3a263f8..82f474e 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -2971,6 +2971,9 @@ libsystemd_terminal_la_CFLAGS = \
 	$(AM_CFLAGS)
 
 libsystemd_terminal_la_SOURCES = \
+	src/libsystemd-terminal/idev.h \
+	src/libsystemd-terminal/idev-internal.h \
+	src/libsystemd-terminal/idev.c \
 	src/libsystemd-terminal/sysview.h \
 	src/libsystemd-terminal/sysview-internal.h \
 	src/libsystemd-terminal/sysview.c \
diff --git a/src/libsystemd-terminal/idev-internal.h b/src/libsystemd-terminal/idev-internal.h
new file mode 100644
index 0000000..bffefbb
--- /dev/null
+++ b/src/libsystemd-terminal/idev-internal.h
@@ -0,0 +1,165 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+  This file is part of systemd.
+
+  Copyright (C) 2014 David Herrmann <dh.herrmann at gmail.com>
+
+  systemd is free software; you can redistribute it and/or modify it
+  under the terms of the GNU Lesser General Public License as published by
+  the Free Software Foundation; either version 2.1 of the License, or
+  (at your option) any later version.
+
+  systemd is distributed in the hope that it will be useful, but
+  WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+  Lesser General Public License for more details.
+
+  You should have received a copy of the GNU Lesser General Public License
+  along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#pragma once
+
+#include <inttypes.h>
+#include <stdbool.h>
+#include <stdlib.h>
+#include <systemd/sd-bus.h>
+#include <systemd/sd-event.h>
+#include "hashmap.h"
+#include "idev.h"
+#include "list.h"
+#include "util.h"
+
+typedef struct idev_link                idev_link;
+typedef struct idev_device_vtable       idev_device_vtable;
+typedef struct idev_element             idev_element;
+typedef struct idev_element_vtable      idev_element_vtable;
+
+/*
+ * Element Links
+ */
+
+struct idev_link {
+        /* element-to-device connection */
+        LIST_FIELDS(idev_link, links_by_element);
+        idev_element *element;
+
+        /* device-to-element connection */
+        LIST_FIELDS(idev_link, links_by_device);
+        idev_device *device;
+};
+
+/*
+ * Devices
+ */
+
+struct idev_device_vtable {
+        void (*free) (idev_device *d);
+        void (*attach) (idev_device *d, idev_link *l);
+        void (*detach) (idev_device *d, idev_link *l);
+        int (*feed) (idev_device *d, idev_data *data);
+};
+
+struct idev_device {
+        const idev_device_vtable *vtable;
+        idev_session *session;
+        char *name;
+
+        LIST_HEAD(idev_link, links);
+
+        bool public : 1;
+        bool enabled : 1;
+};
+
+#define IDEV_DEVICE_INIT(_vtable, _session) ((idev_device){ \
+                .vtable = (_vtable), \
+                .session = (_session), \
+        })
+
+idev_device *idev_find_device(idev_session *s, const char *name);
+
+int idev_device_add(idev_device *d, const char *name);
+idev_device *idev_device_free(idev_device *d);
+
+DEFINE_TRIVIAL_CLEANUP_FUNC(idev_device*, idev_device_free);
+
+int idev_device_feed(idev_device *d, idev_data *data);
+void idev_device_feedback(idev_device *d, idev_data *data);
+
+/*
+ * Elements
+ */
+
+struct idev_element_vtable {
+        void (*free) (idev_element *e);
+        void (*enable) (idev_element *e);
+        void (*disable) (idev_element *e);
+        void (*open) (idev_element *e);
+        void (*close) (idev_element *e);
+        void (*feedback) (idev_element *e, idev_data *data);
+};
+
+struct idev_element {
+        const idev_element_vtable *vtable;
+        idev_session *session;
+        unsigned long n_open;
+        char *name;
+
+        LIST_HEAD(idev_link, links);
+
+        bool enabled : 1;
+        bool readable : 1;
+        bool writable : 1;
+};
+
+#define IDEV_ELEMENT_INIT(_vtable, _session) ((idev_element){ \
+                .vtable = (_vtable), \
+                .session = (_session), \
+        })
+
+idev_element *idev_find_element(idev_session *s, const char *name);
+
+int idev_element_add(idev_element *e, const char *name);
+idev_element *idev_element_free(idev_element *e);
+
+DEFINE_TRIVIAL_CLEANUP_FUNC(idev_element*, idev_element_free);
+
+int idev_element_feed(idev_element *e, idev_data *data);
+void idev_element_feedback(idev_element *e, idev_data *data);
+
+/*
+ * Sessions
+ */
+
+struct idev_session {
+        idev_context *context;
+        char *name;
+        char *path;
+
+        Hashmap *element_map;
+        Hashmap *device_map;
+
+        idev_event_fn event_fn;
+        void *userdata;
+
+        bool custom : 1;
+        bool managed : 1;
+        bool enabled : 1;
+};
+
+idev_session *idev_find_session(idev_context *c, const char *name);
+int idev_session_raise_device_data(idev_session *s, idev_device *d, idev_data *data);
+
+/*
+ * Contexts
+ */
+
+struct idev_context {
+        unsigned long ref;
+        sd_event *event;
+        sd_bus *sysbus;
+
+        Hashmap *session_map;
+        Hashmap *data_map;
+};
diff --git a/src/libsystemd-terminal/idev.c b/src/libsystemd-terminal/idev.c
new file mode 100644
index 0000000..5e30807
--- /dev/null
+++ b/src/libsystemd-terminal/idev.c
@@ -0,0 +1,587 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+  This file is part of systemd.
+
+  Copyright (C) 2014 David Herrmann <dh.herrmann at gmail.com>
+
+  systemd is free software; you can redistribute it and/or modify it
+  under the terms of the GNU Lesser General Public License as published by
+  the Free Software Foundation; either version 2.1 of the License, or
+  (at your option) any later version.
+
+  systemd is distributed in the hope that it will be useful, but
+  WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+  Lesser General Public License for more details.
+
+  You should have received a copy of the GNU Lesser General Public License
+  along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <inttypes.h>
+#include <stdbool.h>
+#include <stdlib.h>
+#include <systemd/sd-bus.h>
+#include <systemd/sd-event.h>
+#include <systemd/sd-login.h>
+#include "hashmap.h"
+#include "idev.h"
+#include "idev-internal.h"
+#include "login-shared.h"
+#include "macro.h"
+#include "set.h"
+#include "util.h"
+
+static void element_open(idev_element *e);
+static void element_close(idev_element *e);
+
+/*
+ * Devices
+ */
+
+idev_device *idev_find_device(idev_session *s, const char *name) {
+        assert_return(s, NULL);
+        assert_return(name, NULL);
+
+        return hashmap_get(s->device_map, name);
+}
+
+int idev_device_add(idev_device *d, const char *name) {
+        int r;
+
+        assert_return(d, -EINVAL);
+        assert_return(d->vtable, -EINVAL);
+        assert_return(d->session, -EINVAL);
+        assert_return(name, -EINVAL);
+
+        d->name = strdup(name);
+        if (!d->name)
+                return -ENOMEM;
+
+        r = hashmap_put(d->session->device_map, d->name, d);
+        if (r < 0)
+                return r;
+
+        return 0;
+}
+
+idev_device *idev_device_free(idev_device *d) {
+        idev_device tmp;
+
+        if (!d)
+                return NULL;
+
+        assert(!d->enabled);
+        assert(!d->public);
+        assert(!d->links);
+        assert(d->vtable);
+        assert(d->vtable->free);
+
+        if (d->name)
+                hashmap_remove_value(d->session->device_map, d->name, d);
+
+        tmp = *d;
+        d->vtable->free(d);
+
+        free(tmp.name);
+
+        return NULL;
+}
+
+int idev_device_feed(idev_device *d, idev_data *data) {
+        assert(d);
+        assert(data);
+        assert(data->type < IDEV_DATA_CNT);
+
+        if (d->vtable->feed)
+                return d->vtable->feed(d, data);
+        else
+                return 0;
+}
+
+void idev_device_feedback(idev_device *d, idev_data *data) {
+        idev_link *l;
+
+        assert(d);
+        assert(data);
+        assert(data->type < IDEV_DATA_CNT);
+
+        LIST_FOREACH(links_by_device, l, d->links)
+                idev_element_feedback(l->element, data);
+}
+
+static void device_attach(idev_device *d, idev_link *l) {
+        assert(d);
+        assert(l);
+
+        if (d->vtable->attach)
+                d->vtable->attach(d, l);
+
+        if (d->enabled)
+                element_open(l->element);
+}
+
+static void device_detach(idev_device *d, idev_link *l) {
+        assert(d);
+        assert(l);
+
+        if (d->enabled)
+                element_close(l->element);
+
+        if (d->vtable->detach)
+                d->vtable->detach(d, l);
+}
+
+void idev_device_enable(idev_device *d) {
+        idev_link *l;
+
+        assert(d);
+
+        if (!d->enabled) {
+                d->enabled = true;
+                LIST_FOREACH(links_by_device, l, d->links)
+                        element_open(l->element);
+        }
+}
+
+void idev_device_disable(idev_device *d) {
+        idev_link *l;
+
+        assert(d);
+
+        if (d->enabled) {
+                d->enabled = false;
+                LIST_FOREACH(links_by_device, l, d->links)
+                        element_close(l->element);
+        }
+}
+
+/*
+ * Elements
+ */
+
+idev_element *idev_find_element(idev_session *s, const char *name) {
+        assert_return(s, NULL);
+        assert_return(name, NULL);
+
+        return hashmap_get(s->element_map, name);
+}
+
+int idev_element_add(idev_element *e, const char *name) {
+        int r;
+
+        assert_return(e, -EINVAL);
+        assert_return(e->vtable, -EINVAL);
+        assert_return(e->session, -EINVAL);
+        assert_return(name, -EINVAL);
+
+        e->name = strdup(name);
+        if (!e->name)
+                return -ENOMEM;
+
+        r = hashmap_put(e->session->element_map, e->name, e);
+        if (r < 0)
+                return r;
+
+        return 0;
+}
+
+idev_element *idev_element_free(idev_element *e) {
+        idev_element tmp;
+
+        if (!e)
+                return NULL;
+
+        assert(!e->enabled);
+        assert(!e->links);
+        assert(e->n_open == 0);
+        assert(e->vtable);
+        assert(e->vtable->free);
+
+        if (e->name)
+                hashmap_remove_value(e->session->element_map, e->name, e);
+
+        tmp = *e;
+        e->vtable->free(e);
+
+        free(tmp.name);
+
+        return NULL;
+}
+
+int idev_element_feed(idev_element *e, idev_data *data) {
+        int r, error = 0;
+        idev_link *l;
+
+        assert(e);
+        assert(data);
+        assert(data->type < IDEV_DATA_CNT);
+
+        LIST_FOREACH(links_by_element, l, e->links) {
+                r = idev_device_feed(l->device, data);
+                if (r != 0)
+                        error = r;
+        }
+
+        return error;
+}
+
+void idev_element_feedback(idev_element *e, idev_data *data) {
+        assert(e);
+        assert(data);
+        assert(data->type < IDEV_DATA_CNT);
+
+        if (e->vtable->feedback)
+               e->vtable->feedback(e, data);
+}
+
+static void element_open(idev_element *e) {
+        assert(e);
+
+        if (e->n_open++ == 0 && e->vtable->open)
+                e->vtable->open(e);
+}
+
+static void element_close(idev_element *e) {
+        assert(e);
+        assert(e->n_open > 0);
+
+        if (--e->n_open == 0 && e->vtable->close)
+                e->vtable->close(e);
+}
+
+static void element_enable(idev_element *e) {
+        assert(e);
+
+        if (!e->enabled) {
+                e->enabled = true;
+                if (e->vtable->enable)
+                        e->vtable->enable(e);
+        }
+}
+
+static void element_disable(idev_element *e) {
+        assert(e);
+
+        if (e->enabled) {
+                e->enabled = false;
+                if (e->vtable->disable)
+                        e->vtable->disable(e);
+        }
+}
+
+/*
+ * Sessions
+ */
+
+static int session_raise(idev_session *s, idev_event *ev) {
+        return s->event_fn(s, s->userdata, ev);
+}
+
+static int session_raise_device_add(idev_session *s, idev_device *d) {
+        idev_event event = {
+                .type = IDEV_EVENT_DEVICE_ADD,
+                .device_add = {
+                        .device = d,
+                },
+        };
+
+        return session_raise(s, &event);
+}
+
+static int session_raise_device_remove(idev_session *s, idev_device *d) {
+        idev_event event = {
+                .type = IDEV_EVENT_DEVICE_REMOVE,
+                .device_remove = {
+                        .device = d,
+                },
+        };
+
+        return session_raise(s, &event);
+}
+
+int idev_session_raise_device_data(idev_session *s, idev_device *d, idev_data *data) {
+        idev_event event = {
+                .type = IDEV_EVENT_DEVICE_DATA,
+                .device_data = {
+                        .device = d,
+                        .data = *data,
+                },
+        };
+
+        return session_raise(s, &event);
+}
+
+static int session_add_device(idev_session *s, idev_device *d) {
+        int r;
+
+        assert(s);
+        assert(d);
+
+        log_debug("idev: %s: add device '%s'", s->name, d->name);
+
+        d->public = true;
+        r = session_raise_device_add(s, d);
+        if (r != 0) {
+                d->public = false;
+                goto error;
+        }
+
+        return 0;
+
+error:
+        if (r < 0)
+                log_debug("idev: %s: error while adding device '%s': %s",
+                          s->name, d->name, strerror(-r));
+        return r;
+}
+
+static int session_remove_device(idev_session *s, idev_device *d) {
+        int r, error = 0;
+
+        assert(s);
+        assert(d);
+
+        log_debug("idev: %s: remove device '%s'", s->name, d->name);
+
+        d->public = false;
+        r = session_raise_device_remove(s, d);
+        if (r != 0)
+                error = r;
+
+        idev_device_disable(d);
+
+        if (error < 0)
+                log_debug("idev: %s: error while removing device '%s': %s",
+                          s->name, d->name, strerror(-error));
+        idev_device_free(d);
+        return error;
+}
+
+static int session_add_element(idev_session *s, idev_element *e) {
+        assert(s);
+        assert(e);
+
+        log_debug("idev: %s: add element '%s'", s->name, e->name);
+
+        if (s->enabled)
+                element_enable(e);
+
+        return 0;
+}
+
+static int session_remove_element(idev_session *s, idev_element *e) {
+        int r, error = 0;
+        idev_device *d;
+        idev_link *l;
+
+        assert(s);
+        assert(e);
+
+        log_debug("idev: %s: remove element '%s'", s->name, e->name);
+
+        while ((l = e->links)) {
+                d = l->device;
+                LIST_REMOVE(links_by_device, d->links, l);
+                LIST_REMOVE(links_by_element, e->links, l);
+                device_detach(d, l);
+
+                if (!d->links) {
+                        r = session_remove_device(s, d);
+                        if (r != 0)
+                                error = r;
+                }
+
+                l->device = NULL;
+                l->element = NULL;
+                free(l);
+        }
+
+        element_disable(e);
+
+        if (error < 0)
+                log_debug("idev: %s: error while removing element '%s': %s",
+                          s->name, e->name, strerror(-r));
+        idev_element_free(e);
+        return error;
+}
+
+idev_session *idev_find_session(idev_context *c, const char *name) {
+        assert_return(c, NULL);
+        assert_return(name, NULL);
+
+        return hashmap_get(c->session_map, name);
+}
+
+int idev_session_new(idev_session **out,
+                     idev_context *c,
+                     unsigned int flags,
+                     const char *name,
+                     idev_event_fn event_fn,
+                     void *userdata) {
+        _cleanup_(idev_session_freep) idev_session *s = NULL;
+        int r;
+
+        assert_return(out, -EINVAL);
+        assert_return(c, -EINVAL);
+        assert_return(name, -EINVAL);
+        assert_return(event_fn, -EINVAL);
+        assert_return((flags & IDEV_SESSION_CUSTOM) == !session_id_valid(name), -EINVAL);
+        assert_return(!(flags & IDEV_SESSION_CUSTOM) || !(flags & IDEV_SESSION_MANAGED), -EINVAL);
+        assert_return(!(flags & IDEV_SESSION_MANAGED) || c->sysbus, -EINVAL);
+
+        s = new0(idev_session, 1);
+        if (!s)
+                return -ENOMEM;
+
+        s->context = idev_context_ref(c);
+        s->custom = flags & IDEV_SESSION_CUSTOM;
+        s->managed = flags & IDEV_SESSION_MANAGED;
+        s->event_fn = event_fn;
+        s->userdata = userdata;
+
+        s->name = strdup(name);
+        if (!s->name)
+                return -ENOMEM;
+
+        if (s->managed) {
+                r = sd_bus_path_encode("/org/freedesktop/login1/session", s->name, &s->path);
+                if (r < 0)
+                        return r;
+        }
+
+        s->element_map = hashmap_new(string_hash_func, string_compare_func);
+        if (!s->element_map)
+                return -ENOMEM;
+
+        s->device_map = hashmap_new(string_hash_func, string_compare_func);
+        if (!s->device_map)
+                return -ENOMEM;
+
+        r = hashmap_put(c->session_map, s->name, s);
+        if (r < 0)
+                return r;
+
+        *out = s;
+        s = NULL;
+        return 0;
+}
+
+idev_session *idev_session_free(idev_session *s) {
+        idev_element *e;
+
+        if (!s)
+                return NULL;
+
+        while ((e = hashmap_first(s->element_map)))
+                session_remove_element(s, e);
+
+        assert(hashmap_size(s->device_map) == 0);
+
+        if (s->name)
+                hashmap_remove_value(s->context->session_map, s->name, s);
+
+        s->context = idev_context_unref(s->context);
+        hashmap_free(s->device_map);
+        hashmap_free(s->element_map);
+        free(s->path);
+        free(s->name);
+        free(s);
+
+        return NULL;
+}
+
+bool idev_session_is_enabled(idev_session *s) {
+        return s && s->enabled;
+}
+
+void idev_session_enable(idev_session *s) {
+        idev_element *e;
+        Iterator i;
+
+        assert(s);
+
+        if (!s->enabled) {
+                s->enabled = true;
+                HASHMAP_FOREACH(e, s->element_map, i)
+                        element_enable(e);
+        }
+}
+
+void idev_session_disable(idev_session *s) {
+        idev_element *e;
+        Iterator i;
+
+        assert(s);
+
+        if (s->enabled) {
+                s->enabled = false;
+                HASHMAP_FOREACH(e, s->element_map, i)
+                        element_disable(e);
+        }
+}
+
+/*
+ * Contexts
+ */
+
+int idev_context_new(idev_context **out, sd_event *event, sd_bus *sysbus) {
+        _cleanup_(idev_context_unrefp) idev_context *c = NULL;
+
+        assert_return(out, -EINVAL);
+        assert_return(event, -EINVAL);
+
+        c = new0(idev_context, 1);
+        if (!c)
+                return -ENOMEM;
+
+        c->ref = 1;
+        c->event = sd_event_ref(event);
+
+        if (sysbus)
+                c->sysbus = sd_bus_ref(sysbus);
+
+        c->session_map = hashmap_new(string_hash_func, string_compare_func);
+        if (!c->session_map)
+                return -ENOMEM;
+
+        c->data_map = hashmap_new(string_hash_func, string_compare_func);
+        if (!c->data_map)
+                return -ENOMEM;
+
+        *out = c;
+        c = NULL;
+        return 0;
+}
+
+static void context_cleanup(idev_context *c) {
+        assert(hashmap_size(c->data_map) == 0);
+        assert(hashmap_size(c->session_map) == 0);
+
+        hashmap_free(c->data_map);
+        hashmap_free(c->session_map);
+        c->sysbus = sd_bus_unref(c->sysbus);
+        c->event = sd_event_unref(c->event);
+        free(c);
+}
+
+idev_context *idev_context_ref(idev_context *c) {
+        assert_return(c, NULL);
+        assert_return(c->ref > 0, NULL);
+
+        ++c->ref;
+        return c;
+}
+
+idev_context *idev_context_unref(idev_context *c) {
+        if (!c)
+                return NULL;
+
+        assert_return(c->ref > 0, NULL);
+
+        if (--c->ref == 0)
+                context_cleanup(c);
+
+        return NULL;
+}
diff --git a/src/libsystemd-terminal/idev.h b/src/libsystemd-terminal/idev.h
new file mode 100644
index 0000000..6f618f3
--- /dev/null
+++ b/src/libsystemd-terminal/idev.h
@@ -0,0 +1,133 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+  This file is part of systemd.
+
+  Copyright (C) 2014 David Herrmann <dh.herrmann at gmail.com>
+
+  systemd is free software; you can redistribute it and/or modify it
+  under the terms of the GNU Lesser General Public License as published by
+  the Free Software Foundation; either version 2.1 of the License, or
+  (at your option) any later version.
+
+  systemd is distributed in the hope that it will be useful, but
+  WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+  Lesser General Public License for more details.
+
+  You should have received a copy of the GNU Lesser General Public License
+  along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+/*
+ * IDev
+ */
+
+#pragma once
+
+#include <inttypes.h>
+#include <stdbool.h>
+#include <stdlib.h>
+#include <systemd/sd-bus.h>
+#include <systemd/sd-event.h>
+#include "util.h"
+
+typedef struct idev_data                idev_data;
+
+typedef struct idev_event               idev_event;
+typedef struct idev_device              idev_device;
+typedef struct idev_session             idev_session;
+typedef struct idev_context             idev_context;
+
+/*
+ * Types
+ */
+
+enum {
+        IDEV_ELEMENT_CNT
+};
+
+enum {
+        IDEV_DEVICE_CNT
+};
+
+/*
+ * Data Packets
+ */
+
+enum {
+        IDEV_DATA_RESYNC,
+        IDEV_DATA_CNT
+};
+
+struct idev_data {
+        unsigned int type;
+        bool resync : 1;
+};
+
+/*
+ * Events
+ */
+
+enum {
+        IDEV_EVENT_DEVICE_ADD,
+        IDEV_EVENT_DEVICE_REMOVE,
+        IDEV_EVENT_DEVICE_DATA,
+        IDEV_EVENT_CNT
+};
+
+struct idev_event {
+        unsigned int type;
+        union {
+                struct {
+                        idev_device *device;
+                } device_add, device_remove;
+
+                struct {
+                        idev_device *device;
+                        idev_data data;
+                } device_data;
+        };
+};
+
+typedef int (*idev_event_fn) (idev_session *s, void *userdata, idev_event *ev);
+
+/*
+ * Devices
+ */
+
+void idev_device_enable(idev_device *d);
+void idev_device_disable(idev_device *d);
+
+/*
+ * Sessions
+ */
+
+enum {
+        IDEV_SESSION_CUSTOM                     = (1 << 0),
+        IDEV_SESSION_MANAGED                    = (1 << 1),
+};
+
+int idev_session_new(idev_session **out,
+                     idev_context *c,
+                     unsigned int flags,
+                     const char *name,
+                     idev_event_fn event_fn,
+                     void *userdata);
+idev_session *idev_session_free(idev_session *s);
+
+DEFINE_TRIVIAL_CLEANUP_FUNC(idev_session*, idev_session_free);
+
+bool idev_session_is_enabled(idev_session *s);
+void idev_session_enable(idev_session *s);
+void idev_session_disable(idev_session *s);
+
+/*
+ * Contexts
+ */
+
+int idev_context_new(idev_context **out, sd_event *event, sd_bus *sysbus);
+idev_context *idev_context_ref(idev_context *c);
+idev_context *idev_context_unref(idev_context *c);
+
+DEFINE_TRIVIAL_CLEANUP_FUNC(idev_context*, idev_context_unref);

commit 7ed3a638b2e4ffb5e76a0cf1a008e1c7233edb75
Author: David Herrmann <dh.herrmann at gmail.com>
Date:   Tue Aug 26 15:03:41 2014 +0200

    terminal: add system view interface
    
    We're going to need multiple binaries that provide session-services via
    logind device management. To avoid re-writing the seat/session/device
    scan/monitor interface for each of them, this commit adds a generic helper
    to libsystemd-terminal:
    
    The sysview interface scans and tracks seats, sessions and devices on a
    system. It basically mirrors the state of logind on the application side.
    Now, each session-service can listen for matching sessions and
    attach to them. On each session, managed device access is provided. This
    way, it is pretty simple to write session-services that attach to multiple
    sessions (even split across seats).

diff --git a/Makefile.am b/Makefile.am
index 70faed4..3a263f8 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -2971,6 +2971,9 @@ libsystemd_terminal_la_CFLAGS = \
 	$(AM_CFLAGS)
 
 libsystemd_terminal_la_SOURCES = \
+	src/libsystemd-terminal/sysview.h \
+	src/libsystemd-terminal/sysview-internal.h \
+	src/libsystemd-terminal/sysview.c \
 	src/libsystemd-terminal/term-internal.h \
 	src/libsystemd-terminal/term-charset.c \
 	src/libsystemd-terminal/term-page.c \
@@ -2981,6 +2984,7 @@ libsystemd_terminal_la_SOURCES = \
 	src/libsystemd-terminal/unifont.c
 
 libsystemd_terminal_la_LIBADD = \
+	libudev-internal.la \
 	libsystemd-internal.la \
 	libsystemd-shared.la
 
diff --git a/src/libsystemd-terminal/sysview-internal.h b/src/libsystemd-terminal/sysview-internal.h
new file mode 100644
index 0000000..5aee9f6
--- /dev/null
+++ b/src/libsystemd-terminal/sysview-internal.h
@@ -0,0 +1,140 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+  This file is part of systemd.
+
+  Copyright (C) 2014 David Herrmann <dh.herrmann at gmail.com>
+
+  systemd is free software; you can redistribute it and/or modify it
+  under the terms of the GNU Lesser General Public License as published by
+  the Free Software Foundation; either version 2.1 of the License, or
+  (at your option) any later version.
+
+  systemd is distributed in the hope that it will be useful, but
+  WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+  Lesser General Public License for more details.
+
+  You should have received a copy of the GNU Lesser General Public License
+  along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#pragma once
+
+#include <inttypes.h>
+#include <libudev.h>
+#include <stdbool.h>
+#include <stdlib.h>
+#include <systemd/sd-bus.h>
+#include <systemd/sd-event.h>
+#include "hashmap.h"
+#include "list.h"
+#include "macro.h"
+#include "sysview.h"
+#include "util.h"
+
+/*
+ * Devices
+ */
+
+struct sysview_device {
+        sysview_seat *seat;
+        const char *name;
+        unsigned int type;
+
+        union {
+                struct {
+                        struct udev_device *ud;
+                } evdev, drm;
+        };
+};
+
+sysview_device *sysview_find_device(sysview_context *c, const char *name);
+
+int sysview_device_new(sysview_device **out, sysview_seat *seat, const char *name);
+sysview_device *sysview_device_free(sysview_device *device);
+
+DEFINE_TRIVIAL_CLEANUP_FUNC(sysview_device*, sysview_device_free);
+
+/*
+ * Sessions
+ */
+
+struct sysview_session {
+        sysview_seat *seat;
+        char *name;
+        char *path;
+
+        sd_bus_slot *slot_take_control;
+
+        bool custom : 1;
+        bool public : 1;
+        bool wants_control : 1;
+        bool has_control : 1;
+};
+
+sysview_session *sysview_find_session(sysview_context *c, const char *name);
+
+int sysview_session_new(sysview_session **out, sysview_seat *seat, const char *name);
+sysview_session *sysview_session_free(sysview_session *session);
+
+DEFINE_TRIVIAL_CLEANUP_FUNC(sysview_session*, sysview_session_free);
+
+/*
+ * Seats
+ */
+
+struct sysview_seat {
+        sysview_context *context;
+        char *name;
+
+        Hashmap *session_map;
+        Hashmap *device_map;
+
+        bool scanned : 1;
+        bool public : 1;
+};
+
+sysview_seat *sysview_find_seat(sysview_context *c, const char *name);
+
+int sysview_seat_new(sysview_seat **out, sysview_context *c, const char *name);
+sysview_seat *sysview_seat_free(sysview_seat *seat);
+
+DEFINE_TRIVIAL_CLEANUP_FUNC(sysview_seat*, sysview_seat_free);
+
+/*
+ * Contexts
+ */
+
+struct sysview_context {
+        sd_event *event;
+        sd_bus *sysbus;
+        struct udev *ud;
+        uint64_t custom_sid;
+
+        Hashmap *seat_map;
+        Hashmap *session_map;
+        Hashmap *device_map;
+
+        sd_event_source *scan_src;
+        sysview_event_fn event_fn;
+        void *userdata;
+
+        /* udev scanner */
+        struct udev_monitor *ud_monitor;
+        sd_event_source *ud_monitor_src;
+
+        /* logind scanner */
+        sd_bus_slot *ld_slot_manager_signal;
+        sd_bus_slot *ld_slot_list_seats;
+        sd_bus_slot *ld_slot_list_sessions;
+
+        bool scan_logind : 1;
+        bool scan_evdev : 1;
+        bool scan_drm : 1;
+        bool running : 1;
+        bool scanned : 1;
+        bool rescan : 1;
+};
+
+int sysview_context_rescan(sysview_context *c);
diff --git a/src/libsystemd-terminal/sysview.c b/src/libsystemd-terminal/sysview.c
new file mode 100644
index 0000000..d885cb4
--- /dev/null
+++ b/src/libsystemd-terminal/sysview.c
@@ -0,0 +1,1471 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+  This file is part of systemd.
+
+  Copyright (C) 2014 David Herrmann <dh.herrmann at gmail.com>
+
+  systemd is free software; you can redistribute it and/or modify it
+  under the terms of the GNU Lesser General Public License as published by
+  the Free Software Foundation; either version 2.1 of the License, or
+  (at your option) any later version.
+
+  systemd is distributed in the hope that it will be useful, but
+  WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+  Lesser General Public License for more details.
+
+  You should have received a copy of the GNU Lesser General Public License
+  along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+#include <inttypes.h>
+#include <libudev.h>
+#include <stdbool.h>
+#include <stdlib.h>
+#include <systemd/sd-bus.h>
+#include <systemd/sd-event.h>
+#include <systemd/sd-login.h>
+#include "bus-util.h"
+#include "event-util.h"
+#include "macro.h"
+#include "set.h"
+#include "sysview.h"
+#include "sysview-internal.h"
+#include "udev-util.h"
+#include "util.h"
+
+static int context_raise_session_control(sysview_context *c, sysview_session *session, int error);
+
+/*
+ * Devices
+ */
+
+sysview_device *sysview_find_device(sysview_context *c, const char *name) {
+        assert_return(c, NULL);
+        assert_return(name, NULL);
+
+        return hashmap_get(c->device_map, name);
+}
+
+int sysview_device_new(sysview_device **out, sysview_seat *seat, const char *name) {
+        _cleanup_(sysview_device_freep) sysview_device *device = NULL;
+        int r;
+
+        assert_return(seat, -EINVAL);
+        assert_return(name, -EINVAL);
+
+        device = new0(sysview_device, 1);
+        if (!device)
+                return -ENOMEM;
+
+        device->seat = seat;
+        device->type = (unsigned)-1;
+
+        device->name = strdup(name);
+        if (!device->name)
+                return -ENOMEM;
+
+        r = hashmap_put(seat->context->device_map, device->name, device);
+        if (r < 0)
+                return r;
+
+        r = hashmap_put(seat->device_map, device->name, device);
+        if (r < 0)
+                return r;
+
+        if (out)
+                *out = device;
+        device = NULL;
+        return 0;
+}
+
+sysview_device *sysview_device_free(sysview_device *device) {
+        if (!device)
+                return NULL;
+
+        if (device->name) {
+                hashmap_remove_value(device->seat->device_map, device->name, device);
+                hashmap_remove_value(device->seat->context->device_map, device->name, device);
+        }
+
+        switch (device->type) {
+        case SYSVIEW_DEVICE_EVDEV:
+                device->evdev.ud = udev_device_unref(device->evdev.ud);
+                break;
+        case SYSVIEW_DEVICE_DRM:
+                device->drm.ud = udev_device_unref(device->drm.ud);
+                break;
+        }
+
+        free(device);
+
+        return NULL;
+}
+
+unsigned int sysview_device_get_type(sysview_device *device) {
+        assert_return(device, (unsigned)-1);
+
+        return device->type;
+}
+
+struct udev_device *sysview_device_get_ud(sysview_device *device) {
+        assert_return(device, NULL);
+
+        switch (device->type) {
+        case SYSVIEW_DEVICE_EVDEV:
+                return device->evdev.ud;
+        case SYSVIEW_DEVICE_DRM:
+                return device->drm.ud;
+        default:
+                assert_return(0, NULL);
+        }
+}
+
+static int device_new_ud(sysview_device **out, sysview_seat *seat, unsigned int type, struct udev_device *ud) {
+        _cleanup_(sysview_device_freep) sysview_device *device = NULL;
+        int r;
+
+        assert_return(seat, -EINVAL);
+        assert_return(ud, -EINVAL);
+
+        r = sysview_device_new(&device, seat, udev_device_get_syspath(ud));
+        if (r < 0)
+                return r;
+
+        device->type = type;
+
+        switch (type) {
+        case SYSVIEW_DEVICE_EVDEV:
+                device->evdev.ud = udev_device_ref(ud);
+                break;
+        case SYSVIEW_DEVICE_DRM:
+                device->drm.ud = udev_device_ref(ud);
+                break;
+        default:
+                assert_not_reached("sysview: invalid udev-device type");
+        }
+
+        if (out)
+                *out = device;
+        device = NULL;
+        return 0;
+}
+
+/*
+ * Sessions
+ */
+
+sysview_session *sysview_find_session(sysview_context *c, const char *name) {
+        assert_return(c, NULL);
+        assert_return(name, NULL);
+
+        return hashmap_get(c->session_map, name);
+}
+
+int sysview_session_new(sysview_session **out, sysview_seat *seat, const char *name) {
+        _cleanup_(sysview_session_freep) sysview_session *session = NULL;
+        int r;
+
+        assert_return(seat, -EINVAL);
+
+        session = new0(sysview_session, 1);
+        if (!session)
+                return -ENOMEM;
+
+        session->seat = seat;
+
+        if (name) {
+                /*
+                 * If a name is given, we require it to be a logind session
+                 * name. The session will be put in managed mode and we use
+                 * logind to request controller access.
+                 */
+
+                session->name = strdup(name);
+                if (!session->name)
+                        return -ENOMEM;
+
+                r = sd_bus_path_encode("/org/freedesktop/login1/session",
+                                       session->name, &session->path);
+                if (r < 0)
+                        return r;
+
+                session->custom = false;;
+        } else {
+                /*
+                 * No session name was given. We assume this is an unmanaged
+                 * session controlled by the application. We don't use logind
+                 * at all and leave session management to the application. The
+                 * name of the session-object is set to a unique random string
+                 * that does not clash with the logind namespace.
+                 */
+
+                r = asprintf(&session->name, "@custom%" PRIu64,
+                             ++seat->context->custom_sid);
+                if (r < 0)
+                        return -ENOMEM;
+
+                session->custom = true;
+        }
+
+        r = hashmap_put(seat->context->session_map, session->name, session);
+        if (r < 0)
+                return r;
+
+        r = hashmap_put(seat->session_map, session->name, session);
+        if (r < 0)
+                return r;
+
+        if (out)
+                *out = session;
+        session = NULL;
+        return 0;
+}
+
+sysview_session *sysview_session_free(sysview_session *session) {
+        if (!session)
+                return NULL;
+
+        assert(!session->public);
+        assert(!session->wants_control);
+
+        if (session->name) {
+                hashmap_remove_value(session->seat->session_map, session->name, session);
+                hashmap_remove_value(session->seat->context->session_map, session->name, session);
+        }
+
+        free(session->path);
+        free(session->name);
+        free(session);
+
+        return NULL;
+}
+
+const char *sysview_session_get_name(sysview_session *session) {
+        assert_return(session, NULL);
+
+        return session->name;
+}
+
+static int session_take_control_fn(sd_bus *bus,
+                                   sd_bus_message *reply,
+                                   void *userdata,
+                                   sd_bus_error *ret_error) {
+        sysview_session *session = userdata;
+        int error;
+
+        session->slot_take_control = sd_bus_slot_unref(session->slot_take_control);
+
+        if (sd_bus_message_is_method_error(reply, NULL)) {
+                const sd_bus_error *e = sd_bus_message_get_error(reply);
+
+                log_debug("sysview: %s: TakeControl failed: %s: %s",
+                          session->name, e->name, e->message);
+                error = sd_bus_error_get_errno(e);
+        } else {
+                session->has_control = true;
+                error = 0;
+        }
+
+        return context_raise_session_control(session->seat->context, session, error);
+}
+
+int sysview_session_take_control(sysview_session *session) {
+        _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
+        int r;
+
+        assert_return(session, -EINVAL);
+        assert_return(!session->custom, -EINVAL);
+
+        if (session->wants_control)
+                return 0;
+
+        r = sd_bus_message_new_method_call(session->seat->context->sysbus,
+                                           &m,
+                                           "org.freedesktop.login1",
+                                           session->path,
+                                           "org.freedesktop.login1.Session",
+                                           "TakeControl");
+        if (r < 0)
+                return r;
+
+        r = sd_bus_message_append(m, "b", 0);
+        if (r < 0)
+                return r;
+
+        r = sd_bus_call_async(session->seat->context->sysbus,
+                              &session->slot_take_control,
+                              m,
+                              session_take_control_fn,
+                              session,
+                              0);
+        if (r < 0)
+                return r;
+
+        session->wants_control = true;
+        return 0;
+}
+
+void sysview_session_release_control(sysview_session *session) {
+        _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
+        int r;
+
+        assert(session);
+        assert(!session->custom);
+
+        if (!session->wants_control)
+                return;
+
+        session->wants_control = false;
+
+        if (!session->has_control && !session->slot_take_control)
+                return;
+
+        session->has_control = false;
+        session->slot_take_control = sd_bus_slot_unref(session->slot_take_control);
+
+        r = sd_bus_message_new_method_call(session->seat->context->sysbus,
+                                           &m,
+                                           "org.freedesktop.login1",
+                                           session->path,
+                                           "org.freedesktop.login1.Session",
+                                           "ReleaseControl");
+        if (r >= 0)
+                r = sd_bus_send(session->seat->context->sysbus, m, NULL);
+
+        if (r < 0 && r != -ENOTCONN)
+                log_debug("sysview: %s: cannot send ReleaseControl: %s",
+                          session->name, strerror(-r));
+}
+
+/*
+ * Seats
+ */
+
+sysview_seat *sysview_find_seat(sysview_context *c, const char *name) {
+        assert_return(c, NULL);
+        assert_return(name, NULL);
+
+        return hashmap_get(c->seat_map, name);
+}
+
+int sysview_seat_new(sysview_seat **out, sysview_context *c, const char *name) {
+        _cleanup_(sysview_seat_freep) sysview_seat *seat = NULL;
+        int r;
+
+        assert_return(c, -EINVAL);
+        assert_return(name, -EINVAL);
+
+        seat = new0(sysview_seat, 1);
+        if (!seat)
+                return -ENOMEM;
+
+        seat->context = c;
+
+        seat->name = strdup(name);
+        if (!seat->name)
+                return -ENOMEM;
+
+        seat->session_map = hashmap_new(string_hash_func, string_compare_func);
+        if (!seat->session_map)
+                return -ENOMEM;
+
+        seat->device_map = hashmap_new(string_hash_func, string_compare_func);
+        if (!seat->device_map)
+                return -ENOMEM;
+
+        r = hashmap_put(c->seat_map, seat->name, seat);
+        if (r < 0)
+                return r;
+
+        if (out)
+                *out = seat;
+        seat = NULL;
+        return 0;
+}
+
+sysview_seat *sysview_seat_free(sysview_seat *seat) {
+        if (!seat)
+                return NULL;
+
+        assert(!seat->public);
+        assert(hashmap_size(seat->device_map) == 0);
+        assert(hashmap_size(seat->session_map) == 0);
+
+        if (seat->name)
+                hashmap_remove_value(seat->context->seat_map, seat->name, seat);
+
+        hashmap_free(seat->device_map);
+        hashmap_free(seat->session_map);
+        free(seat->name);
+        free(seat);
+
+        return NULL;
+}
+
+const char *sysview_seat_get_name(sysview_seat *seat) {
+        assert_return(seat, NULL);
+
+        return seat->name;
+}
+
+/*
+ * Contexts
+ */
+
+static int context_raise(sysview_context *c, sysview_event *event, int def) {
+        return c->running ? c->event_fn(c, c->userdata, event) : def;
+}
+
+static int context_raise_seat_add(sysview_context *c, sysview_seat *seat) {
+        sysview_event event = {
+                .type = SYSVIEW_EVENT_SEAT_ADD,
+                .seat_add = {
+                        .seat = seat,
+                }
+        };
+
+        return context_raise(c, &event, 0);
+}
+
+static int context_raise_seat_remove(sysview_context *c, sysview_seat *seat) {
+        sysview_event event = {
+                .type = SYSVIEW_EVENT_SEAT_REMOVE,
+                .seat_remove = {
+                        .seat = seat,
+                }
+        };
+
+        return context_raise(c, &event, 0);
+}
+
+static int context_raise_session_filter(sysview_context *c,
+                                        const char *id,
+                                        const char *seatid,
+                                        const char *username,
+                                        unsigned int uid) {
+        sysview_event event = {
+                .type = SYSVIEW_EVENT_SESSION_FILTER,
+                .session_filter = {
+                        .id = id,
+                        .seatid = seatid,
+                        .username = username,
+                        .uid = uid,
+                }
+        };
+
+        return context_raise(c, &event, 1);
+}
+
+static int context_raise_session_add(sysview_context *c, sysview_session *session) {
+        sysview_event event = {
+                .type = SYSVIEW_EVENT_SESSION_ADD,
+                .session_add = {
+                        .session = session,
+                }
+        };
+
+        return context_raise(c, &event, 0);
+}
+
+static int context_raise_session_remove(sysview_context *c, sysview_session *session) {
+        sysview_event event = {
+                .type = SYSVIEW_EVENT_SESSION_REMOVE,
+                .session_remove = {
+                        .session = session,
+                }
+        };
+
+        return context_raise(c, &event, 0);
+}
+
+static int context_raise_session_control(sysview_context *c, sysview_session *session, int error) {
+        sysview_event event = {
+                .type = SYSVIEW_EVENT_SESSION_CONTROL,
+                .session_control = {
+                        .session = session,
+                        .error = error,
+                }
+        };
+
+        return context_raise(c, &event, 0);
+}
+
+static int context_raise_session_attach(sysview_context *c, sysview_session *session, sysview_device *device) {
+        sysview_event event = {
+                .type = SYSVIEW_EVENT_SESSION_ATTACH,
+                .session_attach = {
+                        .session = session,
+                        .device = device,
+                }
+        };
+
+        return context_raise(c, &event, 0);
+}
+
+static int context_raise_session_detach(sysview_context *c, sysview_session *session, sysview_device *device) {
+        sysview_event event = {
+                .type = SYSVIEW_EVENT_SESSION_DETACH,
+                .session_detach = {
+                        .session = session,
+                        .device = device,
+                }
+        };
+
+        return context_raise(c, &event, 0);
+}
+
+static int context_add_device(sysview_context *c, sysview_device *device) {
+        sysview_session *session;
+        int r, error = 0;
+        Iterator i;
+
+        assert(c);
+        assert(device);
+
+        log_debug("sysview: add device '%s' on seat '%s'",
+                  device->name, device->seat->name);
+
+        HASHMAP_FOREACH(session, device->seat->session_map, i) {
+                if (!session->public)
+                        continue;
+
+                r = context_raise_session_attach(c, session, device);
+                if (r != 0)
+                        error = r;
+        }
+
+        if (error < 0)
+                log_debug("sysview: error while adding device '%s': %s",
+                          device->name, strerror(-r));
+        return error;
+}
+
+static int context_remove_device(sysview_context *c, sysview_device *device) {
+        sysview_session *session;
+        int r, error = 0;
+        Iterator i;
+
+        assert(c);
+        assert(device);
+
+        log_debug("sysview: remove device '%s'", device->name);
+
+        HASHMAP_FOREACH(session, device->seat->session_map, i) {
+                if (!session->public)
+                        continue;
+
+                r = context_raise_session_detach(c, session, device);
+                if (r != 0)
+                        error = r;
+        }
+
+        if (error < 0)
+                log_debug("sysview: error while removing device '%s': %s",
+                          device->name, strerror(-r));
+        sysview_device_free(device);
+        return error;
+}
+
+static int context_add_session(sysview_context *c, sysview_seat *seat, const char *id) {
+        sysview_session *session;
+        sysview_device *device;
+        int r, error = 0;
+        Iterator i;
+
+        assert(c);
+        assert(seat);
+        assert(id);
+
+        session = sysview_find_session(c, id);
+        if (session)
+                return 0;
+
+        log_debug("sysview: add session '%s' on seat '%s'", id, seat->name);
+
+        r = sysview_session_new(&session, seat, id);
+        if (r < 0)
+                goto error;
+
+        if (!seat->scanned) {
+                r = sysview_context_rescan(c);
+                if (r < 0)
+                        goto error;
+        }
+
+        if (seat->public) {
+                session->public = true;
+                r = context_raise_session_add(c, session);
+                if (r != 0) {
+                        session->public = false;
+                        goto error;
+                }
+
+                HASHMAP_FOREACH(device, seat->device_map, i) {
+                        r = context_raise_session_attach(c, session, device);
+                        if (r != 0)
+                                error = r;
+                }
+
+                r = error;
+                if (r != 0)
+                        goto error;
+        }
+
+        return 0;
+
+error:
+        if (r < 0)
+                log_debug("sysview: error while adding session '%s': %s",
+                          id, strerror(-r));
+        return r;
+}
+
+static int context_remove_session(sysview_context *c, sysview_session *session) {
+        sysview_device *device;
+        int r, error = 0;
+        Iterator i;
+
+        assert(c);
+        assert(session);
+
+        log_debug("sysview: remove session '%s'", session->name);
+
+        if (session->public) {
+                HASHMAP_FOREACH(device, session->seat->device_map, i) {
+                        r = context_raise_session_detach(c, session, device);
+                        if (r != 0)
+                                error = r;
+                }
+
+                session->public = false;
+                r = context_raise_session_remove(c, session);
+                if (r != 0)
+                        error = r;
+        }
+
+        if (!session->custom)
+                sysview_session_release_control(session);
+
+        if (error < 0)
+                log_debug("sysview: error while removing session '%s': %s",
+                          session->name, strerror(-error));
+        sysview_session_free(session);
+        return error;
+}
+
+static int context_add_seat(sysview_context *c, const char *id) {
+        sysview_seat *seat;
+        int r;
+
+        assert(c);
+        assert(id);
+
+        seat = sysview_find_seat(c, id);
+        if (seat)
+                return 0;
+
+        log_debug("sysview: add seat '%s'", id);
+
+        r = sysview_seat_new(&seat, c, id);
+        if (r < 0)
+                goto error;
+
+        seat->public = true;
+        r = context_raise_seat_add(c, seat);
+        if (r != 0) {
+                seat->public = false;
+                goto error;
+        }
+
+        return 0;
+
+error:
+        if (r < 0)
+                log_debug("sysview: error while adding seat '%s': %s",
+                          id, strerror(-r));
+        return r;
+}
+
+static int context_remove_seat(sysview_context *c, sysview_seat *seat) {
+        sysview_session *session;
+        sysview_device *device;
+        int r, error = 0;
+
+        assert(c);
+        assert(seat);
+
+        log_debug("sysview: remove seat '%s'", seat->name);
+
+        while ((device = hashmap_first(seat->device_map))) {
+                r = context_remove_device(c, device);
+                if (r != 0)
+                        error = r;
+        }
+
+        while ((session = hashmap_first(seat->session_map))) {
+                r = context_remove_session(c, session);
+                if (r != 0)
+                        error = r;
+        }
+
+        if (seat->public) {
+                seat->public = false;
+                r = context_raise_seat_remove(c, seat);
+                if (r != 0)
+                        error = r;
+        }
+
+        if (error < 0)
+                log_debug("sysview: error while removing seat '%s': %s",
+                          seat->name, strerror(-error));
+        sysview_seat_free(seat);
+        return error;
+}
+
+int sysview_context_new(sysview_context **out,
+                        unsigned int flags,
+                        sd_event *event,
+                        sd_bus *sysbus,
+                        struct udev *ud) {
+        _cleanup_(sysview_context_freep) sysview_context *c = NULL;
+        int r;
+
+        assert_return(out, -EINVAL);
+        assert_return(event, -EINVAL);
+
+        log_debug("sysview: new");
+
+        c = new0(sysview_context, 1);
+        if (!c)
+                return -ENOMEM;
+
+        c->event = sd_event_ref(event);
+        if (flags & SYSVIEW_CONTEXT_SCAN_LOGIND)
+                c->scan_logind = true;
+        if (flags & SYSVIEW_CONTEXT_SCAN_EVDEV)
+                c->scan_evdev = true;
+        if (flags & SYSVIEW_CONTEXT_SCAN_DRM)
+                c->scan_drm = true;
+
+        if (sysbus) {
+                c->sysbus = sd_bus_ref(sysbus);
+        } else if (c->scan_logind) {
+                r = sd_bus_open_system(&c->sysbus);
+                if (r < 0)
+                        return r;
+        }
+
+        if (ud) {
+                c->ud = udev_ref(ud);
+        } else if (c->scan_evdev || c->scan_drm) {
+                errno = 0;
+                c->ud = udev_new();
+                if (!c->ud)
+                        return errno > 0 ? -errno : -EFAULT;
+        }
+
+        c->seat_map = hashmap_new(string_hash_func, string_compare_func);
+        if (!c->seat_map)
+                return -ENOMEM;
+
+        c->session_map = hashmap_new(string_hash_func, string_compare_func);
+        if (!c->session_map)
+                return -ENOMEM;
+
+        c->device_map = hashmap_new(string_hash_func, string_compare_func);
+        if (!c->device_map)
+                return -ENOMEM;
+
+        *out = c;
+        c = NULL;
+        return 0;
+}
+
+sysview_context *sysview_context_free(sysview_context *c) {
+        if (!c)
+                return NULL;
+
+        log_debug("sysview: free");
+
+        sysview_context_stop(c);
+
+        assert(hashmap_size(c->device_map) == 0);
+        assert(hashmap_size(c->session_map) == 0);
+        assert(hashmap_size(c->seat_map) == 0);
+
+        hashmap_free(c->device_map);
+        hashmap_free(c->session_map);
+        hashmap_free(c->seat_map);
+        c->ud = udev_unref(c->ud);
+        c->sysbus = sd_bus_unref(c->sysbus);
+        c->event = sd_event_unref(c->event);
+        free(c);
+
+        return NULL;
+}
+
+static int context_ud_prepare_monitor(sysview_context *c, struct udev_monitor *m) {
+        int r;
+
+        if (c->scan_evdev) {
+                r = udev_monitor_filter_add_match_subsystem_devtype(m, "input", NULL);
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->scan_drm) {
+                r = udev_monitor_filter_add_match_subsystem_devtype(m, "drm", NULL);
+                if (r < 0)
+                        return r;
+        }
+
+        return r;
+}
+
+static int context_ud_prepare_scan(sysview_context *c, struct udev_enumerate *e) {
+        int r;
+
+        if (c->scan_evdev) {
+                r = udev_enumerate_add_match_subsystem(e, "input");
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->scan_drm) {
+                r = udev_enumerate_add_match_subsystem(e, "drm");
+                if (r < 0)
+                        return r;
+        }
+
+        r = udev_enumerate_add_match_is_initialized(e);
+        if (r < 0)
+                return r;
+
+        return 0;
+}
+
+static int context_ud_hotplug(sysview_context *c, struct udev_device *d) {
+        const char *syspath, *sysname, *subsystem, *action, *seatname;
+        sysview_device *device;
+        int r;
+
+        syspath = udev_device_get_syspath(d);
+        sysname = udev_device_get_sysname(d);
+        subsystem = udev_device_get_subsystem(d);
+        action = udev_device_get_action(d);
+
+        /* not interested in custom devices without syspath/etc */
+        if (!syspath || !sysname || !subsystem)
+                return 0;
+
+        device = sysview_find_device(c, syspath);
+
+        if (streq_ptr(action, "remove")) {
+                if (!device)
+                        return 0;
+
+                return context_remove_device(c, device);
+        } else if (streq_ptr(action, "change")) {
+                if (!device)
+                        return 0;
+
+                /* TODO: send REFRESH event */
+        } else if (!action || streq_ptr(action, "add")) {
+                struct udev_device *p;
+                unsigned int type, t;
+                sysview_seat *seat;
+
+                if (device)
+                        return 0;
+
+                if (streq(subsystem, "input") && startswith(sysname, "event") && safe_atou(sysname + 5, &t) >= 0)
+                        type = SYSVIEW_DEVICE_EVDEV;
+                else if (streq(subsystem, "drm") && startswith(sysname, "card") && safe_atou(sysname + 4, &t) >= 0)
+                        type = SYSVIEW_DEVICE_DRM;
+                else
+                        type = (unsigned)-1;
+
+                if (type >= SYSVIEW_DEVICE_CNT)
+                        return 0;
+
+                p = d;
+                seatname = NULL;
+                while ((p = udev_device_get_parent(p))) {
+                        seatname = udev_device_get_property_value(p, "ID_SEAT");
+                        if (seatname)
+                                break;
+                }
+
+                seat = sysview_find_seat(c, seatname ? : "seat0");
+                if (!seat)
+                        return 0;
+
+                r = device_new_ud(&device, seat, type, d);
+                if (r < 0) {
+                        log_debug("sysview: cannot create device for udev-device '%s': %s",
+                                  syspath, strerror(-r));
+                        return r;
+                }
+
+                return context_add_device(c, device);
+        }
+
+        return 0;
+}
+
+static int context_ud_monitor_fn(sd_event_source *s,
+                                 int fd,
+                                 uint32_t revents,
+                                 void *userdata) {
+        sysview_context *c = userdata;
+        struct udev_device *d;
+        int r;
+
+        if (revents & EPOLLIN) {
+                while ((d = udev_monitor_receive_device(c->ud_monitor))) {
+                        r = context_ud_hotplug(c, d);
+                        udev_device_unref(d);
+                        if (r != 0)
+                                return r;
+                }
+
+                /* as long as EPOLLIN is signalled, read pending data */
+                return 0;
+        }
+
+        if (revents & (EPOLLHUP | EPOLLERR)) {
+                log_debug("sysview: HUP on udev-monitor");
+                c->ud_monitor_src = sd_event_source_unref(c->ud_monitor_src);
+        }
+
+        return 0;
+}
+
+static int context_ud_start(sysview_context *c) {
+        int r, fd;
+
+        if (!c->ud)
+                return 0;
+
+        errno = 0;
+        c->ud_monitor = udev_monitor_new_from_netlink(c->ud, "udev");
+        if (!c->ud_monitor)
+                return errno > 0 ? -errno : -EFAULT;
+
+        r = context_ud_prepare_monitor(c, c->ud_monitor);
+        if (r < 0)
+                return r;
+
+        r = udev_monitor_enable_receiving(c->ud_monitor);
+        if (r < 0)
+                return r;
+
+        fd = udev_monitor_get_fd(c->ud_monitor);
+        r = sd_event_add_io(c->event,
+                            &c->ud_monitor_src,
+                            fd,
+                            EPOLLHUP | EPOLLERR | EPOLLIN,
+                            context_ud_monitor_fn,
+                            c);
+        if (r < 0)
+                return r;
+
+        return 0;
+}
+
+static void context_ud_stop(sysview_context *c) {
+        c->ud_monitor_src = sd_event_source_unref(c->ud_monitor_src);
+        c->ud_monitor = udev_monitor_unref(c->ud_monitor);
+}
+
+static int context_ud_scan(sysview_context *c) {
+        _cleanup_(udev_enumerate_unrefp) struct udev_enumerate *e = NULL;
+        struct udev_list_entry *entry;
+        struct udev_device *d;
+        int r;
+
+        if (!c->ud_monitor)
+                return 0;
+
+        errno = 0;
+        e = udev_enumerate_new(c->ud);
+        if (!e)
+                return errno > 0 ? -errno : -EFAULT;
+
+        r = context_ud_prepare_scan(c, e);
+        if (r < 0)
+                return r;
+
+        r = udev_enumerate_scan_devices(e);
+        if (r < 0)
+                return r;
+
+        udev_list_entry_foreach(entry, udev_enumerate_get_list_entry(e)) {
+                const char *name;
+
+                name = udev_list_entry_get_name(entry);
+
+                errno = 0;
+                d = udev_device_new_from_syspath(c->ud, name);
+                if (!d) {
+                        r = errno > 0 ? -errno : -EFAULT;
+                        log_debug("sysview: cannot create udev-device for %s: %s",
+                                  name, strerror(-r));
+                        continue;
+                }
+
+                r = context_ud_hotplug(c, d);
+                udev_device_unref(d);
+                if (r != 0)
+                        return r;
+        }
+
+        return 0;
+}
+
+static int context_ld_seat_new(sysview_context *c, sd_bus_message *signal) {
+        const char *id, *path;
+        int r;
+
+        r = sd_bus_message_read(signal, "so", &id, &path);
+        if (r < 0) {
+                log_debug("sysview: cannot parse SeatNew from logind: %s",
+                          strerror(-r));
+                return r;
+        }
+
+        return context_add_seat(c, id);
+}
+
+static int context_ld_seat_removed(sysview_context *c, sd_bus_message *signal) {
+        const char *id, *path;
+        sysview_seat *seat;
+        int r;
+
+        r = sd_bus_message_read(signal, "so", &id, &path);
+        if (r < 0) {
+                log_debug("sysview: cannot parse SeatRemoved from logind: %s",
+                          strerror(-r));
+                return r;
+        }
+
+        seat = sysview_find_seat(c, id);
+        if (!seat)
+                return 0;
+
+        return context_remove_seat(c, seat);
+}
+
+static int context_ld_session_new(sysview_context *c, sd_bus_message *signal) {
+        _cleanup_free_ char *seatid = NULL, *username = NULL;
+        const char *id, *path;
+        sysview_seat *seat;
+        uid_t uid;
+        int r;
+
+        r = sd_bus_message_read(signal, "so", &id, &path);
+        if (r < 0) {
+                log_debug("sysview: cannot parse SessionNew from logind: %s",
+                          strerror(-r));
+                return r;
+        }
+
+        /*
+         * As the dbus message didn't contain enough information, we
+         * read missing bits via sd-login. Note that this might race session
+         * destruction, so we handle ENOENT properly.
+         */
+
+        /* ENOENT is also returned for sessions without seats */
+        r = sd_session_get_seat(id, &seatid);
+        if (r == -ENOENT)
+                return 0;
+        else if (r < 0)
+                goto error;
+
+        seat = sysview_find_seat(c, seatid);
+        if (!seat)
+                return 0;
+
+        r = sd_session_get_uid(id, &uid);
+        if (r == -ENOENT)
+                return 0;
+        else if (r < 0)
+                goto error;
+
+        username = lookup_uid(uid);
+        if (!username) {
+                r = -ENOMEM;
+                goto error;
+        }
+
+        r = context_raise_session_filter(c, id, seatid, username, uid);
+        if (r <= 0) {
+                if (r < 0)
+                        log_debug("sysview: cannot filter new session '%s' on seat '%s': %s",
+                                  id, seatid, strerror(-r));
+                return r;
+        }
+
+        return context_add_session(c, seat, id);
+
+error:
+        log_debug("sysview: failed retrieving information for new session '%s': %s",
+                  id, strerror(-r));
+        return r;
+}
+
+static int context_ld_session_removed(sysview_context *c, sd_bus_message *signal) {
+        sysview_session *session;
+        const char *id, *path;
+        int r;
+
+        r = sd_bus_message_read(signal, "so", &id, &path);
+        if (r < 0) {
+                log_debug("sysview: cannot parse SessionRemoved from logind: %s",
+                          strerror(-r));
+                return r;
+        }
+
+        session = sysview_find_session(c, id);
+        if (!session)
+                return 0;
+
+        return context_remove_session(c, session);
+}
+
+static int context_ld_manager_signal_fn(sd_bus *bus,
+                                        sd_bus_message *signal,
+                                        void *userdata,
+                                        sd_bus_error *ret_error) {
+        sysview_context *c = userdata;
+
+        if (sd_bus_message_is_signal(signal, "org.freedesktop.login1.Manager", "SeatNew"))
+                return context_ld_seat_new(c, signal);
+        else if (sd_bus_message_is_signal(signal, "org.freedesktop.login1.Manager", "SeatRemoved"))
+                return context_ld_seat_removed(c, signal);
+        else if (sd_bus_message_is_signal(signal, "org.freedesktop.login1.Manager", "SessionNew"))
+                return context_ld_session_new(c, signal);
+        else if (sd_bus_message_is_signal(signal, "org.freedesktop.login1.Manager", "SessionRemoved"))
+                return context_ld_session_removed(c, signal);
+        else
+                return 0;
+}
+
+static int context_ld_start(sysview_context *c) {
+        int r;
+
+        if (!c->scan_logind)
+                return 0;
+
+        r = sd_bus_add_match(c->sysbus,
+                             &c->ld_slot_manager_signal,
+                             "type='signal',"
+                             "sender='org.freedesktop.login1',"
+                             "interface='org.freedesktop.login1.Manager',"
+                             "path='/org/freedesktop/login1'",
+                             context_ld_manager_signal_fn,
+                             c);
+        if (r < 0)
+                return r;
+
+        return 0;
+}
+
+static void context_ld_stop(sysview_context *c) {
+        c->ld_slot_list_sessions = sd_bus_slot_unref(c->ld_slot_list_sessions);
+        c->ld_slot_list_seats = sd_bus_slot_unref(c->ld_slot_list_seats);
+        c->ld_slot_manager_signal = sd_bus_slot_unref(c->ld_slot_manager_signal);
+}
+
+static int context_ld_list_seats_fn(sd_bus *bus,
+                                    sd_bus_message *reply,
+                                    void *userdata,
+                                    sd_bus_error *ret_error) {
+        sysview_context *c = userdata;
+        int r;
+
+        c->ld_slot_list_seats = sd_bus_slot_unref(c->ld_slot_list_seats);
+
+        if (sd_bus_message_is_method_error(reply, NULL)) {
+                const sd_bus_error *error = sd_bus_message_get_error(reply);
+
+                log_debug("sysview: ListSeats on logind failed: %s: %s",
+                          error->name, error->message);
+                return sd_bus_error_get_errno(error);
+        }
+
+        r = sd_bus_message_enter_container(reply, 'a', "(so)");
+        if (r < 0)
+                goto error;
+
+        while ((r = sd_bus_message_enter_container(reply, 'r', "so")) > 0) {
+                const char *id, *path;
+
+                r = sd_bus_message_read(reply, "so", &id, &path);
+                if (r < 0)
+                        goto error;
+
+                r = context_add_seat(c, id);
+                if (r != 0)
+                        return r;
+
+                r = sd_bus_message_exit_container(reply);
+                if (r < 0)
+                        goto error;
+        }
+
+        if (r < 0)
+                goto error;
+
+        r = sd_bus_message_exit_container(reply);
+        if (r < 0)
+                return r;
+
+        return 0;
+
+error:
+        log_debug("sysview: erroneous ListSeats response from logind: %s",
+                  strerror(-r));
+        return r;
+}
+
+static int context_ld_list_sessions_fn(sd_bus *bus,
+                                       sd_bus_message *reply,
+                                       void *userdata,
+                                       sd_bus_error *ret_error) {
+        sysview_context *c = userdata;
+        int r;
+
+        c->ld_slot_list_sessions = sd_bus_slot_unref(c->ld_slot_list_sessions);
+
+        if (sd_bus_message_is_method_error(reply, NULL)) {
+                const sd_bus_error *error = sd_bus_message_get_error(reply);
+
+                log_debug("sysview: ListSessions on logind failed: %s: %s",
+                          error->name, error->message);
+                return sd_bus_error_get_errno(error);
+        }
+
+        r = sd_bus_message_enter_container(reply, 'a', "(susso)");
+        if (r < 0)
+                goto error;
+
+        while ((r = sd_bus_message_enter_container(reply, 'r', "susso")) > 0) {
+                const char *id, *username, *seatid, *path;
+                sysview_seat *seat;
+                unsigned int uid;
+
+                r = sd_bus_message_read(reply,
+                                        "susso",
+                                        &id,
+                                        &uid,
+                                        &username,
+                                        &seatid,
+                                        &path);
+                if (r < 0)
+                        goto error;
+
+                seat = sysview_find_seat(c, seatid);
+                if (seat) {
+                        r = context_raise_session_filter(c, id, seatid, username, uid);
+                        if (r < 0) {
+                                log_debug("sysview: cannot filter listed session '%s' on seat '%s': %s",
+                                          id, seatid, strerror(-r));
+                                return r;
+                        } else if (r > 0) {
+                                r = context_add_session(c, seat, id);
+                                if (r != 0)
+                                        return r;
+                        }
+                }
+
+                r = sd_bus_message_exit_container(reply);
+                if (r < 0)
+                        goto error;
+        }
+
+        if (r < 0)
+                goto error;
+
+        r = sd_bus_message_exit_container(reply);
+        if (r < 0)
+                return r;
+
+        return 0;
+
+error:
+        log_debug("sysview: erroneous ListSessions response from logind: %s",
+                  strerror(-r));
+        return r;
+}
+
+static int context_ld_scan(sysview_context *c) {
+        _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
+        int r;
+
+        if (!c->ld_slot_manager_signal)
+                return 0;
+
+        /* request seat list */
+
+        r = sd_bus_message_new_method_call(c->sysbus,
+                                           &m,
+                                           "org.freedesktop.login1",
+                                           "/org/freedesktop/login1",
+                                           "org.freedesktop.login1.Manager",
+                                           "ListSeats");
+        if (r < 0)
+                return r;
+
+        r = sd_bus_call_async(c->sysbus,
+                              &c->ld_slot_list_seats,
+                              m,
+                              context_ld_list_seats_fn,
+                              c,
+                              0);
+        if (r < 0)
+                return r;
+
+        /* request session list */
+
+        m = sd_bus_message_unref(m);
+        r = sd_bus_message_new_method_call(c->sysbus,
+                                           &m,
+                                           "org.freedesktop.login1",
+                                           "/org/freedesktop/login1",
+                                           "org.freedesktop.login1.Manager",
+                                           "ListSessions");
+        if (r < 0)
+                return r;
+
+        r = sd_bus_call_async(c->sysbus,
+                              &c->ld_slot_list_sessions,
+                              m,
+                              context_ld_list_sessions_fn,
+                              c,
+                              0);
+        if (r < 0)
+                return r;
+
+        return 0;
+}
+
+bool sysview_context_is_running(sysview_context *c) {
+        return c && c->running;
+}
+
+int sysview_context_start(sysview_context *c, sysview_event_fn event_fn, void *userdata) {
+        int r;
+
+        assert_return(c, -EINVAL);
+        assert_return(event_fn, -EINVAL);
+
+        if (c->running)
+                return -EALREADY;
+
+        log_debug("sysview: start");
+
+        c->running = true;
+        c->event_fn = event_fn;
+        c->userdata = userdata;
+
+        r = context_ld_start(c);
+        if (r < 0)
+                goto error;
+
+        r = context_ud_start(c);
+        if (r < 0)
+                goto error;
+
+        r = sysview_context_rescan(c);
+        if (r < 0)
+                goto error;
+
+        return 0;
+
+error:
+        sysview_context_stop(c);
+        return r;
+}
+
+void sysview_context_stop(sysview_context *c) {
+        sysview_session *session;
+        sysview_device *device;
+        sysview_seat *seat;
+
+        assert(c);
+
+        if (!c->running)
+                return;
+
+        log_debug("sysview: stop");
+
+        c->running = false;
+        c->scanned = false;
+        c->event_fn = NULL;
+        c->userdata = NULL;
+        c->scan_src = sd_event_source_unref(c->scan_src);
+        context_ud_stop(c);
+        context_ld_stop(c);
+
+        /*
+         * Event-callbacks are already cleared, hence we can safely ignore
+         * return codes of the context_remove_*() helpers. They cannot be
+         * originated from user-callbacks, so we already handled them.
+         */
+
+        while ((device = hashmap_first(c->device_map)))
+                context_remove_device(c, device);
+
+        while ((session = hashmap_first(c->session_map)))
+                context_remove_session(c, session);
+
+        while ((seat = hashmap_first(c->seat_map)))
+                context_remove_seat(c, seat);
+}
+
+static int context_scan_fn(sd_event_source *s, void *userdata) {
+        sysview_context *c = userdata;
+        sysview_seat *seat;
+        Iterator i;
+        int r;
+
+        if (!c->scanned) {
+                r = context_ld_scan(c);
+                if (r < 0) {
+                        log_debug("sysview: logind scan failed: %s", strerror(-r));
+                        return r;
+                }
+        }
+
+        /* skip device scans if no sessions are available */
+        if (hashmap_size(c->session_map) > 0) {
+                r = context_ud_scan(c);
+                if (r < 0) {
+                        log_debug("sysview: udev scan failed: %s", strerror(-r));
+                        return r;
+                }
+
+                HASHMAP_FOREACH(seat, c->seat_map, i)
+                        seat->scanned = true;
+        }
+
+        c->scanned = true;
+
+        return 0;
+}
+
+int sysview_context_rescan(sysview_context *c) {
+        assert(c);
+
+        if (!c->running)
+                return 0;
+
+        if (c->scan_src)
+                return sd_event_source_set_enabled(c->scan_src, SD_EVENT_ONESHOT);
+        else
+                return sd_event_add_defer(c->event, &c->scan_src, context_scan_fn, c);
+}
diff --git a/src/libsystemd-terminal/sysview.h b/src/libsystemd-terminal/sysview.h
new file mode 100644
index 0000000..de6ff37
--- /dev/null
+++ b/src/libsystemd-terminal/sysview.h
@@ -0,0 +1,151 @@
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
+
+/***
+  This file is part of systemd.
+
+  Copyright (C) 2014 David Herrmann <dh.herrmann at gmail.com>
+
+  systemd is free software; you can redistribute it and/or modify it
+  under the terms of the GNU Lesser General Public License as published by
+  the Free Software Foundation; either version 2.1 of the License, or
+  (at your option) any later version.
+
+  systemd is distributed in the hope that it will be useful, but
+  WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+  Lesser General Public License for more details.
+
+  You should have received a copy of the GNU Lesser General Public License
+  along with systemd; If not, see <http://www.gnu.org/licenses/>.
+***/
+
+/*
+ * System View
+ * The sysview interface scans and monitors the system for seats, sessions and
+ * devices. It basically mirrors the state of logind on the application side.
+ * It's meant as base for session services that require managed device access.
+ * The logind controller API is employed to allow unprivileged access to all
+ * devices of a user.
+ * Furthermore, the sysview interface can be used for system services that run
+ * in situations where logind is not available, but session-like services are
+ * needed. For instance, the initrd does not run logind but might require
+ * graphics access. It cannot run session services, though. The sysview
+ * interface pretends that a session is available and provides the same
+ * interface as to normal session services.
+ */
+
+#pragma once
+
+#include <inttypes.h>
+#include <libudev.h>
+#include <stdbool.h>
+#include <stdlib.h>
+#include <systemd/sd-bus.h>
+#include <systemd/sd-event.h>
+#include "util.h"
+
+typedef struct sysview_event            sysview_event;
+typedef struct sysview_device           sysview_device;
+typedef struct sysview_session          sysview_session;
+typedef struct sysview_seat             sysview_seat;
+typedef struct sysview_context          sysview_context;
+
+/*
+ * Events
+ */
+
+enum {
+        SYSVIEW_EVENT_SEAT_ADD,
+        SYSVIEW_EVENT_SEAT_REMOVE,
+
+        SYSVIEW_EVENT_SESSION_FILTER,
+        SYSVIEW_EVENT_SESSION_ADD,
+        SYSVIEW_EVENT_SESSION_REMOVE,
+        SYSVIEW_EVENT_SESSION_ATTACH,
+        SYSVIEW_EVENT_SESSION_DETACH,
+        SYSVIEW_EVENT_SESSION_CONTROL,
+};
+
+struct sysview_event {
+        unsigned int type;
+
+        union {
+                struct {
+                        sysview_seat *seat;
+                } seat_add, seat_remove;
+
+                struct {
+                        const char *id;
+                        const char *seatid;
+                        const char *username;
+                        unsigned int uid;
+                } session_filter;
+
+                struct {
+                        sysview_session *session;
+                } session_add, session_remove;
+
+                struct {
+                        sysview_session *session;
+                        sysview_device *device;
+                } session_attach, session_detach;
+
+                struct {
+                        sysview_session *session;
+                        int error;
+                } session_control;
+        };
+};
+
+typedef int (*sysview_event_fn) (sysview_context *c, void *userdata, sysview_event *e);
+
+/*
+ * Devices
+ */
+
+enum {
+        SYSVIEW_DEVICE_EVDEV,
+        SYSVIEW_DEVICE_DRM,
+        SYSVIEW_DEVICE_CNT
+};
+
+unsigned int sysview_device_get_type(sysview_device *device);
+struct udev_device *sysview_device_get_ud(sysview_device *device);
+
+/*
+ * Sessions
+ */
+
+const char *sysview_session_get_name(sysview_session *session);
+
+int sysview_session_take_control(sysview_session *session);
+void sysview_session_release_control(sysview_session *session);
+
+/*
+ * Seats
+ */
+
+const char *sysview_seat_get_name(sysview_seat *seat);
+
+/*
+ * Contexts
+ */
+
+enum {
+        SYSVIEW_CONTEXT_SCAN_LOGIND             = (1 << 0),
+        SYSVIEW_CONTEXT_SCAN_EVDEV              = (1 << 1),
+        SYSVIEW_CONTEXT_SCAN_DRM                = (1 << 2),
+};
+
+int sysview_context_new(sysview_context **out,
+                        unsigned int flags,
+                        sd_event *event,
+                        sd_bus *sysbus,
+                        struct udev *ud);
+sysview_context *sysview_context_free(sysview_context *c);
+
+DEFINE_TRIVIAL_CLEANUP_FUNC(sysview_context*, sysview_context_free);
+
+bool sysview_context_is_running(sysview_context *c);
+int sysview_context_start(sysview_context *c, sysview_event_fn event_fn, void *userdata);
+void sysview_context_stop(sysview_context *c);

commit aae2b488d084cf2af9a552a55e1d9cc614f2a12a
Author: David Herrmann <dh.herrmann at gmail.com>
Date:   Sun Aug 24 18:55:58 2014 +0200

    bus: split bus_map_all_properties into multiple helpers
    
    The bus_map_all_properties() helper calls
    org.freedesktop.DBus.Properties.GetAll() on a given target and parses the
    result according to a given property-table. This simplifies dealing with
    DBus.Properties significantly. However, the function is blocking and thus
    not really useful in many situations.
    
    This patch extracts the core of this function and adds two new helpers
    which directly take dbus-messages as arguments. This way, you can issue
    asynchronous requests and parse the result via these helpers:
    
      bus_message_map_all_properties():
          This is the same as bus_map_all_properties() but takes the result
          message from a GetAll() request as argument. You can thus issue an
          asynchronous GetAll() request and then use this helper once you got
          the result.
    
      bus_message_map_properties_changed():
          This function takes a signal-message that was retrieved via a
          PropertiesChanged signal and then parses it like if you retrieved
          it via GetAll(). Furthermore, this function returns the number of
          matched properties that got invalidated by the PropertiesChanged
          signal, but didn't carry the new value. This way, the caller can
          issue a new GetAll() request and then parse the result.
    
    The old function bus_map_all_properties() is functionally unchanged, but
    now uses bus_message_map_all_properties() internally.

diff --git a/src/libsystemd/sd-bus/bus-util.c b/src/libsystemd/sd-bus/bus-util.c
index c97bf7d..aed3889 100644
--- a/src/libsystemd/sd-bus/bus-util.c
+++ b/src/libsystemd/sd-bus/bus-util.c
@@ -974,32 +974,17 @@ static int map_basic(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_
         return r;
 }
 
-int bus_map_all_properties(sd_bus *bus,
-                           const char *destination,
-                           const char *path,
-                           const struct bus_properties_map *map,
-                           void *userdata) {
-        _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
+int bus_message_map_all_properties(sd_bus *bus,
+                                   sd_bus_message *m,
+                                   const struct bus_properties_map *map,
+                                   void *userdata) {
         _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
         int r;
 
         assert(bus);
-        assert(destination);
-        assert(path);
+        assert(m);
         assert(map);
 
-        r = sd_bus_call_method(
-                        bus,
-                        destination,
-                        path,
-                        "org.freedesktop.DBus.Properties",
-                        "GetAll",
-                        &error,
-                        &m,
-                        "s", "");
-        if (r < 0)
-                return r;
-
         r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "{sv}");
         if (r < 0)
                 return r;
@@ -1052,7 +1037,73 @@ int bus_map_all_properties(sd_bus *bus,
                         return r;
         }
 
-        return r;
+        return sd_bus_message_exit_container(m);
+}
+
+int bus_message_map_properties_changed(sd_bus *bus,
+                                       sd_bus_message *m,
+                                       const struct bus_properties_map *map,
+                                       void *userdata) {
+        const char *member;
+        int r, invalidated, i;
+
+        assert(bus);
+        assert(m);
+        assert(map);
+
+        /* skip interface, but allow callers to do that themselves */
+        sd_bus_message_skip(m, "s");
+
+        r = bus_message_map_all_properties(bus, m, map, userdata);
+        if (r < 0)
+                return r;
+
+        r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "s");
+        if (r < 0)
+                return r;
+
+        invalidated = 0;
+        while ((r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &member)) > 0)
+                for (i = 0; map[i].member; i++)
+                        if (streq(map[i].member, member)) {
+                                ++invalidated;
+                                break;
+                        }
+
+        r = sd_bus_message_exit_container(m);
+        if (r < 0)
+                return r;
+
+        return invalidated;
+}
+
+int bus_map_all_properties(sd_bus *bus,
+                           const char *destination,
+                           const char *path,
+                           const struct bus_properties_map *map,
+                           void *userdata) {
+        _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
+        _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
+        int r;
+
+        assert(bus);
+        assert(destination);
+        assert(path);
+        assert(map);
+
+        r = sd_bus_call_method(
+                        bus,
+                        destination,
+                        path,
+                        "org.freedesktop.DBus.Properties",
+                        "GetAll",
+                        &error,
+                        &m,
+                        "s", "");
+        if (r < 0)
+                return r;
+
+        return bus_message_map_all_properties(bus, m, map, userdata);
 }
 
 int bus_open_transport(BusTransport transport, const char *host, bool user, sd_bus **bus) {
diff --git a/src/libsystemd/sd-bus/bus-util.h b/src/libsystemd/sd-bus/bus-util.h
index faf1775..696daa1 100644
--- a/src/libsystemd/sd-bus/bus-util.h
+++ b/src/libsystemd/sd-bus/bus-util.h
@@ -46,6 +46,14 @@ struct bus_properties_map {
 
 int bus_map_id128(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata);
 
+int bus_message_map_all_properties(sd_bus *bus,
+                                   sd_bus_message *m,
+                                   const struct bus_properties_map *map,
+                                   void *userdata);
+int bus_message_map_properties_changed(sd_bus *bus,
+                                       sd_bus_message *m,
+                                       const struct bus_properties_map *map,
+                                       void *userdata);
 int bus_map_all_properties(sd_bus *bus,
                            const char *destination,
                            const char *path,

commit f1566e63da92cee5cbc0074df9cd9a8dc078a62e
Author: David Herrmann <dh.herrmann at gmail.com>
Date:   Wed Aug 27 18:03:29 2014 +0200

    util: make lookup_uid() global
    
    This is a useful helper, make it global. It will be required for
    libsystemd-terminal, at minimum.

diff --git a/src/shared/util.c b/src/shared/util.c
index fdcf571..9e4ff85 100644
--- a/src/shared/util.c
+++ b/src/shared/util.c
@@ -2604,7 +2604,7 @@ bool hostname_is_set(void) {
         return !isempty(u.nodename) && !streq(u.nodename, "(none)");
 }
 
-static char *lookup_uid(uid_t uid) {
+char *lookup_uid(uid_t uid) {
         long bufsize;
         char *name;
         _cleanup_free_ char *buf = NULL;
diff --git a/src/shared/util.h b/src/shared/util.h
index ea87c96..3401280 100644
--- a/src/shared/util.h
+++ b/src/shared/util.h
@@ -432,6 +432,7 @@ int sigprocmask_many(int how, ...);
 
 bool hostname_is_set(void);
 
+char* lookup_uid(uid_t uid);
 char* gethostname_malloc(void);
 char* getlogname_malloc(void);
 char* getusername_malloc(void);

commit 92e63a51052e9ba2fbe6e47a173b6264ae292a58
Author: David Herrmann <dh.herrmann at gmail.com>
Date:   Wed Aug 27 18:02:17 2014 +0200

    udev: add missing new-line in udevadm error
    
    fprintf() does not add new-lines automatically like log_*() does. Add the
    missing \n specified so "udevadm" invoked without arguments adds a newline
    to:
        udevadm: missing or unknown command

diff --git a/src/udev/udevadm.c b/src/udev/udevadm.c
index 2c11550..df546dd 100644
--- a/src/udev/udevadm.c
+++ b/src/udev/udevadm.c
@@ -134,7 +134,7 @@ int main(int argc, char *argv[]) {
                                 goto out;
                         }
 
-        fprintf(stderr, "%s: missing or unknown command", program_invocation_short_name);
+        fprintf(stderr, "%s: missing or unknown command\n", program_invocation_short_name);
         rc = 2;
 out:
         label_finish();

commit 60240797a4ce464ec7a0537ccbec4c83f599251c
Author: David Herrmann <dh.herrmann at gmail.com>
Date:   Fri Aug 22 14:57:11 2014 +0200

    login: fix memory-leak on DropController()
    
    Our bus-name watch helpers only remove a bus-name if it's not a
    controller, anymore. If we call manager_drop_busname() before
    unregistering the controller, the busname will not be dropped. Therefore,
    first drop the controller, then drop the bus-name.

diff --git a/src/login/logind-session.c b/src/login/logind-session.c
index 136bbce..0c6e425 100644
--- a/src/login/logind-session.c
+++ b/src/login/logind-session.c
@@ -1061,11 +1061,13 @@ bool session_is_controller(Session *s, const char *sender) {
 
 static void session_swap_controller(Session *s, char *name) {
         SessionDevice *sd;
+        char *c;
 
         if (s->controller) {
-                manager_drop_busname(s->manager, s->controller);
-                free(s->controller);
+                c = s->controller;
                 s->controller = NULL;
+                manager_drop_busname(s->manager, c);
+                free(c);
 
                 /* Drop all devices as they're now unused. Do that after the
                  * controller is released to avoid sending out useles

commit fb835651aff79a1e7fc5795086c9b26e59a8e6ca
Author: David Herrmann <dh.herrmann at gmail.com>
Date:   Fri Aug 22 14:41:37 2014 +0200

    shared: make container_of() use unique variable names
    
    If you stack container_of() macros, you will get warnings due to shadowing
    variables of the parent context. To avoid this, use unique names for
    variables.
    
    Two new helpers are added:
      UNIQ: This evaluates to a truly unique value never returned by any
            evaluation of this macro. It's a shortcut for __COUNTER__.
      UNIQ_T: Takes two arguments and concatenates them. It is a shortcut for
              CONCATENATE, but meant to defined typed local variables.
    
    As you usually want to use variables that you just defined, you need to
    reference the same unique value at least two times. However, UNIQ returns
    a new value on each evaluation, therefore, you have to pass the unique
    values into the macro like this:
    
        #define my_macro(a, b) __max_macro(UNIQ, UNIQ, (a), (b))
        #define __my_macro(uniqa, uniqb, a, b) ({
                    typeof(a) UNIQ_T(A, uniqa) = (a);
                    typeof(b) UNIQ_T(B, uniqb) = (b);
                    MY_UNSAFE_MACRO(UNIQ_T(A, uniqa), UNIQ_T(B, uniqb));
            })
    
    This way, MY_UNSAFE_MACRO() can safely evaluate it's arguments multiple
    times as they are local variables. But you can also stack invocations to
    the macro my_macro() without clashing names.
    
    This is the same as if you did:
    
        #define my_macro(a, b) __max_macro(__COUNTER__, __COUNTER__, (a), (b))
        #define __my_macro(prefixa, prefixb, a, b) ({
                    typeof(a) CONCATENATE(A, prefixa) = (a);
                    typeof(b) CONCATENATE(B, prefixb) = (b);
                    MY_UNSAFE_MACRO(CONCATENATE(A, prefixa), CONCATENATE(B, prefixb));
            })
    
    ...but in my opinion, the first macro is easier to write and read.
    
    This patch starts by converting container_of() to use this new helper.
    Other macros may follow (like MIN, MAX, CLAMP, ...).

diff --git a/src/shared/macro.h b/src/shared/macro.h
index 2807bc7..e673480 100644
--- a/src/shared/macro.h
+++ b/src/shared/macro.h
@@ -79,6 +79,9 @@
 #define XCONCATENATE(x, y) x ## y
 #define CONCATENATE(x, y) XCONCATENATE(x, y)
 
+#define UNIQ_T(x, uniq) CONCATENATE(__unique_prefix_, CONCATENATE(x, uniq))
+#define UNIQ __COUNTER__
+
 /* Rounds up */
 
 #define ALIGN4(l) (((l) + 3) & ~3)
@@ -122,13 +125,13 @@ static inline unsigned long ALIGN_POWER2(unsigned long u) {
  * @ptr: the pointer to the member.
  * @type: the type of the container struct this is embedded in.
  * @member: the name of the member within the struct.
- *
  */
-#define container_of(ptr, type, member)                                 \
+#define container_of(ptr, type, member) __container_of(UNIQ, (ptr), type, member)
+#define __container_of(uniq, ptr, type, member)                         \
         __extension__ ({                                                \
-                        const typeof( ((type *)0)->member ) *__mptr = (ptr); \
-                        (type *)( (char *)__mptr - offsetof(type,member) ); \
-                })
+                const typeof( ((type*)0)->member ) *UNIQ_T(A, uniq) = (ptr); \
+                (type*)( (char *)UNIQ_T(A, uniq) - offsetof(type,member) ); \
+        })
 
 #undef MAX
 #define MAX(a,b)                                        \
diff --git a/src/test/test-util.c b/src/test/test-util.c
index 4d9b28f..795f3a1 100644
--- a/src/test/test-util.c
+++ b/src/test/test-util.c
@@ -96,6 +96,24 @@ static void test_max(void) {
         assert_cc(MAXSIZE(char, long) == sizeof(long));
 }
 
+static void test_container_of(void) {
+        struct mytype {
+                uint8_t pad1[3];
+                uint64_t v1;
+                uint8_t pad2[2];
+                uint32_t v2;
+        } _packed_ myval = { };
+
+        assert_cc(sizeof(myval) == 17);
+        assert_se(container_of(&myval.v1, struct mytype, v1) == &myval);
+        assert_se(container_of(&myval.v2, struct mytype, v2) == &myval);
+        assert_se(container_of(&container_of(&myval.v2,
+                                             struct mytype,
+                                             v2)->v1,
+                               struct mytype,
+                               v1) == &myval);
+}
+
 static void test_first_word(void) {
         assert_se(first_word("Hello", ""));
         assert_se(first_word("Hello", "Hello"));
@@ -1218,6 +1236,7 @@ int main(int argc, char *argv[]) {
         test_streq_ptr();
         test_align_power2();
         test_max();
+        test_container_of();
         test_first_word();
         test_close_many();
         test_parse_boolean();

commit 418bcb0ce3b704ea26ee1b4a68706abca536f65a
Author: David Herrmann <dh.herrmann at gmail.com>
Date:   Fri Aug 22 14:38:28 2014 +0200

    shared: drop UNIQUE()
    
    The UNIQUE() macro works fine if used in un-stacked macros. However, once
    you stack them like:
            MAX(MIN(a, b),
                CLAMP(MAX(c, d), e, f))
    you will get warnings due to shadowing other variables. gcc uses the last
    line of a macro expansion as value for __LINE__, therefore, we cannot even
    avoid this by splitting the expressions across lines.
    
    Remove the only user of UNIQUE() so we introduce a new helper in
    follow-ups.

diff --git a/src/shared/macro.h b/src/shared/macro.h
index 43fa3e5..2807bc7 100644
--- a/src/shared/macro.h
+++ b/src/shared/macro.h
@@ -79,8 +79,6 @@
 #define XCONCATENATE(x, y) x ## y
 #define CONCATENATE(x, y) XCONCATENATE(x, y)
 
-#define UNIQUE(prefix) CONCATENATE(prefix, __LINE__)
-
 /* Rounds up */
 
 #define ALIGN4(l) (((l) + 3) & ~3)
@@ -219,7 +217,7 @@ static inline unsigned long ALIGN_POWER2(unsigned long u) {
 #else
 #define assert_cc(expr)                                                 \
         DISABLE_WARNING_DECLARATION_AFTER_STATEMENT;                    \
-        struct UNIQUE(_assert_struct_) {                                \
+        struct CONCATENATE(_assert_struct_, __LINE__) {                 \
                 char x[(expr) ? 0 : -1];                                \
         };                                                              \
         REENABLE_WARNING



More information about the systemd-commits mailing list