summaryrefslogtreecommitdiff
path: root/src/grp-login
diff options
context:
space:
mode:
authorLuke Shumaker <lukeshu@sbcglobal.net>2016-09-15 01:52:25 -0400
committerLuke Shumaker <lukeshu@sbcglobal.net>2016-09-15 01:52:25 -0400
commit5e1f646c67c954fe7d55a747e3ffdd07e20cb46a (patch)
tree05b5a37f021b133682b0f7ebe31b8201f7f78f42 /src/grp-login
parent17b593aacd4e8d056f2be860a7b744004892ecbd (diff)
./tools/notsd-move
Diffstat (limited to 'src/grp-login')
-rw-r--r--src/grp-login/.gitignore6
-rw-r--r--src/grp-login/Makefile63
-rw-r--r--src/grp-login/loginctl/Makefile42
-rw-r--r--src/grp-login/loginctl/loginctl.c1588
-rw-r--r--src/grp-login/loginctl/loginctl.completion.bash111
-rw-r--r--src/grp-login/loginctl/loginctl.completion.zsh172
-rw-r--r--src/grp-login/loginctl/loginctl.xml459
-rw-r--r--src/grp-login/loginctl/sysfs-show.c190
-rw-r--r--src/grp-login/loginctl/sysfs-show.h22
-rw-r--r--src/grp-login/pam_systemd/Makefile55
-rw-r--r--src/grp-login/pam_systemd/pam_systemd.c553
-rw-r--r--src/grp-login/pam_systemd/pam_systemd.sym15
-rw-r--r--src/grp-login/pam_systemd/pam_systemd.xml296
-rw-r--r--src/grp-login/systemd-inhibit/Makefile37
-rw-r--r--src/grp-login/systemd-inhibit/inhibit.c292
-rw-r--r--src/grp-login/systemd-inhibit/systemd-inhibit.completion.zsh33
-rw-r--r--src/grp-login/systemd-inhibit/systemd-inhibit.xml177
-rw-r--r--src/grp-login/systemd-logind/70-power-switch.rules18
-rw-r--r--src/grp-login/systemd-logind/70-uaccess.rules81
-rw-r--r--src/grp-login/systemd-logind/71-seat.rules.in54
-rw-r--r--src/grp-login/systemd-logind/73-seat-late.rules.in17
-rw-r--r--src/grp-login/systemd-logind/Makefile132
-rw-r--r--src/grp-login/systemd-logind/logind-acl.c293
-rw-r--r--src/grp-login/systemd-logind/logind-acl.h56
-rw-r--r--src/grp-login/systemd-logind/logind-action.c179
-rw-r--r--src/grp-login/systemd-logind/logind-action.h49
-rw-r--r--src/grp-login/systemd-logind/logind-button.c290
-rw-r--r--src/grp-login/systemd-logind/logind-button.h44
-rw-r--r--src/grp-login/systemd-logind/logind-core.c560
-rw-r--r--src/grp-login/systemd-logind/logind-dbus.c3170
-rw-r--r--src/grp-login/systemd-logind/logind-device.c125
-rw-r--r--src/grp-login/systemd-logind/logind-device.h44
-rw-r--r--src/grp-login/systemd-logind/logind-gperf.gperf41
-rw-r--r--src/grp-login/systemd-logind/logind-inhibit.c486
-rw-r--r--src/grp-login/systemd-logind/logind-inhibit.h89
-rw-r--r--src/grp-login/systemd-logind/logind-seat-dbus.c475
-rw-r--r--src/grp-login/systemd-logind/logind-seat.c696
-rw-r--r--src/grp-login/systemd-logind/logind-seat.h96
-rw-r--r--src/grp-login/systemd-logind/logind-session-dbus.c799
-rw-r--r--src/grp-login/systemd-logind/logind-session-device.c482
-rw-r--r--src/grp-login/systemd-logind/logind-session-device.h54
-rw-r--r--src/grp-login/systemd-logind/logind-session.c1275
-rw-r--r--src/grp-login/systemd-logind/logind-session.h186
-rw-r--r--src/grp-login/systemd-logind/logind-user-dbus.c399
-rw-r--r--src/grp-login/systemd-logind/logind-user.c917
-rw-r--r--src/grp-login/systemd-logind/logind-user.h94
-rw-r--r--src/grp-login/systemd-logind/logind-utmp.c184
-rw-r--r--src/grp-login/systemd-logind/logind.c1209
-rw-r--r--src/grp-login/systemd-logind/logind.conf.in37
-rw-r--r--src/grp-login/systemd-logind/logind.conf.xml348
-rw-r--r--src/grp-login/systemd-logind/logind.h199
-rw-r--r--src/grp-login/systemd-logind/org.freedesktop.login1.conf274
-rw-r--r--src/grp-login/systemd-logind/org.freedesktop.login1.policy.in325
-rw-r--r--src/grp-login/systemd-logind/org.freedesktop.login1.service12
-rw-r--r--src/grp-login/systemd-logind/systemd-logind.service.in33
-rw-r--r--src/grp-login/systemd-logind/systemd-logind.service.xml121
-rw-r--r--src/grp-login/systemd-logind/systemd-user.pam.m412
-rw-r--r--src/grp-login/systemd-logind/user.slice11
-rw-r--r--src/grp-login/test-inhibit.c112
-rw-r--r--src/grp-login/test-login-shared.c39
-rw-r--r--src/grp-login/test-login-tables.c34
61 files changed, 18262 insertions, 0 deletions
diff --git a/src/grp-login/.gitignore b/src/grp-login/.gitignore
new file mode 100644
index 0000000000..3a8ba497c1
--- /dev/null
+++ b/src/grp-login/.gitignore
@@ -0,0 +1,6 @@
+/logind-gperf.c
+/logind.conf
+/org.freedesktop.login1.policy
+/71-seat.rules
+/73-seat-late.rules
+/systemd-user
diff --git a/src/grp-login/Makefile b/src/grp-login/Makefile
new file mode 100644
index 0000000000..48a15db591
--- /dev/null
+++ b/src/grp-login/Makefile
@@ -0,0 +1,63 @@
+# -*- Mode: makefile; indent-tabs-mode: t -*-
+#
+# This file is part of systemd.
+#
+# Copyright 2010-2012 Lennart Poettering
+# Copyright 2010-2012 Kay Sievers
+# Copyright 2013 Zbigniew Jędrzejewski-Szmek
+# Copyright 2013 David Strauss
+# Copyright 2016 Luke Shumaker
+#
+# 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 $(dir $(lastword $(MAKEFILE_LIST)))/../../config.mk
+include $(topsrcdir)/build-aux/Makefile.head.mk
+
+test_login_SOURCES = \
+ src/libsystemd/sd-login/test-login.c
+
+test_login_LDADD = \
+ libsystemd-shared.la
+
+test_login_shared_SOURCES = \
+ src/login/test-login-shared.c
+
+test_login_shared_LDADD = \
+ libsystemd-shared.la
+
+test_inhibit_SOURCES = \
+ src/login/test-inhibit.c
+
+test_inhibit_LDADD = \
+ libsystemd-shared.la
+
+test_login_tables_SOURCES = \
+ src/login/test-login-tables.c
+
+test_login_tables_LDADD = \
+ liblogind-core.la
+
+manual_tests += \
+ test-login \
+ test-inhibit
+
+tests += \
+ test-login-tables \
+ test-login-shared
+
+nested.subdirs += loginctl
+nested.subdirs += pam_systemd
+nested.subdirs += systemd-inhibit
+nested.subdirs += systemd-logind
+
+include $(topsrcdir)/build-aux/Makefile.tail.mk
diff --git a/src/grp-login/loginctl/Makefile b/src/grp-login/loginctl/Makefile
new file mode 100644
index 0000000000..f1a474e1cc
--- /dev/null
+++ b/src/grp-login/loginctl/Makefile
@@ -0,0 +1,42 @@
+# -*- Mode: makefile; indent-tabs-mode: t -*-
+#
+# This file is part of systemd.
+#
+# Copyright 2010-2012 Lennart Poettering
+# Copyright 2010-2012 Kay Sievers
+# Copyright 2013 Zbigniew Jędrzejewski-Szmek
+# Copyright 2013 David Strauss
+# Copyright 2016 Luke Shumaker
+#
+# 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 $(dir $(lastword $(MAKEFILE_LIST)))/../../../config.mk
+include $(topsrcdir)/build-aux/Makefile.head.mk
+
+loginctl_SOURCES = \
+ src/login/loginctl.c \
+ src/login/sysfs-show.h \
+ src/login/sysfs-show.c
+
+loginctl_LDADD = \
+ libsystemd-shared.la
+
+rootbin_PROGRAMS += \
+ loginctl
+
+dist_bashcompletion_data += \
+ shell-completion/bash/loginctl
+
+dist_zshcompletion_data += shell-completion/zsh/_loginctl
+
+include $(topsrcdir)/build-aux/Makefile.tail.mk
diff --git a/src/grp-login/loginctl/loginctl.c b/src/grp-login/loginctl/loginctl.c
new file mode 100644
index 0000000000..469bec582f
--- /dev/null
+++ b/src/grp-login/loginctl/loginctl.c
@@ -0,0 +1,1588 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ 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 <errno.h>
+#include <getopt.h>
+#include <locale.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <systemd/sd-bus.h>
+
+#include "basic/alloc-util.h"
+#include "basic/cgroup-util.h"
+#include "basic/log.h"
+#include "basic/macro.h"
+#include "basic/parse-util.h"
+#include "basic/process-util.h"
+#include "basic/signal-util.h"
+#include "basic/strv.h"
+#include "basic/terminal-util.h"
+#include "basic/unit-name.h"
+#include "basic/user-util.h"
+#include "basic/util.h"
+#include "basic/verbs.h"
+#include "sd-bus/bus-error.h"
+#include "shared/bus-unit-util.h"
+#include "shared/bus-util.h"
+#include "shared/cgroup-show.h"
+#include "shared/logs-show.h"
+#include "shared/pager.h"
+#include "shared/spawn-polkit-agent.h"
+
+#include "sysfs-show.h"
+
+static char **arg_property = NULL;
+static bool arg_all = false;
+static bool arg_value = false;
+static bool arg_full = false;
+static bool arg_no_pager = false;
+static bool arg_legend = true;
+static const char *arg_kill_who = NULL;
+static int arg_signal = SIGTERM;
+static BusTransport arg_transport = BUS_TRANSPORT_LOCAL;
+static char *arg_host = NULL;
+static bool arg_ask_password = true;
+static unsigned arg_lines = 10;
+static OutputMode arg_output = OUTPUT_SHORT;
+
+static void polkit_agent_open_if_enabled(void) {
+
+ /* Open the polkit agent as a child process if necessary */
+
+ if (!arg_ask_password)
+ return;
+
+ if (arg_transport != BUS_TRANSPORT_LOCAL)
+ return;
+
+ polkit_agent_open();
+}
+
+static OutputFlags get_output_flags(void) {
+
+ return
+ arg_all * OUTPUT_SHOW_ALL |
+ arg_full * OUTPUT_FULL_WIDTH |
+ (!on_tty() || pager_have()) * OUTPUT_FULL_WIDTH |
+ colors_enabled() * OUTPUT_COLOR;
+}
+
+static int list_sessions(int argc, char *argv[], void *userdata) {
+ _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+ _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
+ const char *id, *user, *seat, *object;
+ sd_bus *bus = userdata;
+ unsigned k = 0;
+ uint32_t uid;
+ int r;
+
+ assert(bus);
+ assert(argv);
+
+ pager_open(arg_no_pager, false);
+
+ r = sd_bus_call_method(
+ bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "ListSessions",
+ &error, &reply,
+ "");
+ if (r < 0) {
+ log_error("Failed to list sessions: %s", bus_error_message(&error, r));
+ return r;
+ }
+
+ r = sd_bus_message_enter_container(reply, 'a', "(susso)");
+ if (r < 0)
+ return bus_log_parse_error(r);
+
+ if (arg_legend)
+ printf("%10s %10s %-16s %-16s\n", "SESSION", "UID", "USER", "SEAT");
+
+ while ((r = sd_bus_message_read(reply, "(susso)", &id, &uid, &user, &seat, &object)) > 0) {
+ printf("%10s %10u %-16s %-16s\n", id, (unsigned) uid, user, seat);
+ k++;
+ }
+ if (r < 0)
+ return bus_log_parse_error(r);
+
+ if (arg_legend)
+ printf("\n%u sessions listed.\n", k);
+
+ return 0;
+}
+
+static int list_users(int argc, char *argv[], void *userdata) {
+ _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+ _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
+ const char *user, *object;
+ sd_bus *bus = userdata;
+ unsigned k = 0;
+ uint32_t uid;
+ int r;
+
+ assert(bus);
+ assert(argv);
+
+ pager_open(arg_no_pager, false);
+
+ r = sd_bus_call_method(
+ bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "ListUsers",
+ &error, &reply,
+ "");
+ if (r < 0) {
+ log_error("Failed to list users: %s", bus_error_message(&error, r));
+ return r;
+ }
+
+ r = sd_bus_message_enter_container(reply, 'a', "(uso)");
+ if (r < 0)
+ return bus_log_parse_error(r);
+
+ if (arg_legend)
+ printf("%10s %-16s\n", "UID", "USER");
+
+ while ((r = sd_bus_message_read(reply, "(uso)", &uid, &user, &object)) > 0) {
+ printf("%10u %-16s\n", (unsigned) uid, user);
+ k++;
+ }
+ if (r < 0)
+ return bus_log_parse_error(r);
+
+ if (arg_legend)
+ printf("\n%u users listed.\n", k);
+
+ return 0;
+}
+
+static int list_seats(int argc, char *argv[], void *userdata) {
+ _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+ _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
+ const char *seat, *object;
+ sd_bus *bus = userdata;
+ unsigned k = 0;
+ int r;
+
+ assert(bus);
+ assert(argv);
+
+ pager_open(arg_no_pager, false);
+
+ r = sd_bus_call_method(
+ bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "ListSeats",
+ &error, &reply,
+ "");
+ if (r < 0) {
+ log_error("Failed to list seats: %s", bus_error_message(&error, r));
+ return r;
+ }
+
+ r = sd_bus_message_enter_container(reply, 'a', "(so)");
+ if (r < 0)
+ return bus_log_parse_error(r);
+
+ if (arg_legend)
+ printf("%-16s\n", "SEAT");
+
+ while ((r = sd_bus_message_read(reply, "(so)", &seat, &object)) > 0) {
+ printf("%-16s\n", seat);
+ k++;
+ }
+ if (r < 0)
+ return bus_log_parse_error(r);
+
+ if (arg_legend)
+ printf("\n%u seats listed.\n", k);
+
+ return 0;
+}
+
+static int show_unit_cgroup(sd_bus *bus, const char *interface, const char *unit, pid_t leader) {
+ _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+ _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
+ _cleanup_free_ char *path = NULL;
+ const char *cgroup;
+ unsigned c;
+ int r;
+
+ assert(bus);
+ assert(unit);
+
+ path = unit_dbus_path_from_name(unit);
+ if (!path)
+ return log_oom();
+
+ r = sd_bus_get_property(
+ bus,
+ "org.freedesktop.systemd1",
+ path,
+ interface,
+ "ControlGroup",
+ &error,
+ &reply,
+ "s");
+ if (r < 0)
+ return log_error_errno(r, "Failed to query ControlGroup: %s", bus_error_message(&error, r));
+
+ r = sd_bus_message_read(reply, "s", &cgroup);
+ if (r < 0)
+ return bus_log_parse_error(r);
+
+ if (isempty(cgroup))
+ return 0;
+
+ c = columns();
+ if (c > 18)
+ c -= 18;
+ else
+ c = 0;
+
+ r = unit_show_processes(bus, unit, cgroup, "\t\t ", c, get_output_flags(), &error);
+ if (r == -EBADR) {
+
+ if (arg_transport == BUS_TRANSPORT_REMOTE)
+ return 0;
+
+ /* Fallback for older systemd versions where the GetUnitProcesses() call is not yet available */
+
+ if (cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, cgroup) != 0 && leader <= 0)
+ return 0;
+
+ show_cgroup_and_extra(SYSTEMD_CGROUP_CONTROLLER, cgroup, "\t\t ", c, &leader, leader > 0, get_output_flags());
+ } else if (r < 0)
+ return log_error_errno(r, "Failed to dump process list: %s", bus_error_message(&error, r));
+
+ return 0;
+}
+
+typedef struct SessionStatusInfo {
+ char *id;
+ uid_t uid;
+ char *name;
+ struct dual_timestamp timestamp;
+ unsigned int vtnr;
+ char *seat;
+ char *tty;
+ char *display;
+ int remote;
+ char *remote_host;
+ char *remote_user;
+ char *service;
+ pid_t leader;
+ char *type;
+ char *class;
+ char *state;
+ char *scope;
+ char *desktop;
+} SessionStatusInfo;
+
+typedef struct UserStatusInfo {
+ uid_t uid;
+ int linger;
+ char *name;
+ struct dual_timestamp timestamp;
+ char *state;
+ char **sessions;
+ char *display;
+ char *slice;
+} UserStatusInfo;
+
+typedef struct SeatStatusInfo {
+ char *id;
+ char *active_session;
+ char **sessions;
+} SeatStatusInfo;
+
+static void session_status_info_clear(SessionStatusInfo *info) {
+ if (info) {
+ free(info->id);
+ free(info->name);
+ free(info->seat);
+ free(info->tty);
+ free(info->display);
+ free(info->remote_host);
+ free(info->remote_user);
+ free(info->service);
+ free(info->type);
+ free(info->class);
+ free(info->state);
+ free(info->scope);
+ free(info->desktop);
+ zero(*info);
+ }
+}
+
+static void user_status_info_clear(UserStatusInfo *info) {
+ if (info) {
+ free(info->name);
+ free(info->state);
+ strv_free(info->sessions);
+ free(info->display);
+ free(info->slice);
+ zero(*info);
+ }
+}
+
+static void seat_status_info_clear(SeatStatusInfo *info) {
+ if (info) {
+ free(info->id);
+ free(info->active_session);
+ strv_free(info->sessions);
+ zero(*info);
+ }
+}
+
+static int prop_map_first_of_struct(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
+ const char *contents;
+ int r;
+
+ r = sd_bus_message_peek_type(m, NULL, &contents);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_message_enter_container(m, SD_BUS_TYPE_STRUCT, contents);
+ if (r < 0)
+ return r;
+
+ if (contents[0] == 's' || contents[0] == 'o') {
+ const char *s;
+ char **p = (char **) userdata;
+
+ r = sd_bus_message_read_basic(m, contents[0], &s);
+ if (r < 0)
+ return r;
+
+ r = free_and_strdup(p, s);
+ if (r < 0)
+ return r;
+ } else {
+ r = sd_bus_message_read_basic(m, contents[0], userdata);
+ if (r < 0)
+ return r;
+ }
+
+ r = sd_bus_message_skip(m, contents+1);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_message_exit_container(m);
+ if (r < 0)
+ return r;
+
+ return 0;
+}
+
+static int prop_map_sessions_strv(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
+ const char *name;
+ int r;
+
+ assert(bus);
+ assert(m);
+
+ r = sd_bus_message_enter_container(m, 'a', "(so)");
+ if (r < 0)
+ return r;
+
+ while ((r = sd_bus_message_read(m, "(so)", &name, NULL)) > 0) {
+ r = strv_extend(userdata, name);
+ if (r < 0)
+ return r;
+ }
+ if (r < 0)
+ return r;
+
+ return sd_bus_message_exit_container(m);
+}
+
+static int print_session_status_info(sd_bus *bus, const char *path, bool *new_line) {
+
+ static const struct bus_properties_map map[] = {
+ { "Id", "s", NULL, offsetof(SessionStatusInfo, id) },
+ { "Name", "s", NULL, offsetof(SessionStatusInfo, name) },
+ { "TTY", "s", NULL, offsetof(SessionStatusInfo, tty) },
+ { "Display", "s", NULL, offsetof(SessionStatusInfo, display) },
+ { "RemoteHost", "s", NULL, offsetof(SessionStatusInfo, remote_host) },
+ { "RemoteUser", "s", NULL, offsetof(SessionStatusInfo, remote_user) },
+ { "Service", "s", NULL, offsetof(SessionStatusInfo, service) },
+ { "Desktop", "s", NULL, offsetof(SessionStatusInfo, desktop) },
+ { "Type", "s", NULL, offsetof(SessionStatusInfo, type) },
+ { "Class", "s", NULL, offsetof(SessionStatusInfo, class) },
+ { "Scope", "s", NULL, offsetof(SessionStatusInfo, scope) },
+ { "State", "s", NULL, offsetof(SessionStatusInfo, state) },
+ { "VTNr", "u", NULL, offsetof(SessionStatusInfo, vtnr) },
+ { "Leader", "u", NULL, offsetof(SessionStatusInfo, leader) },
+ { "Remote", "b", NULL, offsetof(SessionStatusInfo, remote) },
+ { "Timestamp", "t", NULL, offsetof(SessionStatusInfo, timestamp.realtime) },
+ { "TimestampMonotonic", "t", NULL, offsetof(SessionStatusInfo, timestamp.monotonic) },
+ { "User", "(uo)", prop_map_first_of_struct, offsetof(SessionStatusInfo, uid) },
+ { "Seat", "(so)", prop_map_first_of_struct, offsetof(SessionStatusInfo, seat) },
+ {}
+ };
+
+ char since1[FORMAT_TIMESTAMP_RELATIVE_MAX], *s1;
+ char since2[FORMAT_TIMESTAMP_MAX], *s2;
+ _cleanup_(session_status_info_clear) SessionStatusInfo i = {};
+ int r;
+
+ r = bus_map_all_properties(bus, "org.freedesktop.login1", path, map, &i);
+ if (r < 0)
+ return log_error_errno(r, "Could not get properties: %m");
+
+ if (*new_line)
+ printf("\n");
+
+ *new_line = true;
+
+ printf("%s - ", strna(i.id));
+
+ if (i.name)
+ printf("%s (%u)\n", i.name, (unsigned) i.uid);
+ else
+ printf("%u\n", (unsigned) i.uid);
+
+ s1 = format_timestamp_relative(since1, sizeof(since1), i.timestamp.realtime);
+ s2 = format_timestamp(since2, sizeof(since2), i.timestamp.realtime);
+
+ if (s1)
+ printf("\t Since: %s; %s\n", s2, s1);
+ else if (s2)
+ printf("\t Since: %s\n", s2);
+
+ if (i.leader > 0) {
+ _cleanup_free_ char *t = NULL;
+
+ printf("\t Leader: %u", (unsigned) i.leader);
+
+ get_process_comm(i.leader, &t);
+ if (t)
+ printf(" (%s)", t);
+
+ printf("\n");
+ }
+
+ if (!isempty(i.seat)) {
+ printf("\t Seat: %s", i.seat);
+
+ if (i.vtnr > 0)
+ printf("; vc%u", i.vtnr);
+
+ printf("\n");
+ }
+
+ if (i.tty)
+ printf("\t TTY: %s\n", i.tty);
+ else if (i.display)
+ printf("\t Display: %s\n", i.display);
+
+ if (i.remote_host && i.remote_user)
+ printf("\t Remote: %s@%s\n", i.remote_user, i.remote_host);
+ else if (i.remote_host)
+ printf("\t Remote: %s\n", i.remote_host);
+ else if (i.remote_user)
+ printf("\t Remote: user %s\n", i.remote_user);
+ else if (i.remote)
+ printf("\t Remote: Yes\n");
+
+ if (i.service) {
+ printf("\t Service: %s", i.service);
+
+ if (i.type)
+ printf("; type %s", i.type);
+
+ if (i.class)
+ printf("; class %s", i.class);
+
+ printf("\n");
+ } else if (i.type) {
+ printf("\t Type: %s", i.type);
+
+ if (i.class)
+ printf("; class %s", i.class);
+
+ printf("\n");
+ } else if (i.class)
+ printf("\t Class: %s\n", i.class);
+
+ if (!isempty(i.desktop))
+ printf("\t Desktop: %s\n", i.desktop);
+
+ if (i.state)
+ printf("\t State: %s\n", i.state);
+
+ if (i.scope) {
+ printf("\t Unit: %s\n", i.scope);
+ show_unit_cgroup(bus, "org.freedesktop.systemd1.Scope", i.scope, i.leader);
+
+ if (arg_transport == BUS_TRANSPORT_LOCAL) {
+
+ show_journal_by_unit(
+ stdout,
+ i.scope,
+ arg_output,
+ 0,
+ i.timestamp.monotonic,
+ arg_lines,
+ 0,
+ get_output_flags() | OUTPUT_BEGIN_NEWLINE,
+ SD_JOURNAL_LOCAL_ONLY,
+ true,
+ NULL);
+ }
+ }
+
+ return 0;
+}
+
+static int print_user_status_info(sd_bus *bus, const char *path, bool *new_line) {
+
+ static const struct bus_properties_map map[] = {
+ { "Name", "s", NULL, offsetof(UserStatusInfo, name) },
+ { "Linger", "b", NULL, offsetof(UserStatusInfo, linger) },
+ { "Slice", "s", NULL, offsetof(UserStatusInfo, slice) },
+ { "State", "s", NULL, offsetof(UserStatusInfo, state) },
+ { "UID", "u", NULL, offsetof(UserStatusInfo, uid) },
+ { "Timestamp", "t", NULL, offsetof(UserStatusInfo, timestamp.realtime) },
+ { "TimestampMonotonic", "t", NULL, offsetof(UserStatusInfo, timestamp.monotonic) },
+ { "Display", "(so)", prop_map_first_of_struct, offsetof(UserStatusInfo, display) },
+ { "Sessions", "a(so)", prop_map_sessions_strv, offsetof(UserStatusInfo, sessions) },
+ {}
+ };
+
+ char since1[FORMAT_TIMESTAMP_RELATIVE_MAX], *s1;
+ char since2[FORMAT_TIMESTAMP_MAX], *s2;
+ _cleanup_(user_status_info_clear) UserStatusInfo i = {};
+ int r;
+
+ r = bus_map_all_properties(bus, "org.freedesktop.login1", path, map, &i);
+ if (r < 0)
+ return log_error_errno(r, "Could not get properties: %m");
+
+ if (*new_line)
+ printf("\n");
+
+ *new_line = true;
+
+ if (i.name)
+ printf("%s (%u)\n", i.name, (unsigned) i.uid);
+ else
+ printf("%u\n", (unsigned) i.uid);
+
+ s1 = format_timestamp_relative(since1, sizeof(since1), i.timestamp.realtime);
+ s2 = format_timestamp(since2, sizeof(since2), i.timestamp.realtime);
+
+ if (s1)
+ printf("\t Since: %s; %s\n", s2, s1);
+ else if (s2)
+ printf("\t Since: %s\n", s2);
+
+ if (!isempty(i.state))
+ printf("\t State: %s\n", i.state);
+
+ if (!strv_isempty(i.sessions)) {
+ char **l;
+ printf("\tSessions:");
+
+ STRV_FOREACH(l, i.sessions)
+ printf(" %s%s",
+ streq_ptr(*l, i.display) ? "*" : "",
+ *l);
+
+ printf("\n");
+ }
+
+ printf("\t Linger: %s\n", yes_no(i.linger));
+
+ if (i.slice) {
+ printf("\t Unit: %s\n", i.slice);
+ show_unit_cgroup(bus, "org.freedesktop.systemd1.Slice", i.slice, 0);
+
+ show_journal_by_unit(
+ stdout,
+ i.slice,
+ arg_output,
+ 0,
+ i.timestamp.monotonic,
+ arg_lines,
+ 0,
+ get_output_flags() | OUTPUT_BEGIN_NEWLINE,
+ SD_JOURNAL_LOCAL_ONLY,
+ true,
+ NULL);
+ }
+
+ return 0;
+}
+
+static int print_seat_status_info(sd_bus *bus, const char *path, bool *new_line) {
+
+ static const struct bus_properties_map map[] = {
+ { "Id", "s", NULL, offsetof(SeatStatusInfo, id) },
+ { "ActiveSession", "(so)", prop_map_first_of_struct, offsetof(SeatStatusInfo, active_session) },
+ { "Sessions", "a(so)", prop_map_sessions_strv, offsetof(SeatStatusInfo, sessions) },
+ {}
+ };
+
+ _cleanup_(seat_status_info_clear) SeatStatusInfo i = {};
+ int r;
+
+ r = bus_map_all_properties(bus, "org.freedesktop.login1", path, map, &i);
+ if (r < 0)
+ return log_error_errno(r, "Could not get properties: %m");
+
+ if (*new_line)
+ printf("\n");
+
+ *new_line = true;
+
+ printf("%s\n", strna(i.id));
+
+ if (!strv_isempty(i.sessions)) {
+ char **l;
+ printf("\tSessions:");
+
+ STRV_FOREACH(l, i.sessions) {
+ if (streq_ptr(*l, i.active_session))
+ printf(" *%s", *l);
+ else
+ printf(" %s", *l);
+ }
+
+ printf("\n");
+ }
+
+ if (arg_transport == BUS_TRANSPORT_LOCAL) {
+ unsigned c;
+
+ c = columns();
+ if (c > 21)
+ c -= 21;
+ else
+ c = 0;
+
+ printf("\t Devices:\n");
+
+ show_sysfs(i.id, "\t\t ", c);
+ }
+
+ return 0;
+}
+
+#define property(name, fmt, ...) \
+ do { \
+ if (arg_value) \
+ printf(fmt "\n", __VA_ARGS__); \
+ else \
+ printf("%s=" fmt "\n", name, __VA_ARGS__); \
+ } while(0)
+
+static int print_property(const char *name, sd_bus_message *m, const char *contents) {
+ int r;
+
+ assert(name);
+ assert(m);
+ assert(contents);
+
+ if (arg_property && !strv_find(arg_property, name))
+ /* skip what we didn't read */
+ return sd_bus_message_skip(m, contents);
+
+ switch (contents[0]) {
+
+ case SD_BUS_TYPE_STRUCT_BEGIN:
+
+ if (contents[1] == SD_BUS_TYPE_STRING && STR_IN_SET(name, "Display", "Seat", "ActiveSession")) {
+ const char *s;
+
+ r = sd_bus_message_read(m, "(so)", &s, NULL);
+ if (r < 0)
+ return bus_log_parse_error(r);
+
+ if (arg_all || !isempty(s))
+ property(name, "%s", s);
+
+ return 0;
+
+ } else if (contents[1] == SD_BUS_TYPE_UINT32 && streq(name, "User")) {
+ uint32_t uid;
+
+ r = sd_bus_message_read(m, "(uo)", &uid, NULL);
+ if (r < 0)
+ return bus_log_parse_error(r);
+
+ if (!uid_is_valid(uid)) {
+ log_error("Invalid user ID: " UID_FMT, uid);
+ return -EINVAL;
+ }
+
+ property(name, UID_FMT, uid);
+ return 0;
+ }
+
+ break;
+
+ case SD_BUS_TYPE_ARRAY:
+
+ if (contents[1] == SD_BUS_TYPE_STRUCT_BEGIN && streq(name, "Sessions")) {
+ const char *s;
+ bool space = false;
+
+ r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(so)");
+ if (r < 0)
+ return bus_log_parse_error(r);
+
+ if (!arg_value)
+ printf("%s=", name);
+
+ while ((r = sd_bus_message_read(m, "(so)", &s, NULL)) > 0) {
+ printf("%s%s", space ? " " : "", s);
+ space = true;
+ }
+
+ if (space || !arg_value)
+ printf("\n");
+
+ if (r < 0)
+ return bus_log_parse_error(r);
+
+ r = sd_bus_message_exit_container(m);
+ if (r < 0)
+ return bus_log_parse_error(r);
+
+ return 0;
+ }
+
+ break;
+ }
+
+ r = bus_print_property(name, m, arg_value, arg_all);
+ if (r < 0)
+ return bus_log_parse_error(r);
+
+ if (r == 0) {
+ r = sd_bus_message_skip(m, contents);
+ if (r < 0)
+ return bus_log_parse_error(r);
+
+ if (arg_all)
+ printf("%s=[unprintable]\n", name);
+ }
+
+ return 0;
+}
+
+static int show_properties(sd_bus *bus, const char *path, bool *new_line) {
+ _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
+ _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+ int r;
+
+ assert(bus);
+ assert(path);
+ assert(new_line);
+
+ r = sd_bus_call_method(
+ bus,
+ "org.freedesktop.login1",
+ path,
+ "org.freedesktop.DBus.Properties",
+ "GetAll",
+ &error,
+ &reply,
+ "s", "");
+ if (r < 0)
+ return log_error_errno(r, "Failed to get properties: %s", bus_error_message(&error, r));
+
+ r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "{sv}");
+ if (r < 0)
+ return bus_log_parse_error(r);
+
+ if (*new_line)
+ printf("\n");
+
+ *new_line = true;
+
+ while ((r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_DICT_ENTRY, "sv")) > 0) {
+ const char *name, *contents;
+
+ r = sd_bus_message_read(reply, "s", &name);
+ if (r < 0)
+ return bus_log_parse_error(r);
+
+ r = sd_bus_message_peek_type(reply, NULL, &contents);
+ if (r < 0)
+ return bus_log_parse_error(r);
+
+ r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_VARIANT, contents);
+ if (r < 0)
+ return bus_log_parse_error(r);
+
+ r = print_property(name, reply, contents);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_message_exit_container(reply);
+ if (r < 0)
+ return bus_log_parse_error(r);
+
+ r = sd_bus_message_exit_container(reply);
+ if (r < 0)
+ return bus_log_parse_error(r);
+ }
+ if (r < 0)
+ return bus_log_parse_error(r);
+
+ r = sd_bus_message_exit_container(reply);
+ if (r < 0)
+ return bus_log_parse_error(r);
+
+ return 0;
+}
+
+static int show_session(int argc, char *argv[], void *userdata) {
+ bool properties, new_line = false;
+ sd_bus *bus = userdata;
+ int r, i;
+
+ assert(bus);
+ assert(argv);
+
+ properties = !strstr(argv[0], "status");
+
+ pager_open(arg_no_pager, false);
+
+ if (argc <= 1) {
+ /* If not argument is specified inspect the manager
+ * itself */
+ if (properties)
+ return show_properties(bus, "/org/freedesktop/login1", &new_line);
+
+ /* And in the pretty case, show data of the calling session */
+ return print_session_status_info(bus, "/org/freedesktop/login1/session/self", &new_line);
+ }
+
+ for (i = 1; i < argc; i++) {
+ _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+ _cleanup_(sd_bus_message_unrefp) sd_bus_message * reply = NULL;
+ const char *path = NULL;
+
+ r = sd_bus_call_method(
+ bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "GetSession",
+ &error, &reply,
+ "s", argv[i]);
+ if (r < 0) {
+ log_error("Failed to get session: %s", bus_error_message(&error, r));
+ return r;
+ }
+
+ r = sd_bus_message_read(reply, "o", &path);
+ if (r < 0)
+ return bus_log_parse_error(r);
+
+ if (properties)
+ r = show_properties(bus, path, &new_line);
+ else
+ r = print_session_status_info(bus, path, &new_line);
+
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+static int show_user(int argc, char *argv[], void *userdata) {
+ bool properties, new_line = false;
+ sd_bus *bus = userdata;
+ int r, i;
+
+ assert(bus);
+ assert(argv);
+
+ properties = !strstr(argv[0], "status");
+
+ pager_open(arg_no_pager, false);
+
+ if (argc <= 1) {
+ /* If not argument is specified inspect the manager
+ * itself */
+ if (properties)
+ return show_properties(bus, "/org/freedesktop/login1", &new_line);
+
+ return print_user_status_info(bus, "/org/freedesktop/login1/user/self", &new_line);
+ }
+
+ for (i = 1; i < argc; i++) {
+ _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+ _cleanup_(sd_bus_message_unrefp) sd_bus_message * reply = NULL;
+ const char *path = NULL;
+ uid_t uid;
+
+ r = get_user_creds((const char**) (argv+i), &uid, NULL, NULL, NULL);
+ if (r < 0)
+ return log_error_errno(r, "Failed to look up user %s: %m", argv[i]);
+
+ r = sd_bus_call_method(
+ bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "GetUser",
+ &error, &reply,
+ "u", (uint32_t) uid);
+ if (r < 0) {
+ log_error("Failed to get user: %s", bus_error_message(&error, r));
+ return r;
+ }
+
+ r = sd_bus_message_read(reply, "o", &path);
+ if (r < 0)
+ return bus_log_parse_error(r);
+
+ if (properties)
+ r = show_properties(bus, path, &new_line);
+ else
+ r = print_user_status_info(bus, path, &new_line);
+
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+static int show_seat(int argc, char *argv[], void *userdata) {
+ bool properties, new_line = false;
+ sd_bus *bus = userdata;
+ int r, i;
+
+ assert(bus);
+ assert(argv);
+
+ properties = !strstr(argv[0], "status");
+
+ pager_open(arg_no_pager, false);
+
+ if (argc <= 1) {
+ /* If not argument is specified inspect the manager
+ * itself */
+ if (properties)
+ return show_properties(bus, "/org/freedesktop/login1", &new_line);
+
+ return print_seat_status_info(bus, "/org/freedesktop/login1/seat/self", &new_line);
+ }
+
+ for (i = 1; i < argc; i++) {
+ _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+ _cleanup_(sd_bus_message_unrefp) sd_bus_message * reply = NULL;
+ const char *path = NULL;
+
+ r = sd_bus_call_method(
+ bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "GetSeat",
+ &error, &reply,
+ "s", argv[i]);
+ if (r < 0) {
+ log_error("Failed to get seat: %s", bus_error_message(&error, r));
+ return r;
+ }
+
+ r = sd_bus_message_read(reply, "o", &path);
+ if (r < 0)
+ return bus_log_parse_error(r);
+
+ if (properties)
+ r = show_properties(bus, path, &new_line);
+ else
+ r = print_seat_status_info(bus, path, &new_line);
+
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+static int activate(int argc, char *argv[], void *userdata) {
+ _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+ sd_bus *bus = userdata;
+ char *short_argv[3];
+ int r, i;
+
+ assert(bus);
+ assert(argv);
+
+ polkit_agent_open_if_enabled();
+
+ if (argc < 2) {
+ /* No argument? Let's convert this into the empty
+ * session name, which the calls will then resolve to
+ * the caller's session. */
+
+ short_argv[0] = argv[0];
+ short_argv[1] = (char*) "";
+ short_argv[2] = NULL;
+
+ argv = short_argv;
+ argc = 2;
+ }
+
+ for (i = 1; i < argc; i++) {
+
+ r = sd_bus_call_method(
+ bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ streq(argv[0], "lock-session") ? "LockSession" :
+ streq(argv[0], "unlock-session") ? "UnlockSession" :
+ streq(argv[0], "terminate-session") ? "TerminateSession" :
+ "ActivateSession",
+ &error, NULL,
+ "s", argv[i]);
+ if (r < 0) {
+ log_error("Failed to issue method call: %s", bus_error_message(&error, -r));
+ return r;
+ }
+ }
+
+ return 0;
+}
+
+static int kill_session(int argc, char *argv[], void *userdata) {
+ _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+ sd_bus *bus = userdata;
+ int r, i;
+
+ assert(bus);
+ assert(argv);
+
+ polkit_agent_open_if_enabled();
+
+ if (!arg_kill_who)
+ arg_kill_who = "all";
+
+ for (i = 1; i < argc; i++) {
+
+ r = sd_bus_call_method(
+ bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "KillSession",
+ &error, NULL,
+ "ssi", argv[i], arg_kill_who, arg_signal);
+ if (r < 0) {
+ log_error("Could not kill session: %s", bus_error_message(&error, -r));
+ return r;
+ }
+ }
+
+ return 0;
+}
+
+static int enable_linger(int argc, char *argv[], void *userdata) {
+ _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+ sd_bus *bus = userdata;
+ char* short_argv[3];
+ bool b;
+ int r, i;
+
+ assert(bus);
+ assert(argv);
+
+ polkit_agent_open_if_enabled();
+
+ b = streq(argv[0], "enable-linger");
+
+ if (argc < 2) {
+ short_argv[0] = argv[0];
+ short_argv[1] = (char*) "";
+ short_argv[2] = NULL;
+ argv = short_argv;
+ argc = 2;
+ }
+
+ for (i = 1; i < argc; i++) {
+ uid_t uid;
+
+ if (isempty(argv[i]))
+ uid = UID_INVALID;
+ else {
+ r = get_user_creds((const char**) (argv+i), &uid, NULL, NULL, NULL);
+ if (r < 0)
+ return log_error_errno(r, "Failed to look up user %s: %m", argv[i]);
+ }
+
+ r = sd_bus_call_method(
+ bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "SetUserLinger",
+ &error, NULL,
+ "ubb", (uint32_t) uid, b, true);
+ if (r < 0) {
+ log_error("Could not enable linger: %s", bus_error_message(&error, -r));
+ return r;
+ }
+ }
+
+ return 0;
+}
+
+static int terminate_user(int argc, char *argv[], void *userdata) {
+ _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+ sd_bus *bus = userdata;
+ int r, i;
+
+ assert(bus);
+ assert(argv);
+
+ polkit_agent_open_if_enabled();
+
+ for (i = 1; i < argc; i++) {
+ uid_t uid;
+
+ r = get_user_creds((const char**) (argv+i), &uid, NULL, NULL, NULL);
+ if (r < 0)
+ return log_error_errno(r, "Failed to look up user %s: %m", argv[i]);
+
+ r = sd_bus_call_method(
+ bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "TerminateUser",
+ &error, NULL,
+ "u", (uint32_t) uid);
+ if (r < 0) {
+ log_error("Could not terminate user: %s", bus_error_message(&error, -r));
+ return r;
+ }
+ }
+
+ return 0;
+}
+
+static int kill_user(int argc, char *argv[], void *userdata) {
+ _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+ sd_bus *bus = userdata;
+ int r, i;
+
+ assert(bus);
+ assert(argv);
+
+ polkit_agent_open_if_enabled();
+
+ if (!arg_kill_who)
+ arg_kill_who = "all";
+
+ for (i = 1; i < argc; i++) {
+ uid_t uid;
+
+ r = get_user_creds((const char**) (argv+i), &uid, NULL, NULL, NULL);
+ if (r < 0)
+ return log_error_errno(r, "Failed to look up user %s: %m", argv[i]);
+
+ r = sd_bus_call_method(
+ bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "KillUser",
+ &error, NULL,
+ "ui", (uint32_t) uid, arg_signal);
+ if (r < 0) {
+ log_error("Could not kill user: %s", bus_error_message(&error, -r));
+ return r;
+ }
+ }
+
+ return 0;
+}
+
+static int attach(int argc, char *argv[], void *userdata) {
+ _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+ sd_bus *bus = userdata;
+ int r, i;
+
+ assert(bus);
+ assert(argv);
+
+ polkit_agent_open_if_enabled();
+
+ for (i = 2; i < argc; i++) {
+
+ r = sd_bus_call_method(
+ bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "AttachDevice",
+ &error, NULL,
+ "ssb", argv[1], argv[i], true);
+
+ if (r < 0) {
+ log_error("Could not attach device: %s", bus_error_message(&error, -r));
+ return r;
+ }
+ }
+
+ return 0;
+}
+
+static int flush_devices(int argc, char *argv[], void *userdata) {
+ _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+ sd_bus *bus = userdata;
+ int r;
+
+ assert(bus);
+ assert(argv);
+
+ polkit_agent_open_if_enabled();
+
+ r = sd_bus_call_method(
+ bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "FlushDevices",
+ &error, NULL,
+ "b", true);
+ if (r < 0)
+ log_error("Could not flush devices: %s", bus_error_message(&error, -r));
+
+ return r;
+}
+
+static int lock_sessions(int argc, char *argv[], void *userdata) {
+ _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+ sd_bus *bus = userdata;
+ int r;
+
+ assert(bus);
+ assert(argv);
+
+ polkit_agent_open_if_enabled();
+
+ r = sd_bus_call_method(
+ bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ streq(argv[0], "lock-sessions") ? "LockSessions" : "UnlockSessions",
+ &error, NULL,
+ NULL);
+ if (r < 0)
+ log_error("Could not lock sessions: %s", bus_error_message(&error, -r));
+
+ return r;
+}
+
+static int terminate_seat(int argc, char *argv[], void *userdata) {
+ _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+ sd_bus *bus = userdata;
+ int r, i;
+
+ assert(bus);
+ assert(argv);
+
+ polkit_agent_open_if_enabled();
+
+ for (i = 1; i < argc; i++) {
+
+ r = sd_bus_call_method(
+ bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "TerminateSeat",
+ &error, NULL,
+ "s", argv[i]);
+ if (r < 0) {
+ log_error("Could not terminate seat: %s", bus_error_message(&error, -r));
+ return r;
+ }
+ }
+
+ return 0;
+}
+
+static int help(int argc, char *argv[], void *userdata) {
+
+ printf("%s [OPTIONS...] {COMMAND} ...\n\n"
+ "Send control commands to or query the login manager.\n\n"
+ " -h --help Show this help\n"
+ " --version Show package version\n"
+ " --no-pager Do not pipe output into a pager\n"
+ " --no-legend Do not show the headers and footers\n"
+ " --no-ask-password Don't prompt for password\n"
+ " -H --host=[USER@]HOST Operate on remote host\n"
+ " -M --machine=CONTAINER Operate on local container\n"
+ " -p --property=NAME Show only properties by this name\n"
+ " -a --all Show all properties, including empty ones\n"
+ " --value When showing properties, only print the value\n"
+ " -l --full Do not ellipsize output\n"
+ " --kill-who=WHO Who to send signal to\n"
+ " -s --signal=SIGNAL Which signal to send\n"
+ " -n --lines=INTEGER Number of journal entries to show\n"
+ " -o --output=STRING Change journal output mode (short, short-monotonic,\n"
+ " verbose, export, json, json-pretty, json-sse, cat)\n\n"
+ "Session Commands:\n"
+ " list-sessions List sessions\n"
+ " session-status [ID...] Show session status\n"
+ " show-session [ID...] Show properties of sessions or the manager\n"
+ " activate [ID] Activate a session\n"
+ " lock-session [ID...] Screen lock one or more sessions\n"
+ " unlock-session [ID...] Screen unlock one or more sessions\n"
+ " lock-sessions Screen lock all current sessions\n"
+ " unlock-sessions Screen unlock all current sessions\n"
+ " terminate-session ID... Terminate one or more sessions\n"
+ " kill-session ID... Send signal to processes of a session\n\n"
+ "User Commands:\n"
+ " list-users List users\n"
+ " user-status [USER...] Show user status\n"
+ " show-user [USER...] Show properties of users or the manager\n"
+ " enable-linger [USER...] Enable linger state of one or more users\n"
+ " disable-linger [USER...] Disable linger state of one or more users\n"
+ " terminate-user USER... Terminate all sessions of one or more users\n"
+ " kill-user USER... Send signal to processes of a user\n\n"
+ "Seat Commands:\n"
+ " list-seats List seats\n"
+ " seat-status [NAME...] Show seat status\n"
+ " show-seat [NAME...] Show properties of seats or the manager\n"
+ " attach NAME DEVICE... Attach one or more devices to a seat\n"
+ " flush-devices Flush all device associations\n"
+ " terminate-seat NAME... Terminate all sessions on one or more seats\n"
+ , program_invocation_short_name);
+
+ return 0;
+}
+
+static int parse_argv(int argc, char *argv[]) {
+
+ enum {
+ ARG_VERSION = 0x100,
+ ARG_VALUE,
+ ARG_NO_PAGER,
+ ARG_NO_LEGEND,
+ ARG_KILL_WHO,
+ ARG_NO_ASK_PASSWORD,
+ };
+
+ static const struct option options[] = {
+ { "help", no_argument, NULL, 'h' },
+ { "version", no_argument, NULL, ARG_VERSION },
+ { "property", required_argument, NULL, 'p' },
+ { "all", no_argument, NULL, 'a' },
+ { "value", no_argument, NULL, ARG_VALUE },
+ { "full", no_argument, NULL, 'l' },
+ { "no-pager", no_argument, NULL, ARG_NO_PAGER },
+ { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
+ { "kill-who", required_argument, NULL, ARG_KILL_WHO },
+ { "signal", required_argument, NULL, 's' },
+ { "host", required_argument, NULL, 'H' },
+ { "machine", required_argument, NULL, 'M' },
+ { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
+ { "lines", required_argument, NULL, 'n' },
+ { "output", required_argument, NULL, 'o' },
+ {}
+ };
+
+ int c, r;
+
+ assert(argc >= 0);
+ assert(argv);
+
+ while ((c = getopt_long(argc, argv, "hp:als:H:M:n:o:", options, NULL)) >= 0)
+
+ switch (c) {
+
+ case 'h':
+ help(0, NULL, NULL);
+ return 0;
+
+ case ARG_VERSION:
+ return version();
+
+ case 'p': {
+ r = strv_extend(&arg_property, optarg);
+ if (r < 0)
+ return log_oom();
+
+ /* If the user asked for a particular
+ * property, show it to him, even if it is
+ * empty. */
+ arg_all = true;
+ break;
+ }
+
+ case 'a':
+ arg_all = true;
+ break;
+
+ case ARG_VALUE:
+ arg_value = true;
+ break;
+
+ case 'l':
+ arg_full = true;
+ break;
+
+ case 'n':
+ if (safe_atou(optarg, &arg_lines) < 0) {
+ log_error("Failed to parse lines '%s'", optarg);
+ return -EINVAL;
+ }
+ break;
+
+ case 'o':
+ arg_output = output_mode_from_string(optarg);
+ if (arg_output < 0) {
+ log_error("Unknown output '%s'.", optarg);
+ return -EINVAL;
+ }
+ break;
+
+ case ARG_NO_PAGER:
+ arg_no_pager = true;
+ break;
+
+ case ARG_NO_LEGEND:
+ arg_legend = false;
+ break;
+
+ case ARG_NO_ASK_PASSWORD:
+ arg_ask_password = false;
+ break;
+
+ case ARG_KILL_WHO:
+ arg_kill_who = optarg;
+ break;
+
+ case 's':
+ arg_signal = signal_from_string_try_harder(optarg);
+ if (arg_signal < 0) {
+ log_error("Failed to parse signal string %s.", optarg);
+ return -EINVAL;
+ }
+ break;
+
+ case 'H':
+ arg_transport = BUS_TRANSPORT_REMOTE;
+ arg_host = optarg;
+ break;
+
+ case 'M':
+ arg_transport = BUS_TRANSPORT_MACHINE;
+ arg_host = optarg;
+ break;
+
+ case '?':
+ return -EINVAL;
+
+ default:
+ assert_not_reached("Unhandled option");
+ }
+
+ return 1;
+}
+
+static int loginctl_main(int argc, char *argv[], sd_bus *bus) {
+
+ static const Verb verbs[] = {
+ { "help", VERB_ANY, VERB_ANY, 0, help },
+ { "list-sessions", VERB_ANY, 1, VERB_DEFAULT, list_sessions },
+ { "session-status", VERB_ANY, VERB_ANY, 0, show_session },
+ { "show-session", VERB_ANY, VERB_ANY, 0, show_session },
+ { "activate", VERB_ANY, 2, 0, activate },
+ { "lock-session", VERB_ANY, VERB_ANY, 0, activate },
+ { "unlock-session", VERB_ANY, VERB_ANY, 0, activate },
+ { "lock-sessions", VERB_ANY, 1, 0, lock_sessions },
+ { "unlock-sessions", VERB_ANY, 1, 0, lock_sessions },
+ { "terminate-session", 2, VERB_ANY, 0, activate },
+ { "kill-session", 2, VERB_ANY, 0, kill_session },
+ { "list-users", VERB_ANY, 1, 0, list_users },
+ { "user-status", VERB_ANY, VERB_ANY, 0, show_user },
+ { "show-user", VERB_ANY, VERB_ANY, 0, show_user },
+ { "enable-linger", VERB_ANY, VERB_ANY, 0, enable_linger },
+ { "disable-linger", VERB_ANY, VERB_ANY, 0, enable_linger },
+ { "terminate-user", 2, VERB_ANY, 0, terminate_user },
+ { "kill-user", 2, VERB_ANY, 0, kill_user },
+ { "list-seats", VERB_ANY, 1, 0, list_seats },
+ { "seat-status", VERB_ANY, VERB_ANY, 0, show_seat },
+ { "show-seat", VERB_ANY, VERB_ANY, 0, show_seat },
+ { "attach", 3, VERB_ANY, 0, attach },
+ { "flush-devices", VERB_ANY, 1, 0, flush_devices },
+ { "terminate-seat", 2, VERB_ANY, 0, terminate_seat },
+ {}
+ };
+
+ return dispatch_verb(argc, argv, verbs, bus);
+}
+
+int main(int argc, char *argv[]) {
+ sd_bus *bus = NULL;
+ int r;
+
+ setlocale(LC_ALL, "");
+ log_parse_environment();
+ log_open();
+
+ r = parse_argv(argc, argv);
+ if (r <= 0)
+ goto finish;
+
+ r = bus_connect_transport(arg_transport, arg_host, false, &bus);
+ if (r < 0) {
+ log_error_errno(r, "Failed to create bus connection: %m");
+ goto finish;
+ }
+
+ sd_bus_set_allow_interactive_authorization(bus, arg_ask_password);
+
+ r = loginctl_main(argc, argv, bus);
+
+finish:
+ sd_bus_flush_close_unref(bus);
+
+ pager_close();
+ polkit_agent_close();
+
+ strv_free(arg_property);
+
+ return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+}
diff --git a/src/grp-login/loginctl/loginctl.completion.bash b/src/grp-login/loginctl/loginctl.completion.bash
new file mode 100644
index 0000000000..776eca4e62
--- /dev/null
+++ b/src/grp-login/loginctl/loginctl.completion.bash
@@ -0,0 +1,111 @@
+# loginctl(1) completion -*- shell-script -*-
+#
+# This file is part of systemd.
+#
+# Copyright 2010 Ran Benita
+#
+# 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
+# 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/>.
+
+__contains_word () {
+ local w word=$1; shift
+ for w in "$@"; do
+ [[ $w = "$word" ]] && return
+ done
+}
+
+__get_all_sessions () { loginctl --no-legend list-sessions | { while read -r a b; do printf "%s\n" "$a"; done; } ; }
+__get_all_users () { loginctl --no-legend list-users | { while read -r a b; do printf "%s\n" "$b"; done; } ; }
+__get_all_seats () { loginctl --no-legend list-seats | { while read -r a b; do printf "%s\n" "$a"; done; } ; }
+
+_loginctl () {
+ local cur=${COMP_WORDS[COMP_CWORD]} prev=${COMP_WORDS[COMP_CWORD-1]}
+ local i verb comps
+
+ local -A OPTS=(
+ [STANDALONE]='--all -a --help -h --no-pager --privileged -P --version
+ --no-legend --no-ask-password -l --full'
+ [ARG]='--host -H --kill-who --property -p --signal -s --machine'
+ )
+
+ if __contains_word "$prev" ${OPTS[ARG]}; then
+ case $prev in
+ --signal|-s)
+ _signals
+ return
+ ;;
+ --kill-who)
+ comps='all leader'
+ ;;
+ --host|-H)
+ comps=$(compgen -A hostname)
+ ;;
+ --property|-p)
+ comps=''
+ ;;
+ esac
+ COMPREPLY=( $(compgen -W '$comps' -- "$cur") )
+ return 0
+ fi
+
+
+ if [[ "$cur" = -* ]]; then
+ COMPREPLY=( $(compgen -W '${OPTS[*]}' -- "$cur") )
+ return 0
+ fi
+
+ local -A VERBS=(
+ [SESSIONS]='session-status show-session activate lock-session unlock-session terminate-session kill-session'
+ [USERS]='user-status show-user enable-linger disable-linger terminate-user kill-user'
+ [SEATS]='seat-status show-seat terminate-seat'
+ [STANDALONE]='list-sessions list-users list-seats flush-devices'
+ [ATTACH]='attach'
+ )
+
+ for ((i=0; i < COMP_CWORD; i++)); do
+ if __contains_word "${COMP_WORDS[i]}" ${VERBS[*]} &&
+ ! __contains_word "${COMP_WORDS[i-1]}" ${OPTS[ARG]}; then
+ verb=${COMP_WORDS[i]}
+ break
+ fi
+ done
+
+ if [[ -z $verb ]]; then
+ comps="${VERBS[*]}"
+
+ elif __contains_word "$verb" ${VERBS[SESSIONS]}; then
+ comps=$( __get_all_sessions )
+
+ elif __contains_word "$verb" ${VERBS[USERS]}; then
+ comps=$( __get_all_users )
+
+ elif __contains_word "$verb" ${VERBS[SEATS]}; then
+ comps=$( __get_all_seats )
+
+ elif __contains_word "$verb" ${VERBS[STANDALONE]}; then
+ comps=''
+
+ elif __contains_word "$verb" ${VERBS[ATTACH]}; then
+ if [[ $prev = $verb ]]; then
+ comps=$( __get_all_seats )
+ else
+ comps=$(compgen -A file -- "$cur" )
+ compopt -o filenames
+ fi
+ fi
+
+ COMPREPLY=( $(compgen -W '$comps' -- "$cur") )
+ return 0
+}
+
+complete -F _loginctl loginctl
diff --git a/src/grp-login/loginctl/loginctl.completion.zsh b/src/grp-login/loginctl/loginctl.completion.zsh
new file mode 100644
index 0000000000..6f6ff6e314
--- /dev/null
+++ b/src/grp-login/loginctl/loginctl.completion.zsh
@@ -0,0 +1,172 @@
+#compdef loginctl
+
+_loginctl_all_sessions() {
+ local session description
+ loginctl --no-legend list-sessions | while read -r session description; do
+ _sys_all_sessions+=( "$session" )
+ _sys_all_sessions_descr+=( "${session}:$description" )
+ done
+}
+
+_loginctl_all_users() {
+ local uid description
+ loginctl --no-legend list-users | while read -r uid description; do
+ _sys_all_users+=( "$uid" )
+ _sys_all_users_descr+=( "${uid}:$description" )
+ done
+}
+
+_loginctl_all_seats() {
+ local seat description
+ loginctl --no-legend list-seats | while read -r seat description; do
+ _sys_all_seats+=( "$seat" )
+ _sys_all_seats_descr+=( "${seat}:$description" )
+ done
+}
+
+local fun
+# Completion functions for SESSIONS
+for fun in session-status show-session activate lock-session unlock-session terminate-session kill-session ; do
+ (( $+functions[_loginctl_$fun] )) || _loginctl_$fun()
+ {
+ local -a _sys_all_sessions{,_descr}
+
+ _loginctl_all_sessions
+ for _ignore in $words[2,-1]; do
+ _sys_all_sessions[(i)$_ignore]=()
+ _sys_all_sessions_descr[(i)$_ignore:*]=()
+ done
+
+ if zstyle -T ":completion:${curcontext}:systemd-sessions" verbose; then
+ _describe -t systemd-sessions session _sys_all_sessions_descr _sys_all_sessions "$@"
+ else
+ local expl
+ _wanted systemd-sessions expl session compadd "$@" -a _sys_all_sessions
+ fi
+ }
+done
+
+# Completion functions for USERS
+for fun in user-status show-user enable-linger disable-linger terminate-user kill-user ; do
+ (( $+functions[_loginctl_$fun] )) || _loginctl_$fun()
+ {
+ local -a _sys_all_users{,_descr}
+ zstyle -a ":completion:${curcontext}:users" users _sys_all_users
+
+ if ! (( $#_sys_all_users )); then
+ _loginctl_all_users
+ fi
+
+ for _ignore in $words[2,-1]; do
+ _sys_all_users[(i)$_ignore]=()
+ _sys_all_users_descr[(i)$_ignore:*]=()
+ done
+
+ # using the common tag `users' here, not rolling our own `systemd-users' tag
+ if zstyle -T ":completion:${curcontext}:users" verbose; then
+ _describe -t users user ${_sys_all_users_descr:+_sys_all_users_descr} _sys_all_users "$@"
+ else
+ local expl
+ _wanted users expl user compadd "$@" -a _sys_all_users
+ fi
+ }
+done
+
+# Completion functions for SEATS
+(( $+functions[_loginctl_seats] )) || _loginctl_seats()
+{
+ local -a _sys_all_seats{,_descr}
+
+ _loginctl_all_seats
+ for _ignore in $words[2,-1]; do
+ _sys_all_seats[(i)$_ignore]=()
+ _sys_all_seats_descr[(i)$_ignore:*]=()
+ done
+
+ if zstyle -T ":completion:${curcontext}:systemd-seats" verbose; then
+ _describe -t systemd-seats seat _sys_all_seats_descr _sys_all_seats "$@"
+ else
+ local expl
+ _wanted systemd-seats expl seat compadd "$@" -a _sys_all_seats
+ fi
+}
+for fun in seat-status show-seat terminate-seat ; do
+ (( $+functions[_loginctl_$fun] )) || _loginctl_$fun()
+ { _loginctl_seats }
+done
+
+# Completion functions for ATTACH
+(( $+functions[_loginctl_attach] )) || _loginctl_attach()
+{
+ _arguments -w -C -S -s \
+ ':seat:_loginctl_seats' \
+ '*:device:_files'
+}
+
+# no loginctl completion for:
+# [STANDALONE]='list-sessions list-users list-seats flush-devices'
+
+(( $+functions[_loginctl_command] )) || _loginctl_command()
+{
+ local -a _loginctl_cmds
+ _loginctl_cmds=(
+ "list-sessions:List sessions"
+ "session-status:Show session status"
+ "show-session:Show properties of one or more sessions"
+ "activate:Activate a session"
+ "lock-session:Screen lock one or more sessions"
+ "unlock-session:Screen unlock one or more sessions"
+ "lock-sessions:Screen lock all current sessions"
+ "unlock-sessions:Screen unlock all current sessions"
+ "terminate-session:Terminate one or more sessions"
+ "kill-session:Send signal to processes of a session"
+ "list-users:List users"
+ "user-status:Show user status"
+ "show-user:Show properties of one or more users"
+ "enable-linger:Enable linger state of one or more users"
+ "disable-linger:Disable linger state of one or more users"
+ "terminate-user:Terminate all sessions of one or more users"
+ "kill-user:Send signal to processes of a user"
+ "list-seats:List seats"
+ "seat-status:Show seat status"
+ "show-seat:Show properties of one or more seats"
+ "attach:Attach one or more devices to a seat"
+ "flush-devices:Flush all device associations"
+ "terminate-seat:Terminate all sessions on one or more seats"
+ )
+
+ if (( CURRENT == 1 )); then
+ _describe -t commands 'loginctl command' _loginctl_cmds || compadd "$@"
+ else
+ local curcontext="$curcontext" _ignore
+
+ cmd="${${_loginctl_cmds[(r)$words[1]:*]%%:*}}"
+
+ if (( $#cmd )); then
+ curcontext="${curcontext%:*:*}:loginctl-${cmd}:"
+
+ _call_function ret _loginctl_$cmd || _message 'no more arguments'
+ else
+ _message "unknown loginctl command: $words[1]"
+ fi
+ return ret
+ fi
+}
+
+
+_arguments -s \
+ {-h,--help}'[Show help]' \
+ '--version[Show package version]' \
+ \*{-p+,--property=}'[Show only properties by this name]:unit property' \
+ {-a,--all}'[Show all properties, including empty ones]' \
+ '--kill-who=[Who to send signal to]:killwho:(main control all)' \
+ {-s+,--signal=}'[Which signal to send]:signal:_signals' \
+ {-H+,--host=}'[Operate on remote host]:userathost:_sd_hosts_or_user_at_host' \
+ {-M+,--machine=}'[Operate on local container]:machine:_sd_machines' \
+ {-l,--full}'[Do not ellipsize output]' \
+ '--no-pager[Do not pipe output into a pager]' \
+ '--no-legend[Do not show the headers and footers]' \
+ '--no-ask-password[Do not ask for system passwords]' \
+ {-n+,--lines=}'[Number of journal entries to show]' \
+ {-o+,--output=}'[Change journal output mode]:output modes:_sd_outputmodes' \
+ '*::loginctl command:_loginctl_command'
diff --git a/src/grp-login/loginctl/loginctl.xml b/src/grp-login/loginctl/loginctl.xml
new file mode 100644
index 0000000000..fb51740503
--- /dev/null
+++ b/src/grp-login/loginctl/loginctl.xml
@@ -0,0 +1,459 @@
+<?xml version='1.0'?> <!--*-nxml-*-->
+<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN"
+ "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd">
+
+<!--
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ 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/>.
+-->
+
+<refentry id="loginctl" conditional='ENABLE_LOGIND'
+ xmlns:xi="http://www.w3.org/2001/XInclude">
+
+ <refentryinfo>
+ <title>loginctl</title>
+ <productname>systemd</productname>
+
+ <authorgroup>
+ <author>
+ <contrib>Developer</contrib>
+ <firstname>Lennart</firstname>
+ <surname>Poettering</surname>
+ <email>lennart@poettering.net</email>
+ </author>
+ </authorgroup>
+ </refentryinfo>
+
+ <refmeta>
+ <refentrytitle>loginctl</refentrytitle>
+ <manvolnum>1</manvolnum>
+ </refmeta>
+
+ <refnamediv>
+ <refname>loginctl</refname>
+ <refpurpose>Control the systemd login manager</refpurpose>
+ </refnamediv>
+
+ <refsynopsisdiv>
+ <cmdsynopsis>
+ <command>loginctl</command>
+ <arg choice="opt" rep="repeat">OPTIONS</arg>
+ <arg choice="req">COMMAND</arg>
+ <arg choice="opt" rep="repeat">NAME</arg>
+ </cmdsynopsis>
+ </refsynopsisdiv>
+
+ <refsect1>
+ <title>Description</title>
+
+ <para><command>loginctl</command> may be used to introspect and
+ control the state of the
+ <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>
+ login manager
+ <citerefentry><refentrytitle>systemd-logind.service</refentrytitle><manvolnum>8</manvolnum></citerefentry>.</para>
+ </refsect1>
+
+ <refsect1>
+ <title>Options</title>
+
+ <para>The following options are understood:</para>
+
+ <variablelist>
+ <varlistentry>
+ <term><option>--no-ask-password</option></term>
+
+ <listitem><para>Do not query the user for authentication for
+ privileged operations.</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><option>-p</option></term>
+ <term><option>--property=</option></term>
+
+ <listitem><para>When showing session/user/seat properties,
+ limit display to certain properties as specified as argument.
+ If not specified, all set properties are shown. The argument
+ should be a property name, such as
+ <literal>Sessions</literal>. If specified more than once, all
+ properties with the specified names are
+ shown.</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><option>--value</option></term>
+
+ <listitem>
+ <para>When printing properties with <command>show</command>,
+ only print the value, and skip the property name and
+ <literal>=</literal>.</para>
+ </listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><option>-a</option></term>
+ <term><option>--all</option></term>
+
+ <listitem><para>When showing session/user/seat properties,
+ show all properties regardless of whether they are set or
+ not.</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><option>-l</option></term>
+ <term><option>--full</option></term>
+
+ <listitem><para>Do not ellipsize process tree entries.</para>
+ </listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><option>--kill-who=</option></term>
+
+ <listitem><para>When used with
+ <command>kill-session</command>, choose which processes to
+ kill. Must be one of <option>leader</option>, or
+ <option>all</option> to select whether to kill only the leader
+ process of the session or all processes of the session. If
+ omitted, defaults to <option>all</option>.</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><option>-s</option></term>
+ <term><option>--signal=</option></term>
+
+ <listitem><para>When used with <command>kill-session</command>
+ or <command>kill-user</command>, choose which signal to send
+ to selected processes. Must be one of the well known signal
+ specifiers, such as <constant>SIGTERM</constant>,
+ <constant>SIGINT</constant> or <constant>SIGSTOP</constant>.
+ If omitted, defaults to
+ <constant>SIGTERM</constant>.</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><option>-n</option></term>
+ <term><option>--lines=</option></term>
+
+ <listitem><para>When used with <command>user-status</command>
+ and <command>session-status</command>, controls the number of
+ journal lines to show, counting from the most recent ones.
+ Takes a positive integer argument. Defaults to 10.</para>
+ </listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><option>-o</option></term>
+ <term><option>--output=</option></term>
+
+ <listitem><para>When used with <command>user-status</command>
+ and <command>session-status</command>, controls the formatting
+ of the journal entries that are shown. For the available
+ choices, see
+ <citerefentry><refentrytitle>journalctl</refentrytitle><manvolnum>1</manvolnum></citerefentry>.
+ Defaults to <literal>short</literal>.</para></listitem>
+ </varlistentry>
+
+ <xi:include href="user-system-options.xml" xpointer="host" />
+ <xi:include href="user-system-options.xml" xpointer="machine" />
+
+ <xi:include href="standard-options.xml" xpointer="no-pager" />
+ <xi:include href="standard-options.xml" xpointer="no-legend" />
+ <xi:include href="standard-options.xml" xpointer="help" />
+ <xi:include href="standard-options.xml" xpointer="version" />
+ </variablelist>
+ </refsect1>
+
+ <refsect1>
+ <title>Commands</title>
+
+ <para>The following commands are understood:</para>
+
+ <refsect2><title>Session Commands</title><variablelist>
+
+ <varlistentry>
+ <term><command>list-sessions</command></term>
+
+ <listitem><para>List current sessions.</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><command>session-status</command> <optional><replaceable>ID</replaceable>...</optional></term>
+
+ <listitem><para>Show terse runtime status information about
+ one or more sessions, followed by the most recent log data
+ from the journal. Takes one or more session identifiers as
+ parameters. If no session identifiers are passed, the status of
+ the caller's session is shown. This function is intended to
+ generate human-readable output. If you are looking for
+ computer-parsable output, use <command>show-session</command>
+ instead.</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><command>show-session</command> <optional><replaceable>ID</replaceable>...</optional></term>
+
+ <listitem><para>Show properties of one or more sessions or the
+ manager itself. If no argument is specified, properties of the
+ manager will be shown. If a session ID is specified,
+ properties of the session are shown. By default, empty
+ properties are suppressed. Use <option>--all</option> to show
+ those too. To select specific properties to show, use
+ <option>--property=</option>. This command is intended to be
+ used whenever computer-parsable output is required. Use
+ <command>session-status</command> if you are looking for
+ formatted human-readable output.</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><command>activate</command> <optional><replaceable>ID</replaceable></optional></term>
+
+ <listitem><para>Activate a session. This brings a session into
+ the foreground if another session is currently in the
+ foreground on the respective seat. Takes a session identifier
+ as argument. If no argument is specified, the session of the
+ caller is put into foreground.</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><command>lock-session</command> <optional><replaceable>ID</replaceable>...</optional></term>
+ <term><command>unlock-session</command> <optional><replaceable>ID</replaceable>...</optional></term>
+
+ <listitem><para>Activates/deactivates the screen lock on one
+ or more sessions, if the session supports it. Takes one or
+ more session identifiers as arguments. If no argument is
+ specified, the session of the caller is locked/unlocked.
+ </para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><command>lock-sessions</command></term>
+ <term><command>unlock-sessions</command></term>
+
+ <listitem><para>Activates/deactivates the screen lock on all
+ current sessions supporting it. </para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><command>terminate-session</command> <replaceable>ID</replaceable>...</term>
+
+ <listitem><para>Terminates a session. This kills all processes
+ of the session and deallocates all resources attached to the
+ session. </para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><command>kill-session</command> <replaceable>ID</replaceable>...</term>
+
+ <listitem><para>Send a signal to one or more processes of the
+ session. Use <option>--kill-who=</option> to select which
+ process to kill. Use <option>--signal=</option> to select the
+ signal to send.</para></listitem>
+ </varlistentry>
+ </variablelist></refsect2>
+
+ <refsect2><title>User Commands</title><variablelist>
+ <varlistentry>
+ <term><command>list-users</command></term>
+
+ <listitem><para>List currently logged in users.
+ </para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><command>user-status</command> <optional><replaceable>USER</replaceable>...</optional></term>
+
+ <listitem><para>Show terse runtime status information about
+ one or more logged in users, followed by the most recent log
+ data from the journal. Takes one or more user names or numeric
+ user IDs as parameters. If no parameters are passed, the status
+ of the caller's user is shown. This function is intended to
+ generate human-readable output. If you are looking for
+ computer-parsable output, use <command>show-user</command>
+ instead. Users may be specified by their usernames or numeric
+ user IDs. </para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><command>show-user</command> <optional><replaceable>USER</replaceable>...</optional></term>
+
+ <listitem><para>Show properties of one or more users or the
+ manager itself. If no argument is specified, properties of the
+ manager will be shown. If a user is specified, properties of
+ the user are shown. By default, empty properties are
+ suppressed. Use <option>--all</option> to show those too. To
+ select specific properties to show, use
+ <option>--property=</option>. This command is intended to be
+ used whenever computer-parsable output is required. Use
+ <command>user-status</command> if you are looking for
+ formatted human-readable output.</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><command>enable-linger</command> <optional><replaceable>USER</replaceable>...</optional></term>
+ <term><command>disable-linger</command> <optional><replaceable>USER</replaceable>...</optional></term>
+
+ <listitem><para>Enable/disable user lingering for one or more
+ users. If enabled for a specific user, a user manager is
+ spawned for the user at boot and kept around after logouts.
+ This allows users who are not logged in to run long-running
+ services. Takes one or more user names or numeric UIDs as
+ argument. If no argument is specified, enables/disables
+ lingering for the user of the session of the caller.</para>
+
+ <para>See also <varname>KillUserProcesses=</varname> setting in
+ <citerefentry><refentrytitle>logind.conf</refentrytitle><manvolnum>5</manvolnum></citerefentry>.
+ </para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><command>terminate-user</command> <replaceable>USER</replaceable>...</term>
+
+ <listitem><para>Terminates all sessions of a user. This kills
+ all processes of all sessions of the user and deallocates all
+ runtime resources attached to the user.</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><command>kill-user</command> <replaceable>USER</replaceable>...</term>
+
+ <listitem><para>Send a signal to all processes of a user. Use
+ <option>--signal=</option> to select the signal to send.
+ </para></listitem>
+ </varlistentry>
+ </variablelist></refsect2>
+
+ <refsect2><title>Seat Commands</title><variablelist>
+ <varlistentry>
+ <term><command>list-seats</command></term>
+
+ <listitem><para>List currently available seats on the local
+ system.</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><command>seat-status</command> <optional><replaceable>NAME</replaceable>...</optional></term>
+
+ <listitem><para>Show terse runtime status information about
+ one or more seats. Takes one or more seat names as parameters.
+ If no seat names are passed the status of the caller's
+ session's seat is shown. This function is intended to generate
+ human-readable output. If you are looking for
+ computer-parsable output, use <command>show-seat</command>
+ instead.</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><command>show-seat</command> <optional><replaceable>NAME</replaceable>...</optional></term>
+
+ <listitem><para>Show properties of one or more seats or the
+ manager itself. If no argument is specified, properties of the
+ manager will be shown. If a seat is specified, properties of
+ the seat are shown. By default, empty properties are
+ suppressed. Use <option>--all</option> to show those too. To
+ select specific properties to show, use
+ <option>--property=</option>. This command is intended to be
+ used whenever computer-parsable output is required. Use
+ <command>seat-status</command> if you are looking for
+ formatted human-readable output.</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><command>attach</command> <replaceable>NAME</replaceable> <replaceable>DEVICE</replaceable>...</term>
+
+ <listitem><para>Persistently attach one or more devices to a
+ seat. The devices should be specified via device paths in the
+ <filename>/sys</filename> file system. To create a new seat,
+ attach at least one graphics card to a previously unused seat
+ name. Seat names may consist only of a–z, A–Z, 0–9,
+ <literal>-</literal> and <literal>_</literal> and must be
+ prefixed with <literal>seat</literal>. To drop assignment of a
+ device to a specific seat, just reassign it to a different
+ seat, or use <command>flush-devices</command>.
+ </para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><command>flush-devices</command></term>
+
+ <listitem><para>Removes all device assignments previously
+ created with <command>attach</command>. After this call, only
+ automatically generated seats will remain, and all seat
+ hardware is assigned to them.</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><command>terminate-seat</command> <replaceable>NAME</replaceable>...</term>
+
+ <listitem><para>Terminates all sessions on a seat. This kills
+ all processes of all sessions on the seat and deallocates all
+ runtime resources attached to them.</para></listitem>
+ </varlistentry>
+ </variablelist></refsect2>
+
+ </refsect1>
+
+ <refsect1>
+ <title>Exit status</title>
+
+ <para>On success, 0 is returned, a non-zero failure code
+ otherwise.</para>
+ </refsect1>
+
+ <refsect1>
+ <title>Examples</title>
+
+ <example>
+ <title>Querying user status</title>
+
+ <programlisting>$ loginctl user-status
+fatima (1005)
+ Since: Sat 2016-04-09 14:23:31 EDT; 54min ago
+ State: active
+ Sessions: 5 *3
+ Unit: user-1005.slice
+ ├─user@1005.service
+ ...
+ ├─session-3.scope
+ ...
+ └─session-5.scope
+ ├─3473 login -- fatima
+ └─3515 -zsh
+
+Apr 09 14:40:30 laptop login[2325]: pam_unix(login:session):
+ session opened for user fatima by LOGIN(uid=0)
+Apr 09 14:40:30 laptop login[2325]: LOGIN ON tty3 BY fatima
+</programlisting>
+
+ <para>There are two sessions, 3 and 5. Session 3 is a graphical session,
+ marked with a star. The tree of processing including the two corresponding
+ scope units and the user manager unit are shown.</para>
+ </example>
+ </refsect1>
+
+ <xi:include href="less-variables.xml" />
+
+ <refsect1>
+ <title>See Also</title>
+ <para>
+ <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>,
+ <citerefentry><refentrytitle>systemctl</refentrytitle><manvolnum>1</manvolnum></citerefentry>,
+ <citerefentry><refentrytitle>systemd-logind.service</refentrytitle><manvolnum>8</manvolnum></citerefentry>,
+ <citerefentry><refentrytitle>logind.conf</refentrytitle><manvolnum>5</manvolnum></citerefentry>
+ </para>
+ </refsect1>
+
+</refentry>
diff --git a/src/grp-login/loginctl/sysfs-show.c b/src/grp-login/loginctl/sysfs-show.c
new file mode 100644
index 0000000000..12808c3336
--- /dev/null
+++ b/src/grp-login/loginctl/sysfs-show.c
@@ -0,0 +1,190 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ 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 <errno.h>
+#include <string.h>
+
+#include <libudev.h>
+
+#include "basic/alloc-util.h"
+#include "basic/locale-util.h"
+#include "basic/path-util.h"
+#include "basic/string-util.h"
+#include "basic/terminal-util.h"
+#include "basic/util.h"
+#include "shared/udev-util.h"
+
+#include "sysfs-show.h"
+
+static int show_sysfs_one(
+ struct udev *udev,
+ const char *seat,
+ struct udev_list_entry **item,
+ const char *sub,
+ const char *prefix,
+ unsigned n_columns) {
+
+ assert(udev);
+ assert(seat);
+ assert(item);
+ assert(prefix);
+
+ while (*item) {
+ _cleanup_udev_device_unref_ struct udev_device *d = NULL;
+ struct udev_list_entry *next, *lookahead;
+ const char *sn, *name, *sysfs, *subsystem, *sysname;
+ _cleanup_free_ char *k = NULL, *l = NULL;
+ bool is_master;
+
+ sysfs = udev_list_entry_get_name(*item);
+ if (!path_startswith(sysfs, sub))
+ return 0;
+
+ d = udev_device_new_from_syspath(udev, sysfs);
+ if (!d) {
+ *item = udev_list_entry_get_next(*item);
+ continue;
+ }
+
+ sn = udev_device_get_property_value(d, "ID_SEAT");
+ if (isempty(sn))
+ sn = "seat0";
+
+ /* Explicitly also check for tag 'seat' here */
+ if (!streq(seat, sn) || !udev_device_has_tag(d, "seat")) {
+ *item = udev_list_entry_get_next(*item);
+ continue;
+ }
+
+ is_master = udev_device_has_tag(d, "master-of-seat");
+
+ name = udev_device_get_sysattr_value(d, "name");
+ if (!name)
+ name = udev_device_get_sysattr_value(d, "id");
+ subsystem = udev_device_get_subsystem(d);
+ sysname = udev_device_get_sysname(d);
+
+ /* Look if there's more coming after this */
+ lookahead = next = udev_list_entry_get_next(*item);
+ while (lookahead) {
+ const char *lookahead_sysfs;
+
+ lookahead_sysfs = udev_list_entry_get_name(lookahead);
+
+ if (path_startswith(lookahead_sysfs, sub) &&
+ !path_startswith(lookahead_sysfs, sysfs)) {
+ _cleanup_udev_device_unref_ struct udev_device *lookahead_d = NULL;
+
+ lookahead_d = udev_device_new_from_syspath(udev, lookahead_sysfs);
+ if (lookahead_d) {
+ const char *lookahead_sn;
+
+ lookahead_sn = udev_device_get_property_value(d, "ID_SEAT");
+ if (isempty(lookahead_sn))
+ lookahead_sn = "seat0";
+
+ if (streq(seat, lookahead_sn) && udev_device_has_tag(lookahead_d, "seat"))
+ break;
+ }
+ }
+
+ lookahead = udev_list_entry_get_next(lookahead);
+ }
+
+ k = ellipsize(sysfs, n_columns, 20);
+ if (!k)
+ return -ENOMEM;
+
+ printf("%s%s%s\n", prefix, special_glyph(lookahead ? TREE_BRANCH : TREE_RIGHT), k);
+
+ if (asprintf(&l,
+ "%s%s:%s%s%s%s",
+ is_master ? "[MASTER] " : "",
+ subsystem, sysname,
+ name ? " \"" : "", strempty(name), name ? "\"" : "") < 0)
+ return -ENOMEM;
+
+ free(k);
+ k = ellipsize(l, n_columns, 70);
+ if (!k)
+ return -ENOMEM;
+
+ printf("%s%s%s\n", prefix, lookahead ? special_glyph(TREE_VERTICAL) : " ", k);
+
+ *item = next;
+ if (*item) {
+ _cleanup_free_ char *p = NULL;
+
+ p = strappend(prefix, lookahead ? special_glyph(TREE_VERTICAL) : " ");
+ if (!p)
+ return -ENOMEM;
+
+ show_sysfs_one(udev, seat, item, sysfs, p, n_columns - 2);
+ }
+ }
+
+ return 0;
+}
+
+int show_sysfs(const char *seat, const char *prefix, unsigned n_columns) {
+ _cleanup_udev_enumerate_unref_ struct udev_enumerate *e = NULL;
+ _cleanup_udev_unref_ struct udev *udev = NULL;
+ struct udev_list_entry *first = NULL;
+ int r;
+
+ if (n_columns <= 0)
+ n_columns = columns();
+
+ if (!prefix)
+ prefix = "";
+
+ if (isempty(seat))
+ seat = "seat0";
+
+ udev = udev_new();
+ if (!udev)
+ return -ENOMEM;
+
+ e = udev_enumerate_new(udev);
+ if (!e)
+ return -ENOMEM;
+
+ if (!streq(seat, "seat0"))
+ r = udev_enumerate_add_match_tag(e, seat);
+ else
+ r = udev_enumerate_add_match_tag(e, "seat");
+ if (r < 0)
+ return r;
+
+ r = udev_enumerate_add_match_is_initialized(e);
+ if (r < 0)
+ return r;
+
+ r = udev_enumerate_scan_devices(e);
+ if (r < 0)
+ return r;
+
+ first = udev_enumerate_get_list_entry(e);
+ if (first)
+ show_sysfs_one(udev, seat, &first, "/", prefix, n_columns);
+ else
+ printf("%s%s%s\n", prefix, special_glyph(TREE_RIGHT), "(none)");
+
+ return r;
+}
diff --git a/src/grp-login/loginctl/sysfs-show.h b/src/grp-login/loginctl/sysfs-show.h
new file mode 100644
index 0000000000..3e94bc3ed5
--- /dev/null
+++ b/src/grp-login/loginctl/sysfs-show.h
@@ -0,0 +1,22 @@
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ 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/>.
+***/
+
+int show_sysfs(const char *seat, const char *prefix, unsigned columns);
diff --git a/src/grp-login/pam_systemd/Makefile b/src/grp-login/pam_systemd/Makefile
new file mode 100644
index 0000000000..8de05d9b7b
--- /dev/null
+++ b/src/grp-login/pam_systemd/Makefile
@@ -0,0 +1,55 @@
+# -*- Mode: makefile; indent-tabs-mode: t -*-
+#
+# This file is part of systemd.
+#
+# Copyright 2010-2012 Lennart Poettering
+# Copyright 2010-2012 Kay Sievers
+# Copyright 2013 Zbigniew Jędrzejewski-Szmek
+# Copyright 2013 David Strauss
+# Copyright 2016 Luke Shumaker
+#
+# 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 $(dir $(lastword $(MAKEFILE_LIST)))/../../../config.mk
+include $(topsrcdir)/build-aux/Makefile.head.mk
+
+ifneq ($(HAVE_PAM),)
+pam_systemd_la_SOURCES = \
+ src/login/pam_systemd.sym \
+ src/login/pam_systemd.c
+
+pam_systemd_la_CFLAGS = \
+ $(PAM_CFLAGS)
+
+pam_systemd_la_LDFLAGS = \
+ -module \
+ -export-dynamic \
+ -avoid-version \
+ -shared \
+ -Wl,--version-script=$(srcdir)/pam_systemd.sym
+
+pam_systemd_la_LIBADD = \
+ libshared.la \
+ $(PAM_LIBS)
+
+pamlib_LTLIBRARIES = \
+ pam_systemd.la
+
+dist_pamconf_DATA = \
+ src/login/systemd-user
+
+EXTRA_DIST += \
+ src/login/systemd-user.m4
+endif # HAVE_PAM
+
+include $(topsrcdir)/build-aux/Makefile.tail.mk
diff --git a/src/grp-login/pam_systemd/pam_systemd.c b/src/grp-login/pam_systemd/pam_systemd.c
new file mode 100644
index 0000000000..11f527cda0
--- /dev/null
+++ b/src/grp-login/pam_systemd/pam_systemd.c
@@ -0,0 +1,553 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ 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 <endian.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <pwd.h>
+#include <security/_pam_macros.h>
+#include <security/pam_ext.h>
+#include <security/pam_misc.h>
+#include <security/pam_modules.h>
+#include <security/pam_modutil.h>
+#include <sys/file.h>
+
+#include "basic/alloc-util.h"
+#include "basic/audit-util.h"
+#include "basic/def.h"
+#include "basic/fd-util.h"
+#include "basic/fileio.h"
+#include "basic/formats-util.h"
+#include "basic/hostname-util.h"
+#include "basic/login-util.h"
+#include "basic/macro.h"
+#include "basic/parse-util.h"
+#include "basic/socket-util.h"
+#include "basic/strv.h"
+#include "basic/terminal-util.h"
+#include "basic/util.h"
+#include "sd-bus/bus-common-errors.h"
+#include "sd-bus/bus-error.h"
+#include "shared/bus-util.h"
+
+static int parse_argv(
+ pam_handle_t *handle,
+ int argc, const char **argv,
+ const char **class,
+ const char **type,
+ bool *debug) {
+
+ unsigned i;
+
+ assert(argc >= 0);
+ assert(argc == 0 || argv);
+
+ for (i = 0; i < (unsigned) argc; i++) {
+ if (startswith(argv[i], "class=")) {
+ if (class)
+ *class = argv[i] + 6;
+
+ } else if (startswith(argv[i], "type=")) {
+ if (type)
+ *type = argv[i] + 5;
+
+ } else if (streq(argv[i], "debug")) {
+ if (debug)
+ *debug = true;
+
+ } else if (startswith(argv[i], "debug=")) {
+ int k;
+
+ k = parse_boolean(argv[i] + 6);
+ if (k < 0)
+ pam_syslog(handle, LOG_WARNING, "Failed to parse debug= argument, ignoring.");
+ else if (debug)
+ *debug = k;
+
+ } else
+ pam_syslog(handle, LOG_WARNING, "Unknown parameter '%s', ignoring", argv[i]);
+ }
+
+ return 0;
+}
+
+static int get_user_data(
+ pam_handle_t *handle,
+ const char **ret_username,
+ struct passwd **ret_pw) {
+
+ const char *username = NULL;
+ struct passwd *pw = NULL;
+ int r;
+
+ assert(handle);
+ assert(ret_username);
+ assert(ret_pw);
+
+ r = pam_get_user(handle, &username, NULL);
+ if (r != PAM_SUCCESS) {
+ pam_syslog(handle, LOG_ERR, "Failed to get user name.");
+ return r;
+ }
+
+ if (isempty(username)) {
+ pam_syslog(handle, LOG_ERR, "User name not valid.");
+ return PAM_AUTH_ERR;
+ }
+
+ pw = pam_modutil_getpwnam(handle, username);
+ if (!pw) {
+ pam_syslog(handle, LOG_ERR, "Failed to get user data.");
+ return PAM_USER_UNKNOWN;
+ }
+
+ *ret_pw = pw;
+ *ret_username = username;
+
+ return PAM_SUCCESS;
+}
+
+static int get_seat_from_display(const char *display, const char **seat, uint32_t *vtnr) {
+ union sockaddr_union sa = {
+ .un.sun_family = AF_UNIX,
+ };
+ _cleanup_free_ char *p = NULL, *tty = NULL;
+ _cleanup_close_ int fd = -1;
+ struct ucred ucred;
+ int v, r;
+
+ assert(display);
+ assert(vtnr);
+
+ /* We deduce the X11 socket from the display name, then use
+ * SO_PEERCRED to determine the X11 server process, ask for
+ * the controlling tty of that and if it's a VC then we know
+ * the seat and the virtual terminal. Sounds ugly, is only
+ * semi-ugly. */
+
+ r = socket_from_display(display, &p);
+ if (r < 0)
+ return r;
+ strncpy(sa.un.sun_path, p, sizeof(sa.un.sun_path)-1);
+
+ fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0);
+ if (fd < 0)
+ return -errno;
+
+ if (connect(fd, &sa.sa, SOCKADDR_UN_LEN(sa.un)) < 0)
+ return -errno;
+
+ r = getpeercred(fd, &ucred);
+ if (r < 0)
+ return r;
+
+ r = get_ctty(ucred.pid, NULL, &tty);
+ if (r < 0)
+ return r;
+
+ v = vtnr_from_tty(tty);
+ if (v < 0)
+ return v;
+ else if (v == 0)
+ return -ENOENT;
+
+ if (seat)
+ *seat = "seat0";
+ *vtnr = (uint32_t) v;
+
+ return 0;
+}
+
+static int export_legacy_dbus_address(
+ pam_handle_t *handle,
+ uid_t uid,
+ const char *runtime) {
+
+ _cleanup_free_ char *s = NULL;
+ int r = PAM_BUF_ERR;
+
+ /* FIXME: We *really* should move the access() check into the
+ * daemons that spawn dbus-daemon, instead of forcing
+ * DBUS_SESSION_BUS_ADDRESS= here. */
+
+ s = strjoin(runtime, "/bus", NULL);
+ if (!s)
+ goto error;
+
+ if (access(s, F_OK) < 0)
+ return PAM_SUCCESS;
+
+ s = mfree(s);
+ if (asprintf(&s, UNIX_USER_BUS_ADDRESS_FMT, runtime) < 0)
+ goto error;
+
+ r = pam_misc_setenv(handle, "DBUS_SESSION_BUS_ADDRESS", s, 0);
+ if (r != PAM_SUCCESS)
+ goto error;
+
+ return PAM_SUCCESS;
+
+error:
+ pam_syslog(handle, LOG_ERR, "Failed to set bus variable.");
+ return r;
+}
+
+_public_ PAM_EXTERN int pam_sm_open_session(
+ pam_handle_t *handle,
+ int flags,
+ int argc, const char **argv) {
+
+ _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+ _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
+ const char
+ *username, *id, *object_path, *runtime_path,
+ *service = NULL,
+ *tty = NULL, *display = NULL,
+ *remote_user = NULL, *remote_host = NULL,
+ *seat = NULL,
+ *type = NULL, *class = NULL,
+ *class_pam = NULL, *type_pam = NULL, *cvtnr = NULL, *desktop = NULL;
+ _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
+ int session_fd = -1, existing, r;
+ bool debug = false, remote;
+ struct passwd *pw;
+ uint32_t vtnr = 0;
+ uid_t original_uid;
+
+ assert(handle);
+
+ /* Make this a NOP on non-logind systems */
+ if (!logind_running())
+ return PAM_SUCCESS;
+
+ if (parse_argv(handle,
+ argc, argv,
+ &class_pam,
+ &type_pam,
+ &debug) < 0)
+ return PAM_SESSION_ERR;
+
+ if (debug)
+ pam_syslog(handle, LOG_DEBUG, "pam-systemd initializing");
+
+ r = get_user_data(handle, &username, &pw);
+ if (r != PAM_SUCCESS) {
+ pam_syslog(handle, LOG_ERR, "Failed to get user data.");
+ return r;
+ }
+
+ /* Make sure we don't enter a loop by talking to
+ * systemd-logind when it is actually waiting for the
+ * background to finish start-up. If the service is
+ * "systemd-user" we simply set XDG_RUNTIME_DIR and
+ * leave. */
+
+ pam_get_item(handle, PAM_SERVICE, (const void**) &service);
+ if (streq_ptr(service, "systemd-user")) {
+ _cleanup_free_ char *rt = NULL;
+
+ if (asprintf(&rt, "/run/user/"UID_FMT, pw->pw_uid) < 0)
+ return PAM_BUF_ERR;
+
+ r = pam_misc_setenv(handle, "XDG_RUNTIME_DIR", rt, 0);
+ if (r != PAM_SUCCESS) {
+ pam_syslog(handle, LOG_ERR, "Failed to set runtime dir.");
+ return r;
+ }
+
+ r = export_legacy_dbus_address(handle, pw->pw_uid, rt);
+ if (r != PAM_SUCCESS)
+ return r;
+
+ return PAM_SUCCESS;
+ }
+
+ /* Otherwise, we ask logind to create a session for us */
+
+ pam_get_item(handle, PAM_XDISPLAY, (const void**) &display);
+ pam_get_item(handle, PAM_TTY, (const void**) &tty);
+ pam_get_item(handle, PAM_RUSER, (const void**) &remote_user);
+ pam_get_item(handle, PAM_RHOST, (const void**) &remote_host);
+
+ seat = pam_getenv(handle, "XDG_SEAT");
+ if (isempty(seat))
+ seat = getenv("XDG_SEAT");
+
+ cvtnr = pam_getenv(handle, "XDG_VTNR");
+ if (isempty(cvtnr))
+ cvtnr = getenv("XDG_VTNR");
+
+ type = pam_getenv(handle, "XDG_SESSION_TYPE");
+ if (isempty(type))
+ type = getenv("XDG_SESSION_TYPE");
+ if (isempty(type))
+ type = type_pam;
+
+ class = pam_getenv(handle, "XDG_SESSION_CLASS");
+ if (isempty(class))
+ class = getenv("XDG_SESSION_CLASS");
+ if (isempty(class))
+ class = class_pam;
+
+ desktop = pam_getenv(handle, "XDG_SESSION_DESKTOP");
+ if (isempty(desktop))
+ desktop = getenv("XDG_SESSION_DESKTOP");
+
+ tty = strempty(tty);
+
+ if (strchr(tty, ':')) {
+ /* A tty with a colon is usually an X11 display,
+ * placed there to show up in utmp. We rearrange
+ * things and don't pretend that an X display was a
+ * tty. */
+
+ if (isempty(display))
+ display = tty;
+ tty = NULL;
+ } else if (streq(tty, "cron")) {
+ /* cron has been setting PAM_TTY to "cron" for a very
+ * long time and it probably shouldn't stop doing that
+ * for compatibility reasons. */
+ type = "unspecified";
+ class = "background";
+ tty = NULL;
+ } else if (streq(tty, "ssh")) {
+ /* ssh has been setting PAM_TTY to "ssh" for a very
+ * long time and probably shouldn't stop doing that
+ * for compatibility reasons. */
+ type ="tty";
+ class = "user";
+ tty = NULL;
+ }
+
+ /* If this fails vtnr will be 0, that's intended */
+ if (!isempty(cvtnr))
+ (void) safe_atou32(cvtnr, &vtnr);
+
+ if (!isempty(display) && !vtnr) {
+ if (isempty(seat))
+ get_seat_from_display(display, &seat, &vtnr);
+ else if (streq(seat, "seat0"))
+ get_seat_from_display(display, NULL, &vtnr);
+ }
+
+ if (seat && !streq(seat, "seat0") && vtnr != 0) {
+ pam_syslog(handle, LOG_DEBUG, "Ignoring vtnr %"PRIu32" for %s which is not seat0", vtnr, seat);
+ vtnr = 0;
+ }
+
+ if (isempty(type))
+ type = !isempty(display) ? "x11" :
+ !isempty(tty) ? "tty" : "unspecified";
+
+ if (isempty(class))
+ class = streq(type, "unspecified") ? "background" : "user";
+
+ remote = !isempty(remote_host) && !is_localhost(remote_host);
+
+ /* Talk to logind over the message bus */
+
+ r = sd_bus_open_system(&bus);
+ if (r < 0) {
+ pam_syslog(handle, LOG_ERR, "Failed to connect to system bus: %s", strerror(-r));
+ return PAM_SESSION_ERR;
+ }
+
+ if (debug)
+ pam_syslog(handle, LOG_DEBUG, "Asking logind to create session: "
+ "uid="UID_FMT" pid="PID_FMT" service=%s type=%s class=%s desktop=%s seat=%s vtnr=%"PRIu32" tty=%s display=%s remote=%s remote_user=%s remote_host=%s",
+ pw->pw_uid, getpid(),
+ strempty(service),
+ type, class, strempty(desktop),
+ strempty(seat), vtnr, strempty(tty), strempty(display),
+ yes_no(remote), strempty(remote_user), strempty(remote_host));
+
+ r = sd_bus_call_method(bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "CreateSession",
+ &error,
+ &reply,
+ "uusssssussbssa(sv)",
+ (uint32_t) pw->pw_uid,
+ (uint32_t) getpid(),
+ service,
+ type,
+ class,
+ desktop,
+ seat,
+ vtnr,
+ tty,
+ display,
+ remote,
+ remote_user,
+ remote_host,
+ 0);
+ if (r < 0) {
+ if (sd_bus_error_has_name(&error, BUS_ERROR_SESSION_BUSY)) {
+ pam_syslog(handle, LOG_DEBUG, "Cannot create session: %s", bus_error_message(&error, r));
+ return PAM_SUCCESS;
+ } else {
+ pam_syslog(handle, LOG_ERR, "Failed to create session: %s", bus_error_message(&error, r));
+ return PAM_SYSTEM_ERR;
+ }
+ }
+
+ r = sd_bus_message_read(reply,
+ "soshusub",
+ &id,
+ &object_path,
+ &runtime_path,
+ &session_fd,
+ &original_uid,
+ &seat,
+ &vtnr,
+ &existing);
+ if (r < 0) {
+ pam_syslog(handle, LOG_ERR, "Failed to parse message: %s", strerror(-r));
+ return PAM_SESSION_ERR;
+ }
+
+ if (debug)
+ pam_syslog(handle, LOG_DEBUG, "Reply from logind: "
+ "id=%s object_path=%s runtime_path=%s session_fd=%d seat=%s vtnr=%u original_uid=%u",
+ id, object_path, runtime_path, session_fd, seat, vtnr, original_uid);
+
+ r = pam_misc_setenv(handle, "XDG_SESSION_ID", id, 0);
+ if (r != PAM_SUCCESS) {
+ pam_syslog(handle, LOG_ERR, "Failed to set session id.");
+ return r;
+ }
+
+ if (original_uid == pw->pw_uid) {
+ /* Don't set $XDG_RUNTIME_DIR if the user we now
+ * authenticated for does not match the original user
+ * of the session. We do this in order not to result
+ * in privileged apps clobbering the runtime directory
+ * unnecessarily. */
+
+ r = pam_misc_setenv(handle, "XDG_RUNTIME_DIR", runtime_path, 0);
+ if (r != PAM_SUCCESS) {
+ pam_syslog(handle, LOG_ERR, "Failed to set runtime dir.");
+ return r;
+ }
+
+ r = export_legacy_dbus_address(handle, pw->pw_uid, runtime_path);
+ if (r != PAM_SUCCESS)
+ return r;
+ }
+
+ if (!isempty(seat)) {
+ r = pam_misc_setenv(handle, "XDG_SEAT", seat, 0);
+ if (r != PAM_SUCCESS) {
+ pam_syslog(handle, LOG_ERR, "Failed to set seat.");
+ return r;
+ }
+ }
+
+ if (vtnr > 0) {
+ char buf[DECIMAL_STR_MAX(vtnr)];
+ sprintf(buf, "%u", vtnr);
+
+ r = pam_misc_setenv(handle, "XDG_VTNR", buf, 0);
+ if (r != PAM_SUCCESS) {
+ pam_syslog(handle, LOG_ERR, "Failed to set virtual terminal number.");
+ return r;
+ }
+ }
+
+ r = pam_set_data(handle, "systemd.existing", INT_TO_PTR(!!existing), NULL);
+ if (r != PAM_SUCCESS) {
+ pam_syslog(handle, LOG_ERR, "Failed to install existing flag.");
+ return r;
+ }
+
+ if (session_fd >= 0) {
+ session_fd = fcntl(session_fd, F_DUPFD_CLOEXEC, 3);
+ if (session_fd < 0) {
+ pam_syslog(handle, LOG_ERR, "Failed to dup session fd: %m");
+ return PAM_SESSION_ERR;
+ }
+
+ r = pam_set_data(handle, "systemd.session-fd", FD_TO_PTR(session_fd), NULL);
+ if (r != PAM_SUCCESS) {
+ pam_syslog(handle, LOG_ERR, "Failed to install session fd.");
+ safe_close(session_fd);
+ return r;
+ }
+ }
+
+ return PAM_SUCCESS;
+}
+
+_public_ PAM_EXTERN int pam_sm_close_session(
+ pam_handle_t *handle,
+ int flags,
+ int argc, const char **argv) {
+
+ _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+ _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
+ const void *existing = NULL;
+ const char *id;
+ int r;
+
+ assert(handle);
+
+ /* Only release session if it wasn't pre-existing when we
+ * tried to create it */
+ pam_get_data(handle, "systemd.existing", &existing);
+
+ id = pam_getenv(handle, "XDG_SESSION_ID");
+ if (id && !existing) {
+
+ /* Before we go and close the FIFO we need to tell
+ * logind that this is a clean session shutdown, so
+ * that it doesn't just go and slaughter us
+ * immediately after closing the fd */
+
+ r = sd_bus_open_system(&bus);
+ if (r < 0) {
+ pam_syslog(handle, LOG_ERR, "Failed to connect to system bus: %s", strerror(-r));
+ return PAM_SESSION_ERR;
+ }
+
+ r = sd_bus_call_method(bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "ReleaseSession",
+ &error,
+ NULL,
+ "s",
+ id);
+ if (r < 0) {
+ pam_syslog(handle, LOG_ERR, "Failed to release session: %s", bus_error_message(&error, r));
+ return PAM_SESSION_ERR;
+ }
+ }
+
+ /* Note that we are knowingly leaking the FIFO fd here. This
+ * way, logind can watch us die. If we closed it here it would
+ * not have any clue when that is completed. Given that one
+ * cannot really have multiple PAM sessions open from the same
+ * process this means we will leak one FD at max. */
+
+ return PAM_SUCCESS;
+}
diff --git a/src/grp-login/pam_systemd/pam_systemd.sym b/src/grp-login/pam_systemd/pam_systemd.sym
new file mode 100644
index 0000000000..23ff75f688
--- /dev/null
+++ b/src/grp-login/pam_systemd/pam_systemd.sym
@@ -0,0 +1,15 @@
+/***
+ This file is part of systemd.
+
+ 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.
+***/
+
+{
+global:
+ pam_sm_close_session;
+ pam_sm_open_session;
+local: *;
+};
diff --git a/src/grp-login/pam_systemd/pam_systemd.xml b/src/grp-login/pam_systemd/pam_systemd.xml
new file mode 100644
index 0000000000..ddda81bc90
--- /dev/null
+++ b/src/grp-login/pam_systemd/pam_systemd.xml
@@ -0,0 +1,296 @@
+<?xml version='1.0'?> <!--*-nxml-*-->
+<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN"
+ "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd">
+
+<!--
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ 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/>.
+-->
+
+<refentry id="pam_systemd" conditional='HAVE_PAM'>
+
+ <refentryinfo>
+ <title>pam_systemd</title>
+ <productname>systemd</productname>
+
+ <authorgroup>
+ <author>
+ <contrib>Developer</contrib>
+ <firstname>Lennart</firstname>
+ <surname>Poettering</surname>
+ <email>lennart@poettering.net</email>
+ </author>
+ </authorgroup>
+ </refentryinfo>
+
+ <refmeta>
+ <refentrytitle>pam_systemd</refentrytitle>
+ <manvolnum>8</manvolnum>
+ </refmeta>
+
+ <refnamediv>
+ <refname>pam_systemd</refname>
+ <refpurpose>Register user sessions in the systemd login manager</refpurpose>
+ </refnamediv>
+
+ <refsynopsisdiv>
+ <para><filename>pam_systemd.so</filename></para>
+ </refsynopsisdiv>
+
+ <refsect1>
+ <title>Description</title>
+
+ <para><command>pam_systemd</command> registers user sessions with
+ the systemd login manager
+ <citerefentry><refentrytitle>systemd-logind.service</refentrytitle><manvolnum>8</manvolnum></citerefentry>,
+ and hence the systemd control group hierarchy.</para>
+
+ <para>On login, this module ensures the following:</para>
+
+ <orderedlist>
+ <listitem><para>If it does not exist yet, the user runtime
+ directory <filename>/run/user/$USER</filename> is created and
+ its ownership changed to the user that is logging
+ in.</para></listitem>
+
+ <listitem><para>The <varname>$XDG_SESSION_ID</varname>
+ environment variable is initialized. If auditing is available
+ and <command>pam_loginuid.so</command> was run before this
+ module (which is highly recommended), the variable is
+ initialized from the auditing session id
+ (<filename>/proc/self/sessionid</filename>). Otherwise, an
+ independent session counter is used.</para></listitem>
+
+ <listitem><para>A new systemd scope unit is created for the
+ session. If this is the first concurrent session of the user, an
+ implicit slice below <filename>user.slice</filename> is
+ automatically created and the scope placed into it. An instance
+ of the system service <filename>user@.service</filename>, which
+ runs the systemd user manager instance, is started.
+ </para></listitem>
+ </orderedlist>
+
+ <para>On logout, this module ensures the following:</para>
+
+ <orderedlist>
+ <listitem><para>If enabled in
+ <citerefentry><refentrytitle>logind.conf</refentrytitle>
+ <manvolnum>5</manvolnum></citerefentry>, all processes of the
+ session are terminated. If the last concurrent session of a user
+ ends, the user's systemd instance will be terminated too, and so
+ will the user's slice unit.</para></listitem>
+
+ <listitem><para>If the last concurrent session of a user ends,
+ the <varname>$XDG_RUNTIME_DIR</varname> directory and all its
+ contents are removed, too.</para></listitem>
+ </orderedlist>
+
+ <para>If the system was not booted up with systemd as init system,
+ this module does nothing and immediately returns
+ <constant>PAM_SUCCESS</constant>.</para>
+
+ </refsect1>
+
+ <refsect1>
+ <title>Options</title>
+
+ <para>The following options are understood:</para>
+
+ <variablelist class='pam-directives'>
+
+ <varlistentry>
+ <term><option>class=</option></term>
+
+ <listitem><para>Takes a string argument which sets the session
+ class. The XDG_SESSION_CLASS environmental variable takes
+ precedence. One of
+ <literal>user</literal>,
+ <literal>greeter</literal>,
+ <literal>lock-screen</literal> or
+ <literal>background</literal>. See
+ <citerefentry><refentrytitle>sd_session_get_class</refentrytitle><manvolnum>3</manvolnum></citerefentry>
+ for details about the session class.</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><option>type=</option></term>
+
+ <listitem><para>Takes a string argument which sets the session
+ type. The XDG_SESSION_TYPE environmental variable takes
+ precedence. One of
+ <literal>unspecified</literal>,
+ <literal>tty</literal>,
+ <literal>x11</literal>,
+ <literal>wayland</literal> or
+ <literal>mir</literal>. See
+ <citerefentry><refentrytitle>sd_session_get_type</refentrytitle><manvolnum>3</manvolnum></citerefentry>
+ for details about the session type.</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><option>debug<optional>=</optional></option></term>
+
+ <listitem><para>Takes an optional
+ boolean argument. If yes or without
+ the argument, the module will log
+ debugging information as it
+ operates.</para></listitem>
+ </varlistentry>
+ </variablelist>
+ </refsect1>
+
+ <refsect1>
+ <title>Module Types Provided</title>
+
+ <para>Only <option>session</option> is provided.</para>
+ </refsect1>
+
+ <refsect1>
+ <title>Environment</title>
+
+ <para>The following environment variables are set for the
+ processes of the user's session:</para>
+
+ <variablelist class='environment-variables'>
+ <varlistentry>
+ <term><varname>$XDG_SESSION_ID</varname></term>
+
+ <listitem><para>A session identifier, suitable to be used in
+ filenames. The string itself should be considered opaque,
+ although often it is just the audit session ID as reported by
+ <filename>/proc/self/sessionid</filename>. Each ID will be
+ assigned only once during machine uptime. It may hence be used
+ to uniquely label files or other resources of this
+ session.</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><varname>$XDG_RUNTIME_DIR</varname></term>
+
+ <listitem><para>Path to a user-private user-writable directory
+ that is bound to the user login time on the machine. It is
+ automatically created the first time a user logs in and
+ removed on the user's final logout. If a user logs in twice at
+ the same time, both sessions will see the same
+ <varname>$XDG_RUNTIME_DIR</varname> and the same contents. If
+ a user logs in once, then logs out again, and logs in again,
+ the directory contents will have been lost in between, but
+ applications should not rely on this behavior and must be able
+ to deal with stale files. To store session-private data in
+ this directory, the user should include the value of
+ <varname>$XDG_SESSION_ID</varname> in the filename. This
+ directory shall be used for runtime file system objects such
+ as <constant>AF_UNIX</constant> sockets, FIFOs, PID files and
+ similar. It is guaranteed that this directory is local and
+ offers the greatest possible file system feature set the
+ operating system provides. For further details, see the <ulink
+ url="http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html">XDG
+ Base Directory Specification</ulink>.</para></listitem>
+ </varlistentry>
+
+ </variablelist>
+
+ <para>The following environment variables are read by the module
+ and may be used by the PAM service to pass metadata to the
+ module:</para>
+
+ <variablelist class='environment-variables'>
+ <varlistentry>
+ <term><varname>$XDG_SESSION_TYPE</varname></term>
+
+ <listitem><para>The session type. This may be used instead of
+ <option>session=</option> on the module parameter line, and is
+ usually preferred.</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><varname>$XDG_SESSION_CLASS</varname></term>
+
+ <listitem><para>The session class. This may be used instead of
+ <option>class=</option> on the module parameter line, and is
+ usually preferred.</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><varname>$XDG_SESSION_DESKTOP</varname></term>
+
+ <listitem><para>A single, short identifier string for the
+ desktop environment. This may be used to indicate the session
+ desktop used, where this applies and if this information is
+ available. For example: <literal>GNOME</literal>, or
+ <literal>KDE</literal>. It is recommended to use the same
+ identifiers and capitalization as for
+ <varname>$XDG_CURRENT_DESKTOP</varname>, as defined by the
+ <ulink
+ url="http://standards.freedesktop.org/desktop-entry-spec/latest/">Desktop
+ Entry Specification</ulink>. (However, note that
+ <varname>$XDG_SESSION_DESKTOP</varname> only takes a single
+ item, and not a colon-separated list like
+ <varname>$XDG_CURRENT_DESKTOP</varname>.) See
+ <citerefentry><refentrytitle>sd_session_get_desktop</refentrytitle><manvolnum>3</manvolnum></citerefentry>
+ for more details.</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><varname>$XDG_SEAT</varname></term>
+
+ <listitem><para>The seat name the session shall be registered
+ for, if any.</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><varname>$XDG_VTNR</varname></term>
+
+ <listitem><para>The VT number the session shall be registered
+ for, if any. (Only applies to seats with a VT available, such
+ as <literal>seat0</literal>)</para></listitem>
+ </varlistentry>
+
+ </variablelist>
+ </refsect1>
+
+ <refsect1>
+ <title>Example</title>
+
+ <programlisting>#%PAM-1.0
+auth required pam_unix.so
+auth required pam_nologin.so
+account required pam_unix.so
+password required pam_unix.so
+session required pam_unix.so
+session required pam_loginuid.so
+session required pam_systemd.so</programlisting>
+ </refsect1>
+
+ <refsect1>
+ <title>See Also</title>
+ <para>
+ <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>,
+ <citerefentry><refentrytitle>systemd-logind.service</refentrytitle><manvolnum>8</manvolnum></citerefentry>,
+ <citerefentry><refentrytitle>logind.conf</refentrytitle><manvolnum>5</manvolnum></citerefentry>,
+ <citerefentry><refentrytitle>loginctl</refentrytitle><manvolnum>1</manvolnum></citerefentry>,
+ <citerefentry project='man-pages'><refentrytitle>pam.conf</refentrytitle><manvolnum>5</manvolnum></citerefentry>,
+ <citerefentry project='man-pages'><refentrytitle>pam.d</refentrytitle><manvolnum>5</manvolnum></citerefentry>,
+ <citerefentry project='man-pages'><refentrytitle>pam</refentrytitle><manvolnum>8</manvolnum></citerefentry>,
+ <citerefentry project='man-pages'><refentrytitle>pam_loginuid</refentrytitle><manvolnum>8</manvolnum></citerefentry>,
+ <citerefentry><refentrytitle>systemd.scope</refentrytitle><manvolnum>5</manvolnum></citerefentry>,
+ <citerefentry><refentrytitle>systemd.slice</refentrytitle><manvolnum>5</manvolnum></citerefentry>,
+ <citerefentry><refentrytitle>systemd.service</refentrytitle><manvolnum>5</manvolnum></citerefentry>
+ </para>
+ </refsect1>
+
+</refentry>
diff --git a/src/grp-login/systemd-inhibit/Makefile b/src/grp-login/systemd-inhibit/Makefile
new file mode 100644
index 0000000000..8b3b7995d9
--- /dev/null
+++ b/src/grp-login/systemd-inhibit/Makefile
@@ -0,0 +1,37 @@
+# -*- Mode: makefile; indent-tabs-mode: t -*-
+#
+# This file is part of systemd.
+#
+# Copyright 2010-2012 Lennart Poettering
+# Copyright 2010-2012 Kay Sievers
+# Copyright 2013 Zbigniew Jędrzejewski-Szmek
+# Copyright 2013 David Strauss
+# Copyright 2016 Luke Shumaker
+#
+# 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 $(dir $(lastword $(MAKEFILE_LIST)))/../../../config.mk
+include $(topsrcdir)/build-aux/Makefile.head.mk
+
+dist_zshcompletion_data += shell-completion/zsh/_systemd-inhibit
+
+systemd_inhibit_SOURCES = \
+ src/login/inhibit.c
+
+systemd_inhibit_LDADD = \
+ libsystemd-shared.la
+
+rootbin_PROGRAMS += \
+ systemd-inhibit
+
+include $(topsrcdir)/build-aux/Makefile.tail.mk
diff --git a/src/grp-login/systemd-inhibit/inhibit.c b/src/grp-login/systemd-inhibit/inhibit.c
new file mode 100644
index 0000000000..543bdb9e80
--- /dev/null
+++ b/src/grp-login/systemd-inhibit/inhibit.c
@@ -0,0 +1,292 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ 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 <getopt.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+#include <systemd/sd-bus.h>
+
+#include "basic/alloc-util.h"
+#include "basic/fd-util.h"
+#include "basic/formats-util.h"
+#include "basic/process-util.h"
+#include "basic/signal-util.h"
+#include "basic/strv.h"
+#include "basic/user-util.h"
+#include "basic/util.h"
+#include "sd-bus/bus-error.h"
+#include "shared/bus-util.h"
+
+static const char* arg_what = "idle:sleep:shutdown";
+static const char* arg_who = NULL;
+static const char* arg_why = "Unknown reason";
+static const char* arg_mode = NULL;
+
+static enum {
+ ACTION_INHIBIT,
+ ACTION_LIST
+} arg_action = ACTION_INHIBIT;
+
+static int inhibit(sd_bus *bus, sd_bus_error *error) {
+ _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
+ int r;
+ int fd;
+
+ r = sd_bus_call_method(
+ bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "Inhibit",
+ error,
+ &reply,
+ "ssss", arg_what, arg_who, arg_why, arg_mode);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_message_read_basic(reply, SD_BUS_TYPE_UNIX_FD, &fd);
+ if (r < 0)
+ return r;
+
+ r = fcntl(fd, F_DUPFD_CLOEXEC, 3);
+ if (r < 0)
+ return -errno;
+
+ return r;
+}
+
+static int print_inhibitors(sd_bus *bus, sd_bus_error *error) {
+ _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
+ const char *what, *who, *why, *mode;
+ unsigned int uid, pid;
+ unsigned n = 0;
+ int r;
+
+ r = sd_bus_call_method(
+ bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "ListInhibitors",
+ error,
+ &reply,
+ "");
+ if (r < 0)
+ return r;
+
+ r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ssssuu)");
+ if (r < 0)
+ return bus_log_parse_error(r);
+
+ while ((r = sd_bus_message_read(reply, "(ssssuu)", &what, &who, &why, &mode, &uid, &pid)) > 0) {
+ _cleanup_free_ char *comm = NULL, *u = NULL;
+
+ if (arg_mode && !streq(mode, arg_mode))
+ continue;
+
+ get_process_comm(pid, &comm);
+ u = uid_to_name(uid);
+
+ printf(" Who: %s (UID "UID_FMT"/%s, PID "PID_FMT"/%s)\n"
+ " What: %s\n"
+ " Why: %s\n"
+ " Mode: %s\n\n",
+ who, uid, strna(u), pid, strna(comm),
+ what,
+ why,
+ mode);
+
+ n++;
+ }
+ if (r < 0)
+ return bus_log_parse_error(r);
+
+ r = sd_bus_message_exit_container(reply);
+ if (r < 0)
+ return bus_log_parse_error(r);
+
+ printf("%u inhibitors listed.\n", n);
+ return 0;
+}
+
+static void help(void) {
+ printf("%s [OPTIONS...] {COMMAND} ...\n\n"
+ "Execute a process while inhibiting shutdown/sleep/idle.\n\n"
+ " -h --help Show this help\n"
+ " --version Show package version\n"
+ " --what=WHAT Operations to inhibit, colon separated list of:\n"
+ " shutdown, sleep, idle, handle-power-key,\n"
+ " handle-suspend-key, handle-hibernate-key,\n"
+ " handle-lid-switch\n"
+ " --who=STRING A descriptive string who is inhibiting\n"
+ " --why=STRING A descriptive string why is being inhibited\n"
+ " --mode=MODE One of block or delay\n"
+ " --list List active inhibitors\n"
+ , program_invocation_short_name);
+}
+
+static int parse_argv(int argc, char *argv[]) {
+
+ enum {
+ ARG_VERSION = 0x100,
+ ARG_WHAT,
+ ARG_WHO,
+ ARG_WHY,
+ ARG_MODE,
+ ARG_LIST,
+ };
+
+ static const struct option options[] = {
+ { "help", no_argument, NULL, 'h' },
+ { "version", no_argument, NULL, ARG_VERSION },
+ { "what", required_argument, NULL, ARG_WHAT },
+ { "who", required_argument, NULL, ARG_WHO },
+ { "why", required_argument, NULL, ARG_WHY },
+ { "mode", required_argument, NULL, ARG_MODE },
+ { "list", no_argument, NULL, ARG_LIST },
+ {}
+ };
+
+ 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:
+ return version();
+
+ case ARG_WHAT:
+ arg_what = optarg;
+ break;
+
+ case ARG_WHO:
+ arg_who = optarg;
+ break;
+
+ case ARG_WHY:
+ arg_why = optarg;
+ break;
+
+ case ARG_MODE:
+ arg_mode = optarg;
+ break;
+
+ case ARG_LIST:
+ arg_action = ACTION_LIST;
+ break;
+
+ case '?':
+ return -EINVAL;
+
+ default:
+ assert_not_reached("Unhandled option");
+ }
+
+ if (arg_action == ACTION_INHIBIT && optind == argc)
+ arg_action = ACTION_LIST;
+
+ else if (arg_action == ACTION_INHIBIT && optind >= argc) {
+ log_error("Missing command line to execute.");
+ return -EINVAL;
+ }
+
+ return 1;
+}
+
+int main(int argc, char *argv[]) {
+ _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+ _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
+ int r;
+
+ log_parse_environment();
+ log_open();
+
+ r = parse_argv(argc, argv);
+ if (r < 0)
+ return EXIT_FAILURE;
+ if (r == 0)
+ return EXIT_SUCCESS;
+
+ r = sd_bus_default_system(&bus);
+ if (r < 0) {
+ log_error_errno(r, "Failed to connect to bus: %m");
+ return EXIT_FAILURE;
+ }
+
+ if (arg_action == ACTION_LIST) {
+
+ r = print_inhibitors(bus, &error);
+ if (r < 0) {
+ log_error("Failed to list inhibitors: %s", bus_error_message(&error, -r));
+ return EXIT_FAILURE;
+ }
+
+ } else {
+ _cleanup_close_ int fd = -1;
+ _cleanup_free_ char *w = NULL;
+ pid_t pid;
+
+ if (!arg_who)
+ arg_who = w = strv_join(argv + optind, " ");
+
+ if (!arg_mode)
+ arg_mode = "block";
+
+ fd = inhibit(bus, &error);
+ if (fd < 0) {
+ log_error("Failed to inhibit: %s", bus_error_message(&error, fd));
+ return EXIT_FAILURE;
+ }
+
+ pid = fork();
+ if (pid < 0) {
+ log_error_errno(errno, "Failed to fork: %m");
+ return EXIT_FAILURE;
+ }
+
+ if (pid == 0) {
+ /* Child */
+
+ (void) reset_all_signal_handlers();
+ (void) reset_signal_mask();
+
+ close_all_fds(NULL, 0);
+
+ execvp(argv[optind], argv + optind);
+ log_error_errno(errno, "Failed to execute %s: %m", argv[optind]);
+ _exit(EXIT_FAILURE);
+ }
+
+ r = wait_for_terminate_and_warn(argv[optind], pid, true);
+ return r < 0 ? EXIT_FAILURE : r;
+ }
+
+ return 0;
+}
diff --git a/src/grp-login/systemd-inhibit/systemd-inhibit.completion.zsh b/src/grp-login/systemd-inhibit/systemd-inhibit.completion.zsh
new file mode 100644
index 0000000000..1b3247b2cd
--- /dev/null
+++ b/src/grp-login/systemd-inhibit/systemd-inhibit.completion.zsh
@@ -0,0 +1,33 @@
+#compdef systemd-inhibit
+
+_systemd_inhibit_command(){
+ if (( CURRENT == 1 )); then
+ compset -q
+ _normal
+ else
+ local n=${words[(b:2:i)[^-]*]}
+ if (( n <= CURRENT )); then
+ compset -n $n
+ _alternative \
+ 'files:file:_files' \
+ 'commands:command:_normal' && return 0
+ fi
+ _default
+ fi
+}
+
+_inhibit_what() {
+ local _inhibit
+ _inhibit=(shutdown sleep idle handle-power-key handle-suspend-key handle-hibernate-key handle-lid-switch)
+ _values -s : "${_inhibit[@]}"
+}
+
+_arguments \
+ {-h,--help}'[Show this help]' \
+ '--version[Show package version]' \
+ '--what=[Operations to inhibit]:options:_inhibit_what' \
+ '--who=[A descriptive string who is inhibiting]:who is inhibiting:' \
+ '--why=[A descriptive string why is being inhibited]:reason for the lock:' \
+ '--mode=[One of block or delay]:lock mode:( block delay )' \
+ '--list[List active inhibitors]' \
+ '*:commands:_systemd_inhibit_command'
diff --git a/src/grp-login/systemd-inhibit/systemd-inhibit.xml b/src/grp-login/systemd-inhibit/systemd-inhibit.xml
new file mode 100644
index 0000000000..9d85908f97
--- /dev/null
+++ b/src/grp-login/systemd-inhibit/systemd-inhibit.xml
@@ -0,0 +1,177 @@
+<?xml version='1.0'?> <!--*-nxml-*-->
+<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN"
+ "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd">
+
+<!--
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ 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/>.
+-->
+
+<refentry id="systemd-inhibit"
+ xmlns:xi="http://www.w3.org/2001/XInclude">
+
+ <refentryinfo>
+ <title>systemd-inhibit</title>
+ <productname>systemd</productname>
+
+ <authorgroup>
+ <author>
+ <contrib>Developer</contrib>
+ <firstname>Lennart</firstname>
+ <surname>Poettering</surname>
+ <email>lennart@poettering.net</email>
+ </author>
+ </authorgroup>
+ </refentryinfo>
+
+ <refmeta>
+ <refentrytitle>systemd-inhibit</refentrytitle>
+ <manvolnum>1</manvolnum>
+ </refmeta>
+
+ <refnamediv>
+ <refname>systemd-inhibit</refname>
+ <refpurpose>Execute a program with an inhibition lock taken</refpurpose>
+ </refnamediv>
+
+ <refsynopsisdiv>
+ <cmdsynopsis>
+ <command>systemd-inhibit <arg choice="opt" rep="repeat">OPTIONS</arg> <arg>COMMAND</arg> <arg choice="opt" rep="repeat">ARGUMENTS</arg></command>
+ </cmdsynopsis>
+ <cmdsynopsis>
+ <command>systemd-inhibit <arg choice="opt" rep="repeat">OPTIONS</arg> --list</command>
+ </cmdsynopsis>
+ </refsynopsisdiv>
+
+ <refsect1>
+ <title>Description</title>
+
+ <para><command>systemd-inhibit</command> may be used to execute a
+ program with a shutdown, sleep or idle inhibitor lock taken. The
+ lock will be acquired before the specified command line is
+ executed and released afterwards.</para>
+
+ <para>Inhibitor locks may be used to block or delay system sleep
+ and shutdown requests from the user, as well as automatic idle
+ handling of the OS. This is useful to avoid system suspends while
+ an optical disc is being recorded, or similar operations that
+ should not be interrupted.</para>
+
+ <para>For more information see the <ulink
+ url="http://www.freedesktop.org/wiki/Software/systemd/inhibit">Inhibitor
+ Lock Developer Documentation</ulink>.</para>
+ </refsect1>
+
+ <refsect1>
+ <title>Options</title>
+
+ <para>The following options are understood:</para>
+
+ <variablelist>
+ <varlistentry>
+ <term><option>--what=</option></term>
+
+ <listitem><para>Takes a colon-separated list of one or more
+ operations to inhibit:
+ <literal>shutdown</literal>,
+ <literal>sleep</literal>,
+ <literal>idle</literal>,
+ <literal>handle-power-key</literal>,
+ <literal>handle-suspend-key</literal>,
+ <literal>handle-hibernate-key</literal>,
+ <literal>handle-lid-switch</literal>,
+ for inhibiting reboot/power-off/halt/kexec,
+ suspending/hibernating, the automatic idle detection, or the
+ low-level handling of the power/sleep key and the lid switch,
+ respectively. If omitted, defaults to
+ <literal>idle:sleep:shutdown</literal>.</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><option>--who=</option></term>
+
+ <listitem><para>Takes a short, human-readable descriptive
+ string for the program taking the lock. If not passed,
+ defaults to the command line string.</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><option>--why=</option></term>
+
+ <listitem><para>Takes a short, human-readable descriptive
+ string for the reason for taking the lock. Defaults to
+ "Unknown reason".</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><option>--mode=</option></term>
+
+ <listitem><para>Takes either <literal>block</literal> or
+ <literal>delay</literal> and describes how the lock is
+ applied. If <literal>block</literal> is used (the default),
+ the lock prohibits any of the requested operations without
+ time limit, and only privileged users may override it. If
+ <literal>delay</literal> is used, the lock can only delay the
+ requested operations for a limited time. If the time elapses,
+ the lock is ignored and the operation executed. The time limit
+ may be specified in
+ <citerefentry><refentrytitle>logind.conf</refentrytitle><manvolnum>5</manvolnum></citerefentry>.
+ Note that <literal>delay</literal> is only available for
+ <literal>sleep</literal> and
+ <literal>shutdown</literal>.</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><option>--list</option></term>
+
+ <listitem><para>Lists all active inhibition locks instead of
+ acquiring one.</para></listitem>
+ </varlistentry>
+
+ <xi:include href="standard-options.xml" xpointer="help" />
+ <xi:include href="standard-options.xml" xpointer="version" />
+ </variablelist>
+
+ </refsect1>
+
+ <refsect1>
+ <title>Exit status</title>
+
+ <para>Returns the exit status of the executed program.</para>
+ </refsect1>
+
+ <refsect1>
+ <title>Example</title>
+
+ <programlisting># systemd-inhibit wodim foobar.iso</programlisting>
+
+ <para>This burns the ISO image
+ <filename>foobar.iso</filename> on a CD using
+ <citerefentry project='man-pages'><refentrytitle>wodim</refentrytitle><manvolnum>1</manvolnum></citerefentry>,
+ and inhibits system sleeping, shutdown and idle while
+ doing so.</para>
+ </refsect1>
+
+ <refsect1>
+ <title>See Also</title>
+ <para>
+ <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>,
+ <citerefentry><refentrytitle>logind.conf</refentrytitle><manvolnum>5</manvolnum></citerefentry>
+ </para>
+ </refsect1>
+
+</refentry>
diff --git a/src/grp-login/systemd-logind/70-power-switch.rules b/src/grp-login/systemd-logind/70-power-switch.rules
new file mode 100644
index 0000000000..e2855b50f7
--- /dev/null
+++ b/src/grp-login/systemd-logind/70-power-switch.rules
@@ -0,0 +1,18 @@
+# This file is part of systemd.
+#
+# 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.
+
+ACTION=="remove", GOTO="power_switch_end"
+
+SUBSYSTEM=="input", KERNEL=="event*", SUBSYSTEMS=="acpi", TAG+="power-switch"
+SUBSYSTEM=="input", KERNEL=="event*", KERNELS=="thinkpad_acpi", TAG+="power-switch"
+SUBSYSTEM=="input", KERNEL=="event*", ATTRS{name}=="twl4030_pwrbutton", TAG+="power-switch"
+SUBSYSTEM=="input", KERNEL=="event*", ATTRS{name}=="tps65217_pwr_but", TAG+="power-switch"
+SUBSYSTEM=="input", KERNEL=="event*", ATTRS{name}=="* WMI hotkeys", TAG+="power-switch"
+SUBSYSTEM=="input", KERNEL=="event*", \
+ SUBSYSTEMS=="platform", DRIVERS=="gpio-keys", ATTRS{keys}=="*,116|116,*|116|*,116,*", TAG+="power-switch"
+
+LABEL="power_switch_end"
diff --git a/src/grp-login/systemd-logind/70-uaccess.rules b/src/grp-login/systemd-logind/70-uaccess.rules
new file mode 100644
index 0000000000..50dcd2e275
--- /dev/null
+++ b/src/grp-login/systemd-logind/70-uaccess.rules
@@ -0,0 +1,81 @@
+# This file is part of systemd.
+#
+# 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.
+
+ACTION=="remove", GOTO="uaccess_end"
+ENV{MAJOR}=="", GOTO="uaccess_end"
+
+# PTP/MTP protocol devices, cameras, portable media players
+SUBSYSTEM=="usb", ENV{ID_USB_INTERFACES}=="*:060101:*", TAG+="uaccess"
+
+# Digicams with proprietary protocol
+ENV{ID_GPHOTO2}=="?*", TAG+="uaccess"
+
+# SCSI and USB scanners
+ENV{libsane_matched}=="yes", TAG+="uaccess"
+
+# HPLIP devices (necessary for ink level check and HP tool maintenance)
+ENV{ID_HPLIP}=="1", TAG+="uaccess"
+
+# optical drives
+SUBSYSTEM=="block", ENV{ID_CDROM}=="1", TAG+="uaccess"
+SUBSYSTEM=="scsi_generic", SUBSYSTEMS=="scsi", ATTRS{type}=="4|5", TAG+="uaccess"
+
+# Sound devices
+SUBSYSTEM=="sound", TAG+="uaccess" \
+ OPTIONS+="static_node=snd/timer", OPTIONS+="static_node=snd/seq"
+
+# ffado is an userspace driver for firewire sound cards
+SUBSYSTEM=="firewire", ENV{ID_FFADO}=="1", TAG+="uaccess"
+
+# Webcams, frame grabber, TV cards
+SUBSYSTEM=="video4linux", TAG+="uaccess"
+SUBSYSTEM=="dvb", TAG+="uaccess"
+
+# IIDC devices: industrial cameras and some webcams
+SUBSYSTEM=="firewire", ATTR{units}=="*0x00a02d:0x00010*", TAG+="uaccess"
+SUBSYSTEM=="firewire", ATTR{units}=="*0x00b09d:0x00010*", TAG+="uaccess"
+# AV/C devices: camcorders, set-top boxes, TV sets, audio devices, and more
+SUBSYSTEM=="firewire", ATTR{units}=="*0x00a02d:0x010001*", TAG+="uaccess"
+SUBSYSTEM=="firewire", ATTR{units}=="*0x00a02d:0x014001*", TAG+="uaccess"
+
+# DRI video devices
+SUBSYSTEM=="drm", KERNEL=="card*|renderD*", TAG+="uaccess"
+
+# KVM
+SUBSYSTEM=="misc", KERNEL=="kvm", TAG+="uaccess"
+
+# smart-card readers
+ENV{ID_SMARTCARD_READER}=="?*", TAG+="uaccess"
+
+# (USB) authentication devices
+ENV{ID_SECURITY_TOKEN}=="?*", TAG+="uaccess"
+
+# PDA devices
+ENV{ID_PDA}=="?*", TAG+="uaccess"
+
+# Programmable remote control
+ENV{ID_REMOTE_CONTROL}=="1", TAG+="uaccess"
+
+# joysticks
+SUBSYSTEM=="input", ENV{ID_INPUT_JOYSTICK}=="?*", TAG+="uaccess"
+
+# color measurement devices
+ENV{COLOR_MEASUREMENT_DEVICE}=="?*", TAG+="uaccess"
+
+# DDC/CI device, usually high-end monitors such as the DreamColor
+ENV{DDC_DEVICE}=="?*", TAG+="uaccess"
+
+# media player raw devices (for user-mode drivers, Android SDK, etc.)
+SUBSYSTEM=="usb", ENV{ID_MEDIA_PLAYER}=="?*", TAG+="uaccess"
+
+# software-defined radio communication devices
+ENV{ID_SOFTWARE_RADIO}=="?*", TAG+="uaccess"
+
+# 3D printers, CNC machines, laser cutters, 3D scanners, etc.
+ENV{ID_MAKER_TOOL}=="?*", TAG+="uaccess"
+
+LABEL="uaccess_end"
diff --git a/src/grp-login/systemd-logind/71-seat.rules.in b/src/grp-login/systemd-logind/71-seat.rules.in
new file mode 100644
index 0000000000..de55c9a4ec
--- /dev/null
+++ b/src/grp-login/systemd-logind/71-seat.rules.in
@@ -0,0 +1,54 @@
+# This file is part of systemd.
+#
+# 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.
+
+ACTION=="remove", GOTO="seat_end"
+
+TAG=="uaccess", SUBSYSTEM!="sound", TAG+="seat"
+SUBSYSTEM=="sound", KERNEL=="card*", TAG+="seat"
+SUBSYSTEM=="input", KERNEL=="input*", TAG+="seat"
+SUBSYSTEM=="graphics", KERNEL=="fb[0-9]*", TAG+="seat", TAG+="master-of-seat"
+SUBSYSTEM=="drm", KERNEL=="card[0-9]*", TAG+="seat", TAG+="master-of-seat"
+SUBSYSTEM=="usb", ATTR{bDeviceClass}=="09", TAG+="seat"
+
+# 'Plugable' USB hub, sound, network, graphics adapter
+SUBSYSTEM=="usb", ATTR{idVendor}=="2230", ATTR{idProduct}=="000[13]", ENV{ID_AUTOSEAT}="1"
+
+# qemu (version 2.4+) has a PCI-PCI bridge (-device pci-bridge-seat) to group
+# devices belonging to one seat. See:
+# http://git.qemu.org/?p=qemu.git;a=blob;f=docs/multiseat.txt
+SUBSYSTEM=="pci", ATTR{vendor}=="0x1b36", ATTR{device}=="0x000a", TAG+="seat", ENV{ID_AUTOSEAT}="1"
+
+# Mimo 720, with integrated USB hub, displaylink graphics, and e2i
+# touchscreen. This device carries no proper VID/PID in the USB hub,
+# but it does carry good ID data in the graphics component, hence we
+# check it from the parent. There's a bit of a race here however,
+# given that the child devices might not exist yet at the time this
+# rule is executed. To work around this we'll trigger the parent from
+# the child if we notice that the parent wasn't recognized yet.
+
+# Match parent
+SUBSYSTEM=="usb", ATTR{idVendor}=="058f", ATTR{idProduct}=="6254", \
+ ATTR{%k.2/idVendor}=="17e9", ATTR{%k.2/idProduct}=="401a", ATTR{%k.2/product}=="mimo inc", \
+ ENV{ID_AUTOSEAT}="1", ENV{ID_AVOID_LOOP}="1"
+
+# Match child, look for parent's ID_AVOID_LOOP
+SUBSYSTEM=="usb", ATTR{idVendor}=="17e9", ATTR{idProduct}=="401a", ATTR{product}=="mimo inc", \
+ ATTR{../idVendor}=="058f", ATTR{../idProduct}=="6254", \
+ IMPORT{parent}="ID_AVOID_LOOP"
+
+# Match child, retrigger parent
+SUBSYSTEM=="usb", ATTR{idVendor}=="17e9", ATTR{idProduct}=="401a", ATTR{product}=="mimo inc", \
+ ATTR{../idVendor}=="058f", ATTR{../idProduct}=="6254", \
+ ENV{ID_AVOID_LOOP}=="", \
+ RUN+="@rootbindir@/udevadm trigger --parent-match=%p/.."
+
+TAG=="seat", ENV{ID_PATH}=="", IMPORT{builtin}="path_id"
+TAG=="seat", ENV{ID_FOR_SEAT}=="", ENV{ID_PATH_TAG}!="", ENV{ID_FOR_SEAT}="$env{SUBSYSTEM}-$env{ID_PATH_TAG}"
+
+SUBSYSTEM=="input", ATTR{name}=="Wiebetech LLC Wiebetech", RUN+="@rootbindir@/loginctl lock-sessions"
+
+LABEL="seat_end"
diff --git a/src/grp-login/systemd-logind/73-seat-late.rules.in b/src/grp-login/systemd-logind/73-seat-late.rules.in
new file mode 100644
index 0000000000..901df750fd
--- /dev/null
+++ b/src/grp-login/systemd-logind/73-seat-late.rules.in
@@ -0,0 +1,17 @@
+# This file is part of systemd.
+#
+# 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.
+
+ACTION=="remove", GOTO="seat_late_end"
+
+ENV{ID_SEAT}=="", ENV{ID_AUTOSEAT}=="1", ENV{ID_FOR_SEAT}!="", ENV{ID_SEAT}="seat-$env{ID_FOR_SEAT}"
+ENV{ID_SEAT}=="", IMPORT{parent}="ID_SEAT"
+
+ENV{ID_SEAT}!="", TAG+="$env{ID_SEAT}"
+
+TAG=="uaccess", ENV{MAJOR}!="", RUN{builtin}+="uaccess"
+
+LABEL="seat_late_end"
diff --git a/src/grp-login/systemd-logind/Makefile b/src/grp-login/systemd-logind/Makefile
new file mode 100644
index 0000000000..24de945818
--- /dev/null
+++ b/src/grp-login/systemd-logind/Makefile
@@ -0,0 +1,132 @@
+# -*- Mode: makefile; indent-tabs-mode: t -*-
+#
+# This file is part of systemd.
+#
+# Copyright 2010-2012 Lennart Poettering
+# Copyright 2010-2012 Kay Sievers
+# Copyright 2013 Zbigniew Jędrzejewski-Szmek
+# Copyright 2013 David Strauss
+# Copyright 2016 Luke Shumaker
+#
+# 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 $(dir $(lastword $(MAKEFILE_LIST)))/../../../config.mk
+include $(topsrcdir)/build-aux/Makefile.head.mk
+
+ifneq ($(ENABLE_LOGIND),)
+
+systemd_logind_SOURCES = \
+ src/login/logind.c \
+ src/login/logind.h
+
+nodist_systemd_logind_SOURCES = \
+ src/login/logind-gperf.c
+
+systemd_logind_LDADD = \
+ liblogind-core.la
+
+liblogind_core_la_SOURCES = \
+ src/login/logind-core.c \
+ src/login/logind-device.c \
+ src/login/logind-device.h \
+ src/login/logind-button.c \
+ src/login/logind-button.h \
+ src/login/logind-action.c \
+ src/login/logind-action.h \
+ src/login/logind-seat.c \
+ src/login/logind-seat.h \
+ src/login/logind-session.c \
+ src/login/logind-session.h \
+ src/login/logind-session-device.c \
+ src/login/logind-session-device.h \
+ src/login/logind-user.c \
+ src/login/logind-user.h \
+ src/login/logind-inhibit.c \
+ src/login/logind-inhibit.h \
+ src/login/logind-dbus.c \
+ src/login/logind-session-dbus.c \
+ src/login/logind-seat-dbus.c \
+ src/login/logind-user-dbus.c \
+ src/login/logind-utmp.c \
+ src/login/logind-acl.h
+
+liblogind_core_la_LIBADD = \
+ libsystemd-shared.la
+
+ifneq ($(HAVE_ACL),)
+liblogind_core_la_SOURCES += \
+ src/login/logind-acl.c
+endif # HAVE_ACL
+
+noinst_LTLIBRARIES += \
+ liblogind-core.la
+
+rootlibexec_PROGRAMS += \
+ systemd-logind
+
+nodist_systemunit_DATA += \
+ units/systemd-logind.service
+
+dist_systemunit_DATA += \
+ units/user.slice
+
+dist_systemunit_DATA_busnames += \
+ units/org.freedesktop.login1.busname
+
+dist_dbussystemservice_DATA += \
+ src/login/org.freedesktop.login1.service
+
+dist_dbuspolicy_DATA += \
+ src/login/org.freedesktop.login1.conf
+
+nodist_pkgsysconf_DATA += \
+ src/login/logind.conf
+
+polkitpolicy_files += \
+ src/login/org.freedesktop.login1.policy
+
+INSTALL_DIRS += \
+ $(systemdstatedir)
+
+MULTI_USER_TARGET_WANTS += \
+ systemd-logind.service
+
+SYSTEM_UNIT_ALIASES += \
+ systemd-logind.service dbus-org.freedesktop.login1.service
+
+BUSNAMES_TARGET_WANTS += \
+ org.freedesktop.login1.busname
+
+dist_udevrules_DATA += \
+ src/login/70-uaccess.rules \
+ src/login/70-power-switch.rules
+
+nodist_udevrules_DATA += \
+ src/login/71-seat.rules \
+ src/login/73-seat-late.rules
+
+endif # ENABLE_LOGIND
+
+polkitpolicy_in_files += \
+ src/login/org.freedesktop.login1.policy.in
+
+gperf_gperf_sources += \
+ src/login/logind-gperf.gperf
+
+EXTRA_DIST += \
+ src/login/71-seat.rules.in \
+ src/login/73-seat-late.rules.in \
+ units/systemd-logind.service.in \
+ src/login/logind.conf.in
+
+include $(topsrcdir)/build-aux/Makefile.tail.mk
diff --git a/src/grp-login/systemd-logind/logind-acl.c b/src/grp-login/systemd-logind/logind-acl.c
new file mode 100644
index 0000000000..44e49c1dad
--- /dev/null
+++ b/src/grp-login/systemd-logind/logind-acl.c
@@ -0,0 +1,293 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ 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 <errno.h>
+#include <string.h>
+
+#include "basic/alloc-util.h"
+#include "basic/dirent-util.h"
+#include "basic/escape.h"
+#include "basic/fd-util.h"
+#include "basic/formats-util.h"
+#include "basic/set.h"
+#include "basic/string-util.h"
+#include "basic/util.h"
+#include "shared/acl-util.h"
+#include "shared/udev-util.h"
+
+#include "logind-acl.h"
+
+static int flush_acl(acl_t acl) {
+ acl_entry_t i;
+ int found;
+ bool changed = false;
+
+ assert(acl);
+
+ for (found = acl_get_entry(acl, ACL_FIRST_ENTRY, &i);
+ found > 0;
+ found = acl_get_entry(acl, ACL_NEXT_ENTRY, &i)) {
+
+ acl_tag_t tag;
+
+ if (acl_get_tag_type(i, &tag) < 0)
+ return -errno;
+
+ if (tag != ACL_USER)
+ continue;
+
+ if (acl_delete_entry(acl, i) < 0)
+ return -errno;
+
+ changed = true;
+ }
+
+ if (found < 0)
+ return -errno;
+
+ return changed;
+}
+
+int devnode_acl(const char *path,
+ bool flush,
+ bool del, uid_t old_uid,
+ bool add, uid_t new_uid) {
+
+ acl_t acl;
+ int r = 0;
+ bool changed = false;
+
+ assert(path);
+
+ acl = acl_get_file(path, ACL_TYPE_ACCESS);
+ if (!acl)
+ return -errno;
+
+ if (flush) {
+
+ r = flush_acl(acl);
+ if (r < 0)
+ goto finish;
+ if (r > 0)
+ changed = true;
+
+ } else if (del && old_uid > 0) {
+ acl_entry_t entry;
+
+ r = acl_find_uid(acl, old_uid, &entry);
+ if (r < 0)
+ goto finish;
+
+ if (r > 0) {
+ if (acl_delete_entry(acl, entry) < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ changed = true;
+ }
+ }
+
+ if (add && new_uid > 0) {
+ acl_entry_t entry;
+ acl_permset_t permset;
+ int rd, wt;
+
+ r = acl_find_uid(acl, new_uid, &entry);
+ if (r < 0)
+ goto finish;
+
+ if (r == 0) {
+ if (acl_create_entry(&acl, &entry) < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ if (acl_set_tag_type(entry, ACL_USER) < 0 ||
+ acl_set_qualifier(entry, &new_uid) < 0) {
+ r = -errno;
+ goto finish;
+ }
+ }
+
+ if (acl_get_permset(entry, &permset) < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ rd = acl_get_perm(permset, ACL_READ);
+ if (rd < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ wt = acl_get_perm(permset, ACL_WRITE);
+ if (wt < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ if (!rd || !wt) {
+
+ if (acl_add_perm(permset, ACL_READ|ACL_WRITE) < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ changed = true;
+ }
+ }
+
+ if (!changed)
+ goto finish;
+
+ if (acl_calc_mask(&acl) < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ if (acl_set_file(path, ACL_TYPE_ACCESS, acl) < 0) {
+ r = -errno;
+ goto finish;
+ }
+
+ r = 0;
+
+finish:
+ acl_free(acl);
+
+ return r;
+}
+
+int devnode_acl_all(struct udev *udev,
+ const char *seat,
+ bool flush,
+ bool del, uid_t old_uid,
+ bool add, uid_t new_uid) {
+
+ _cleanup_udev_enumerate_unref_ struct udev_enumerate *e = NULL;
+ struct udev_list_entry *item = NULL, *first = NULL;
+ _cleanup_set_free_free_ Set *nodes = NULL;
+ _cleanup_closedir_ DIR *dir = NULL;
+ struct dirent *dent;
+ Iterator i;
+ char *n;
+ int r;
+
+ assert(udev);
+
+ nodes = set_new(&string_hash_ops);
+ if (!nodes)
+ return -ENOMEM;
+
+ e = udev_enumerate_new(udev);
+ if (!e)
+ return -ENOMEM;
+
+ if (isempty(seat))
+ seat = "seat0";
+
+ /* We can only match by one tag in libudev. We choose
+ * "uaccess" for that. If we could match for two tags here we
+ * could add the seat name as second match tag, but this would
+ * be hardly optimizable in libudev, and hence checking the
+ * second tag manually in our loop is a good solution. */
+ r = udev_enumerate_add_match_tag(e, "uaccess");
+ if (r < 0)
+ return r;
+
+ r = udev_enumerate_add_match_is_initialized(e);
+ if (r < 0)
+ return r;
+
+ r = udev_enumerate_scan_devices(e);
+ if (r < 0)
+ return r;
+
+ first = udev_enumerate_get_list_entry(e);
+ udev_list_entry_foreach(item, first) {
+ _cleanup_udev_device_unref_ struct udev_device *d = NULL;
+ const char *node, *sn;
+
+ d = udev_device_new_from_syspath(udev, udev_list_entry_get_name(item));
+ if (!d)
+ return -ENOMEM;
+
+ sn = udev_device_get_property_value(d, "ID_SEAT");
+ if (isempty(sn))
+ sn = "seat0";
+
+ if (!streq(seat, sn))
+ continue;
+
+ node = udev_device_get_devnode(d);
+ /* In case people mistag devices with nodes, we need to ignore this */
+ if (!node)
+ continue;
+
+ n = strdup(node);
+ if (!n)
+ return -ENOMEM;
+
+ log_debug("Found udev node %s for seat %s", n, seat);
+ r = set_consume(nodes, n);
+ if (r < 0)
+ return r;
+ }
+
+ /* udev exports "dead" device nodes to allow module on-demand loading,
+ * these devices are not known to the kernel at this moment */
+ dir = opendir("/run/udev/static_node-tags/uaccess");
+ if (dir) {
+ FOREACH_DIRENT(dent, dir, return -errno) {
+ _cleanup_free_ char *unescaped_devname = NULL;
+
+ if (cunescape(dent->d_name, UNESCAPE_RELAX, &unescaped_devname) < 0)
+ return -ENOMEM;
+
+ n = strappend("/dev/", unescaped_devname);
+ if (!n)
+ return -ENOMEM;
+
+ log_debug("Found static node %s for seat %s", n, seat);
+ r = set_consume(nodes, n);
+ if (r == -EEXIST)
+ continue;
+ if (r < 0)
+ return r;
+ }
+ }
+
+ r = 0;
+ SET_FOREACH(n, nodes, i) {
+ int k;
+
+ log_debug("Changing ACLs at %s for seat %s (uid "UID_FMT"→"UID_FMT"%s%s)",
+ n, seat, old_uid, new_uid,
+ del ? " del" : "", add ? " add" : "");
+
+ k = devnode_acl(n, flush, del, old_uid, add, new_uid);
+ if (k == -ENOENT)
+ log_debug("Device %s disappeared while setting ACLs", n);
+ else if (k < 0 && r == 0)
+ r = k;
+ }
+
+ return r;
+}
diff --git a/src/grp-login/systemd-logind/logind-acl.h b/src/grp-login/systemd-logind/logind-acl.h
new file mode 100644
index 0000000000..7d324ea90a
--- /dev/null
+++ b/src/grp-login/systemd-logind/logind-acl.h
@@ -0,0 +1,56 @@
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ 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 <stdbool.h>
+#include <sys/types.h>
+
+#include <libudev.h>
+
+#ifdef HAVE_ACL
+
+int devnode_acl(const char *path,
+ bool flush,
+ bool del, uid_t old_uid,
+ bool add, uid_t new_uid);
+
+int devnode_acl_all(struct udev *udev,
+ const char *seat,
+ bool flush,
+ bool del, uid_t old_uid,
+ bool add, uid_t new_uid);
+#else
+
+static inline int devnode_acl(const char *path,
+ bool flush,
+ bool del, uid_t old_uid,
+ bool add, uid_t new_uid) {
+ return 0;
+}
+
+static inline int devnode_acl_all(struct udev *udev,
+ const char *seat,
+ bool flush,
+ bool del, uid_t old_uid,
+ bool add, uid_t new_uid) {
+ return 0;
+}
+
+#endif
diff --git a/src/grp-login/systemd-logind/logind-action.c b/src/grp-login/systemd-logind/logind-action.c
new file mode 100644
index 0000000000..a7c88e7e65
--- /dev/null
+++ b/src/grp-login/systemd-logind/logind-action.c
@@ -0,0 +1,179 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ 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 <unistd.h>
+
+#include "basic/alloc-util.h"
+#include "basic/formats-util.h"
+#include "basic/process-util.h"
+#include "basic/special.h"
+#include "basic/string-table.h"
+#include "basic/terminal-util.h"
+#include "basic/user-util.h"
+#include "sd-bus/bus-error.h"
+#include "shared/bus-util.h"
+#include "shared/conf-parser.h"
+#include "shared/sleep-config.h"
+
+#include "logind-action.h"
+
+int manager_handle_action(
+ Manager *m,
+ InhibitWhat inhibit_key,
+ HandleAction handle,
+ bool ignore_inhibited,
+ bool is_edge) {
+
+ static const char * const message_table[_HANDLE_ACTION_MAX] = {
+ [HANDLE_POWEROFF] = "Powering Off...",
+ [HANDLE_REBOOT] = "Rebooting...",
+ [HANDLE_HALT] = "Halting...",
+ [HANDLE_KEXEC] = "Rebooting via kexec...",
+ [HANDLE_SUSPEND] = "Suspending...",
+ [HANDLE_HIBERNATE] = "Hibernating...",
+ [HANDLE_HYBRID_SLEEP] = "Hibernating and suspending..."
+ };
+
+ static const char * const target_table[_HANDLE_ACTION_MAX] = {
+ [HANDLE_POWEROFF] = SPECIAL_POWEROFF_TARGET,
+ [HANDLE_REBOOT] = SPECIAL_REBOOT_TARGET,
+ [HANDLE_HALT] = SPECIAL_HALT_TARGET,
+ [HANDLE_KEXEC] = SPECIAL_KEXEC_TARGET,
+ [HANDLE_SUSPEND] = SPECIAL_SUSPEND_TARGET,
+ [HANDLE_HIBERNATE] = SPECIAL_HIBERNATE_TARGET,
+ [HANDLE_HYBRID_SLEEP] = SPECIAL_HYBRID_SLEEP_TARGET
+ };
+
+ _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+ InhibitWhat inhibit_operation;
+ Inhibitor *offending = NULL;
+ bool supported;
+ int r;
+
+ assert(m);
+
+ /* If the key handling is turned off, don't do anything */
+ if (handle == HANDLE_IGNORE) {
+ log_debug("Refusing operation, as it is turned off.");
+ return 0;
+ }
+
+ if (inhibit_key == INHIBIT_HANDLE_LID_SWITCH) {
+ /* If the last system suspend or startup is too close,
+ * let's not suspend for now, to give USB docking
+ * stations some time to settle so that we can
+ * properly watch its displays. */
+ if (m->lid_switch_ignore_event_source) {
+ log_debug("Ignoring lid switch request, system startup or resume too close.");
+ return 0;
+ }
+ }
+
+ /* If the key handling is inhibited, don't do anything */
+ if (!ignore_inhibited && inhibit_key > 0) {
+ if (manager_is_inhibited(m, inhibit_key, INHIBIT_BLOCK, NULL, true, false, 0, NULL)) {
+ log_debug("Refusing operation, %s is inhibited.", inhibit_what_to_string(inhibit_key));
+ return 0;
+ }
+ }
+
+ /* Locking is handled differently from the rest. */
+ if (handle == HANDLE_LOCK) {
+
+ if (!is_edge)
+ return 0;
+
+ log_info("Locking sessions...");
+ session_send_lock_all(m, true);
+ return 1;
+ }
+
+ if (handle == HANDLE_SUSPEND)
+ supported = can_sleep("suspend") > 0;
+ else if (handle == HANDLE_HIBERNATE)
+ supported = can_sleep("hibernate") > 0;
+ else if (handle == HANDLE_HYBRID_SLEEP)
+ supported = can_sleep("hybrid-sleep") > 0;
+ else if (handle == HANDLE_KEXEC)
+ supported = access(KEXEC, X_OK) >= 0;
+ else
+ supported = true;
+
+ if (!supported) {
+ log_warning("Requested operation not supported, ignoring.");
+ return -EOPNOTSUPP;
+ }
+
+ if (m->action_what) {
+ log_debug("Action already in progress, ignoring.");
+ return -EALREADY;
+ }
+
+ inhibit_operation = IN_SET(handle, HANDLE_SUSPEND, HANDLE_HIBERNATE, HANDLE_HYBRID_SLEEP) ? INHIBIT_SLEEP : INHIBIT_SHUTDOWN;
+
+ /* If the actual operation is inhibited, warn and fail */
+ if (!ignore_inhibited &&
+ manager_is_inhibited(m, inhibit_operation, INHIBIT_BLOCK, NULL, false, false, 0, &offending)) {
+ _cleanup_free_ char *comm = NULL, *u = NULL;
+
+ get_process_comm(offending->pid, &comm);
+ u = uid_to_name(offending->uid);
+
+ /* If this is just a recheck of the lid switch then don't warn about anything */
+ if (!is_edge) {
+ log_debug("Refusing operation, %s is inhibited by UID "UID_FMT"/%s, PID "PID_FMT"/%s.",
+ inhibit_what_to_string(inhibit_operation),
+ offending->uid, strna(u),
+ offending->pid, strna(comm));
+ return 0;
+ }
+
+ log_error("Refusing operation, %s is inhibited by UID "UID_FMT"/%s, PID "PID_FMT"/%s.",
+ inhibit_what_to_string(inhibit_operation),
+ offending->uid, strna(u),
+ offending->pid, strna(comm));
+
+ return -EPERM;
+ }
+
+ log_info("%s", message_table[handle]);
+
+ r = bus_manager_shutdown_or_sleep_now_or_later(m, target_table[handle], inhibit_operation, &error);
+ if (r < 0) {
+ log_error("Failed to execute operation: %s", bus_error_message(&error, r));
+ return r;
+ }
+
+ return 1;
+}
+
+static const char* const handle_action_table[_HANDLE_ACTION_MAX] = {
+ [HANDLE_IGNORE] = "ignore",
+ [HANDLE_POWEROFF] = "poweroff",
+ [HANDLE_REBOOT] = "reboot",
+ [HANDLE_HALT] = "halt",
+ [HANDLE_KEXEC] = "kexec",
+ [HANDLE_SUSPEND] = "suspend",
+ [HANDLE_HIBERNATE] = "hibernate",
+ [HANDLE_HYBRID_SLEEP] = "hybrid-sleep",
+ [HANDLE_LOCK] = "lock"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(handle_action, HandleAction);
+DEFINE_CONFIG_PARSE_ENUM(config_parse_handle_action, handle_action, HandleAction, "Failed to parse handle action setting");
diff --git a/src/grp-login/systemd-logind/logind-action.h b/src/grp-login/systemd-logind/logind-action.h
new file mode 100644
index 0000000000..fb40ae48d2
--- /dev/null
+++ b/src/grp-login/systemd-logind/logind-action.h
@@ -0,0 +1,49 @@
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ 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/>.
+***/
+
+typedef enum HandleAction {
+ HANDLE_IGNORE,
+ HANDLE_POWEROFF,
+ HANDLE_REBOOT,
+ HANDLE_HALT,
+ HANDLE_KEXEC,
+ HANDLE_SUSPEND,
+ HANDLE_HIBERNATE,
+ HANDLE_HYBRID_SLEEP,
+ HANDLE_LOCK,
+ _HANDLE_ACTION_MAX,
+ _HANDLE_ACTION_INVALID = -1
+} HandleAction;
+
+#include "logind-inhibit.h"
+#include "logind.h"
+
+int manager_handle_action(
+ Manager *m,
+ InhibitWhat inhibit_key,
+ HandleAction handle,
+ bool ignore_inhibited,
+ bool is_edge);
+
+const char* handle_action_to_string(HandleAction h) _const_;
+HandleAction handle_action_from_string(const char *s) _pure_;
+
+int config_parse_handle_action(const char *unit, const char *filename, unsigned line, const char *section, unsigned section_line, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
diff --git a/src/grp-login/systemd-logind/logind-button.c b/src/grp-login/systemd-logind/logind-button.c
new file mode 100644
index 0000000000..81c82117fc
--- /dev/null
+++ b/src/grp-login/systemd-logind/logind-button.c
@@ -0,0 +1,290 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ 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 <errno.h>
+#include <fcntl.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <unistd.h>
+
+#include <linux/input.h>
+
+#include <systemd/sd-messages.h>
+
+#include "basic/alloc-util.h"
+#include "basic/fd-util.h"
+#include "basic/string-util.h"
+#include "basic/util.h"
+
+#include "logind-button.h"
+
+Button* button_new(Manager *m, const char *name) {
+ Button *b;
+
+ assert(m);
+ assert(name);
+
+ b = new0(Button, 1);
+ if (!b)
+ return NULL;
+
+ b->name = strdup(name);
+ if (!b->name) {
+ free(b);
+ return NULL;
+ }
+
+ if (hashmap_put(m->buttons, b->name, b) < 0) {
+ free(b->name);
+ free(b);
+ return NULL;
+ }
+
+ b->manager = m;
+ b->fd = -1;
+
+ return b;
+}
+
+void button_free(Button *b) {
+ assert(b);
+
+ hashmap_remove(b->manager->buttons, b->name);
+
+ sd_event_source_unref(b->io_event_source);
+ sd_event_source_unref(b->check_event_source);
+
+ if (b->fd >= 0)
+ /* If the device has been unplugged close() returns
+ * ENODEV, let's ignore this, hence we don't use
+ * safe_close() */
+ (void) close(b->fd);
+
+ free(b->name);
+ free(b->seat);
+ free(b);
+}
+
+int button_set_seat(Button *b, const char *sn) {
+ char *s;
+
+ assert(b);
+ assert(sn);
+
+ s = strdup(sn);
+ if (!s)
+ return -ENOMEM;
+
+ free(b->seat);
+ b->seat = s;
+
+ return 0;
+}
+
+static void button_lid_switch_handle_action(Manager *manager, bool is_edge) {
+ HandleAction handle_action;
+
+ assert(manager);
+
+ /* If we are docked, handle the lid switch differently */
+ if (manager_is_docked_or_external_displays(manager))
+ handle_action = manager->handle_lid_switch_docked;
+ else
+ handle_action = manager->handle_lid_switch;
+
+ manager_handle_action(manager, INHIBIT_HANDLE_LID_SWITCH, handle_action, manager->lid_switch_ignore_inhibited, is_edge);
+}
+
+static int button_recheck(sd_event_source *e, void *userdata) {
+ Button *b = userdata;
+
+ assert(b);
+ assert(b->lid_closed);
+
+ button_lid_switch_handle_action(b->manager, false);
+ return 1;
+}
+
+static int button_install_check_event_source(Button *b) {
+ int r;
+ assert(b);
+
+ /* Install a post handler, so that we keep rechecking as long as the lid is closed. */
+
+ if (b->check_event_source)
+ return 0;
+
+ r = sd_event_add_post(b->manager->event, &b->check_event_source, button_recheck, b);
+ if (r < 0)
+ return r;
+
+ return sd_event_source_set_priority(b->check_event_source, SD_EVENT_PRIORITY_IDLE+1);
+}
+
+static int button_dispatch(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
+ Button *b = userdata;
+ struct input_event ev;
+ ssize_t l;
+
+ assert(s);
+ assert(fd == b->fd);
+ assert(b);
+
+ l = read(b->fd, &ev, sizeof(ev));
+ if (l < 0)
+ return errno != EAGAIN ? -errno : 0;
+ if ((size_t) l < sizeof(ev))
+ return -EIO;
+
+ if (ev.type == EV_KEY && ev.value > 0) {
+
+ switch (ev.code) {
+
+ case KEY_POWER:
+ case KEY_POWER2:
+ log_struct(LOG_INFO,
+ LOG_MESSAGE("Power key pressed."),
+ LOG_MESSAGE_ID(SD_MESSAGE_POWER_KEY),
+ NULL);
+
+ manager_handle_action(b->manager, INHIBIT_HANDLE_POWER_KEY, b->manager->handle_power_key, b->manager->power_key_ignore_inhibited, true);
+ break;
+
+ /* The kernel is a bit confused here:
+
+ KEY_SLEEP = suspend-to-ram, which everybody else calls "suspend"
+ KEY_SUSPEND = suspend-to-disk, which everybody else calls "hibernate"
+ */
+
+ case KEY_SLEEP:
+ log_struct(LOG_INFO,
+ LOG_MESSAGE("Suspend key pressed."),
+ LOG_MESSAGE_ID(SD_MESSAGE_SUSPEND_KEY),
+ NULL);
+
+ manager_handle_action(b->manager, INHIBIT_HANDLE_SUSPEND_KEY, b->manager->handle_suspend_key, b->manager->suspend_key_ignore_inhibited, true);
+ break;
+
+ case KEY_SUSPEND:
+ log_struct(LOG_INFO,
+ LOG_MESSAGE("Hibernate key pressed."),
+ LOG_MESSAGE_ID(SD_MESSAGE_HIBERNATE_KEY),
+ NULL);
+
+ manager_handle_action(b->manager, INHIBIT_HANDLE_HIBERNATE_KEY, b->manager->handle_hibernate_key, b->manager->hibernate_key_ignore_inhibited, true);
+ break;
+ }
+
+ } else if (ev.type == EV_SW && ev.value > 0) {
+
+ if (ev.code == SW_LID) {
+ log_struct(LOG_INFO,
+ LOG_MESSAGE("Lid closed."),
+ LOG_MESSAGE_ID(SD_MESSAGE_LID_CLOSED),
+ NULL);
+
+ b->lid_closed = true;
+ button_lid_switch_handle_action(b->manager, true);
+ button_install_check_event_source(b);
+
+ } else if (ev.code == SW_DOCK) {
+ log_struct(LOG_INFO,
+ LOG_MESSAGE("System docked."),
+ LOG_MESSAGE_ID(SD_MESSAGE_SYSTEM_DOCKED),
+ NULL);
+
+ b->docked = true;
+ }
+
+ } else if (ev.type == EV_SW && ev.value == 0) {
+
+ if (ev.code == SW_LID) {
+ log_struct(LOG_INFO,
+ LOG_MESSAGE("Lid opened."),
+ LOG_MESSAGE_ID(SD_MESSAGE_LID_OPENED),
+ NULL);
+
+ b->lid_closed = false;
+ b->check_event_source = sd_event_source_unref(b->check_event_source);
+
+ } else if (ev.code == SW_DOCK) {
+ log_struct(LOG_INFO,
+ LOG_MESSAGE("System undocked."),
+ LOG_MESSAGE_ID(SD_MESSAGE_SYSTEM_UNDOCKED),
+ NULL);
+
+ b->docked = false;
+ }
+ }
+
+ return 0;
+}
+
+int button_open(Button *b) {
+ char *p, name[256];
+ int r;
+
+ assert(b);
+
+ b->fd = safe_close(b->fd);
+
+ p = strjoina("/dev/input/", b->name);
+
+ b->fd = open(p, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK);
+ if (b->fd < 0)
+ return log_warning_errno(errno, "Failed to open %s: %m", b->name);
+
+ if (ioctl(b->fd, EVIOCGNAME(sizeof(name)), name) < 0) {
+ r = log_error_errno(errno, "Failed to get input name: %m");
+ goto fail;
+ }
+
+ r = sd_event_add_io(b->manager->event, &b->io_event_source, b->fd, EPOLLIN, button_dispatch, b);
+ if (r < 0) {
+ log_error_errno(r, "Failed to add button event: %m");
+ goto fail;
+ }
+
+ log_info("Watching system buttons on /dev/input/%s (%s)", b->name, name);
+
+ return 0;
+
+fail:
+ b->fd = safe_close(b->fd);
+ return r;
+}
+
+int button_check_switches(Button *b) {
+ uint8_t switches[SW_MAX/8+1] = {};
+ assert(b);
+
+ if (b->fd < 0)
+ return -EINVAL;
+
+ if (ioctl(b->fd, EVIOCGSW(sizeof(switches)), switches) < 0)
+ return -errno;
+
+ b->lid_closed = (switches[SW_LID/8] >> (SW_LID % 8)) & 1;
+ b->docked = (switches[SW_DOCK/8] >> (SW_DOCK % 8)) & 1;
+
+ if (b->lid_closed)
+ button_install_check_event_source(b);
+
+ return 0;
+}
diff --git a/src/grp-login/systemd-logind/logind-button.h b/src/grp-login/systemd-logind/logind-button.h
new file mode 100644
index 0000000000..f30cba2959
--- /dev/null
+++ b/src/grp-login/systemd-logind/logind-button.h
@@ -0,0 +1,44 @@
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ 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/>.
+***/
+
+typedef struct Button Button;
+
+#include "logind.h"
+
+struct Button {
+ Manager *manager;
+
+ sd_event_source *io_event_source;
+ sd_event_source *check_event_source;
+
+ char *name;
+ char *seat;
+ int fd;
+
+ bool lid_closed;
+ bool docked;
+};
+
+Button* button_new(Manager *m, const char *name);
+void button_free(Button*b);
+int button_open(Button *b);
+int button_set_seat(Button *b, const char *sn);
+int button_check_switches(Button *b);
diff --git a/src/grp-login/systemd-logind/logind-core.c b/src/grp-login/systemd-logind/logind-core.c
new file mode 100644
index 0000000000..b2ae7c2e1a
--- /dev/null
+++ b/src/grp-login/systemd-logind/logind-core.c
@@ -0,0 +1,560 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ 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 <pwd.h>
+#include <sys/ioctl.h>
+#include <sys/types.h>
+
+#include <linux/vt.h>
+
+#include "basic/alloc-util.h"
+#include "basic/cgroup-util.h"
+#include "basic/fd-util.h"
+#include "basic/strv.h"
+#include "basic/terminal-util.h"
+#include "basic/user-util.h"
+#include "sd-bus/bus-error.h"
+#include "shared/bus-util.h"
+#include "shared/udev-util.h"
+
+#include "logind.h"
+
+int manager_add_device(Manager *m, const char *sysfs, bool master, Device **_device) {
+ Device *d;
+
+ assert(m);
+ assert(sysfs);
+
+ d = hashmap_get(m->devices, sysfs);
+ if (d)
+ /* we support adding master-flags, but not removing them */
+ d->master = d->master || master;
+ else {
+ d = device_new(m, sysfs, master);
+ if (!d)
+ return -ENOMEM;
+ }
+
+ if (_device)
+ *_device = d;
+
+ return 0;
+}
+
+int manager_add_seat(Manager *m, const char *id, Seat **_seat) {
+ Seat *s;
+
+ assert(m);
+ assert(id);
+
+ s = hashmap_get(m->seats, id);
+ if (!s) {
+ s = seat_new(m, id);
+ if (!s)
+ return -ENOMEM;
+ }
+
+ if (_seat)
+ *_seat = s;
+
+ return 0;
+}
+
+int manager_add_session(Manager *m, const char *id, Session **_session) {
+ Session *s;
+
+ assert(m);
+ assert(id);
+
+ s = hashmap_get(m->sessions, id);
+ if (!s) {
+ s = session_new(m, id);
+ if (!s)
+ return -ENOMEM;
+ }
+
+ if (_session)
+ *_session = s;
+
+ return 0;
+}
+
+int manager_add_user(Manager *m, uid_t uid, gid_t gid, const char *name, User **_user) {
+ User *u;
+ int r;
+
+ assert(m);
+ assert(name);
+
+ u = hashmap_get(m->users, UID_TO_PTR(uid));
+ if (!u) {
+ r = user_new(&u, m, uid, gid, name);
+ if (r < 0)
+ return r;
+ }
+
+ if (_user)
+ *_user = u;
+
+ return 0;
+}
+
+int manager_add_user_by_name(Manager *m, const char *name, User **_user) {
+ uid_t uid;
+ gid_t gid;
+ int r;
+
+ assert(m);
+ assert(name);
+
+ r = get_user_creds(&name, &uid, &gid, NULL, NULL);
+ if (r < 0)
+ return r;
+
+ return manager_add_user(m, uid, gid, name, _user);
+}
+
+int manager_add_user_by_uid(Manager *m, uid_t uid, User **_user) {
+ struct passwd *p;
+
+ assert(m);
+
+ errno = 0;
+ p = getpwuid(uid);
+ if (!p)
+ return errno > 0 ? -errno : -ENOENT;
+
+ return manager_add_user(m, uid, p->pw_gid, p->pw_name, _user);
+}
+
+int manager_add_inhibitor(Manager *m, const char* id, Inhibitor **_inhibitor) {
+ Inhibitor *i;
+
+ assert(m);
+ assert(id);
+
+ i = hashmap_get(m->inhibitors, id);
+ if (i) {
+ if (_inhibitor)
+ *_inhibitor = i;
+
+ return 0;
+ }
+
+ i = inhibitor_new(m, id);
+ if (!i)
+ return -ENOMEM;
+
+ if (_inhibitor)
+ *_inhibitor = i;
+
+ return 0;
+}
+
+int manager_add_button(Manager *m, const char *name, Button **_button) {
+ Button *b;
+
+ assert(m);
+ assert(name);
+
+ b = hashmap_get(m->buttons, name);
+ if (!b) {
+ b = button_new(m, name);
+ if (!b)
+ return -ENOMEM;
+ }
+
+ if (_button)
+ *_button = b;
+
+ return 0;
+}
+
+int manager_process_seat_device(Manager *m, struct udev_device *d) {
+ Device *device;
+ int r;
+
+ assert(m);
+
+ if (streq_ptr(udev_device_get_action(d), "remove")) {
+
+ device = hashmap_get(m->devices, udev_device_get_syspath(d));
+ if (!device)
+ return 0;
+
+ seat_add_to_gc_queue(device->seat);
+ device_free(device);
+
+ } else {
+ const char *sn;
+ Seat *seat = NULL;
+ bool master;
+
+ sn = udev_device_get_property_value(d, "ID_SEAT");
+ if (isempty(sn))
+ sn = "seat0";
+
+ if (!seat_name_is_valid(sn)) {
+ log_warning("Device with invalid seat name %s found, ignoring.", sn);
+ return 0;
+ }
+
+ seat = hashmap_get(m->seats, sn);
+ master = udev_device_has_tag(d, "master-of-seat");
+
+ /* Ignore non-master devices for unknown seats */
+ if (!master && !seat)
+ return 0;
+
+ r = manager_add_device(m, udev_device_get_syspath(d), master, &device);
+ if (r < 0)
+ return r;
+
+ if (!seat) {
+ r = manager_add_seat(m, sn, &seat);
+ if (r < 0) {
+ if (!device->seat)
+ device_free(device);
+
+ return r;
+ }
+ }
+
+ device_attach(device, seat);
+ seat_start(seat);
+ }
+
+ return 0;
+}
+
+int manager_process_button_device(Manager *m, struct udev_device *d) {
+ Button *b;
+
+ int r;
+
+ assert(m);
+
+ if (streq_ptr(udev_device_get_action(d), "remove")) {
+
+ b = hashmap_get(m->buttons, udev_device_get_sysname(d));
+ if (!b)
+ return 0;
+
+ button_free(b);
+
+ } else {
+ const char *sn;
+
+ r = manager_add_button(m, udev_device_get_sysname(d), &b);
+ if (r < 0)
+ return r;
+
+ sn = udev_device_get_property_value(d, "ID_SEAT");
+ if (isempty(sn))
+ sn = "seat0";
+
+ button_set_seat(b, sn);
+ button_open(b);
+ }
+
+ return 0;
+}
+
+int manager_get_session_by_pid(Manager *m, pid_t pid, Session **session) {
+ _cleanup_free_ char *unit = NULL;
+ Session *s;
+ int r;
+
+ assert(m);
+
+ if (pid < 1)
+ return -EINVAL;
+
+ r = cg_pid_get_unit(pid, &unit);
+ if (r < 0)
+ return 0;
+
+ s = hashmap_get(m->session_units, unit);
+ if (!s)
+ return 0;
+
+ if (session)
+ *session = s;
+ return 1;
+}
+
+int manager_get_user_by_pid(Manager *m, pid_t pid, User **user) {
+ _cleanup_free_ char *unit = NULL;
+ User *u;
+ int r;
+
+ assert(m);
+ assert(user);
+
+ if (pid < 1)
+ return -EINVAL;
+
+ r = cg_pid_get_slice(pid, &unit);
+ if (r < 0)
+ return 0;
+
+ u = hashmap_get(m->user_units, unit);
+ if (!u)
+ return 0;
+
+ *user = u;
+ return 1;
+}
+
+int manager_get_idle_hint(Manager *m, dual_timestamp *t) {
+ Session *s;
+ bool idle_hint;
+ dual_timestamp ts = DUAL_TIMESTAMP_NULL;
+ Iterator i;
+
+ assert(m);
+
+ idle_hint = !manager_is_inhibited(m, INHIBIT_IDLE, INHIBIT_BLOCK, t, false, false, 0, NULL);
+
+ HASHMAP_FOREACH(s, m->sessions, i) {
+ dual_timestamp k;
+ int ih;
+
+ ih = session_get_idle_hint(s, &k);
+ if (ih < 0)
+ return ih;
+
+ if (!ih) {
+ if (!idle_hint) {
+ if (k.monotonic < ts.monotonic)
+ ts = k;
+ } else {
+ idle_hint = false;
+ ts = k;
+ }
+ } else if (idle_hint) {
+
+ if (k.monotonic > ts.monotonic)
+ ts = k;
+ }
+ }
+
+ if (t)
+ *t = ts;
+
+ return idle_hint;
+}
+
+bool manager_shall_kill(Manager *m, const char *user) {
+ assert(m);
+ assert(user);
+
+ if (!m->kill_exclude_users && streq(user, "root"))
+ return false;
+
+ if (strv_contains(m->kill_exclude_users, user))
+ return false;
+
+ if (!strv_isempty(m->kill_only_users))
+ return strv_contains(m->kill_only_users, user);
+
+ return m->kill_user_processes;
+}
+
+static int vt_is_busy(unsigned int vtnr) {
+ struct vt_stat vt_stat;
+ int r = 0;
+ _cleanup_close_ int fd;
+
+ assert(vtnr >= 1);
+
+ /* We explicitly open /dev/tty1 here instead of /dev/tty0. If
+ * we'd open the latter we'd open the foreground tty which
+ * hence would be unconditionally busy. By opening /dev/tty1
+ * we avoid this. Since tty1 is special and needs to be an
+ * explicitly loaded getty or DM this is safe. */
+
+ fd = open_terminal("/dev/tty1", O_RDWR|O_NOCTTY|O_CLOEXEC);
+ if (fd < 0)
+ return -errno;
+
+ if (ioctl(fd, VT_GETSTATE, &vt_stat) < 0)
+ r = -errno;
+ else
+ r = !!(vt_stat.v_state & (1 << vtnr));
+
+ return r;
+}
+
+int manager_spawn_autovt(Manager *m, unsigned int vtnr) {
+ _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+ char name[sizeof("autovt@tty.service") + DECIMAL_STR_MAX(unsigned int)];
+ int r;
+
+ assert(m);
+ assert(vtnr >= 1);
+
+ if (vtnr > m->n_autovts &&
+ vtnr != m->reserve_vt)
+ return 0;
+
+ if (vtnr != m->reserve_vt) {
+ /* If this is the reserved TTY, we'll start the getty
+ * on it in any case, but otherwise only if it is not
+ * busy. */
+
+ r = vt_is_busy(vtnr);
+ if (r < 0)
+ return r;
+ else if (r > 0)
+ return -EBUSY;
+ }
+
+ snprintf(name, sizeof(name), "autovt@tty%u.service", vtnr);
+ r = sd_bus_call_method(
+ m->bus,
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "StartUnit",
+ &error,
+ NULL,
+ "ss", name, "fail");
+ if (r < 0)
+ log_error("Failed to start %s: %s", name, bus_error_message(&error, r));
+
+ return r;
+}
+
+static bool manager_is_docked(Manager *m) {
+ Iterator i;
+ Button *b;
+
+ HASHMAP_FOREACH(b, m->buttons, i)
+ if (b->docked)
+ return true;
+
+ return false;
+}
+
+static int manager_count_external_displays(Manager *m) {
+ _cleanup_udev_enumerate_unref_ struct udev_enumerate *e = NULL;
+ struct udev_list_entry *item = NULL, *first = NULL;
+ int r;
+ int n = 0;
+
+ e = udev_enumerate_new(m->udev);
+ if (!e)
+ return -ENOMEM;
+
+ r = udev_enumerate_add_match_subsystem(e, "drm");
+ if (r < 0)
+ return r;
+
+ r = udev_enumerate_scan_devices(e);
+ if (r < 0)
+ return r;
+
+ first = udev_enumerate_get_list_entry(e);
+ udev_list_entry_foreach(item, first) {
+ _cleanup_udev_device_unref_ struct udev_device *d = NULL;
+ struct udev_device *p;
+ const char *status, *enabled, *dash, *nn, *i;
+ bool external = false;
+
+ d = udev_device_new_from_syspath(m->udev, udev_list_entry_get_name(item));
+ if (!d)
+ return -ENOMEM;
+
+ p = udev_device_get_parent(d);
+ if (!p)
+ continue;
+
+ /* If the parent shares the same subsystem as the
+ * device we are looking at then it is a connector,
+ * which is what we are interested in. */
+ if (!streq_ptr(udev_device_get_subsystem(p), "drm"))
+ continue;
+
+ nn = udev_device_get_sysname(d);
+ if (!nn)
+ continue;
+
+ /* Ignore internal displays: the type is encoded in
+ * the sysfs name, as the second dash separated item
+ * (the first is the card name, the last the connector
+ * number). We implement a whitelist of external
+ * displays here, rather than a whitelist, to ensure
+ * we don't block suspends too eagerly. */
+ dash = strchr(nn, '-');
+ if (!dash)
+ continue;
+
+ dash++;
+ FOREACH_STRING(i, "VGA-", "DVI-I-", "DVI-D-", "DVI-A-"
+ "Composite-", "SVIDEO-", "Component-",
+ "DIN-", "DP-", "HDMI-A-", "HDMI-B-", "TV-") {
+
+ if (startswith(dash, i)) {
+ external = true;
+ break;
+ }
+ }
+ if (!external)
+ continue;
+
+ /* Ignore ports that are not enabled */
+ enabled = udev_device_get_sysattr_value(d, "enabled");
+ if (!enabled)
+ continue;
+ if (!streq_ptr(enabled, "enabled"))
+ continue;
+
+ /* We count any connector which is not explicitly
+ * "disconnected" as connected. */
+ status = udev_device_get_sysattr_value(d, "status");
+ if (!streq_ptr(status, "disconnected"))
+ n++;
+ }
+
+ return n;
+}
+
+bool manager_is_docked_or_external_displays(Manager *m) {
+ int n;
+
+ /* If we are docked don't react to lid closing */
+ if (manager_is_docked(m)) {
+ log_debug("System is docked.");
+ return true;
+ }
+
+ /* If we have more than one display connected,
+ * assume that we are docked. */
+ n = manager_count_external_displays(m);
+ if (n < 0)
+ log_warning_errno(n, "Display counting failed: %m");
+ else if (n >= 1) {
+ log_debug("External (%i) displays connected.", n);
+ return true;
+ }
+
+ return false;
+}
diff --git a/src/grp-login/systemd-logind/logind-dbus.c b/src/grp-login/systemd-logind/logind-dbus.c
new file mode 100644
index 0000000000..282ba64a3d
--- /dev/null
+++ b/src/grp-login/systemd-logind/logind-dbus.c
@@ -0,0 +1,3170 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ 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 <errno.h>
+#include <pwd.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <systemd/sd-messages.h>
+
+#include "basic/alloc-util.h"
+#include "basic/audit-util.h"
+#include "basic/dirent-util.h"
+#include "basic/escape.h"
+#include "basic/fd-util.h"
+#include "basic/fileio-label.h"
+#include "basic/formats-util.h"
+#include "basic/fs-util.h"
+#include "basic/mkdir.h"
+#include "basic/path-util.h"
+#include "basic/process-util.h"
+#include "basic/selinux-util.h"
+#include "basic/special.h"
+#include "basic/strv.h"
+#include "basic/terminal-util.h"
+#include "basic/unit-name.h"
+#include "basic/user-util.h"
+#include "sd-bus/bus-common-errors.h"
+#include "sd-bus/bus-error.h"
+#include "shared/bus-util.h"
+#include "shared/efivars.h"
+#include "shared/sleep-config.h"
+#include "shared/udev-util.h"
+#include "shared/utmp-wtmp.h"
+
+#include "logind.h"
+
+int manager_get_session_from_creds(Manager *m, sd_bus_message *message, const char *name, sd_bus_error *error, Session **ret) {
+ _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
+ Session *session;
+ int r;
+
+ assert(m);
+ assert(message);
+ assert(ret);
+
+ if (isempty(name)) {
+ r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_SESSION|SD_BUS_CREDS_AUGMENT, &creds);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_creds_get_session(creds, &name);
+ if (r < 0)
+ return r;
+ }
+
+ session = hashmap_get(m->sessions, name);
+ if (!session)
+ return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_SESSION, "No session '%s' known", name);
+
+ *ret = session;
+ return 0;
+}
+
+int manager_get_user_from_creds(Manager *m, sd_bus_message *message, uid_t uid, sd_bus_error *error, User **ret) {
+ User *user;
+ int r;
+
+ assert(m);
+ assert(message);
+ assert(ret);
+
+ if (uid == UID_INVALID) {
+ _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
+
+ /* Note that we get the owner UID of the session, not the actual client UID here! */
+ r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_OWNER_UID|SD_BUS_CREDS_AUGMENT, &creds);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_creds_get_owner_uid(creds, &uid);
+ if (r < 0)
+ return r;
+ }
+
+ user = hashmap_get(m->users, UID_TO_PTR(uid));
+ if (!user)
+ return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_USER, "No user "UID_FMT" known or logged in", uid);
+
+ *ret = user;
+ return 0;
+}
+
+int manager_get_seat_from_creds(Manager *m, sd_bus_message *message, const char *name, sd_bus_error *error, Seat **ret) {
+ Seat *seat;
+ int r;
+
+ assert(m);
+ assert(message);
+ assert(ret);
+
+ if (isempty(name)) {
+ Session *session;
+
+ r = manager_get_session_from_creds(m, message, NULL, error, &session);
+ if (r < 0)
+ return r;
+
+ seat = session->seat;
+ if (!seat)
+ return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_SEAT, "Session has no seat.");
+ } else {
+ seat = hashmap_get(m->seats, name);
+ if (!seat)
+ return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_SEAT, "No seat '%s' known", name);
+ }
+
+ *ret = seat;
+ return 0;
+}
+
+static int property_get_idle_hint(
+ sd_bus *bus,
+ const char *path,
+ const char *interface,
+ const char *property,
+ sd_bus_message *reply,
+ void *userdata,
+ sd_bus_error *error) {
+
+ Manager *m = userdata;
+
+ assert(bus);
+ assert(reply);
+ assert(m);
+
+ return sd_bus_message_append(reply, "b", manager_get_idle_hint(m, NULL) > 0);
+}
+
+static int property_get_idle_since_hint(
+ sd_bus *bus,
+ const char *path,
+ const char *interface,
+ const char *property,
+ sd_bus_message *reply,
+ void *userdata,
+ sd_bus_error *error) {
+
+ Manager *m = userdata;
+ dual_timestamp t = DUAL_TIMESTAMP_NULL;
+
+ assert(bus);
+ assert(reply);
+ assert(m);
+
+ manager_get_idle_hint(m, &t);
+
+ return sd_bus_message_append(reply, "t", streq(property, "IdleSinceHint") ? t.realtime : t.monotonic);
+}
+
+static int property_get_inhibited(
+ sd_bus *bus,
+ const char *path,
+ const char *interface,
+ const char *property,
+ sd_bus_message *reply,
+ void *userdata,
+ sd_bus_error *error) {
+
+ Manager *m = userdata;
+ InhibitWhat w;
+
+ assert(bus);
+ assert(reply);
+ assert(m);
+
+ w = manager_inhibit_what(m, streq(property, "BlockInhibited") ? INHIBIT_BLOCK : INHIBIT_DELAY);
+
+ return sd_bus_message_append(reply, "s", inhibit_what_to_string(w));
+}
+
+static int property_get_preparing(
+ sd_bus *bus,
+ const char *path,
+ const char *interface,
+ const char *property,
+ sd_bus_message *reply,
+ void *userdata,
+ sd_bus_error *error) {
+
+ Manager *m = userdata;
+ bool b;
+
+ assert(bus);
+ assert(reply);
+ assert(m);
+
+ if (streq(property, "PreparingForShutdown"))
+ b = !!(m->action_what & INHIBIT_SHUTDOWN);
+ else
+ b = !!(m->action_what & INHIBIT_SLEEP);
+
+ return sd_bus_message_append(reply, "b", b);
+}
+
+static int property_get_scheduled_shutdown(
+ sd_bus *bus,
+ const char *path,
+ const char *interface,
+ const char *property,
+ sd_bus_message *reply,
+ void *userdata,
+ sd_bus_error *error) {
+
+ Manager *m = userdata;
+ int r;
+
+ assert(bus);
+ assert(reply);
+ assert(m);
+
+ r = sd_bus_message_open_container(reply, 'r', "st");
+ if (r < 0)
+ return r;
+
+ r = sd_bus_message_append(reply, "st", m->scheduled_shutdown_type, m->scheduled_shutdown_timeout);
+ if (r < 0)
+ return r;
+
+ return sd_bus_message_close_container(reply);
+}
+
+static BUS_DEFINE_PROPERTY_GET_ENUM(property_get_handle_action, handle_action, HandleAction);
+
+static int property_get_docked(
+ sd_bus *bus,
+ const char *path,
+ const char *interface,
+ const char *property,
+ sd_bus_message *reply,
+ void *userdata,
+ sd_bus_error *error) {
+
+ Manager *m = userdata;
+
+ assert(bus);
+ assert(reply);
+ assert(m);
+
+ return sd_bus_message_append(reply, "b", manager_is_docked_or_external_displays(m));
+}
+
+static int property_get_current_sessions(
+ sd_bus *bus,
+ const char *path,
+ const char *interface,
+ const char *property,
+ sd_bus_message *reply,
+ void *userdata,
+ sd_bus_error *error) {
+
+ Manager *m = userdata;
+
+ assert(bus);
+ assert(reply);
+ assert(m);
+
+ return sd_bus_message_append(reply, "t", (uint64_t) hashmap_size(m->sessions));
+}
+
+static int property_get_current_inhibitors(
+ sd_bus *bus,
+ const char *path,
+ const char *interface,
+ const char *property,
+ sd_bus_message *reply,
+ void *userdata,
+ sd_bus_error *error) {
+
+ Manager *m = userdata;
+
+ assert(bus);
+ assert(reply);
+ assert(m);
+
+ return sd_bus_message_append(reply, "t", (uint64_t) hashmap_size(m->inhibitors));
+}
+
+static int method_get_session(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ _cleanup_free_ char *p = NULL;
+ Manager *m = userdata;
+ const char *name;
+ Session *session;
+ int r;
+
+ assert(message);
+ assert(m);
+
+ r = sd_bus_message_read(message, "s", &name);
+ if (r < 0)
+ return r;
+
+ r = manager_get_session_from_creds(m, message, name, error, &session);
+ if (r < 0)
+ return r;
+
+ p = session_bus_path(session);
+ if (!p)
+ return -ENOMEM;
+
+ return sd_bus_reply_method_return(message, "o", p);
+}
+
+static int method_get_session_by_pid(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ _cleanup_free_ char *p = NULL;
+ Session *session = NULL;
+ Manager *m = userdata;
+ pid_t pid;
+ int r;
+
+ assert(message);
+ assert(m);
+
+ assert_cc(sizeof(pid_t) == sizeof(uint32_t));
+
+ r = sd_bus_message_read(message, "u", &pid);
+ if (r < 0)
+ return r;
+ if (pid < 0)
+ return -EINVAL;
+
+ if (pid == 0) {
+ r = manager_get_session_from_creds(m, message, NULL, error, &session);
+ if (r < 0)
+ return r;
+ } else {
+ r = manager_get_session_by_pid(m, pid, &session);
+ if (r < 0)
+ return r;
+
+ if (!session)
+ return sd_bus_error_setf(error, BUS_ERROR_NO_SESSION_FOR_PID, "PID "PID_FMT" does not belong to any known session", pid);
+ }
+
+ p = session_bus_path(session);
+ if (!p)
+ return -ENOMEM;
+
+ return sd_bus_reply_method_return(message, "o", p);
+}
+
+static int method_get_user(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ _cleanup_free_ char *p = NULL;
+ Manager *m = userdata;
+ uint32_t uid;
+ User *user;
+ int r;
+
+ assert(message);
+ assert(m);
+
+ r = sd_bus_message_read(message, "u", &uid);
+ if (r < 0)
+ return r;
+
+ r = manager_get_user_from_creds(m, message, uid, error, &user);
+ if (r < 0)
+ return r;
+
+ p = user_bus_path(user);
+ if (!p)
+ return -ENOMEM;
+
+ return sd_bus_reply_method_return(message, "o", p);
+}
+
+static int method_get_user_by_pid(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ _cleanup_free_ char *p = NULL;
+ Manager *m = userdata;
+ User *user = NULL;
+ pid_t pid;
+ int r;
+
+ assert(message);
+ assert(m);
+
+ assert_cc(sizeof(pid_t) == sizeof(uint32_t));
+
+ r = sd_bus_message_read(message, "u", &pid);
+ if (r < 0)
+ return r;
+ if (pid < 0)
+ return -EINVAL;
+
+ if (pid == 0) {
+ r = manager_get_user_from_creds(m, message, UID_INVALID, error, &user);
+ if (r < 0)
+ return r;
+ } else {
+ r = manager_get_user_by_pid(m, pid, &user);
+ if (r < 0)
+ return r;
+ if (!user)
+ return sd_bus_error_setf(error, BUS_ERROR_NO_USER_FOR_PID, "PID "PID_FMT" does not belong to any known or logged in user", pid);
+ }
+
+ p = user_bus_path(user);
+ if (!p)
+ return -ENOMEM;
+
+ return sd_bus_reply_method_return(message, "o", p);
+}
+
+static int method_get_seat(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ _cleanup_free_ char *p = NULL;
+ Manager *m = userdata;
+ const char *name;
+ Seat *seat;
+ int r;
+
+ assert(message);
+ assert(m);
+
+ r = sd_bus_message_read(message, "s", &name);
+ if (r < 0)
+ return r;
+
+ r = manager_get_seat_from_creds(m, message, name, error, &seat);
+ if (r < 0)
+ return r;
+
+ p = seat_bus_path(seat);
+ if (!p)
+ return -ENOMEM;
+
+ return sd_bus_reply_method_return(message, "o", p);
+}
+
+static int method_list_sessions(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
+ Manager *m = userdata;
+ Session *session;
+ Iterator i;
+ int r;
+
+ assert(message);
+ assert(m);
+
+ r = sd_bus_message_new_method_return(message, &reply);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_message_open_container(reply, 'a', "(susso)");
+ if (r < 0)
+ return r;
+
+ HASHMAP_FOREACH(session, m->sessions, i) {
+ _cleanup_free_ char *p = NULL;
+
+ p = session_bus_path(session);
+ if (!p)
+ return -ENOMEM;
+
+ r = sd_bus_message_append(reply, "(susso)",
+ session->id,
+ (uint32_t) session->user->uid,
+ session->user->name,
+ session->seat ? session->seat->id : "",
+ p);
+ if (r < 0)
+ return r;
+ }
+
+ r = sd_bus_message_close_container(reply);
+ if (r < 0)
+ return r;
+
+ return sd_bus_send(NULL, reply, NULL);
+}
+
+static int method_list_users(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
+ Manager *m = userdata;
+ User *user;
+ Iterator i;
+ int r;
+
+ assert(message);
+ assert(m);
+
+ r = sd_bus_message_new_method_return(message, &reply);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_message_open_container(reply, 'a', "(uso)");
+ if (r < 0)
+ return r;
+
+ HASHMAP_FOREACH(user, m->users, i) {
+ _cleanup_free_ char *p = NULL;
+
+ p = user_bus_path(user);
+ if (!p)
+ return -ENOMEM;
+
+ r = sd_bus_message_append(reply, "(uso)",
+ (uint32_t) user->uid,
+ user->name,
+ p);
+ if (r < 0)
+ return r;
+ }
+
+ r = sd_bus_message_close_container(reply);
+ if (r < 0)
+ return r;
+
+ return sd_bus_send(NULL, reply, NULL);
+}
+
+static int method_list_seats(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
+ Manager *m = userdata;
+ Seat *seat;
+ Iterator i;
+ int r;
+
+ assert(message);
+ assert(m);
+
+ r = sd_bus_message_new_method_return(message, &reply);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_message_open_container(reply, 'a', "(so)");
+ if (r < 0)
+ return r;
+
+ HASHMAP_FOREACH(seat, m->seats, i) {
+ _cleanup_free_ char *p = NULL;
+
+ p = seat_bus_path(seat);
+ if (!p)
+ return -ENOMEM;
+
+ r = sd_bus_message_append(reply, "(so)", seat->id, p);
+ if (r < 0)
+ return r;
+ }
+
+ r = sd_bus_message_close_container(reply);
+ if (r < 0)
+ return r;
+
+ return sd_bus_send(NULL, reply, NULL);
+}
+
+static int method_list_inhibitors(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
+ Manager *m = userdata;
+ Inhibitor *inhibitor;
+ Iterator i;
+ int r;
+
+ assert(message);
+ assert(m);
+
+ r = sd_bus_message_new_method_return(message, &reply);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_message_open_container(reply, 'a', "(ssssuu)");
+ if (r < 0)
+ return r;
+
+ HASHMAP_FOREACH(inhibitor, m->inhibitors, i) {
+
+ r = sd_bus_message_append(reply, "(ssssuu)",
+ strempty(inhibit_what_to_string(inhibitor->what)),
+ strempty(inhibitor->who),
+ strempty(inhibitor->why),
+ strempty(inhibit_mode_to_string(inhibitor->mode)),
+ (uint32_t) inhibitor->uid,
+ (uint32_t) inhibitor->pid);
+ if (r < 0)
+ return r;
+ }
+
+ r = sd_bus_message_close_container(reply);
+ if (r < 0)
+ return r;
+
+ return sd_bus_send(NULL, reply, NULL);
+}
+
+static int method_create_session(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ const char *service, *type, *class, *cseat, *tty, *display, *remote_user, *remote_host, *desktop;
+ uint32_t audit_id = 0;
+ _cleanup_free_ char *id = NULL;
+ Session *session = NULL;
+ Manager *m = userdata;
+ User *user = NULL;
+ Seat *seat = NULL;
+ pid_t leader;
+ uid_t uid;
+ int remote;
+ uint32_t vtnr = 0;
+ SessionType t;
+ SessionClass c;
+ int r;
+
+ assert(message);
+ assert(m);
+
+ assert_cc(sizeof(pid_t) == sizeof(uint32_t));
+ assert_cc(sizeof(uid_t) == sizeof(uint32_t));
+
+ r = sd_bus_message_read(message, "uusssssussbss", &uid, &leader, &service, &type, &class, &desktop, &cseat, &vtnr, &tty, &display, &remote, &remote_user, &remote_host);
+ if (r < 0)
+ return r;
+
+ if (!uid_is_valid(uid))
+ return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid UID");
+ if (leader < 0 || leader == 1)
+ return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid leader PID");
+
+ if (isempty(type))
+ t = _SESSION_TYPE_INVALID;
+ else {
+ t = session_type_from_string(type);
+ if (t < 0)
+ return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid session type %s", type);
+ }
+
+ if (isempty(class))
+ c = _SESSION_CLASS_INVALID;
+ else {
+ c = session_class_from_string(class);
+ if (c < 0)
+ return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid session class %s", class);
+ }
+
+ if (isempty(desktop))
+ desktop = NULL;
+ else {
+ if (!string_is_safe(desktop))
+ return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid desktop string %s", desktop);
+ }
+
+ if (isempty(cseat))
+ seat = NULL;
+ else {
+ seat = hashmap_get(m->seats, cseat);
+ if (!seat)
+ return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_SEAT, "No seat '%s' known", cseat);
+ }
+
+ if (tty_is_vc(tty)) {
+ int v;
+
+ if (!seat)
+ seat = m->seat0;
+ else if (seat != m->seat0)
+ return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "TTY %s is virtual console but seat %s is not seat0", tty, seat->id);
+
+ v = vtnr_from_tty(tty);
+ if (v <= 0)
+ return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Cannot determine VT number from virtual console TTY %s", tty);
+
+ if (!vtnr)
+ vtnr = (uint32_t) v;
+ else if (vtnr != (uint32_t) v)
+ return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Specified TTY and VT number do not match");
+
+ } else if (tty_is_console(tty)) {
+
+ if (!seat)
+ seat = m->seat0;
+ else if (seat != m->seat0)
+ return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Console TTY specified but seat is not seat0");
+
+ if (vtnr != 0)
+ return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Console TTY specified but VT number is not 0");
+ }
+
+ if (seat) {
+ if (seat_has_vts(seat)) {
+ if (!vtnr || vtnr > 63)
+ return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "VT number out of range");
+ } else {
+ if (vtnr != 0)
+ return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Seat has no VTs but VT number not 0");
+ }
+ }
+
+ r = sd_bus_message_enter_container(message, 'a', "(sv)");
+ if (r < 0)
+ return r;
+
+ if (t == _SESSION_TYPE_INVALID) {
+ if (!isempty(display))
+ t = SESSION_X11;
+ else if (!isempty(tty))
+ t = SESSION_TTY;
+ else
+ t = SESSION_UNSPECIFIED;
+ }
+
+ if (c == _SESSION_CLASS_INVALID) {
+ if (t == SESSION_UNSPECIFIED)
+ c = SESSION_BACKGROUND;
+ else
+ c = SESSION_USER;
+ }
+
+ if (leader == 0) {
+ _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
+
+ r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_PID, &creds);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_creds_get_pid(creds, (pid_t*) &leader);
+ if (r < 0)
+ return r;
+ }
+
+ r = manager_get_session_by_pid(m, leader, NULL);
+ if (r > 0)
+ return sd_bus_error_setf(error, BUS_ERROR_SESSION_BUSY, "Already running in a session");
+
+ /*
+ * Old gdm and lightdm start the user-session on the same VT as
+ * the greeter session. But they destroy the greeter session
+ * after the user-session and want the user-session to take
+ * over the VT. We need to support this for
+ * backwards-compatibility, so make sure we allow new sessions
+ * on a VT that a greeter is running on. Furthermore, to allow
+ * re-logins, we have to allow a greeter to take over a used VT for
+ * the exact same reasons.
+ */
+ if (c != SESSION_GREETER &&
+ vtnr > 0 &&
+ vtnr < m->seat0->position_count &&
+ m->seat0->positions[vtnr] &&
+ m->seat0->positions[vtnr]->class != SESSION_GREETER)
+ return sd_bus_error_setf(error, BUS_ERROR_SESSION_BUSY, "Already occupied by a session");
+
+ if (hashmap_size(m->sessions) >= m->sessions_max)
+ return sd_bus_error_setf(error, SD_BUS_ERROR_LIMITS_EXCEEDED, "Maximum number of sessions (%" PRIu64 ") reached, refusing further sessions.", m->sessions_max);
+
+ audit_session_from_pid(leader, &audit_id);
+ if (audit_id > 0) {
+ /* Keep our session IDs and the audit session IDs in sync */
+
+ if (asprintf(&id, "%"PRIu32, audit_id) < 0)
+ return -ENOMEM;
+
+ /* Wut? There's already a session by this name and we
+ * didn't find it above? Weird, then let's not trust
+ * the audit data and let's better register a new
+ * ID */
+ if (hashmap_get(m->sessions, id)) {
+ log_warning("Existing logind session ID %s used by new audit session, ignoring", id);
+ audit_id = 0;
+
+ id = mfree(id);
+ }
+ }
+
+ if (!id) {
+ do {
+ id = mfree(id);
+
+ if (asprintf(&id, "c%lu", ++m->session_counter) < 0)
+ return -ENOMEM;
+
+ } while (hashmap_get(m->sessions, id));
+ }
+
+ r = manager_add_user_by_uid(m, uid, &user);
+ if (r < 0)
+ goto fail;
+
+ r = manager_add_session(m, id, &session);
+ if (r < 0)
+ goto fail;
+
+ session_set_user(session, user);
+
+ session->leader = leader;
+ session->audit_id = audit_id;
+ session->type = t;
+ session->class = c;
+ session->remote = remote;
+ session->vtnr = vtnr;
+
+ if (!isempty(tty)) {
+ session->tty = strdup(tty);
+ if (!session->tty) {
+ r = -ENOMEM;
+ goto fail;
+ }
+ }
+
+ if (!isempty(display)) {
+ session->display = strdup(display);
+ if (!session->display) {
+ r = -ENOMEM;
+ goto fail;
+ }
+ }
+
+ if (!isempty(remote_user)) {
+ session->remote_user = strdup(remote_user);
+ if (!session->remote_user) {
+ r = -ENOMEM;
+ goto fail;
+ }
+ }
+
+ if (!isempty(remote_host)) {
+ session->remote_host = strdup(remote_host);
+ if (!session->remote_host) {
+ r = -ENOMEM;
+ goto fail;
+ }
+ }
+
+ if (!isempty(service)) {
+ session->service = strdup(service);
+ if (!session->service) {
+ r = -ENOMEM;
+ goto fail;
+ }
+ }
+
+ if (!isempty(desktop)) {
+ session->desktop = strdup(desktop);
+ if (!session->desktop) {
+ r = -ENOMEM;
+ goto fail;
+ }
+ }
+
+ if (seat) {
+ r = seat_attach_session(seat, session);
+ if (r < 0)
+ goto fail;
+ }
+
+ r = session_start(session);
+ if (r < 0)
+ goto fail;
+
+ session->create_message = sd_bus_message_ref(message);
+
+ /* Now, let's wait until the slice unit and stuff got
+ * created. We send the reply back from
+ * session_send_create_reply(). */
+
+ return 1;
+
+fail:
+ if (session)
+ session_add_to_gc_queue(session);
+
+ if (user)
+ user_add_to_gc_queue(user);
+
+ return r;
+}
+
+static int method_release_session(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ Manager *m = userdata;
+ Session *session;
+ const char *name;
+ int r;
+
+ assert(message);
+ assert(m);
+
+ r = sd_bus_message_read(message, "s", &name);
+ if (r < 0)
+ return r;
+
+ r = manager_get_session_from_creds(m, message, name, error, &session);
+ if (r < 0)
+ return r;
+
+ r = session_release(session);
+ if (r < 0)
+ return r;
+
+ return sd_bus_reply_method_return(message, NULL);
+}
+
+static int method_activate_session(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ Manager *m = userdata;
+ Session *session;
+ const char *name;
+ int r;
+
+ assert(message);
+ assert(m);
+
+ r = sd_bus_message_read(message, "s", &name);
+ if (r < 0)
+ return r;
+
+ r = manager_get_session_from_creds(m, message, name, error, &session);
+ if (r < 0)
+ return r;
+
+ return bus_session_method_activate(message, session, error);
+}
+
+static int method_activate_session_on_seat(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ const char *session_name, *seat_name;
+ Manager *m = userdata;
+ Session *session;
+ Seat *seat;
+ int r;
+
+ assert(message);
+ assert(m);
+
+ /* Same as ActivateSession() but refuses to work if
+ * the seat doesn't match */
+
+ r = sd_bus_message_read(message, "ss", &session_name, &seat_name);
+ if (r < 0)
+ return r;
+
+ r = manager_get_session_from_creds(m, message, session_name, error, &session);
+ if (r < 0)
+ return r;
+
+ r = manager_get_seat_from_creds(m, message, seat_name, error, &seat);
+ if (r < 0)
+ return r;
+
+ if (session->seat != seat)
+ return sd_bus_error_setf(error, BUS_ERROR_SESSION_NOT_ON_SEAT, "Session %s not on seat %s", session_name, seat_name);
+
+ r = session_activate(session);
+ if (r < 0)
+ return r;
+
+ return sd_bus_reply_method_return(message, NULL);
+}
+
+static int method_lock_session(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ Manager *m = userdata;
+ Session *session;
+ const char *name;
+ int r;
+
+ assert(message);
+ assert(m);
+
+ r = sd_bus_message_read(message, "s", &name);
+ if (r < 0)
+ return r;
+
+ r = manager_get_session_from_creds(m, message, name, error, &session);
+ if (r < 0)
+ return r;
+
+ return bus_session_method_lock(message, session, error);
+}
+
+static int method_lock_sessions(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ Manager *m = userdata;
+ int r;
+
+ assert(message);
+ assert(m);
+
+ r = bus_verify_polkit_async(
+ message,
+ CAP_SYS_ADMIN,
+ "org.freedesktop.login1.lock-sessions",
+ NULL,
+ false,
+ UID_INVALID,
+ &m->polkit_registry,
+ error);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ return 1; /* Will call us back */
+
+ r = session_send_lock_all(m, streq(sd_bus_message_get_member(message), "LockSessions"));
+ if (r < 0)
+ return r;
+
+ return sd_bus_reply_method_return(message, NULL);
+}
+
+static int method_kill_session(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ const char *name;
+ Manager *m = userdata;
+ Session *session;
+ int r;
+
+ assert(message);
+ assert(m);
+
+ r = sd_bus_message_read(message, "s", &name);
+ if (r < 0)
+ return r;
+
+ r = manager_get_session_from_creds(m, message, name, error, &session);
+ if (r < 0)
+ return r;
+
+ return bus_session_method_kill(message, session, error);
+}
+
+static int method_kill_user(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ Manager *m = userdata;
+ uint32_t uid;
+ User *user;
+ int r;
+
+ assert(message);
+ assert(m);
+
+ r = sd_bus_message_read(message, "u", &uid);
+ if (r < 0)
+ return r;
+
+ r = manager_get_user_from_creds(m, message, uid, error, &user);
+ if (r < 0)
+ return r;
+
+ return bus_user_method_kill(message, user, error);
+}
+
+static int method_terminate_session(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ Manager *m = userdata;
+ const char *name;
+ Session *session;
+ int r;
+
+ assert(message);
+ assert(m);
+
+ r = sd_bus_message_read(message, "s", &name);
+ if (r < 0)
+ return r;
+
+ r = manager_get_session_from_creds(m, message, name, error, &session);
+ if (r < 0)
+ return r;
+
+ return bus_session_method_terminate(message, session, error);
+}
+
+static int method_terminate_user(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ Manager *m = userdata;
+ uint32_t uid;
+ User *user;
+ int r;
+
+ assert(message);
+ assert(m);
+
+ r = sd_bus_message_read(message, "u", &uid);
+ if (r < 0)
+ return r;
+
+ r = manager_get_user_from_creds(m, message, uid, error, &user);
+ if (r < 0)
+ return r;
+
+ return bus_user_method_terminate(message, user, error);
+}
+
+static int method_terminate_seat(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ Manager *m = userdata;
+ const char *name;
+ Seat *seat;
+ int r;
+
+ assert(message);
+ assert(m);
+
+ r = sd_bus_message_read(message, "s", &name);
+ if (r < 0)
+ return r;
+
+ r = manager_get_seat_from_creds(m, message, name, error, &seat);
+ if (r < 0)
+ return r;
+
+ return bus_seat_method_terminate(message, seat, error);
+}
+
+static int method_set_user_linger(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ _cleanup_free_ char *cc = NULL;
+ Manager *m = userdata;
+ int r, b, interactive;
+ struct passwd *pw;
+ const char *path;
+ uint32_t uid;
+ bool self = false;
+
+ assert(message);
+ assert(m);
+
+ r = sd_bus_message_read(message, "ubb", &uid, &b, &interactive);
+ if (r < 0)
+ return r;
+
+ if (uid == UID_INVALID) {
+ _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
+
+ /* Note that we get the owner UID of the session, not the actual client UID here! */
+ r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_OWNER_UID|SD_BUS_CREDS_AUGMENT, &creds);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_creds_get_owner_uid(creds, &uid);
+ if (r < 0)
+ return r;
+
+ self = true;
+
+ } else if (!uid_is_valid(uid))
+ return -EINVAL;
+
+ errno = 0;
+ pw = getpwuid(uid);
+ if (!pw)
+ return errno > 0 ? -errno : -ENOENT;
+
+ r = bus_verify_polkit_async(
+ message,
+ CAP_SYS_ADMIN,
+ self ? "org.freedesktop.login1.set-self-linger" : "org.freedesktop.login1.set-user-linger",
+ NULL,
+ interactive,
+ UID_INVALID,
+ &m->polkit_registry,
+ error);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
+
+ mkdir_p_label("/var/lib/systemd", 0755);
+
+ r = mkdir_safe_label("/var/lib/systemd/linger", 0755, 0, 0);
+ if (r < 0)
+ return r;
+
+ cc = cescape(pw->pw_name);
+ if (!cc)
+ return -ENOMEM;
+
+ path = strjoina("/var/lib/systemd/linger/", cc);
+ if (b) {
+ User *u;
+
+ r = touch(path);
+ if (r < 0)
+ return r;
+
+ if (manager_add_user_by_uid(m, uid, &u) >= 0)
+ user_start(u);
+
+ } else {
+ User *u;
+
+ r = unlink(path);
+ if (r < 0 && errno != ENOENT)
+ return -errno;
+
+ u = hashmap_get(m->users, UID_TO_PTR(uid));
+ if (u)
+ user_add_to_gc_queue(u);
+ }
+
+ return sd_bus_reply_method_return(message, NULL);
+}
+
+static int trigger_device(Manager *m, struct udev_device *d) {
+ _cleanup_udev_enumerate_unref_ struct udev_enumerate *e = NULL;
+ struct udev_list_entry *first, *item;
+ int r;
+
+ assert(m);
+
+ e = udev_enumerate_new(m->udev);
+ if (!e)
+ return -ENOMEM;
+
+ if (d) {
+ r = udev_enumerate_add_match_parent(e, d);
+ if (r < 0)
+ return r;
+ }
+
+ r = udev_enumerate_scan_devices(e);
+ if (r < 0)
+ return r;
+
+ first = udev_enumerate_get_list_entry(e);
+ udev_list_entry_foreach(item, first) {
+ _cleanup_free_ char *t = NULL;
+ const char *p;
+
+ p = udev_list_entry_get_name(item);
+
+ t = strappend(p, "/uevent");
+ if (!t)
+ return -ENOMEM;
+
+ write_string_file(t, "change", WRITE_STRING_FILE_CREATE);
+ }
+
+ return 0;
+}
+
+static int attach_device(Manager *m, const char *seat, const char *sysfs) {
+ _cleanup_udev_device_unref_ struct udev_device *d = NULL;
+ _cleanup_free_ char *rule = NULL, *file = NULL;
+ const char *id_for_seat;
+ int r;
+
+ assert(m);
+ assert(seat);
+ assert(sysfs);
+
+ d = udev_device_new_from_syspath(m->udev, sysfs);
+ if (!d)
+ return -ENODEV;
+
+ if (!udev_device_has_tag(d, "seat"))
+ return -ENODEV;
+
+ id_for_seat = udev_device_get_property_value(d, "ID_FOR_SEAT");
+ if (!id_for_seat)
+ return -ENODEV;
+
+ if (asprintf(&file, "/etc/udev/rules.d/72-seat-%s.rules", id_for_seat) < 0)
+ return -ENOMEM;
+
+ if (asprintf(&rule, "TAG==\"seat\", ENV{ID_FOR_SEAT}==\"%s\", ENV{ID_SEAT}=\"%s\"", id_for_seat, seat) < 0)
+ return -ENOMEM;
+
+ mkdir_p_label("/etc/udev/rules.d", 0755);
+ r = write_string_file_atomic_label(file, rule);
+ if (r < 0)
+ return r;
+
+ return trigger_device(m, d);
+}
+
+static int flush_devices(Manager *m) {
+ _cleanup_closedir_ DIR *d;
+
+ assert(m);
+
+ d = opendir("/etc/udev/rules.d");
+ if (!d) {
+ if (errno != ENOENT)
+ log_warning_errno(errno, "Failed to open /etc/udev/rules.d: %m");
+ } else {
+ struct dirent *de;
+
+ while ((de = readdir(d))) {
+
+ if (!dirent_is_file(de))
+ continue;
+
+ if (!startswith(de->d_name, "72-seat-"))
+ continue;
+
+ if (!endswith(de->d_name, ".rules"))
+ continue;
+
+ if (unlinkat(dirfd(d), de->d_name, 0) < 0)
+ log_warning_errno(errno, "Failed to unlink %s: %m", de->d_name);
+ }
+ }
+
+ return trigger_device(m, NULL);
+}
+
+static int method_attach_device(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ const char *sysfs, *seat;
+ Manager *m = userdata;
+ int interactive, r;
+
+ assert(message);
+ assert(m);
+
+ r = sd_bus_message_read(message, "ssb", &seat, &sysfs, &interactive);
+ if (r < 0)
+ return r;
+
+ if (!path_startswith(sysfs, "/sys"))
+ return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Path %s is not in /sys", sysfs);
+
+ if (!seat_name_is_valid(seat))
+ return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Seat %s is not valid", seat);
+
+ r = bus_verify_polkit_async(
+ message,
+ CAP_SYS_ADMIN,
+ "org.freedesktop.login1.attach-device",
+ NULL,
+ interactive,
+ UID_INVALID,
+ &m->polkit_registry,
+ error);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
+
+ r = attach_device(m, seat, sysfs);
+ if (r < 0)
+ return r;
+
+ return sd_bus_reply_method_return(message, NULL);
+}
+
+static int method_flush_devices(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ Manager *m = userdata;
+ int interactive, r;
+
+ assert(message);
+ assert(m);
+
+ r = sd_bus_message_read(message, "b", &interactive);
+ if (r < 0)
+ return r;
+
+ r = bus_verify_polkit_async(
+ message,
+ CAP_SYS_ADMIN,
+ "org.freedesktop.login1.flush-devices",
+ NULL,
+ interactive,
+ UID_INVALID,
+ &m->polkit_registry,
+ error);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
+
+ r = flush_devices(m);
+ if (r < 0)
+ return r;
+
+ return sd_bus_reply_method_return(message, NULL);
+}
+
+static int have_multiple_sessions(
+ Manager *m,
+ uid_t uid) {
+
+ Session *session;
+ Iterator i;
+
+ assert(m);
+
+ /* Check for other users' sessions. Greeter sessions do not
+ * count, and non-login sessions do not count either. */
+ HASHMAP_FOREACH(session, m->sessions, i)
+ if (session->class == SESSION_USER &&
+ session->user->uid != uid)
+ return true;
+
+ return false;
+}
+
+static int bus_manager_log_shutdown(
+ Manager *m,
+ InhibitWhat w,
+ const char *unit_name) {
+
+ const char *p, *q;
+
+ assert(m);
+ assert(unit_name);
+
+ if (w != INHIBIT_SHUTDOWN)
+ return 0;
+
+ if (streq(unit_name, SPECIAL_POWEROFF_TARGET)) {
+ p = "MESSAGE=System is powering down";
+ q = "SHUTDOWN=power-off";
+ } else if (streq(unit_name, SPECIAL_HALT_TARGET)) {
+ p = "MESSAGE=System is halting";
+ q = "SHUTDOWN=halt";
+ } else if (streq(unit_name, SPECIAL_REBOOT_TARGET)) {
+ p = "MESSAGE=System is rebooting";
+ q = "SHUTDOWN=reboot";
+ } else if (streq(unit_name, SPECIAL_KEXEC_TARGET)) {
+ p = "MESSAGE=System is rebooting with kexec";
+ q = "SHUTDOWN=kexec";
+ } else {
+ p = "MESSAGE=System is shutting down";
+ q = NULL;
+ }
+
+ if (isempty(m->wall_message))
+ p = strjoina(p, ".");
+ else
+ p = strjoina(p, " (", m->wall_message, ").");
+
+ return log_struct(LOG_NOTICE,
+ LOG_MESSAGE_ID(SD_MESSAGE_SHUTDOWN),
+ p,
+ q,
+ NULL);
+}
+
+static int lid_switch_ignore_handler(sd_event_source *e, uint64_t usec, void *userdata) {
+ Manager *m = userdata;
+
+ assert(e);
+ assert(m);
+
+ m->lid_switch_ignore_event_source = sd_event_source_unref(m->lid_switch_ignore_event_source);
+ return 0;
+}
+
+int manager_set_lid_switch_ignore(Manager *m, usec_t until) {
+ int r;
+
+ assert(m);
+
+ if (until <= now(CLOCK_MONOTONIC))
+ return 0;
+
+ /* We want to ignore the lid switch for a while after each
+ * suspend, and after boot-up. Hence let's install a timer for
+ * this. As long as the event source exists we ignore the lid
+ * switch. */
+
+ if (m->lid_switch_ignore_event_source) {
+ usec_t u;
+
+ r = sd_event_source_get_time(m->lid_switch_ignore_event_source, &u);
+ if (r < 0)
+ return r;
+
+ if (until <= u)
+ return 0;
+
+ r = sd_event_source_set_time(m->lid_switch_ignore_event_source, until);
+ } else
+ r = sd_event_add_time(
+ m->event,
+ &m->lid_switch_ignore_event_source,
+ CLOCK_MONOTONIC,
+ until, 0,
+ lid_switch_ignore_handler, m);
+
+ return r;
+}
+
+static void reset_scheduled_shutdown(Manager *m) {
+ m->scheduled_shutdown_timeout_source = sd_event_source_unref(m->scheduled_shutdown_timeout_source);
+ m->wall_message_timeout_source = sd_event_source_unref(m->wall_message_timeout_source);
+ m->nologin_timeout_source = sd_event_source_unref(m->nologin_timeout_source);
+ m->scheduled_shutdown_type = mfree(m->scheduled_shutdown_type);
+ m->scheduled_shutdown_timeout = 0;
+ m->shutdown_dry_run = false;
+
+ if (m->unlink_nologin) {
+ (void) unlink("/run/nologin");
+ m->unlink_nologin = false;
+ }
+}
+
+static int execute_shutdown_or_sleep(
+ Manager *m,
+ InhibitWhat w,
+ const char *unit_name,
+ sd_bus_error *error) {
+
+ _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
+ char *c = NULL;
+ const char *p;
+ int r;
+
+ assert(m);
+ assert(w >= 0);
+ assert(w < _INHIBIT_WHAT_MAX);
+ assert(unit_name);
+
+ bus_manager_log_shutdown(m, w, unit_name);
+
+ if (m->shutdown_dry_run) {
+ log_info("Running in dry run, suppressing action.");
+ reset_scheduled_shutdown(m);
+ } else {
+ r = sd_bus_call_method(
+ m->bus,
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "StartUnit",
+ error,
+ &reply,
+ "ss", unit_name, "replace-irreversibly");
+ if (r < 0)
+ return r;
+
+ r = sd_bus_message_read(reply, "o", &p);
+ if (r < 0)
+ return r;
+
+ c = strdup(p);
+ if (!c)
+ return -ENOMEM;
+ }
+
+ m->action_unit = unit_name;
+ free(m->action_job);
+ m->action_job = c;
+ m->action_what = w;
+
+ /* Make sure the lid switch is ignored for a while */
+ manager_set_lid_switch_ignore(m, now(CLOCK_MONOTONIC) + m->holdoff_timeout_usec);
+
+ return 0;
+}
+
+int manager_dispatch_delayed(Manager *manager, bool timeout) {
+
+ _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+ Inhibitor *offending = NULL;
+ int r;
+
+ assert(manager);
+
+ if (manager->action_what == 0 || manager->action_job)
+ return 0;
+
+ if (manager_is_inhibited(manager, manager->action_what, INHIBIT_DELAY, NULL, false, false, 0, &offending)) {
+ _cleanup_free_ char *comm = NULL, *u = NULL;
+
+ if (!timeout)
+ return 0;
+
+ (void) get_process_comm(offending->pid, &comm);
+ u = uid_to_name(offending->uid);
+
+ log_notice("Delay lock is active (UID "UID_FMT"/%s, PID "PID_FMT"/%s) but inhibitor timeout is reached.",
+ offending->uid, strna(u),
+ offending->pid, strna(comm));
+ }
+
+ /* Actually do the operation */
+ r = execute_shutdown_or_sleep(manager, manager->action_what, manager->action_unit, &error);
+ if (r < 0) {
+ log_warning("Failed to send delayed message: %s", bus_error_message(&error, r));
+
+ manager->action_unit = NULL;
+ manager->action_what = 0;
+ return r;
+ }
+
+ return 1;
+}
+
+static int manager_inhibit_timeout_handler(
+ sd_event_source *s,
+ uint64_t usec,
+ void *userdata) {
+
+ Manager *manager = userdata;
+ int r;
+
+ assert(manager);
+ assert(manager->inhibit_timeout_source == s);
+
+ r = manager_dispatch_delayed(manager, true);
+ return (r < 0) ? r : 0;
+}
+
+static int delay_shutdown_or_sleep(
+ Manager *m,
+ InhibitWhat w,
+ const char *unit_name) {
+
+ int r;
+ usec_t timeout_val;
+
+ assert(m);
+ assert(w >= 0);
+ assert(w < _INHIBIT_WHAT_MAX);
+ assert(unit_name);
+
+ timeout_val = now(CLOCK_MONOTONIC) + m->inhibit_delay_max;
+
+ if (m->inhibit_timeout_source) {
+ r = sd_event_source_set_time(m->inhibit_timeout_source, timeout_val);
+ if (r < 0)
+ return log_error_errno(r, "sd_event_source_set_time() failed: %m");
+
+ r = sd_event_source_set_enabled(m->inhibit_timeout_source, SD_EVENT_ONESHOT);
+ if (r < 0)
+ return log_error_errno(r, "sd_event_source_set_enabled() failed: %m");
+ } else {
+ r = sd_event_add_time(m->event, &m->inhibit_timeout_source, CLOCK_MONOTONIC,
+ timeout_val, 0, manager_inhibit_timeout_handler, m);
+ if (r < 0)
+ return r;
+ }
+
+ m->action_unit = unit_name;
+ m->action_what = w;
+
+ return 0;
+}
+
+static int send_prepare_for(Manager *m, InhibitWhat w, bool _active) {
+
+ static const char * const signal_name[_INHIBIT_WHAT_MAX] = {
+ [INHIBIT_SHUTDOWN] = "PrepareForShutdown",
+ [INHIBIT_SLEEP] = "PrepareForSleep"
+ };
+
+ int active = _active;
+
+ assert(m);
+ assert(w >= 0);
+ assert(w < _INHIBIT_WHAT_MAX);
+ assert(signal_name[w]);
+
+ return sd_bus_emit_signal(m->bus,
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ signal_name[w],
+ "b",
+ active);
+}
+
+int bus_manager_shutdown_or_sleep_now_or_later(
+ Manager *m,
+ const char *unit_name,
+ InhibitWhat w,
+ sd_bus_error *error) {
+
+ bool delayed;
+ int r;
+
+ assert(m);
+ assert(unit_name);
+ assert(w >= 0);
+ assert(w <= _INHIBIT_WHAT_MAX);
+ assert(!m->action_job);
+
+ /* Tell everybody to prepare for shutdown/sleep */
+ send_prepare_for(m, w, true);
+
+ delayed =
+ m->inhibit_delay_max > 0 &&
+ manager_is_inhibited(m, w, INHIBIT_DELAY, NULL, false, false, 0, NULL);
+
+ if (delayed)
+ /* Shutdown is delayed, keep in mind what we
+ * want to do, and start a timeout */
+ r = delay_shutdown_or_sleep(m, w, unit_name);
+ else
+ /* Shutdown is not delayed, execute it
+ * immediately */
+ r = execute_shutdown_or_sleep(m, w, unit_name, error);
+
+ return r;
+}
+
+static int verify_shutdown_creds(
+ Manager *m,
+ sd_bus_message *message,
+ InhibitWhat w,
+ bool interactive,
+ const char *action,
+ const char *action_multiple_sessions,
+ const char *action_ignore_inhibit,
+ sd_bus_error *error) {
+
+ _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
+ bool multiple_sessions, blocked;
+ uid_t uid;
+ int r;
+
+ assert(m);
+ assert(message);
+ assert(w >= 0);
+ assert(w <= _INHIBIT_WHAT_MAX);
+
+ r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_EUID, &creds);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_creds_get_euid(creds, &uid);
+ if (r < 0)
+ return r;
+
+ r = have_multiple_sessions(m, uid);
+ if (r < 0)
+ return r;
+
+ multiple_sessions = r > 0;
+ blocked = manager_is_inhibited(m, w, INHIBIT_BLOCK, NULL, false, true, uid, NULL);
+
+ if (multiple_sessions && action_multiple_sessions) {
+ r = bus_verify_polkit_async(message, CAP_SYS_BOOT, action_multiple_sessions, NULL, interactive, UID_INVALID, &m->polkit_registry, error);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
+ }
+
+ if (blocked && action_ignore_inhibit) {
+ r = bus_verify_polkit_async(message, CAP_SYS_BOOT, action_ignore_inhibit, NULL, interactive, UID_INVALID, &m->polkit_registry, error);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
+ }
+
+ if (!multiple_sessions && !blocked && action) {
+ r = bus_verify_polkit_async(message, CAP_SYS_BOOT, action, NULL, interactive, UID_INVALID, &m->polkit_registry, error);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
+ }
+
+ return 0;
+}
+
+static int method_do_shutdown_or_sleep(
+ Manager *m,
+ sd_bus_message *message,
+ const char *unit_name,
+ InhibitWhat w,
+ const char *action,
+ const char *action_multiple_sessions,
+ const char *action_ignore_inhibit,
+ const char *sleep_verb,
+ sd_bus_error *error) {
+
+ int interactive, r;
+
+ assert(m);
+ assert(message);
+ assert(unit_name);
+ assert(w >= 0);
+ assert(w <= _INHIBIT_WHAT_MAX);
+
+ r = sd_bus_message_read(message, "b", &interactive);
+ if (r < 0)
+ return r;
+
+ /* Don't allow multiple jobs being executed at the same time */
+ if (m->action_what)
+ return sd_bus_error_setf(error, BUS_ERROR_OPERATION_IN_PROGRESS, "There's already a shutdown or sleep operation in progress");
+
+ if (sleep_verb) {
+ r = can_sleep(sleep_verb);
+ if (r < 0)
+ return r;
+
+ if (r == 0)
+ return sd_bus_error_setf(error, BUS_ERROR_SLEEP_VERB_NOT_SUPPORTED, "Sleep verb not supported");
+ }
+
+ r = verify_shutdown_creds(m, message, w, interactive, action, action_multiple_sessions,
+ action_ignore_inhibit, error);
+ if (r != 0)
+ return r;
+
+ r = bus_manager_shutdown_or_sleep_now_or_later(m, unit_name, w, error);
+ if (r < 0)
+ return r;
+
+ return sd_bus_reply_method_return(message, NULL);
+}
+
+static int method_poweroff(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ Manager *m = userdata;
+
+ return method_do_shutdown_or_sleep(
+ m, message,
+ SPECIAL_POWEROFF_TARGET,
+ INHIBIT_SHUTDOWN,
+ "org.freedesktop.login1.power-off",
+ "org.freedesktop.login1.power-off-multiple-sessions",
+ "org.freedesktop.login1.power-off-ignore-inhibit",
+ NULL,
+ error);
+}
+
+static int method_reboot(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ Manager *m = userdata;
+
+ return method_do_shutdown_or_sleep(
+ m, message,
+ SPECIAL_REBOOT_TARGET,
+ INHIBIT_SHUTDOWN,
+ "org.freedesktop.login1.reboot",
+ "org.freedesktop.login1.reboot-multiple-sessions",
+ "org.freedesktop.login1.reboot-ignore-inhibit",
+ NULL,
+ error);
+}
+
+static int method_suspend(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ Manager *m = userdata;
+
+ return method_do_shutdown_or_sleep(
+ m, message,
+ SPECIAL_SUSPEND_TARGET,
+ INHIBIT_SLEEP,
+ "org.freedesktop.login1.suspend",
+ "org.freedesktop.login1.suspend-multiple-sessions",
+ "org.freedesktop.login1.suspend-ignore-inhibit",
+ "suspend",
+ error);
+}
+
+static int nologin_timeout_handler(
+ sd_event_source *s,
+ uint64_t usec,
+ void *userdata) {
+
+ Manager *m = userdata;
+ int r;
+
+ log_info("Creating /run/nologin, blocking further logins...");
+
+ r = write_string_file_atomic_label("/run/nologin", "System is going down.");
+ if (r < 0)
+ log_error_errno(r, "Failed to create /run/nologin: %m");
+ else
+ m->unlink_nologin = true;
+
+ return 0;
+}
+
+static int update_schedule_file(Manager *m) {
+ _cleanup_free_ char *temp_path = NULL;
+ _cleanup_fclose_ FILE *f = NULL;
+ int r;
+
+ assert(m);
+
+ r = mkdir_safe_label("/run/systemd/shutdown", 0755, 0, 0);
+ if (r < 0)
+ return log_error_errno(r, "Failed to create shutdown subdirectory: %m");
+
+ r = fopen_temporary("/run/systemd/shutdown/scheduled", &f, &temp_path);
+ if (r < 0)
+ return log_error_errno(r, "Failed to save information about scheduled shutdowns: %m");
+
+ (void) fchmod(fileno(f), 0644);
+
+ fprintf(f,
+ "USEC="USEC_FMT"\n"
+ "WARN_WALL=%i\n"
+ "MODE=%s\n",
+ m->scheduled_shutdown_timeout,
+ m->enable_wall_messages,
+ m->scheduled_shutdown_type);
+
+ if (!isempty(m->wall_message)) {
+ _cleanup_free_ char *t;
+
+ t = cescape(m->wall_message);
+ if (!t) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ fprintf(f, "WALL_MESSAGE=%s\n", t);
+ }
+
+ r = fflush_and_check(f);
+ if (r < 0)
+ goto fail;
+
+ if (rename(temp_path, "/run/systemd/shutdown/scheduled") < 0) {
+ r = -errno;
+ goto fail;
+ }
+
+ return 0;
+
+fail:
+ (void) unlink(temp_path);
+ (void) unlink("/run/systemd/shutdown/scheduled");
+
+ return log_error_errno(r, "Failed to write information about scheduled shutdowns: %m");
+}
+
+static int manager_scheduled_shutdown_handler(
+ sd_event_source *s,
+ uint64_t usec,
+ void *userdata) {
+
+ _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+ Manager *m = userdata;
+ const char *target;
+ int r;
+
+ assert(m);
+
+ if (isempty(m->scheduled_shutdown_type))
+ return 0;
+
+ if (streq(m->scheduled_shutdown_type, "halt"))
+ target = SPECIAL_HALT_TARGET;
+ else if (streq(m->scheduled_shutdown_type, "poweroff"))
+ target = SPECIAL_POWEROFF_TARGET;
+ else
+ target = SPECIAL_REBOOT_TARGET;
+
+ r = execute_shutdown_or_sleep(m, 0, target, &error);
+ if (r < 0)
+ return log_error_errno(r, "Unable to execute transition to %s: %m", target);
+
+ return 0;
+}
+
+static int method_schedule_shutdown(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ Manager *m = userdata;
+ _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
+ const char *action_multiple_sessions = NULL;
+ const char *action_ignore_inhibit = NULL;
+ const char *action = NULL;
+ uint64_t elapse;
+ char *type;
+ int r;
+
+ assert(m);
+ assert(message);
+
+ r = sd_bus_message_read(message, "st", &type, &elapse);
+ if (r < 0)
+ return r;
+
+ if (startswith(type, "dry-")) {
+ type += 4;
+ m->shutdown_dry_run = true;
+ }
+
+ if (streq(type, "reboot")) {
+ action = "org.freedesktop.login1.reboot";
+ action_multiple_sessions = "org.freedesktop.login1.reboot-multiple-sessions";
+ action_ignore_inhibit = "org.freedesktop.login1.reboot-ignore-inhibit";
+ } else if (streq(type, "halt")) {
+ action = "org.freedesktop.login1.halt";
+ action_multiple_sessions = "org.freedesktop.login1.halt-multiple-sessions";
+ action_ignore_inhibit = "org.freedesktop.login1.halt-ignore-inhibit";
+ } else if (streq(type, "poweroff")) {
+ action = "org.freedesktop.login1.power-off";
+ action_multiple_sessions = "org.freedesktop.login1.power-off-multiple-sessions";
+ action_ignore_inhibit = "org.freedesktop.login1.power-off-ignore-inhibit";
+ } else
+ return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Unsupported shutdown type");
+
+ r = verify_shutdown_creds(m, message, INHIBIT_SHUTDOWN, false,
+ action, action_multiple_sessions, action_ignore_inhibit, error);
+ if (r != 0)
+ return r;
+
+ if (m->scheduled_shutdown_timeout_source) {
+ r = sd_event_source_set_time(m->scheduled_shutdown_timeout_source, elapse);
+ if (r < 0)
+ return log_error_errno(r, "sd_event_source_set_time() failed: %m");
+
+ r = sd_event_source_set_enabled(m->scheduled_shutdown_timeout_source, SD_EVENT_ONESHOT);
+ if (r < 0)
+ return log_error_errno(r, "sd_event_source_set_enabled() failed: %m");
+ } else {
+ r = sd_event_add_time(m->event, &m->scheduled_shutdown_timeout_source,
+ CLOCK_REALTIME, elapse, 0, manager_scheduled_shutdown_handler, m);
+ if (r < 0)
+ return log_error_errno(r, "sd_event_add_time() failed: %m");
+ }
+
+ r = free_and_strdup(&m->scheduled_shutdown_type, type);
+ if (r < 0) {
+ m->scheduled_shutdown_timeout_source = sd_event_source_unref(m->scheduled_shutdown_timeout_source);
+ return log_oom();
+ }
+
+ if (m->nologin_timeout_source) {
+ r = sd_event_source_set_time(m->nologin_timeout_source, elapse);
+ if (r < 0)
+ return log_error_errno(r, "sd_event_source_set_time() failed: %m");
+
+ r = sd_event_source_set_enabled(m->nologin_timeout_source, SD_EVENT_ONESHOT);
+ if (r < 0)
+ return log_error_errno(r, "sd_event_source_set_enabled() failed: %m");
+ } else {
+ r = sd_event_add_time(m->event, &m->nologin_timeout_source,
+ CLOCK_REALTIME, elapse - 5 * USEC_PER_MINUTE, 0, nologin_timeout_handler, m);
+ if (r < 0)
+ return log_error_errno(r, "sd_event_add_time() failed: %m");
+ }
+
+ m->scheduled_shutdown_timeout = elapse;
+
+ r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_AUGMENT|SD_BUS_CREDS_TTY|SD_BUS_CREDS_UID, &creds);
+ if (r >= 0) {
+ const char *tty = NULL;
+
+ (void) sd_bus_creds_get_uid(creds, &m->scheduled_shutdown_uid);
+ (void) sd_bus_creds_get_tty(creds, &tty);
+
+ r = free_and_strdup(&m->scheduled_shutdown_tty, tty);
+ if (r < 0) {
+ m->scheduled_shutdown_timeout_source = sd_event_source_unref(m->scheduled_shutdown_timeout_source);
+ return log_oom();
+ }
+ }
+
+ r = manager_setup_wall_message_timer(m);
+ if (r < 0)
+ return r;
+
+ if (!isempty(type)) {
+ r = update_schedule_file(m);
+ if (r < 0)
+ return r;
+ } else
+ (void) unlink("/run/systemd/shutdown/scheduled");
+
+ return sd_bus_reply_method_return(message, NULL);
+}
+
+static int method_cancel_scheduled_shutdown(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ Manager *m = userdata;
+ bool cancelled;
+
+ assert(m);
+ assert(message);
+
+ cancelled = m->scheduled_shutdown_type != NULL;
+ reset_scheduled_shutdown(m);
+
+ if (cancelled) {
+ _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
+ const char *tty = NULL;
+ uid_t uid = 0;
+ int r;
+
+ r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_AUGMENT|SD_BUS_CREDS_TTY|SD_BUS_CREDS_UID, &creds);
+ if (r >= 0) {
+ (void) sd_bus_creds_get_uid(creds, &uid);
+ (void) sd_bus_creds_get_tty(creds, &tty);
+ }
+
+ utmp_wall("The system shutdown has been cancelled",
+ uid_to_name(uid), tty, logind_wall_tty_filter, m);
+ }
+
+ return sd_bus_reply_method_return(message, "b", cancelled);
+}
+
+static int method_hibernate(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ Manager *m = userdata;
+
+ return method_do_shutdown_or_sleep(
+ m, message,
+ SPECIAL_HIBERNATE_TARGET,
+ INHIBIT_SLEEP,
+ "org.freedesktop.login1.hibernate",
+ "org.freedesktop.login1.hibernate-multiple-sessions",
+ "org.freedesktop.login1.hibernate-ignore-inhibit",
+ "hibernate",
+ error);
+}
+
+static int method_hybrid_sleep(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ Manager *m = userdata;
+
+ return method_do_shutdown_or_sleep(
+ m, message,
+ SPECIAL_HYBRID_SLEEP_TARGET,
+ INHIBIT_SLEEP,
+ "org.freedesktop.login1.hibernate",
+ "org.freedesktop.login1.hibernate-multiple-sessions",
+ "org.freedesktop.login1.hibernate-ignore-inhibit",
+ "hybrid-sleep",
+ error);
+}
+
+static int method_can_shutdown_or_sleep(
+ Manager *m,
+ sd_bus_message *message,
+ InhibitWhat w,
+ const char *action,
+ const char *action_multiple_sessions,
+ const char *action_ignore_inhibit,
+ const char *sleep_verb,
+ sd_bus_error *error) {
+
+ _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
+ bool multiple_sessions, challenge, blocked;
+ const char *result = NULL;
+ uid_t uid;
+ int r;
+
+ assert(m);
+ assert(message);
+ assert(w >= 0);
+ assert(w <= _INHIBIT_WHAT_MAX);
+ assert(action);
+ assert(action_multiple_sessions);
+ assert(action_ignore_inhibit);
+
+ if (sleep_verb) {
+ r = can_sleep(sleep_verb);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ return sd_bus_reply_method_return(message, "s", "na");
+ }
+
+ r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_EUID, &creds);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_creds_get_euid(creds, &uid);
+ if (r < 0)
+ return r;
+
+ r = have_multiple_sessions(m, uid);
+ if (r < 0)
+ return r;
+
+ multiple_sessions = r > 0;
+ blocked = manager_is_inhibited(m, w, INHIBIT_BLOCK, NULL, false, true, uid, NULL);
+
+ if (multiple_sessions) {
+ r = bus_test_polkit(message, CAP_SYS_BOOT, action_multiple_sessions, NULL, UID_INVALID, &challenge, error);
+ if (r < 0)
+ return r;
+
+ if (r > 0)
+ result = "yes";
+ else if (challenge)
+ result = "challenge";
+ else
+ result = "no";
+ }
+
+ if (blocked) {
+ r = bus_test_polkit(message, CAP_SYS_BOOT, action_ignore_inhibit, NULL, UID_INVALID, &challenge, error);
+ if (r < 0)
+ return r;
+
+ if (r > 0 && !result)
+ result = "yes";
+ else if (challenge && (!result || streq(result, "yes")))
+ result = "challenge";
+ else
+ result = "no";
+ }
+
+ if (!multiple_sessions && !blocked) {
+ /* If neither inhibit nor multiple sessions
+ * apply then just check the normal policy */
+
+ r = bus_test_polkit(message, CAP_SYS_BOOT, action, NULL, UID_INVALID, &challenge, error);
+ if (r < 0)
+ return r;
+
+ if (r > 0)
+ result = "yes";
+ else if (challenge)
+ result = "challenge";
+ else
+ result = "no";
+ }
+
+ return sd_bus_reply_method_return(message, "s", result);
+}
+
+static int method_can_poweroff(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ Manager *m = userdata;
+
+ return method_can_shutdown_or_sleep(
+ m, message,
+ INHIBIT_SHUTDOWN,
+ "org.freedesktop.login1.power-off",
+ "org.freedesktop.login1.power-off-multiple-sessions",
+ "org.freedesktop.login1.power-off-ignore-inhibit",
+ NULL,
+ error);
+}
+
+static int method_can_reboot(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ Manager *m = userdata;
+
+ return method_can_shutdown_or_sleep(
+ m, message,
+ INHIBIT_SHUTDOWN,
+ "org.freedesktop.login1.reboot",
+ "org.freedesktop.login1.reboot-multiple-sessions",
+ "org.freedesktop.login1.reboot-ignore-inhibit",
+ NULL,
+ error);
+}
+
+static int method_can_suspend(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ Manager *m = userdata;
+
+ return method_can_shutdown_or_sleep(
+ m, message,
+ INHIBIT_SLEEP,
+ "org.freedesktop.login1.suspend",
+ "org.freedesktop.login1.suspend-multiple-sessions",
+ "org.freedesktop.login1.suspend-ignore-inhibit",
+ "suspend",
+ error);
+}
+
+static int method_can_hibernate(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ Manager *m = userdata;
+
+ return method_can_shutdown_or_sleep(
+ m, message,
+ INHIBIT_SLEEP,
+ "org.freedesktop.login1.hibernate",
+ "org.freedesktop.login1.hibernate-multiple-sessions",
+ "org.freedesktop.login1.hibernate-ignore-inhibit",
+ "hibernate",
+ error);
+}
+
+static int method_can_hybrid_sleep(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ Manager *m = userdata;
+
+ return method_can_shutdown_or_sleep(
+ m, message,
+ INHIBIT_SLEEP,
+ "org.freedesktop.login1.hibernate",
+ "org.freedesktop.login1.hibernate-multiple-sessions",
+ "org.freedesktop.login1.hibernate-ignore-inhibit",
+ "hybrid-sleep",
+ error);
+}
+
+static int property_get_reboot_to_firmware_setup(
+ sd_bus *bus,
+ const char *path,
+ const char *interface,
+ const char *property,
+ sd_bus_message *reply,
+ void *userdata,
+ sd_bus_error *error) {
+ int r;
+
+ assert(bus);
+ assert(reply);
+ assert(userdata);
+
+ r = efi_get_reboot_to_firmware();
+ if (r < 0 && r != -EOPNOTSUPP)
+ return r;
+
+ return sd_bus_message_append(reply, "b", r > 0);
+}
+
+static int method_set_reboot_to_firmware_setup(
+ sd_bus_message *message,
+ void *userdata,
+ sd_bus_error *error) {
+
+ int b, r;
+ Manager *m = userdata;
+
+ assert(message);
+ assert(m);
+
+ r = sd_bus_message_read(message, "b", &b);
+ if (r < 0)
+ return r;
+
+ r = bus_verify_polkit_async(message,
+ CAP_SYS_ADMIN,
+ "org.freedesktop.login1.set-reboot-to-firmware-setup",
+ NULL,
+ false,
+ UID_INVALID,
+ &m->polkit_registry,
+ error);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
+
+ r = efi_set_reboot_to_firmware(b);
+ if (r < 0)
+ return r;
+
+ return sd_bus_reply_method_return(message, NULL);
+}
+
+static int method_can_reboot_to_firmware_setup(
+ sd_bus_message *message,
+ void *userdata,
+ sd_bus_error *error) {
+
+ int r;
+ bool challenge;
+ const char *result;
+ Manager *m = userdata;
+
+ assert(message);
+ assert(m);
+
+ r = efi_reboot_to_firmware_supported();
+ if (r == -EOPNOTSUPP)
+ return sd_bus_reply_method_return(message, "s", "na");
+ else if (r < 0)
+ return r;
+
+ r = bus_test_polkit(message,
+ CAP_SYS_ADMIN,
+ "org.freedesktop.login1.set-reboot-to-firmware-setup",
+ NULL,
+ UID_INVALID,
+ &challenge,
+ error);
+ if (r < 0)
+ return r;
+
+ if (r > 0)
+ result = "yes";
+ else if (challenge)
+ result = "challenge";
+ else
+ result = "no";
+
+ return sd_bus_reply_method_return(message, "s", result);
+}
+
+static int method_set_wall_message(
+ sd_bus_message *message,
+ void *userdata,
+ sd_bus_error *error) {
+
+ int r;
+ Manager *m = userdata;
+ char *wall_message;
+ int enable_wall_messages;
+
+ assert(message);
+ assert(m);
+
+ r = sd_bus_message_read(message, "sb", &wall_message, &enable_wall_messages);
+ if (r < 0)
+ return r;
+
+ r = bus_verify_polkit_async(message,
+ CAP_SYS_ADMIN,
+ "org.freedesktop.login1.set-wall-message",
+ NULL,
+ false,
+ UID_INVALID,
+ &m->polkit_registry,
+ error);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ return 1; /* Will call us back */
+
+ if (isempty(wall_message))
+ m->wall_message = mfree(m->wall_message);
+ else {
+ r = free_and_strdup(&m->wall_message, wall_message);
+ if (r < 0)
+ return log_oom();
+ }
+
+ m->enable_wall_messages = enable_wall_messages;
+
+ return sd_bus_reply_method_return(message, NULL);
+}
+
+static int method_inhibit(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
+ const char *who, *why, *what, *mode;
+ _cleanup_free_ char *id = NULL;
+ _cleanup_close_ int fifo_fd = -1;
+ Manager *m = userdata;
+ Inhibitor *i = NULL;
+ InhibitMode mm;
+ InhibitWhat w;
+ pid_t pid;
+ uid_t uid;
+ int r;
+
+ assert(message);
+ assert(m);
+
+ r = sd_bus_message_read(message, "ssss", &what, &who, &why, &mode);
+ if (r < 0)
+ return r;
+
+ w = inhibit_what_from_string(what);
+ if (w <= 0)
+ return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid what specification %s", what);
+
+ mm = inhibit_mode_from_string(mode);
+ if (mm < 0)
+ return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid mode specification %s", mode);
+
+ /* Delay is only supported for shutdown/sleep */
+ if (mm == INHIBIT_DELAY && (w & ~(INHIBIT_SHUTDOWN|INHIBIT_SLEEP)))
+ return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Delay inhibitors only supported for shutdown and sleep");
+
+ /* Don't allow taking delay locks while we are already
+ * executing the operation. We shouldn't create the impression
+ * that the lock was successful if the machine is about to go
+ * down/suspend any moment. */
+ if (m->action_what & w)
+ return sd_bus_error_setf(error, BUS_ERROR_OPERATION_IN_PROGRESS, "The operation inhibition has been requested for is already running");
+
+ r = bus_verify_polkit_async(
+ message,
+ CAP_SYS_BOOT,
+ w == INHIBIT_SHUTDOWN ? (mm == INHIBIT_BLOCK ? "org.freedesktop.login1.inhibit-block-shutdown" : "org.freedesktop.login1.inhibit-delay-shutdown") :
+ w == INHIBIT_SLEEP ? (mm == INHIBIT_BLOCK ? "org.freedesktop.login1.inhibit-block-sleep" : "org.freedesktop.login1.inhibit-delay-sleep") :
+ w == INHIBIT_IDLE ? "org.freedesktop.login1.inhibit-block-idle" :
+ w == INHIBIT_HANDLE_POWER_KEY ? "org.freedesktop.login1.inhibit-handle-power-key" :
+ w == INHIBIT_HANDLE_SUSPEND_KEY ? "org.freedesktop.login1.inhibit-handle-suspend-key" :
+ w == INHIBIT_HANDLE_HIBERNATE_KEY ? "org.freedesktop.login1.inhibit-handle-hibernate-key" :
+ "org.freedesktop.login1.inhibit-handle-lid-switch",
+ NULL,
+ false,
+ UID_INVALID,
+ &m->polkit_registry,
+ error);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
+
+ r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_EUID|SD_BUS_CREDS_PID, &creds);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_creds_get_euid(creds, &uid);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_creds_get_pid(creds, &pid);
+ if (r < 0)
+ return r;
+
+ if (hashmap_size(m->inhibitors) >= m->inhibitors_max)
+ return sd_bus_error_setf(error, SD_BUS_ERROR_LIMITS_EXCEEDED, "Maximum number of inhibitors (%" PRIu64 ") reached, refusing further inhibitors.", m->inhibitors_max);
+
+ do {
+ id = mfree(id);
+
+ if (asprintf(&id, "%lu", ++m->inhibit_counter) < 0)
+ return -ENOMEM;
+
+ } while (hashmap_get(m->inhibitors, id));
+
+ r = manager_add_inhibitor(m, id, &i);
+ if (r < 0)
+ return r;
+
+ i->what = w;
+ i->mode = mm;
+ i->pid = pid;
+ i->uid = uid;
+ i->why = strdup(why);
+ i->who = strdup(who);
+
+ if (!i->why || !i->who) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ fifo_fd = inhibitor_create_fifo(i);
+ if (fifo_fd < 0) {
+ r = fifo_fd;
+ goto fail;
+ }
+
+ inhibitor_start(i);
+
+ return sd_bus_reply_method_return(message, "h", fifo_fd);
+
+fail:
+ if (i)
+ inhibitor_free(i);
+
+ return r;
+}
+
+const sd_bus_vtable manager_vtable[] = {
+ SD_BUS_VTABLE_START(0),
+
+ SD_BUS_WRITABLE_PROPERTY("EnableWallMessages", "b", NULL, NULL, offsetof(Manager, enable_wall_messages), 0),
+ SD_BUS_WRITABLE_PROPERTY("WallMessage", "s", NULL, NULL, offsetof(Manager, wall_message), 0),
+
+ SD_BUS_PROPERTY("NAutoVTs", "u", NULL, offsetof(Manager, n_autovts), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("KillOnlyUsers", "as", NULL, offsetof(Manager, kill_only_users), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("KillExcludeUsers", "as", NULL, offsetof(Manager, kill_exclude_users), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("KillUserProcesses", "b", NULL, offsetof(Manager, kill_user_processes), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("RebootToFirmwareSetup", "b", property_get_reboot_to_firmware_setup, 0, SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("IdleHint", "b", property_get_idle_hint, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
+ SD_BUS_PROPERTY("IdleSinceHint", "t", property_get_idle_since_hint, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
+ SD_BUS_PROPERTY("IdleSinceHintMonotonic", "t", property_get_idle_since_hint, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
+ SD_BUS_PROPERTY("BlockInhibited", "s", property_get_inhibited, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
+ SD_BUS_PROPERTY("DelayInhibited", "s", property_get_inhibited, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
+ SD_BUS_PROPERTY("InhibitDelayMaxUSec", "t", NULL, offsetof(Manager, inhibit_delay_max), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("HandlePowerKey", "s", property_get_handle_action, offsetof(Manager, handle_power_key), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("HandleSuspendKey", "s", property_get_handle_action, offsetof(Manager, handle_suspend_key), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("HandleHibernateKey", "s", property_get_handle_action, offsetof(Manager, handle_hibernate_key), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("HandleLidSwitch", "s", property_get_handle_action, offsetof(Manager, handle_lid_switch), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("HandleLidSwitchDocked", "s", property_get_handle_action, offsetof(Manager, handle_lid_switch_docked), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("HoldoffTimeoutUSec", "t", NULL, offsetof(Manager, holdoff_timeout_usec), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("IdleAction", "s", property_get_handle_action, offsetof(Manager, idle_action), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("IdleActionUSec", "t", NULL, offsetof(Manager, idle_action_usec), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("PreparingForShutdown", "b", property_get_preparing, 0, 0),
+ SD_BUS_PROPERTY("PreparingForSleep", "b", property_get_preparing, 0, 0),
+ SD_BUS_PROPERTY("ScheduledShutdown", "(st)", property_get_scheduled_shutdown, 0, 0),
+ SD_BUS_PROPERTY("Docked", "b", property_get_docked, 0, 0),
+ SD_BUS_PROPERTY("RemoveIPC", "b", bus_property_get_bool, offsetof(Manager, remove_ipc), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("RuntimeDirectorySize", "t", bus_property_get_size, offsetof(Manager, runtime_dir_size), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("InhibitorsMax", "t", NULL, offsetof(Manager, inhibitors_max), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("NCurrentInhibitors", "t", property_get_current_inhibitors, 0, 0),
+ SD_BUS_PROPERTY("SessionsMax", "t", NULL, offsetof(Manager, sessions_max), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("NCurrentSessions", "t", property_get_current_sessions, 0, 0),
+ SD_BUS_PROPERTY("UserTasksMax", "t", NULL, offsetof(Manager, user_tasks_max), SD_BUS_VTABLE_PROPERTY_CONST),
+
+ SD_BUS_METHOD("GetSession", "s", "o", method_get_session, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("GetSessionByPID", "u", "o", method_get_session_by_pid, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("GetUser", "u", "o", method_get_user, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("GetUserByPID", "u", "o", method_get_user_by_pid, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("GetSeat", "s", "o", method_get_seat, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("ListSessions", NULL, "a(susso)", method_list_sessions, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("ListUsers", NULL, "a(uso)", method_list_users, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("ListSeats", NULL, "a(so)", method_list_seats, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("ListInhibitors", NULL, "a(ssssuu)", method_list_inhibitors, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("CreateSession", "uusssssussbssa(sv)", "soshusub", method_create_session, 0),
+ SD_BUS_METHOD("ReleaseSession", "s", NULL, method_release_session, 0),
+ SD_BUS_METHOD("ActivateSession", "s", NULL, method_activate_session, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("ActivateSessionOnSeat", "ss", NULL, method_activate_session_on_seat, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("LockSession", "s", NULL, method_lock_session, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("UnlockSession", "s", NULL, method_lock_session, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("LockSessions", NULL, NULL, method_lock_sessions, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("UnlockSessions", NULL, NULL, method_lock_sessions, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("KillSession", "ssi", NULL, method_kill_session, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("KillUser", "ui", NULL, method_kill_user, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("TerminateSession", "s", NULL, method_terminate_session, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("TerminateUser", "u", NULL, method_terminate_user, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("TerminateSeat", "s", NULL, method_terminate_seat, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("SetUserLinger", "ubb", NULL, method_set_user_linger, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("AttachDevice", "ssb", NULL, method_attach_device, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("FlushDevices", "b", NULL, method_flush_devices, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("PowerOff", "b", NULL, method_poweroff, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("Reboot", "b", NULL, method_reboot, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("Suspend", "b", NULL, method_suspend, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("Hibernate", "b", NULL, method_hibernate, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("HybridSleep", "b", NULL, method_hybrid_sleep, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("CanPowerOff", NULL, "s", method_can_poweroff, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("CanReboot", NULL, "s", method_can_reboot, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("CanSuspend", NULL, "s", method_can_suspend, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("CanHibernate", NULL, "s", method_can_hibernate, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("CanHybridSleep", NULL, "s", method_can_hybrid_sleep, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("ScheduleShutdown", "st", NULL, method_schedule_shutdown, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("CancelScheduledShutdown", NULL, "b", method_cancel_scheduled_shutdown, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("Inhibit", "ssss", "h", method_inhibit, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("CanRebootToFirmwareSetup", NULL, "s", method_can_reboot_to_firmware_setup, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("SetRebootToFirmwareSetup", "b", NULL, method_set_reboot_to_firmware_setup, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("SetWallMessage", "sb", NULL, method_set_wall_message, SD_BUS_VTABLE_UNPRIVILEGED),
+
+ SD_BUS_SIGNAL("SessionNew", "so", 0),
+ SD_BUS_SIGNAL("SessionRemoved", "so", 0),
+ SD_BUS_SIGNAL("UserNew", "uo", 0),
+ SD_BUS_SIGNAL("UserRemoved", "uo", 0),
+ SD_BUS_SIGNAL("SeatNew", "so", 0),
+ SD_BUS_SIGNAL("SeatRemoved", "so", 0),
+ SD_BUS_SIGNAL("PrepareForShutdown", "b", 0),
+ SD_BUS_SIGNAL("PrepareForSleep", "b", 0),
+
+ SD_BUS_VTABLE_END
+};
+
+static int session_jobs_reply(Session *s, const char *unit, const char *result) {
+ int r = 0;
+
+ assert(s);
+ assert(unit);
+
+ if (!s->started)
+ return r;
+
+ if (streq(result, "done"))
+ r = session_send_create_reply(s, NULL);
+ else {
+ _cleanup_(sd_bus_error_free) sd_bus_error e = SD_BUS_ERROR_NULL;
+
+ sd_bus_error_setf(&e, BUS_ERROR_JOB_FAILED, "Start job for unit %s failed with '%s'", unit, result);
+ r = session_send_create_reply(s, &e);
+ }
+
+ return r;
+}
+
+int match_job_removed(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ const char *path, *result, *unit;
+ Manager *m = userdata;
+ Session *session;
+ uint32_t id;
+ User *user;
+ int r;
+
+ assert(message);
+ assert(m);
+
+ r = sd_bus_message_read(message, "uoss", &id, &path, &unit, &result);
+ if (r < 0) {
+ bus_log_parse_error(r);
+ return 0;
+ }
+
+ if (m->action_job && streq(m->action_job, path)) {
+ log_info("Operation '%s' finished.", inhibit_what_to_string(m->action_what));
+
+ /* Tell people that they now may take a lock again */
+ send_prepare_for(m, m->action_what, false);
+
+ m->action_job = mfree(m->action_job);
+ m->action_unit = NULL;
+ m->action_what = 0;
+ return 0;
+ }
+
+ session = hashmap_get(m->session_units, unit);
+ if (session && streq_ptr(path, session->scope_job)) {
+ session->scope_job = mfree(session->scope_job);
+ session_jobs_reply(session, unit, result);
+
+ session_save(session);
+ user_save(session->user);
+ session_add_to_gc_queue(session);
+ }
+
+ user = hashmap_get(m->user_units, unit);
+ if (user &&
+ (streq_ptr(path, user->service_job) ||
+ streq_ptr(path, user->slice_job))) {
+
+ if (streq_ptr(path, user->service_job))
+ user->service_job = mfree(user->service_job);
+
+ if (streq_ptr(path, user->slice_job))
+ user->slice_job = mfree(user->slice_job);
+
+ LIST_FOREACH(sessions_by_user, session, user->sessions)
+ session_jobs_reply(session, unit, result);
+
+ user_save(user);
+ user_add_to_gc_queue(user);
+ }
+
+ return 0;
+}
+
+int match_unit_removed(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ const char *path, *unit;
+ Manager *m = userdata;
+ Session *session;
+ User *user;
+ int r;
+
+ assert(message);
+ assert(m);
+
+ r = sd_bus_message_read(message, "so", &unit, &path);
+ if (r < 0) {
+ bus_log_parse_error(r);
+ return 0;
+ }
+
+ session = hashmap_get(m->session_units, unit);
+ if (session)
+ session_add_to_gc_queue(session);
+
+ user = hashmap_get(m->user_units, unit);
+ if (user)
+ user_add_to_gc_queue(user);
+
+ return 0;
+}
+
+int match_properties_changed(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ _cleanup_free_ char *unit = NULL;
+ Manager *m = userdata;
+ const char *path;
+ Session *session;
+ User *user;
+ int r;
+
+ assert(message);
+ assert(m);
+
+ path = sd_bus_message_get_path(message);
+ if (!path)
+ return 0;
+
+ r = unit_name_from_dbus_path(path, &unit);
+ if (r == -EINVAL) /* not a unit */
+ return 0;
+ if (r < 0) {
+ log_oom();
+ return 0;
+ }
+
+ session = hashmap_get(m->session_units, unit);
+ if (session)
+ session_add_to_gc_queue(session);
+
+ user = hashmap_get(m->user_units, unit);
+ if (user)
+ user_add_to_gc_queue(user);
+
+ return 0;
+}
+
+int match_reloading(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ Manager *m = userdata;
+ Session *session;
+ Iterator i;
+ int b, r;
+
+ assert(message);
+ assert(m);
+
+ r = sd_bus_message_read(message, "b", &b);
+ if (r < 0) {
+ bus_log_parse_error(r);
+ return 0;
+ }
+
+ if (b)
+ return 0;
+
+ /* systemd finished reloading, let's recheck all our sessions */
+ log_debug("System manager has been reloaded, rechecking sessions...");
+
+ HASHMAP_FOREACH(session, m->sessions, i)
+ session_add_to_gc_queue(session);
+
+ return 0;
+}
+
+int manager_send_changed(Manager *manager, const char *property, ...) {
+ char **l;
+
+ assert(manager);
+
+ l = strv_from_stdarg_alloca(property);
+
+ return sd_bus_emit_properties_changed_strv(
+ manager->bus,
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ l);
+}
+
+static int strdup_job(sd_bus_message *reply, char **job) {
+ const char *j;
+ char *copy;
+ int r;
+
+ r = sd_bus_message_read(reply, "o", &j);
+ if (r < 0)
+ return r;
+
+ copy = strdup(j);
+ if (!copy)
+ return -ENOMEM;
+
+ *job = copy;
+ return 1;
+}
+
+int manager_start_slice(
+ Manager *manager,
+ const char *slice,
+ const char *description,
+ const char *after,
+ const char *after2,
+ uint64_t tasks_max,
+ sd_bus_error *error,
+ char **job) {
+
+ _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
+ int r;
+
+ assert(manager);
+ assert(slice);
+ assert(job);
+
+ r = sd_bus_message_new_method_call(
+ manager->bus,
+ &m,
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "StartTransientUnit");
+ if (r < 0)
+ return r;
+
+ r = sd_bus_message_append(m, "ss", strempty(slice), "fail");
+ if (r < 0)
+ return r;
+
+ r = sd_bus_message_open_container(m, 'a', "(sv)");
+ if (r < 0)
+ return r;
+
+ if (!isempty(description)) {
+ r = sd_bus_message_append(m, "(sv)", "Description", "s", description);
+ if (r < 0)
+ return r;
+ }
+
+ if (!isempty(after)) {
+ r = sd_bus_message_append(m, "(sv)", "After", "as", 1, after);
+ if (r < 0)
+ return r;
+ }
+
+ if (!isempty(after2)) {
+ r = sd_bus_message_append(m, "(sv)", "After", "as", 1, after2);
+ if (r < 0)
+ return r;
+ }
+
+ r = sd_bus_message_append(m, "(sv)", "TasksMax", "t", tasks_max);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_message_close_container(m);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_message_append(m, "a(sa(sv))", 0);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_call(manager->bus, m, 0, error, &reply);
+ if (r < 0)
+ return r;
+
+ return strdup_job(reply, job);
+}
+
+int manager_start_scope(
+ Manager *manager,
+ const char *scope,
+ pid_t pid,
+ const char *slice,
+ const char *description,
+ const char *after,
+ const char *after2,
+ uint64_t tasks_max,
+ sd_bus_error *error,
+ char **job) {
+
+ _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
+ int r;
+
+ assert(manager);
+ assert(scope);
+ assert(pid > 1);
+ assert(job);
+
+ r = sd_bus_message_new_method_call(
+ manager->bus,
+ &m,
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "StartTransientUnit");
+ if (r < 0)
+ return r;
+
+ r = sd_bus_message_append(m, "ss", strempty(scope), "fail");
+ if (r < 0)
+ return r;
+
+ r = sd_bus_message_open_container(m, 'a', "(sv)");
+ if (r < 0)
+ return r;
+
+ if (!isempty(slice)) {
+ r = sd_bus_message_append(m, "(sv)", "Slice", "s", slice);
+ if (r < 0)
+ return r;
+ }
+
+ if (!isempty(description)) {
+ r = sd_bus_message_append(m, "(sv)", "Description", "s", description);
+ if (r < 0)
+ return r;
+ }
+
+ if (!isempty(after)) {
+ r = sd_bus_message_append(m, "(sv)", "After", "as", 1, after);
+ if (r < 0)
+ return r;
+ }
+
+ if (!isempty(after2)) {
+ r = sd_bus_message_append(m, "(sv)", "After", "as", 1, after2);
+ if (r < 0)
+ return r;
+ }
+
+ /* cgroup empty notification is not available in containers
+ * currently. To make this less problematic, let's shorten the
+ * stop timeout for sessions, so that we don't wait
+ * forever. */
+
+ /* Make sure that the session shells are terminated with
+ * SIGHUP since bash and friends tend to ignore SIGTERM */
+ r = sd_bus_message_append(m, "(sv)", "SendSIGHUP", "b", true);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_message_append(m, "(sv)", "PIDs", "au", 1, pid);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_message_append(m, "(sv)", "TasksMax", "t", tasks_max);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_message_close_container(m);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_message_append(m, "a(sa(sv))", 0);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_call(manager->bus, m, 0, error, &reply);
+ if (r < 0)
+ return r;
+
+ return strdup_job(reply, job);
+}
+
+int manager_start_unit(Manager *manager, const char *unit, sd_bus_error *error, char **job) {
+ _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
+ int r;
+
+ assert(manager);
+ assert(unit);
+ assert(job);
+
+ r = sd_bus_call_method(
+ manager->bus,
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "StartUnit",
+ error,
+ &reply,
+ "ss", unit, "replace");
+ if (r < 0)
+ return r;
+
+ return strdup_job(reply, job);
+}
+
+int manager_stop_unit(Manager *manager, const char *unit, sd_bus_error *error, char **job) {
+ _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
+ int r;
+
+ assert(manager);
+ assert(unit);
+ assert(job);
+
+ r = sd_bus_call_method(
+ manager->bus,
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "StopUnit",
+ error,
+ &reply,
+ "ss", unit, "fail");
+ if (r < 0) {
+ if (sd_bus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT) ||
+ sd_bus_error_has_name(error, BUS_ERROR_LOAD_FAILED)) {
+
+ *job = NULL;
+ sd_bus_error_free(error);
+ return 0;
+ }
+
+ return r;
+ }
+
+ return strdup_job(reply, job);
+}
+
+int manager_abandon_scope(Manager *manager, const char *scope, sd_bus_error *error) {
+ _cleanup_free_ char *path = NULL;
+ int r;
+
+ assert(manager);
+ assert(scope);
+
+ path = unit_dbus_path_from_name(scope);
+ if (!path)
+ return -ENOMEM;
+
+ r = sd_bus_call_method(
+ manager->bus,
+ "org.freedesktop.systemd1",
+ path,
+ "org.freedesktop.systemd1.Scope",
+ "Abandon",
+ error,
+ NULL,
+ NULL);
+ if (r < 0) {
+ if (sd_bus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT) ||
+ sd_bus_error_has_name(error, BUS_ERROR_LOAD_FAILED) ||
+ sd_bus_error_has_name(error, BUS_ERROR_SCOPE_NOT_RUNNING)) {
+ sd_bus_error_free(error);
+ return 0;
+ }
+
+ return r;
+ }
+
+ return 1;
+}
+
+int manager_kill_unit(Manager *manager, const char *unit, KillWho who, int signo, sd_bus_error *error) {
+ assert(manager);
+ assert(unit);
+
+ return sd_bus_call_method(
+ manager->bus,
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "KillUnit",
+ error,
+ NULL,
+ "ssi", unit, who == KILL_LEADER ? "main" : "all", signo);
+}
+
+int manager_unit_is_active(Manager *manager, const char *unit) {
+ _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+ _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
+ _cleanup_free_ char *path = NULL;
+ const char *state;
+ int r;
+
+ assert(manager);
+ assert(unit);
+
+ path = unit_dbus_path_from_name(unit);
+ if (!path)
+ return -ENOMEM;
+
+ r = sd_bus_get_property(
+ manager->bus,
+ "org.freedesktop.systemd1",
+ path,
+ "org.freedesktop.systemd1.Unit",
+ "ActiveState",
+ &error,
+ &reply,
+ "s");
+ if (r < 0) {
+ /* systemd might have droppped off momentarily, let's
+ * not make this an error */
+ if (sd_bus_error_has_name(&error, SD_BUS_ERROR_NO_REPLY) ||
+ sd_bus_error_has_name(&error, SD_BUS_ERROR_DISCONNECTED))
+ return true;
+
+ /* If the unit is already unloaded then it's not
+ * active */
+ if (sd_bus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT) ||
+ sd_bus_error_has_name(&error, BUS_ERROR_LOAD_FAILED))
+ return false;
+
+ return r;
+ }
+
+ r = sd_bus_message_read(reply, "s", &state);
+ if (r < 0)
+ return -EINVAL;
+
+ return !streq(state, "inactive") && !streq(state, "failed");
+}
+
+int manager_job_is_active(Manager *manager, const char *path) {
+ _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+ _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
+ int r;
+
+ assert(manager);
+ assert(path);
+
+ r = sd_bus_get_property(
+ manager->bus,
+ "org.freedesktop.systemd1",
+ path,
+ "org.freedesktop.systemd1.Job",
+ "State",
+ &error,
+ &reply,
+ "s");
+ if (r < 0) {
+ if (sd_bus_error_has_name(&error, SD_BUS_ERROR_NO_REPLY) ||
+ sd_bus_error_has_name(&error, SD_BUS_ERROR_DISCONNECTED))
+ return true;
+
+ if (sd_bus_error_has_name(&error, SD_BUS_ERROR_UNKNOWN_OBJECT))
+ return false;
+
+ return r;
+ }
+
+ /* We don't actually care about the state really. The fact
+ * that we could read the job state is enough for us */
+
+ return true;
+}
diff --git a/src/grp-login/systemd-logind/logind-device.c b/src/grp-login/systemd-logind/logind-device.c
new file mode 100644
index 0000000000..6165a9ea6e
--- /dev/null
+++ b/src/grp-login/systemd-logind/logind-device.c
@@ -0,0 +1,125 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ 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 <string.h>
+
+#include "basic/alloc-util.h"
+#include "basic/util.h"
+
+#include "logind-device.h"
+
+Device* device_new(Manager *m, const char *sysfs, bool master) {
+ Device *d;
+
+ assert(m);
+ assert(sysfs);
+
+ d = new0(Device, 1);
+ if (!d)
+ return NULL;
+
+ d->sysfs = strdup(sysfs);
+ if (!d->sysfs) {
+ free(d);
+ return NULL;
+ }
+
+ if (hashmap_put(m->devices, d->sysfs, d) < 0) {
+ free(d->sysfs);
+ free(d);
+ return NULL;
+ }
+
+ d->manager = m;
+ d->master = master;
+ dual_timestamp_get(&d->timestamp);
+
+ return d;
+}
+
+static void device_detach(Device *d) {
+ Seat *s;
+ SessionDevice *sd;
+
+ assert(d);
+
+ if (!d->seat)
+ return;
+
+ while ((sd = d->session_devices))
+ session_device_free(sd);
+
+ s = d->seat;
+ LIST_REMOVE(devices, d->seat->devices, d);
+ d->seat = NULL;
+
+ if (!seat_has_master_device(s)) {
+ seat_add_to_gc_queue(s);
+ seat_send_changed(s, "CanGraphical", NULL);
+ }
+}
+
+void device_free(Device *d) {
+ assert(d);
+
+ device_detach(d);
+
+ hashmap_remove(d->manager->devices, d->sysfs);
+
+ free(d->sysfs);
+ free(d);
+}
+
+void device_attach(Device *d, Seat *s) {
+ Device *i;
+ bool had_master;
+
+ assert(d);
+ assert(s);
+
+ if (d->seat == s)
+ return;
+
+ if (d->seat)
+ device_detach(d);
+
+ d->seat = s;
+ had_master = seat_has_master_device(s);
+
+ /* We keep the device list sorted by the "master" flag. That is, master
+ * devices are at the front, other devices at the tail. As there is no
+ * way to easily add devices at the list-tail, we need to iterate the
+ * list to find the first non-master device when adding non-master
+ * devices. We assume there is only a few (normally 1) master devices
+ * per seat, so we iterate only a few times. */
+
+ if (d->master || !s->devices)
+ LIST_PREPEND(devices, s->devices, d);
+ else {
+ LIST_FOREACH(devices, i, s->devices) {
+ if (!i->devices_next || !i->master) {
+ LIST_INSERT_AFTER(devices, s->devices, i, d);
+ break;
+ }
+ }
+ }
+
+ if (!had_master && d->master)
+ seat_send_changed(s, "CanGraphical", NULL);
+}
diff --git a/src/grp-login/systemd-logind/logind-device.h b/src/grp-login/systemd-logind/logind-device.h
new file mode 100644
index 0000000000..9e2678d801
--- /dev/null
+++ b/src/grp-login/systemd-logind/logind-device.h
@@ -0,0 +1,44 @@
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ 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 "basic/list.h"
+
+typedef struct Device Device;
+
+#include "logind-seat.h"
+#include "logind-session-device.h"
+
+struct Device {
+ Manager *manager;
+
+ char *sysfs;
+ Seat *seat;
+ bool master;
+
+ dual_timestamp timestamp;
+
+ LIST_FIELDS(struct Device, devices);
+ LIST_HEAD(SessionDevice, session_devices);
+};
+
+Device* device_new(Manager *m, const char *sysfs, bool master);
+void device_free(Device *d);
+void device_attach(Device *d, Seat *s);
diff --git a/src/grp-login/systemd-logind/logind-gperf.gperf b/src/grp-login/systemd-logind/logind-gperf.gperf
new file mode 100644
index 0000000000..1a39c3bf96
--- /dev/null
+++ b/src/grp-login/systemd-logind/logind-gperf.gperf
@@ -0,0 +1,41 @@
+%{
+#include <stddef.h>
+
+#include "shared/conf-parser.h"
+
+#include "logind.h"
+%}
+struct ConfigPerfItem;
+%null_strings
+%language=ANSI-C
+%define slot-name section_and_lvalue
+%define hash-function-name logind_gperf_hash
+%define lookup-function-name logind_gperf_lookup
+%readonly-tables
+%omit-struct-type
+%struct-type
+%includes
+%%
+Login.NAutoVTs, config_parse_unsigned, 0, offsetof(Manager, n_autovts)
+Login.ReserveVT, config_parse_unsigned, 0, offsetof(Manager, reserve_vt)
+Login.KillUserProcesses, config_parse_bool, 0, offsetof(Manager, kill_user_processes)
+Login.KillOnlyUsers, config_parse_strv, 0, offsetof(Manager, kill_only_users)
+Login.KillExcludeUsers, config_parse_strv, 0, offsetof(Manager, kill_exclude_users)
+Login.InhibitDelayMaxSec, config_parse_sec, 0, offsetof(Manager, inhibit_delay_max)
+Login.HandlePowerKey, config_parse_handle_action, 0, offsetof(Manager, handle_power_key)
+Login.HandleSuspendKey, config_parse_handle_action, 0, offsetof(Manager, handle_suspend_key)
+Login.HandleHibernateKey, config_parse_handle_action, 0, offsetof(Manager, handle_hibernate_key)
+Login.HandleLidSwitch, config_parse_handle_action, 0, offsetof(Manager, handle_lid_switch)
+Login.HandleLidSwitchDocked, config_parse_handle_action, 0, offsetof(Manager, handle_lid_switch_docked)
+Login.PowerKeyIgnoreInhibited, config_parse_bool, 0, offsetof(Manager, power_key_ignore_inhibited)
+Login.SuspendKeyIgnoreInhibited, config_parse_bool, 0, offsetof(Manager, suspend_key_ignore_inhibited)
+Login.HibernateKeyIgnoreInhibited, config_parse_bool, 0, offsetof(Manager, hibernate_key_ignore_inhibited)
+Login.LidSwitchIgnoreInhibited, config_parse_bool, 0, offsetof(Manager, lid_switch_ignore_inhibited)
+Login.HoldoffTimeoutSec, config_parse_sec, 0, offsetof(Manager, holdoff_timeout_usec)
+Login.IdleAction, config_parse_handle_action, 0, offsetof(Manager, idle_action)
+Login.IdleActionSec, config_parse_sec, 0, offsetof(Manager, idle_action_usec)
+Login.RuntimeDirectorySize, config_parse_tmpfs_size, 0, offsetof(Manager, runtime_dir_size)
+Login.RemoveIPC, config_parse_bool, 0, offsetof(Manager, remove_ipc)
+Login.InhibitorsMax, config_parse_uint64, 0, offsetof(Manager, inhibitors_max)
+Login.SessionsMax, config_parse_uint64, 0, offsetof(Manager, sessions_max)
+Login.UserTasksMax, config_parse_user_tasks_max,0, offsetof(Manager, user_tasks_max)
diff --git a/src/grp-login/systemd-logind/logind-inhibit.c b/src/grp-login/systemd-logind/logind-inhibit.c
new file mode 100644
index 0000000000..8a35db0dc8
--- /dev/null
+++ b/src/grp-login/systemd-logind/logind-inhibit.c
@@ -0,0 +1,486 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ 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 <errno.h>
+#include <fcntl.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "basic/alloc-util.h"
+#include "basic/escape.h"
+#include "basic/fd-util.h"
+#include "basic/fileio.h"
+#include "basic/formats-util.h"
+#include "basic/mkdir.h"
+#include "basic/parse-util.h"
+#include "basic/string-table.h"
+#include "basic/string-util.h"
+#include "basic/user-util.h"
+#include "basic/util.h"
+
+#include "logind-inhibit.h"
+
+Inhibitor* inhibitor_new(Manager *m, const char* id) {
+ Inhibitor *i;
+
+ assert(m);
+
+ i = new0(Inhibitor, 1);
+ if (!i)
+ return NULL;
+
+ i->state_file = strappend("/run/systemd/inhibit/", id);
+ if (!i->state_file) {
+ free(i);
+ return NULL;
+ }
+
+ i->id = basename(i->state_file);
+
+ if (hashmap_put(m->inhibitors, i->id, i) < 0) {
+ free(i->state_file);
+ free(i);
+ return NULL;
+ }
+
+ i->manager = m;
+ i->fifo_fd = -1;
+
+ return i;
+}
+
+void inhibitor_free(Inhibitor *i) {
+ assert(i);
+
+ hashmap_remove(i->manager->inhibitors, i->id);
+
+ inhibitor_remove_fifo(i);
+
+ free(i->who);
+ free(i->why);
+
+ if (i->state_file) {
+ unlink(i->state_file);
+ free(i->state_file);
+ }
+
+ free(i);
+}
+
+int inhibitor_save(Inhibitor *i) {
+ _cleanup_free_ char *temp_path = NULL;
+ _cleanup_fclose_ FILE *f = NULL;
+ int r;
+
+ assert(i);
+
+ r = mkdir_safe_label("/run/systemd/inhibit", 0755, 0, 0);
+ if (r < 0)
+ goto fail;
+
+ r = fopen_temporary(i->state_file, &f, &temp_path);
+ if (r < 0)
+ goto fail;
+
+ fchmod(fileno(f), 0644);
+
+ fprintf(f,
+ "# This is private data. Do not parse.\n"
+ "WHAT=%s\n"
+ "MODE=%s\n"
+ "UID="UID_FMT"\n"
+ "PID="PID_FMT"\n",
+ inhibit_what_to_string(i->what),
+ inhibit_mode_to_string(i->mode),
+ i->uid,
+ i->pid);
+
+ if (i->who) {
+ _cleanup_free_ char *cc = NULL;
+
+ cc = cescape(i->who);
+ if (!cc) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ fprintf(f, "WHO=%s\n", cc);
+ }
+
+ if (i->why) {
+ _cleanup_free_ char *cc = NULL;
+
+ cc = cescape(i->why);
+ if (!cc) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ fprintf(f, "WHY=%s\n", cc);
+ }
+
+ if (i->fifo_path)
+ fprintf(f, "FIFO=%s\n", i->fifo_path);
+
+ r = fflush_and_check(f);
+ if (r < 0)
+ goto fail;
+
+ if (rename(temp_path, i->state_file) < 0) {
+ r = -errno;
+ goto fail;
+ }
+
+ return 0;
+
+fail:
+ (void) unlink(i->state_file);
+
+ if (temp_path)
+ (void) unlink(temp_path);
+
+ return log_error_errno(r, "Failed to save inhibit data %s: %m", i->state_file);
+}
+
+int inhibitor_start(Inhibitor *i) {
+ assert(i);
+
+ if (i->started)
+ return 0;
+
+ dual_timestamp_get(&i->since);
+
+ log_debug("Inhibitor %s (%s) pid="PID_FMT" uid="UID_FMT" mode=%s started.",
+ strna(i->who), strna(i->why),
+ i->pid, i->uid,
+ inhibit_mode_to_string(i->mode));
+
+ inhibitor_save(i);
+
+ i->started = true;
+
+ manager_send_changed(i->manager, i->mode == INHIBIT_BLOCK ? "BlockInhibited" : "DelayInhibited", NULL);
+
+ return 0;
+}
+
+int inhibitor_stop(Inhibitor *i) {
+ assert(i);
+
+ if (i->started)
+ log_debug("Inhibitor %s (%s) pid="PID_FMT" uid="UID_FMT" mode=%s stopped.",
+ strna(i->who), strna(i->why),
+ i->pid, i->uid,
+ inhibit_mode_to_string(i->mode));
+
+ if (i->state_file)
+ unlink(i->state_file);
+
+ i->started = false;
+
+ manager_send_changed(i->manager, i->mode == INHIBIT_BLOCK ? "BlockInhibited" : "DelayInhibited", NULL);
+
+ return 0;
+}
+
+int inhibitor_load(Inhibitor *i) {
+
+ _cleanup_free_ char
+ *what = NULL,
+ *uid = NULL,
+ *pid = NULL,
+ *who = NULL,
+ *why = NULL,
+ *mode = NULL;
+
+ InhibitWhat w;
+ InhibitMode mm;
+ char *cc;
+ int r;
+
+ r = parse_env_file(i->state_file, NEWLINE,
+ "WHAT", &what,
+ "UID", &uid,
+ "PID", &pid,
+ "WHO", &who,
+ "WHY", &why,
+ "MODE", &mode,
+ "FIFO", &i->fifo_path,
+ NULL);
+ if (r < 0)
+ return r;
+
+ w = what ? inhibit_what_from_string(what) : 0;
+ if (w >= 0)
+ i->what = w;
+
+ mm = mode ? inhibit_mode_from_string(mode) : INHIBIT_BLOCK;
+ if (mm >= 0)
+ i->mode = mm;
+
+ if (uid) {
+ r = parse_uid(uid, &i->uid);
+ if (r < 0)
+ return r;
+ }
+
+ if (pid) {
+ r = parse_pid(pid, &i->pid);
+ if (r < 0)
+ return r;
+ }
+
+ if (who) {
+ r = cunescape(who, 0, &cc);
+ if (r < 0)
+ return r;
+
+ free(i->who);
+ i->who = cc;
+ }
+
+ if (why) {
+ r = cunescape(why, 0, &cc);
+ if (r < 0)
+ return r;
+
+ free(i->why);
+ i->why = cc;
+ }
+
+ if (i->fifo_path) {
+ int fd;
+
+ fd = inhibitor_create_fifo(i);
+ safe_close(fd);
+ }
+
+ return 0;
+}
+
+static int inhibitor_dispatch_fifo(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
+ Inhibitor *i = userdata;
+
+ assert(s);
+ assert(fd == i->fifo_fd);
+ assert(i);
+
+ inhibitor_stop(i);
+ inhibitor_free(i);
+
+ return 0;
+}
+
+int inhibitor_create_fifo(Inhibitor *i) {
+ int r;
+
+ assert(i);
+
+ /* Create FIFO */
+ if (!i->fifo_path) {
+ r = mkdir_safe_label("/run/systemd/inhibit", 0755, 0, 0);
+ if (r < 0)
+ return r;
+
+ i->fifo_path = strjoin("/run/systemd/inhibit/", i->id, ".ref", NULL);
+ if (!i->fifo_path)
+ return -ENOMEM;
+
+ if (mkfifo(i->fifo_path, 0600) < 0 && errno != EEXIST)
+ return -errno;
+ }
+
+ /* Open reading side */
+ if (i->fifo_fd < 0) {
+ i->fifo_fd = open(i->fifo_path, O_RDONLY|O_CLOEXEC|O_NDELAY);
+ if (i->fifo_fd < 0)
+ return -errno;
+ }
+
+ if (!i->event_source) {
+ r = sd_event_add_io(i->manager->event, &i->event_source, i->fifo_fd, 0, inhibitor_dispatch_fifo, i);
+ if (r < 0)
+ return r;
+
+ r = sd_event_source_set_priority(i->event_source, SD_EVENT_PRIORITY_IDLE-10);
+ if (r < 0)
+ return r;
+ }
+
+ /* Open writing side */
+ r = open(i->fifo_path, O_WRONLY|O_CLOEXEC|O_NDELAY);
+ if (r < 0)
+ return -errno;
+
+ return r;
+}
+
+void inhibitor_remove_fifo(Inhibitor *i) {
+ assert(i);
+
+ i->event_source = sd_event_source_unref(i->event_source);
+ i->fifo_fd = safe_close(i->fifo_fd);
+
+ if (i->fifo_path) {
+ unlink(i->fifo_path);
+ i->fifo_path = mfree(i->fifo_path);
+ }
+}
+
+InhibitWhat manager_inhibit_what(Manager *m, InhibitMode mm) {
+ Inhibitor *i;
+ Iterator j;
+ InhibitWhat what = 0;
+
+ assert(m);
+
+ HASHMAP_FOREACH(i, m->inhibitors, j)
+ if (i->mode == mm)
+ what |= i->what;
+
+ return what;
+}
+
+static int pid_is_active(Manager *m, pid_t pid) {
+ Session *s;
+ int r;
+
+ r = manager_get_session_by_pid(m, pid, &s);
+ if (r < 0)
+ return r;
+
+ /* If there's no session assigned to it, then it's globally
+ * active on all ttys */
+ if (r == 0)
+ return 1;
+
+ return session_is_active(s);
+}
+
+bool manager_is_inhibited(
+ Manager *m,
+ InhibitWhat w,
+ InhibitMode mm,
+ dual_timestamp *since,
+ bool ignore_inactive,
+ bool ignore_uid,
+ uid_t uid,
+ Inhibitor **offending) {
+
+ Inhibitor *i;
+ Iterator j;
+ struct dual_timestamp ts = DUAL_TIMESTAMP_NULL;
+ bool inhibited = false;
+
+ assert(m);
+ assert(w > 0 && w < _INHIBIT_WHAT_MAX);
+
+ HASHMAP_FOREACH(i, m->inhibitors, j) {
+ if (!(i->what & w))
+ continue;
+
+ if (i->mode != mm)
+ continue;
+
+ if (ignore_inactive && pid_is_active(m, i->pid) <= 0)
+ continue;
+
+ if (ignore_uid && i->uid == uid)
+ continue;
+
+ if (!inhibited ||
+ i->since.monotonic < ts.monotonic)
+ ts = i->since;
+
+ inhibited = true;
+
+ if (offending)
+ *offending = i;
+ }
+
+ if (since)
+ *since = ts;
+
+ return inhibited;
+}
+
+const char *inhibit_what_to_string(InhibitWhat w) {
+ static thread_local char buffer[97];
+ char *p;
+
+ if (w < 0 || w >= _INHIBIT_WHAT_MAX)
+ return NULL;
+
+ p = buffer;
+ if (w & INHIBIT_SHUTDOWN)
+ p = stpcpy(p, "shutdown:");
+ if (w & INHIBIT_SLEEP)
+ p = stpcpy(p, "sleep:");
+ if (w & INHIBIT_IDLE)
+ p = stpcpy(p, "idle:");
+ if (w & INHIBIT_HANDLE_POWER_KEY)
+ p = stpcpy(p, "handle-power-key:");
+ if (w & INHIBIT_HANDLE_SUSPEND_KEY)
+ p = stpcpy(p, "handle-suspend-key:");
+ if (w & INHIBIT_HANDLE_HIBERNATE_KEY)
+ p = stpcpy(p, "handle-hibernate-key:");
+ if (w & INHIBIT_HANDLE_LID_SWITCH)
+ p = stpcpy(p, "handle-lid-switch:");
+
+ if (p > buffer)
+ *(p-1) = 0;
+ else
+ *p = 0;
+
+ return buffer;
+}
+
+InhibitWhat inhibit_what_from_string(const char *s) {
+ InhibitWhat what = 0;
+ const char *word, *state;
+ size_t l;
+
+ FOREACH_WORD_SEPARATOR(word, l, s, ":", state) {
+ if (l == 8 && strneq(word, "shutdown", l))
+ what |= INHIBIT_SHUTDOWN;
+ else if (l == 5 && strneq(word, "sleep", l))
+ what |= INHIBIT_SLEEP;
+ else if (l == 4 && strneq(word, "idle", l))
+ what |= INHIBIT_IDLE;
+ else if (l == 16 && strneq(word, "handle-power-key", l))
+ what |= INHIBIT_HANDLE_POWER_KEY;
+ else if (l == 18 && strneq(word, "handle-suspend-key", l))
+ what |= INHIBIT_HANDLE_SUSPEND_KEY;
+ else if (l == 20 && strneq(word, "handle-hibernate-key", l))
+ what |= INHIBIT_HANDLE_HIBERNATE_KEY;
+ else if (l == 17 && strneq(word, "handle-lid-switch", l))
+ what |= INHIBIT_HANDLE_LID_SWITCH;
+ else
+ return _INHIBIT_WHAT_INVALID;
+ }
+
+ return what;
+}
+
+static const char* const inhibit_mode_table[_INHIBIT_MODE_MAX] = {
+ [INHIBIT_BLOCK] = "block",
+ [INHIBIT_DELAY] = "delay"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(inhibit_mode, InhibitMode);
diff --git a/src/grp-login/systemd-logind/logind-inhibit.h b/src/grp-login/systemd-logind/logind-inhibit.h
new file mode 100644
index 0000000000..70de199c60
--- /dev/null
+++ b/src/grp-login/systemd-logind/logind-inhibit.h
@@ -0,0 +1,89 @@
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ 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/>.
+***/
+
+typedef struct Inhibitor Inhibitor;
+
+
+typedef enum InhibitWhat {
+ INHIBIT_SHUTDOWN = 1,
+ INHIBIT_SLEEP = 2,
+ INHIBIT_IDLE = 4,
+ INHIBIT_HANDLE_POWER_KEY = 8,
+ INHIBIT_HANDLE_SUSPEND_KEY = 16,
+ INHIBIT_HANDLE_HIBERNATE_KEY = 32,
+ INHIBIT_HANDLE_LID_SWITCH = 64,
+ _INHIBIT_WHAT_MAX = 128,
+ _INHIBIT_WHAT_INVALID = -1
+} InhibitWhat;
+
+typedef enum InhibitMode {
+ INHIBIT_BLOCK,
+ INHIBIT_DELAY,
+ _INHIBIT_MODE_MAX,
+ _INHIBIT_MODE_INVALID = -1
+} InhibitMode;
+
+#include "logind.h"
+
+struct Inhibitor {
+ Manager *manager;
+
+ sd_event_source *event_source;
+
+ char *id;
+ char *state_file;
+
+ bool started;
+
+ InhibitWhat what;
+ char *who;
+ char *why;
+ InhibitMode mode;
+
+ pid_t pid;
+ uid_t uid;
+
+ dual_timestamp since;
+
+ char *fifo_path;
+ int fifo_fd;
+};
+
+Inhibitor* inhibitor_new(Manager *m, const char *id);
+void inhibitor_free(Inhibitor *i);
+
+int inhibitor_save(Inhibitor *i);
+int inhibitor_load(Inhibitor *i);
+
+int inhibitor_start(Inhibitor *i);
+int inhibitor_stop(Inhibitor *i);
+
+int inhibitor_create_fifo(Inhibitor *i);
+void inhibitor_remove_fifo(Inhibitor *i);
+
+InhibitWhat manager_inhibit_what(Manager *m, InhibitMode mm);
+bool manager_is_inhibited(Manager *m, InhibitWhat w, InhibitMode mm, dual_timestamp *since, bool ignore_inactive, bool ignore_uid, uid_t uid, Inhibitor **offending);
+
+const char *inhibit_what_to_string(InhibitWhat k);
+InhibitWhat inhibit_what_from_string(const char *s);
+
+const char *inhibit_mode_to_string(InhibitMode k);
+InhibitMode inhibit_mode_from_string(const char *s);
diff --git a/src/grp-login/systemd-logind/logind-seat-dbus.c b/src/grp-login/systemd-logind/logind-seat-dbus.c
new file mode 100644
index 0000000000..e4febe1ab5
--- /dev/null
+++ b/src/grp-login/systemd-logind/logind-seat-dbus.c
@@ -0,0 +1,475 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ 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 <errno.h>
+#include <string.h>
+
+#include "basic/alloc-util.h"
+#include "basic/bus-label.h"
+#include "basic/strv.h"
+#include "basic/user-util.h"
+#include "basic/util.h"
+#include "sd-bus/bus-common-errors.h"
+#include "shared/bus-util.h"
+
+#include "logind-seat.h"
+#include "logind.h"
+
+static int property_get_active_session(
+ sd_bus *bus,
+ const char *path,
+ const char *interface,
+ const char *property,
+ sd_bus_message *reply,
+ void *userdata,
+ sd_bus_error *error) {
+
+ _cleanup_free_ char *p = NULL;
+ Seat *s = userdata;
+
+ assert(bus);
+ assert(reply);
+ assert(s);
+
+ p = s->active ? session_bus_path(s->active) : strdup("/");
+ if (!p)
+ return -ENOMEM;
+
+ return sd_bus_message_append(reply, "(so)", s->active ? s->active->id : "", p);
+}
+
+static int property_get_can_multi_session(
+ sd_bus *bus,
+ const char *path,
+ const char *interface,
+ const char *property,
+ sd_bus_message *reply,
+ void *userdata,
+ sd_bus_error *error) {
+
+ Seat *s = userdata;
+
+ assert(bus);
+ assert(reply);
+ assert(s);
+
+ return sd_bus_message_append(reply, "b", seat_can_multi_session(s));
+}
+
+static int property_get_can_tty(
+ sd_bus *bus,
+ const char *path,
+ const char *interface,
+ const char *property,
+ sd_bus_message *reply,
+ void *userdata,
+ sd_bus_error *error) {
+
+ Seat *s = userdata;
+
+ assert(bus);
+ assert(reply);
+ assert(s);
+
+ return sd_bus_message_append(reply, "b", seat_can_tty(s));
+}
+
+static int property_get_can_graphical(
+ sd_bus *bus,
+ const char *path,
+ const char *interface,
+ const char *property,
+ sd_bus_message *reply,
+ void *userdata,
+ sd_bus_error *error) {
+
+ Seat *s = userdata;
+
+ assert(bus);
+ assert(reply);
+ assert(s);
+
+ return sd_bus_message_append(reply, "b", seat_can_graphical(s));
+}
+
+static int property_get_sessions(
+ sd_bus *bus,
+ const char *path,
+ const char *interface,
+ const char *property,
+ sd_bus_message *reply,
+ void *userdata,
+ sd_bus_error *error) {
+
+ Seat *s = userdata;
+ Session *session;
+ int r;
+
+ assert(bus);
+ assert(reply);
+ assert(s);
+
+ r = sd_bus_message_open_container(reply, 'a', "(so)");
+ if (r < 0)
+ return r;
+
+ LIST_FOREACH(sessions_by_seat, session, s->sessions) {
+ _cleanup_free_ char *p = NULL;
+
+ p = session_bus_path(session);
+ if (!p)
+ return -ENOMEM;
+
+ r = sd_bus_message_append(reply, "(so)", session->id, p);
+ if (r < 0)
+ return r;
+
+ }
+
+ r = sd_bus_message_close_container(reply);
+ if (r < 0)
+ return r;
+
+ return 1;
+}
+
+static int property_get_idle_hint(
+ sd_bus *bus,
+ const char *path,
+ const char *interface,
+ const char *property,
+ sd_bus_message *reply,
+ void *userdata,
+ sd_bus_error *error) {
+
+ Seat *s = userdata;
+
+ assert(bus);
+ assert(reply);
+ assert(s);
+
+ return sd_bus_message_append(reply, "b", seat_get_idle_hint(s, NULL) > 0);
+}
+
+static int property_get_idle_since_hint(
+ sd_bus *bus,
+ const char *path,
+ const char *interface,
+ const char *property,
+ sd_bus_message *reply,
+ void *userdata,
+ sd_bus_error *error) {
+
+ Seat *s = userdata;
+ dual_timestamp t;
+ uint64_t u;
+ int r;
+
+ assert(bus);
+ assert(reply);
+ assert(s);
+
+ r = seat_get_idle_hint(s, &t);
+ if (r < 0)
+ return r;
+
+ u = streq(property, "IdleSinceHint") ? t.realtime : t.monotonic;
+
+ return sd_bus_message_append(reply, "t", u);
+}
+
+int bus_seat_method_terminate(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ Seat *s = userdata;
+ int r;
+
+ assert(message);
+ assert(s);
+
+ r = bus_verify_polkit_async(
+ message,
+ CAP_KILL,
+ "org.freedesktop.login1.manage",
+ NULL,
+ false,
+ UID_INVALID,
+ &s->manager->polkit_registry,
+ error);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ return 1; /* Will call us back */
+
+ r = seat_stop_sessions(s, true);
+ if (r < 0)
+ return r;
+
+ return sd_bus_reply_method_return(message, NULL);
+}
+
+static int method_activate_session(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ Seat *s = userdata;
+ const char *name;
+ Session *session;
+ int r;
+
+ assert(message);
+ assert(s);
+
+ r = sd_bus_message_read(message, "s", &name);
+ if (r < 0)
+ return r;
+
+ session = hashmap_get(s->manager->sessions, name);
+ if (!session)
+ return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_SESSION, "No session '%s' known", name);
+
+ if (session->seat != s)
+ return sd_bus_error_setf(error, BUS_ERROR_SESSION_NOT_ON_SEAT, "Session %s not on seat %s", name, s->id);
+
+ r = session_activate(session);
+ if (r < 0)
+ return r;
+
+ return sd_bus_reply_method_return(message, NULL);
+}
+
+static int method_switch_to(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ Seat *s = userdata;
+ unsigned int to;
+ int r;
+
+ assert(message);
+ assert(s);
+
+ r = sd_bus_message_read(message, "u", &to);
+ if (r < 0)
+ return r;
+
+ if (to <= 0)
+ return -EINVAL;
+
+ r = seat_switch_to(s, to);
+ if (r < 0)
+ return r;
+
+ return sd_bus_reply_method_return(message, NULL);
+}
+
+static int method_switch_to_next(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ Seat *s = userdata;
+ int r;
+
+ assert(message);
+ assert(s);
+
+ r = seat_switch_to_next(s);
+ if (r < 0)
+ return r;
+
+ return sd_bus_reply_method_return(message, NULL);
+}
+
+static int method_switch_to_previous(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ Seat *s = userdata;
+ int r;
+
+ assert(message);
+ assert(s);
+
+ r = seat_switch_to_previous(s);
+ if (r < 0)
+ return r;
+
+ return sd_bus_reply_method_return(message, NULL);
+}
+
+const sd_bus_vtable seat_vtable[] = {
+ SD_BUS_VTABLE_START(0),
+
+ SD_BUS_PROPERTY("Id", "s", NULL, offsetof(Seat, id), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("ActiveSession", "(so)", property_get_active_session, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
+ SD_BUS_PROPERTY("CanMultiSession", "b", property_get_can_multi_session, 0, SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("CanTTY", "b", property_get_can_tty, 0, SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("CanGraphical", "b", property_get_can_graphical, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
+ SD_BUS_PROPERTY("Sessions", "a(so)", property_get_sessions, 0, 0),
+ SD_BUS_PROPERTY("IdleHint", "b", property_get_idle_hint, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
+ SD_BUS_PROPERTY("IdleSinceHint", "t", property_get_idle_since_hint, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
+ SD_BUS_PROPERTY("IdleSinceHintMonotonic", "t", property_get_idle_since_hint, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
+
+ SD_BUS_METHOD("Terminate", NULL, NULL, bus_seat_method_terminate, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("ActivateSession", "s", NULL, method_activate_session, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("SwitchTo", "u", NULL, method_switch_to, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("SwitchToNext", NULL, NULL, method_switch_to_next, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("SwitchToPrevious", NULL, NULL, method_switch_to_previous, SD_BUS_VTABLE_UNPRIVILEGED),
+
+ SD_BUS_VTABLE_END
+};
+
+int seat_object_find(sd_bus *bus, const char *path, const char *interface, void *userdata, void **found, sd_bus_error *error) {
+ Manager *m = userdata;
+ Seat *seat;
+ int r;
+
+ assert(bus);
+ assert(path);
+ assert(interface);
+ assert(found);
+ assert(m);
+
+ if (streq(path, "/org/freedesktop/login1/seat/self")) {
+ _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
+ sd_bus_message *message;
+ Session *session;
+ const char *name;
+
+ message = sd_bus_get_current_message(bus);
+ if (!message)
+ return 0;
+
+ r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_SESSION|SD_BUS_CREDS_AUGMENT, &creds);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_creds_get_session(creds, &name);
+ if (r < 0)
+ return r;
+
+ session = hashmap_get(m->sessions, name);
+ if (!session)
+ return 0;
+
+ seat = session->seat;
+ } else {
+ _cleanup_free_ char *e = NULL;
+ const char *p;
+
+ p = startswith(path, "/org/freedesktop/login1/seat/");
+ if (!p)
+ return 0;
+
+ e = bus_label_unescape(p);
+ if (!e)
+ return -ENOMEM;
+
+ seat = hashmap_get(m->seats, e);
+ }
+
+ if (!seat)
+ return 0;
+
+ *found = seat;
+ return 1;
+}
+
+char *seat_bus_path(Seat *s) {
+ _cleanup_free_ char *t = NULL;
+
+ assert(s);
+
+ t = bus_label_escape(s->id);
+ if (!t)
+ return NULL;
+
+ return strappend("/org/freedesktop/login1/seat/", t);
+}
+
+int seat_node_enumerator(sd_bus *bus, const char *path, void *userdata, char ***nodes, sd_bus_error *error) {
+ _cleanup_strv_free_ char **l = NULL;
+ sd_bus_message *message;
+ Manager *m = userdata;
+ Seat *seat;
+ Iterator i;
+ int r;
+
+ assert(bus);
+ assert(path);
+ assert(nodes);
+
+ HASHMAP_FOREACH(seat, m->seats, i) {
+ char *p;
+
+ p = seat_bus_path(seat);
+ if (!p)
+ return -ENOMEM;
+
+ r = strv_consume(&l, p);
+ if (r < 0)
+ return r;
+ }
+
+ message = sd_bus_get_current_message(bus);
+ if (message) {
+ _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
+ const char *name;
+ Session *session;
+
+ r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_SESSION|SD_BUS_CREDS_AUGMENT, &creds);
+ if (r >= 0) {
+ r = sd_bus_creds_get_session(creds, &name);
+ if (r >= 0) {
+ session = hashmap_get(m->sessions, name);
+ if (session && session->seat) {
+ r = strv_extend(&l, "/org/freedesktop/login1/seat/self");
+ if (r < 0)
+ return r;
+ }
+ }
+ }
+ }
+
+ *nodes = l;
+ l = NULL;
+
+ return 1;
+}
+
+int seat_send_signal(Seat *s, bool new_seat) {
+ _cleanup_free_ char *p = NULL;
+
+ assert(s);
+
+ p = seat_bus_path(s);
+ if (!p)
+ return -ENOMEM;
+
+ return sd_bus_emit_signal(
+ s->manager->bus,
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ new_seat ? "SeatNew" : "SeatRemoved",
+ "so", s->id, p);
+}
+
+int seat_send_changed(Seat *s, const char *properties, ...) {
+ _cleanup_free_ char *p = NULL;
+ char **l;
+
+ assert(s);
+
+ if (!s->started)
+ return 0;
+
+ p = seat_bus_path(s);
+ if (!p)
+ return -ENOMEM;
+
+ l = strv_from_stdarg_alloca(properties);
+
+ return sd_bus_emit_properties_changed_strv(s->manager->bus, p, "org.freedesktop.login1.Seat", l);
+}
diff --git a/src/grp-login/systemd-logind/logind-seat.c b/src/grp-login/systemd-logind/logind-seat.c
new file mode 100644
index 0000000000..6525ad5d7b
--- /dev/null
+++ b/src/grp-login/systemd-logind/logind-seat.c
@@ -0,0 +1,696 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ 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 <errno.h>
+#include <fcntl.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <systemd/sd-messages.h>
+
+#include "basic/alloc-util.h"
+#include "basic/fd-util.h"
+#include "basic/fileio.h"
+#include "basic/formats-util.h"
+#include "basic/mkdir.h"
+#include "basic/parse-util.h"
+#include "basic/stdio-util.h"
+#include "basic/string-util.h"
+#include "basic/terminal-util.h"
+#include "basic/util.h"
+
+#include "logind-acl.h"
+#include "logind-seat.h"
+
+Seat *seat_new(Manager *m, const char *id) {
+ Seat *s;
+
+ assert(m);
+ assert(id);
+
+ s = new0(Seat, 1);
+ if (!s)
+ return NULL;
+
+ s->state_file = strappend("/run/systemd/seats/", id);
+ if (!s->state_file) {
+ free(s);
+ return NULL;
+ }
+
+ s->id = basename(s->state_file);
+ s->manager = m;
+
+ if (hashmap_put(m->seats, s->id, s) < 0) {
+ free(s->state_file);
+ free(s);
+ return NULL;
+ }
+
+ return s;
+}
+
+void seat_free(Seat *s) {
+ assert(s);
+
+ if (s->in_gc_queue)
+ LIST_REMOVE(gc_queue, s->manager->seat_gc_queue, s);
+
+ while (s->sessions)
+ session_free(s->sessions);
+
+ assert(!s->active);
+
+ while (s->devices)
+ device_free(s->devices);
+
+ hashmap_remove(s->manager->seats, s->id);
+
+ free(s->positions);
+ free(s->state_file);
+ free(s);
+}
+
+int seat_save(Seat *s) {
+ _cleanup_free_ char *temp_path = NULL;
+ _cleanup_fclose_ FILE *f = NULL;
+ int r;
+
+ assert(s);
+
+ if (!s->started)
+ return 0;
+
+ r = mkdir_safe_label("/run/systemd/seats", 0755, 0, 0);
+ if (r < 0)
+ goto fail;
+
+ r = fopen_temporary(s->state_file, &f, &temp_path);
+ if (r < 0)
+ goto fail;
+
+ fchmod(fileno(f), 0644);
+
+ fprintf(f,
+ "# This is private data. Do not parse.\n"
+ "IS_SEAT0=%i\n"
+ "CAN_MULTI_SESSION=%i\n"
+ "CAN_TTY=%i\n"
+ "CAN_GRAPHICAL=%i\n",
+ seat_is_seat0(s),
+ seat_can_multi_session(s),
+ seat_can_tty(s),
+ seat_can_graphical(s));
+
+ if (s->active) {
+ assert(s->active->user);
+
+ fprintf(f,
+ "ACTIVE=%s\n"
+ "ACTIVE_UID="UID_FMT"\n",
+ s->active->id,
+ s->active->user->uid);
+ }
+
+ if (s->sessions) {
+ Session *i;
+
+ fputs("SESSIONS=", f);
+ LIST_FOREACH(sessions_by_seat, i, s->sessions) {
+ fprintf(f,
+ "%s%c",
+ i->id,
+ i->sessions_by_seat_next ? ' ' : '\n');
+ }
+
+ fputs("UIDS=", f);
+ LIST_FOREACH(sessions_by_seat, i, s->sessions)
+ fprintf(f,
+ UID_FMT"%c",
+ i->user->uid,
+ i->sessions_by_seat_next ? ' ' : '\n');
+ }
+
+ r = fflush_and_check(f);
+ if (r < 0)
+ goto fail;
+
+ if (rename(temp_path, s->state_file) < 0) {
+ r = -errno;
+ goto fail;
+ }
+
+ return 0;
+
+fail:
+ (void) unlink(s->state_file);
+
+ if (temp_path)
+ (void) unlink(temp_path);
+
+ return log_error_errno(r, "Failed to save seat data %s: %m", s->state_file);
+}
+
+int seat_load(Seat *s) {
+ assert(s);
+
+ /* There isn't actually anything to read here ... */
+
+ return 0;
+}
+
+static int vt_allocate(unsigned int vtnr) {
+ char p[sizeof("/dev/tty") + DECIMAL_STR_MAX(unsigned int)];
+ _cleanup_close_ int fd = -1;
+
+ assert(vtnr >= 1);
+
+ xsprintf(p, "/dev/tty%u", vtnr);
+ fd = open_terminal(p, O_RDWR|O_NOCTTY|O_CLOEXEC);
+ if (fd < 0)
+ return -errno;
+
+ return 0;
+}
+
+int seat_preallocate_vts(Seat *s) {
+ int r = 0;
+ unsigned i;
+
+ assert(s);
+ assert(s->manager);
+
+ log_debug("Preallocating VTs...");
+
+ if (s->manager->n_autovts <= 0)
+ return 0;
+
+ if (!seat_has_vts(s))
+ return 0;
+
+ for (i = 1; i <= s->manager->n_autovts; i++) {
+ int q;
+
+ q = vt_allocate(i);
+ if (q < 0) {
+ log_error_errno(q, "Failed to preallocate VT %u: %m", i);
+ r = q;
+ }
+ }
+
+ return r;
+}
+
+int seat_apply_acls(Seat *s, Session *old_active) {
+ int r;
+
+ assert(s);
+
+ r = devnode_acl_all(s->manager->udev,
+ s->id,
+ false,
+ !!old_active, old_active ? old_active->user->uid : 0,
+ !!s->active, s->active ? s->active->user->uid : 0);
+
+ if (r < 0)
+ log_error_errno(r, "Failed to apply ACLs: %m");
+
+ return r;
+}
+
+int seat_set_active(Seat *s, Session *session) {
+ Session *old_active;
+
+ assert(s);
+ assert(!session || session->seat == s);
+
+ if (session == s->active)
+ return 0;
+
+ old_active = s->active;
+ s->active = session;
+
+ if (old_active) {
+ session_device_pause_all(old_active);
+ session_send_changed(old_active, "Active", NULL);
+ }
+
+ seat_apply_acls(s, old_active);
+
+ if (session && session->started) {
+ session_send_changed(session, "Active", NULL);
+ session_device_resume_all(session);
+ }
+
+ if (!session || session->started)
+ seat_send_changed(s, "ActiveSession", NULL);
+
+ seat_save(s);
+
+ if (session) {
+ session_save(session);
+ user_save(session->user);
+ }
+
+ if (old_active) {
+ session_save(old_active);
+ if (!session || session->user != old_active->user)
+ user_save(old_active->user);
+ }
+
+ return 0;
+}
+
+int seat_switch_to(Seat *s, unsigned int num) {
+ /* Public session positions skip 0 (there is only F1-F12). Maybe it
+ * will get reassigned in the future, so return error for now. */
+ if (num == 0)
+ return -EINVAL;
+
+ if (num >= s->position_count || !s->positions[num]) {
+ /* allow switching to unused VTs to trigger auto-activate */
+ if (seat_has_vts(s) && num < 64)
+ return chvt(num);
+
+ return -EINVAL;
+ }
+
+ return session_activate(s->positions[num]);
+}
+
+int seat_switch_to_next(Seat *s) {
+ unsigned int start, i;
+
+ if (s->position_count == 0)
+ return -EINVAL;
+
+ start = 1;
+ if (s->active && s->active->position > 0)
+ start = s->active->position;
+
+ for (i = start + 1; i < s->position_count; ++i)
+ if (s->positions[i])
+ return session_activate(s->positions[i]);
+
+ for (i = 1; i < start; ++i)
+ if (s->positions[i])
+ return session_activate(s->positions[i]);
+
+ return -EINVAL;
+}
+
+int seat_switch_to_previous(Seat *s) {
+ unsigned int start, i;
+
+ if (s->position_count == 0)
+ return -EINVAL;
+
+ start = 1;
+ if (s->active && s->active->position > 0)
+ start = s->active->position;
+
+ for (i = start - 1; i > 0; --i)
+ if (s->positions[i])
+ return session_activate(s->positions[i]);
+
+ for (i = s->position_count - 1; i > start; --i)
+ if (s->positions[i])
+ return session_activate(s->positions[i]);
+
+ return -EINVAL;
+}
+
+int seat_active_vt_changed(Seat *s, unsigned int vtnr) {
+ Session *i, *new_active = NULL;
+ int r;
+
+ assert(s);
+ assert(vtnr >= 1);
+
+ if (!seat_has_vts(s))
+ return -EINVAL;
+
+ log_debug("VT changed to %u", vtnr);
+
+ /* we might have earlier closing sessions on the same VT, so try to
+ * find a running one first */
+ LIST_FOREACH(sessions_by_seat, i, s->sessions)
+ if (i->vtnr == vtnr && !i->stopping) {
+ new_active = i;
+ break;
+ }
+
+ if (!new_active) {
+ /* no running one? then we can't decide which one is the
+ * active one, let the first one win */
+ LIST_FOREACH(sessions_by_seat, i, s->sessions)
+ if (i->vtnr == vtnr) {
+ new_active = i;
+ break;
+ }
+ }
+
+ r = seat_set_active(s, new_active);
+ manager_spawn_autovt(s->manager, vtnr);
+
+ return r;
+}
+
+int seat_read_active_vt(Seat *s) {
+ char t[64];
+ ssize_t k;
+ unsigned int vtnr;
+ int r;
+
+ assert(s);
+
+ if (!seat_has_vts(s))
+ return 0;
+
+ lseek(s->manager->console_active_fd, SEEK_SET, 0);
+
+ k = read(s->manager->console_active_fd, t, sizeof(t)-1);
+ if (k <= 0) {
+ log_error("Failed to read current console: %s", k < 0 ? strerror(-errno) : "EOF");
+ return k < 0 ? -errno : -EIO;
+ }
+
+ t[k] = 0;
+ truncate_nl(t);
+
+ if (!startswith(t, "tty")) {
+ log_error("Hm, /sys/class/tty/tty0/active is badly formatted.");
+ return -EIO;
+ }
+
+ r = safe_atou(t+3, &vtnr);
+ if (r < 0) {
+ log_error("Failed to parse VT number %s", t+3);
+ return r;
+ }
+
+ if (!vtnr) {
+ log_error("VT number invalid: %s", t+3);
+ return -EIO;
+ }
+
+ return seat_active_vt_changed(s, vtnr);
+}
+
+int seat_start(Seat *s) {
+ assert(s);
+
+ if (s->started)
+ return 0;
+
+ log_struct(LOG_INFO,
+ LOG_MESSAGE_ID(SD_MESSAGE_SEAT_START),
+ "SEAT_ID=%s", s->id,
+ LOG_MESSAGE("New seat %s.", s->id),
+ NULL);
+
+ /* Initialize VT magic stuff */
+ seat_preallocate_vts(s);
+
+ /* Read current VT */
+ seat_read_active_vt(s);
+
+ s->started = true;
+
+ /* Save seat data */
+ seat_save(s);
+
+ seat_send_signal(s, true);
+
+ return 0;
+}
+
+int seat_stop(Seat *s, bool force) {
+ int r = 0;
+
+ assert(s);
+
+ if (s->started)
+ log_struct(LOG_INFO,
+ LOG_MESSAGE_ID(SD_MESSAGE_SEAT_STOP),
+ "SEAT_ID=%s", s->id,
+ LOG_MESSAGE("Removed seat %s.", s->id),
+ NULL);
+
+ seat_stop_sessions(s, force);
+
+ unlink(s->state_file);
+ seat_add_to_gc_queue(s);
+
+ if (s->started)
+ seat_send_signal(s, false);
+
+ s->started = false;
+
+ return r;
+}
+
+int seat_stop_sessions(Seat *s, bool force) {
+ Session *session;
+ int r = 0, k;
+
+ assert(s);
+
+ LIST_FOREACH(sessions_by_seat, session, s->sessions) {
+ k = session_stop(session, force);
+ if (k < 0)
+ r = k;
+ }
+
+ return r;
+}
+
+void seat_evict_position(Seat *s, Session *session) {
+ Session *iter;
+ unsigned int pos = session->position;
+
+ session->position = 0;
+
+ if (pos == 0)
+ return;
+
+ if (pos < s->position_count && s->positions[pos] == session) {
+ s->positions[pos] = NULL;
+
+ /* There might be another session claiming the same
+ * position (eg., during gdm->session transition), so let's look
+ * for it and set it on the free slot. */
+ LIST_FOREACH(sessions_by_seat, iter, s->sessions) {
+ if (iter->position == pos && session_get_state(iter) != SESSION_CLOSING) {
+ s->positions[pos] = iter;
+ break;
+ }
+ }
+ }
+}
+
+void seat_claim_position(Seat *s, Session *session, unsigned int pos) {
+ /* with VTs, the position is always the same as the VTnr */
+ if (seat_has_vts(s))
+ pos = session->vtnr;
+
+ if (!GREEDY_REALLOC0(s->positions, s->position_count, pos + 1))
+ return;
+
+ seat_evict_position(s, session);
+
+ session->position = pos;
+ if (pos > 0)
+ s->positions[pos] = session;
+}
+
+static void seat_assign_position(Seat *s, Session *session) {
+ unsigned int pos;
+
+ if (session->position > 0)
+ return;
+
+ for (pos = 1; pos < s->position_count; ++pos)
+ if (!s->positions[pos])
+ break;
+
+ seat_claim_position(s, session, pos);
+}
+
+int seat_attach_session(Seat *s, Session *session) {
+ assert(s);
+ assert(session);
+ assert(!session->seat);
+
+ if (!seat_has_vts(s) != !session->vtnr)
+ return -EINVAL;
+
+ session->seat = s;
+ LIST_PREPEND(sessions_by_seat, s->sessions, session);
+ seat_assign_position(s, session);
+
+ seat_send_changed(s, "Sessions", NULL);
+
+ /* On seats with VTs, the VT logic defines which session is active. On
+ * seats without VTs, we automatically activate new sessions. */
+ if (!seat_has_vts(s))
+ seat_set_active(s, session);
+
+ return 0;
+}
+
+void seat_complete_switch(Seat *s) {
+ Session *session;
+
+ assert(s);
+
+ /* if no session-switch is pending or if it got canceled, do nothing */
+ if (!s->pending_switch)
+ return;
+
+ session = s->pending_switch;
+ s->pending_switch = NULL;
+
+ seat_set_active(s, session);
+}
+
+bool seat_has_vts(Seat *s) {
+ assert(s);
+
+ return seat_is_seat0(s) && s->manager->console_active_fd >= 0;
+}
+
+bool seat_is_seat0(Seat *s) {
+ assert(s);
+
+ return s->manager->seat0 == s;
+}
+
+bool seat_can_multi_session(Seat *s) {
+ assert(s);
+
+ return seat_has_vts(s);
+}
+
+bool seat_can_tty(Seat *s) {
+ assert(s);
+
+ return seat_has_vts(s);
+}
+
+bool seat_has_master_device(Seat *s) {
+ assert(s);
+
+ /* device list is ordered by "master" flag */
+ return !!s->devices && s->devices->master;
+}
+
+bool seat_can_graphical(Seat *s) {
+ assert(s);
+
+ return seat_has_master_device(s);
+}
+
+int seat_get_idle_hint(Seat *s, dual_timestamp *t) {
+ Session *session;
+ bool idle_hint = true;
+ dual_timestamp ts = DUAL_TIMESTAMP_NULL;
+
+ assert(s);
+
+ LIST_FOREACH(sessions_by_seat, session, s->sessions) {
+ dual_timestamp k;
+ int ih;
+
+ ih = session_get_idle_hint(session, &k);
+ if (ih < 0)
+ return ih;
+
+ if (!ih) {
+ if (!idle_hint) {
+ if (k.monotonic > ts.monotonic)
+ ts = k;
+ } else {
+ idle_hint = false;
+ ts = k;
+ }
+ } else if (idle_hint) {
+
+ if (k.monotonic > ts.monotonic)
+ ts = k;
+ }
+ }
+
+ if (t)
+ *t = ts;
+
+ return idle_hint;
+}
+
+bool seat_check_gc(Seat *s, bool drop_not_started) {
+ assert(s);
+
+ if (drop_not_started && !s->started)
+ return false;
+
+ if (seat_is_seat0(s))
+ return true;
+
+ return seat_has_master_device(s);
+}
+
+void seat_add_to_gc_queue(Seat *s) {
+ assert(s);
+
+ if (s->in_gc_queue)
+ return;
+
+ LIST_PREPEND(gc_queue, s->manager->seat_gc_queue, s);
+ s->in_gc_queue = true;
+}
+
+static bool seat_name_valid_char(char c) {
+ return
+ (c >= 'a' && c <= 'z') ||
+ (c >= 'A' && c <= 'Z') ||
+ (c >= '0' && c <= '9') ||
+ c == '-' ||
+ c == '_';
+}
+
+bool seat_name_is_valid(const char *name) {
+ const char *p;
+
+ assert(name);
+
+ if (!startswith(name, "seat"))
+ return false;
+
+ if (!name[4])
+ return false;
+
+ for (p = name; *p; p++)
+ if (!seat_name_valid_char(*p))
+ return false;
+
+ if (strlen(name) > 255)
+ return false;
+
+ return true;
+}
diff --git a/src/grp-login/systemd-logind/logind-seat.h b/src/grp-login/systemd-logind/logind-seat.h
new file mode 100644
index 0000000000..7fbeb5a727
--- /dev/null
+++ b/src/grp-login/systemd-logind/logind-seat.h
@@ -0,0 +1,96 @@
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ 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 "basic/list.h"
+
+typedef struct Seat Seat;
+
+#include "logind-session.h"
+
+struct Seat {
+ Manager *manager;
+ char *id;
+
+ char *state_file;
+
+ LIST_HEAD(Device, devices);
+
+ Session *active;
+ Session *pending_switch;
+ LIST_HEAD(Session, sessions);
+
+ Session **positions;
+ size_t position_count;
+
+ bool in_gc_queue:1;
+ bool started:1;
+
+ LIST_FIELDS(Seat, gc_queue);
+};
+
+Seat *seat_new(Manager *m, const char *id);
+void seat_free(Seat *s);
+
+int seat_save(Seat *s);
+int seat_load(Seat *s);
+
+int seat_apply_acls(Seat *s, Session *old_active);
+int seat_set_active(Seat *s, Session *session);
+int seat_switch_to(Seat *s, unsigned int num);
+int seat_switch_to_next(Seat *s);
+int seat_switch_to_previous(Seat *s);
+int seat_active_vt_changed(Seat *s, unsigned int vtnr);
+int seat_read_active_vt(Seat *s);
+int seat_preallocate_vts(Seat *s);
+
+int seat_attach_session(Seat *s, Session *session);
+void seat_complete_switch(Seat *s);
+void seat_evict_position(Seat *s, Session *session);
+void seat_claim_position(Seat *s, Session *session, unsigned int pos);
+
+bool seat_has_vts(Seat *s);
+bool seat_is_seat0(Seat *s);
+bool seat_can_multi_session(Seat *s);
+bool seat_can_tty(Seat *s);
+bool seat_has_master_device(Seat *s);
+bool seat_can_graphical(Seat *s);
+
+int seat_get_idle_hint(Seat *s, dual_timestamp *t);
+
+int seat_start(Seat *s);
+int seat_stop(Seat *s, bool force);
+int seat_stop_sessions(Seat *s, bool force);
+
+bool seat_check_gc(Seat *s, bool drop_not_started);
+void seat_add_to_gc_queue(Seat *s);
+
+bool seat_name_is_valid(const char *name);
+
+extern const sd_bus_vtable seat_vtable[];
+
+int seat_node_enumerator(sd_bus *bus, const char *path, void *userdata, char ***nodes, sd_bus_error *error);
+int seat_object_find(sd_bus *bus, const char *path, const char *interface, void *userdata, void **found, sd_bus_error *error);
+char *seat_bus_path(Seat *s);
+
+int seat_send_signal(Seat *s, bool new_seat);
+int seat_send_changed(Seat *s, const char *properties, ...) _sentinel_;
+
+int bus_seat_method_terminate(sd_bus_message *message, void *userdata, sd_bus_error *error);
diff --git a/src/grp-login/systemd-logind/logind-session-dbus.c b/src/grp-login/systemd-logind/logind-session-dbus.c
new file mode 100644
index 0000000000..f79f9b5003
--- /dev/null
+++ b/src/grp-login/systemd-logind/logind-session-dbus.c
@@ -0,0 +1,799 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ 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 <errno.h>
+#include <string.h>
+
+#include "basic/alloc-util.h"
+#include "basic/bus-label.h"
+#include "basic/fd-util.h"
+#include "basic/signal-util.h"
+#include "basic/strv.h"
+#include "basic/util.h"
+#include "sd-bus/bus-common-errors.h"
+#include "shared/bus-util.h"
+
+#include "logind-session-device.h"
+#include "logind-session.h"
+#include "logind.h"
+
+static int property_get_user(
+ sd_bus *bus,
+ const char *path,
+ const char *interface,
+ const char *property,
+ sd_bus_message *reply,
+ void *userdata,
+ sd_bus_error *error) {
+
+ _cleanup_free_ char *p = NULL;
+ Session *s = userdata;
+
+ assert(bus);
+ assert(reply);
+ assert(s);
+
+ p = user_bus_path(s->user);
+ if (!p)
+ return -ENOMEM;
+
+ return sd_bus_message_append(reply, "(uo)", (uint32_t) s->user->uid, p);
+}
+
+static int property_get_name(
+ sd_bus *bus,
+ const char *path,
+ const char *interface,
+ const char *property,
+ sd_bus_message *reply,
+ void *userdata,
+ sd_bus_error *error) {
+
+ Session *s = userdata;
+
+ assert(bus);
+ assert(reply);
+ assert(s);
+
+ return sd_bus_message_append(reply, "s", s->user->name);
+}
+
+static int property_get_seat(
+ sd_bus *bus,
+ const char *path,
+ const char *interface,
+ const char *property,
+ sd_bus_message *reply,
+ void *userdata,
+ sd_bus_error *error) {
+
+ _cleanup_free_ char *p = NULL;
+ Session *s = userdata;
+
+ assert(bus);
+ assert(reply);
+ assert(s);
+
+ p = s->seat ? seat_bus_path(s->seat) : strdup("/");
+ if (!p)
+ return -ENOMEM;
+
+ return sd_bus_message_append(reply, "(so)", s->seat ? s->seat->id : "", p);
+}
+
+static BUS_DEFINE_PROPERTY_GET_ENUM(property_get_type, session_type, SessionType);
+static BUS_DEFINE_PROPERTY_GET_ENUM(property_get_class, session_class, SessionClass);
+
+static int property_get_active(
+ sd_bus *bus,
+ const char *path,
+ const char *interface,
+ const char *property,
+ sd_bus_message *reply,
+ void *userdata,
+ sd_bus_error *error) {
+
+ Session *s = userdata;
+
+ assert(bus);
+ assert(reply);
+ assert(s);
+
+ return sd_bus_message_append(reply, "b", session_is_active(s));
+}
+
+static int property_get_state(
+ sd_bus *bus,
+ const char *path,
+ const char *interface,
+ const char *property,
+ sd_bus_message *reply,
+ void *userdata,
+ sd_bus_error *error) {
+
+ Session *s = userdata;
+
+ assert(bus);
+ assert(reply);
+ assert(s);
+
+ return sd_bus_message_append(reply, "s", session_state_to_string(session_get_state(s)));
+}
+
+static int property_get_idle_hint(
+ sd_bus *bus,
+ const char *path,
+ const char *interface,
+ const char *property,
+ sd_bus_message *reply,
+ void *userdata,
+ sd_bus_error *error) {
+
+ Session *s = userdata;
+
+ assert(bus);
+ assert(reply);
+ assert(s);
+
+ return sd_bus_message_append(reply, "b", session_get_idle_hint(s, NULL) > 0);
+}
+
+static int property_get_idle_since_hint(
+ sd_bus *bus,
+ const char *path,
+ const char *interface,
+ const char *property,
+ sd_bus_message *reply,
+ void *userdata,
+ sd_bus_error *error) {
+
+ Session *s = userdata;
+ dual_timestamp t = DUAL_TIMESTAMP_NULL;
+ uint64_t u;
+ int r;
+
+ assert(bus);
+ assert(reply);
+ assert(s);
+
+ r = session_get_idle_hint(s, &t);
+ if (r < 0)
+ return r;
+
+ u = streq(property, "IdleSinceHint") ? t.realtime : t.monotonic;
+
+ return sd_bus_message_append(reply, "t", u);
+}
+
+static int property_get_locked_hint(
+ sd_bus *bus,
+ const char *path,
+ const char *interface,
+ const char *property,
+ sd_bus_message *reply,
+ void *userdata,
+ sd_bus_error *error) {
+
+ Session *s = userdata;
+
+ assert(bus);
+ assert(reply);
+ assert(s);
+
+ return sd_bus_message_append(reply, "b", session_get_locked_hint(s) > 0);
+}
+
+int bus_session_method_terminate(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ Session *s = userdata;
+ int r;
+
+ assert(message);
+ assert(s);
+
+ r = bus_verify_polkit_async(
+ message,
+ CAP_KILL,
+ "org.freedesktop.login1.manage",
+ NULL,
+ false,
+ s->user->uid,
+ &s->manager->polkit_registry,
+ error);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ return 1; /* Will call us back */
+
+ r = session_stop(s, true);
+ if (r < 0)
+ return r;
+
+ return sd_bus_reply_method_return(message, NULL);
+}
+
+int bus_session_method_activate(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ Session *s = userdata;
+ int r;
+
+ assert(message);
+ assert(s);
+
+ r = session_activate(s);
+ if (r < 0)
+ return r;
+
+ return sd_bus_reply_method_return(message, NULL);
+}
+
+int bus_session_method_lock(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ Session *s = userdata;
+ int r;
+
+ assert(message);
+ assert(s);
+
+ r = bus_verify_polkit_async(
+ message,
+ CAP_SYS_ADMIN,
+ "org.freedesktop.login1.lock-sessions",
+ NULL,
+ false,
+ s->user->uid,
+ &s->manager->polkit_registry,
+ error);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ return 1; /* Will call us back */
+
+ r = session_send_lock(s, strstr(sd_bus_message_get_member(message), "Lock"));
+ if (r < 0)
+ return r;
+
+ return sd_bus_reply_method_return(message, NULL);
+}
+
+static int method_set_idle_hint(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
+ Session *s = userdata;
+ uid_t uid;
+ int r, b;
+
+ assert(message);
+ assert(s);
+
+ r = sd_bus_message_read(message, "b", &b);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_EUID, &creds);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_creds_get_euid(creds, &uid);
+ if (r < 0)
+ return r;
+
+ if (uid != 0 && uid != s->user->uid)
+ return sd_bus_error_setf(error, SD_BUS_ERROR_ACCESS_DENIED, "Only owner of session may set idle hint");
+
+ session_set_idle_hint(s, b);
+
+ return sd_bus_reply_method_return(message, NULL);
+}
+
+static int method_set_locked_hint(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
+ Session *s = userdata;
+ uid_t uid;
+ int r, b;
+
+ assert(message);
+ assert(s);
+
+ r = sd_bus_message_read(message, "b", &b);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_EUID, &creds);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_creds_get_euid(creds, &uid);
+ if (r < 0)
+ return r;
+
+ if (uid != 0 && uid != s->user->uid)
+ return sd_bus_error_setf(error, SD_BUS_ERROR_ACCESS_DENIED, "Only owner of session may set locked hint");
+
+ session_set_locked_hint(s, b);
+
+ return sd_bus_reply_method_return(message, NULL);
+}
+
+int bus_session_method_kill(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ Session *s = userdata;
+ const char *swho;
+ int32_t signo;
+ KillWho who;
+ int r;
+
+ assert(message);
+ assert(s);
+
+ r = sd_bus_message_read(message, "si", &swho, &signo);
+ if (r < 0)
+ return r;
+
+ if (isempty(swho))
+ who = KILL_ALL;
+ else {
+ who = kill_who_from_string(swho);
+ if (who < 0)
+ return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid kill parameter '%s'", swho);
+ }
+
+ if (!SIGNAL_VALID(signo))
+ return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid signal %i", signo);
+
+ r = bus_verify_polkit_async(
+ message,
+ CAP_KILL,
+ "org.freedesktop.login1.manage",
+ NULL,
+ false,
+ s->user->uid,
+ &s->manager->polkit_registry,
+ error);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ return 1; /* Will call us back */
+
+ r = session_kill(s, who, signo);
+ if (r < 0)
+ return r;
+
+ return sd_bus_reply_method_return(message, NULL);
+}
+
+static int method_take_control(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
+ Session *s = userdata;
+ int r, force;
+ uid_t uid;
+
+ assert(message);
+ assert(s);
+
+ r = sd_bus_message_read(message, "b", &force);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_EUID, &creds);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_creds_get_euid(creds, &uid);
+ if (r < 0)
+ return r;
+
+ if (uid != 0 && (force || uid != s->user->uid))
+ return sd_bus_error_setf(error, SD_BUS_ERROR_ACCESS_DENIED, "Only owner of session may take control");
+
+ r = session_set_controller(s, sd_bus_message_get_sender(message), force);
+ if (r < 0)
+ return r;
+
+ return sd_bus_reply_method_return(message, NULL);
+}
+
+static int method_release_control(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ Session *s = userdata;
+
+ assert(message);
+ assert(s);
+
+ if (!session_is_controller(s, sd_bus_message_get_sender(message)))
+ return sd_bus_error_setf(error, BUS_ERROR_NOT_IN_CONTROL, "You are not in control of this session");
+
+ session_drop_controller(s);
+
+ return sd_bus_reply_method_return(message, NULL);
+}
+
+static int method_take_device(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ Session *s = userdata;
+ uint32_t major, minor;
+ SessionDevice *sd;
+ dev_t dev;
+ int r;
+
+ assert(message);
+ assert(s);
+
+ r = sd_bus_message_read(message, "uu", &major, &minor);
+ if (r < 0)
+ return r;
+
+ if (!session_is_controller(s, sd_bus_message_get_sender(message)))
+ return sd_bus_error_setf(error, BUS_ERROR_NOT_IN_CONTROL, "You are not in control of this session");
+
+ dev = makedev(major, minor);
+ sd = hashmap_get(s->devices, &dev);
+ if (sd)
+ /* We don't allow retrieving a device multiple times.
+ * The related ReleaseDevice call is not ref-counted.
+ * The caller should use dup() if it requires more
+ * than one fd (it would be functionally
+ * equivalent). */
+ return sd_bus_error_setf(error, BUS_ERROR_DEVICE_IS_TAKEN, "Device already taken");
+
+ r = session_device_new(s, dev, &sd);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_reply_method_return(message, "hb", sd->fd, !sd->active);
+ if (r < 0)
+ session_device_free(sd);
+
+ return r;
+}
+
+static int method_release_device(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ Session *s = userdata;
+ uint32_t major, minor;
+ SessionDevice *sd;
+ dev_t dev;
+ int r;
+
+ assert(message);
+ assert(s);
+
+ r = sd_bus_message_read(message, "uu", &major, &minor);
+ if (r < 0)
+ return r;
+
+ if (!session_is_controller(s, sd_bus_message_get_sender(message)))
+ return sd_bus_error_setf(error, BUS_ERROR_NOT_IN_CONTROL, "You are not in control of this session");
+
+ dev = makedev(major, minor);
+ sd = hashmap_get(s->devices, &dev);
+ if (!sd)
+ return sd_bus_error_setf(error, BUS_ERROR_DEVICE_NOT_TAKEN, "Device not taken");
+
+ session_device_free(sd);
+ return sd_bus_reply_method_return(message, NULL);
+}
+
+static int method_pause_device_complete(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ Session *s = userdata;
+ uint32_t major, minor;
+ SessionDevice *sd;
+ dev_t dev;
+ int r;
+
+ assert(message);
+ assert(s);
+
+ r = sd_bus_message_read(message, "uu", &major, &minor);
+ if (r < 0)
+ return r;
+
+ if (!session_is_controller(s, sd_bus_message_get_sender(message)))
+ return sd_bus_error_setf(error, BUS_ERROR_NOT_IN_CONTROL, "You are not in control of this session");
+
+ dev = makedev(major, minor);
+ sd = hashmap_get(s->devices, &dev);
+ if (!sd)
+ return sd_bus_error_setf(error, BUS_ERROR_DEVICE_NOT_TAKEN, "Device not taken");
+
+ session_device_complete_pause(sd);
+
+ return sd_bus_reply_method_return(message, NULL);
+}
+
+const sd_bus_vtable session_vtable[] = {
+ SD_BUS_VTABLE_START(0),
+
+ SD_BUS_PROPERTY("Id", "s", NULL, offsetof(Session, id), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("User", "(uo)", property_get_user, 0, SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("Name", "s", property_get_name, 0, SD_BUS_VTABLE_PROPERTY_CONST),
+ BUS_PROPERTY_DUAL_TIMESTAMP("Timestamp", offsetof(Session, timestamp), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("VTNr", "u", NULL, offsetof(Session, vtnr), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("Seat", "(so)", property_get_seat, 0, SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("TTY", "s", NULL, offsetof(Session, tty), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("Display", "s", NULL, offsetof(Session, display), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("Remote", "b", bus_property_get_bool, offsetof(Session, remote), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("RemoteHost", "s", NULL, offsetof(Session, remote_host), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("RemoteUser", "s", NULL, offsetof(Session, remote_user), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("Service", "s", NULL, offsetof(Session, service), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("Desktop", "s", NULL, offsetof(Session, desktop), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("Scope", "s", NULL, offsetof(Session, scope), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("Leader", "u", bus_property_get_pid, offsetof(Session, leader), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("Audit", "u", NULL, offsetof(Session, audit_id), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("Type", "s", property_get_type, offsetof(Session, type), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("Class", "s", property_get_class, offsetof(Session, class), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("Active", "b", property_get_active, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
+ SD_BUS_PROPERTY("State", "s", property_get_state, 0, 0),
+ SD_BUS_PROPERTY("IdleHint", "b", property_get_idle_hint, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
+ SD_BUS_PROPERTY("IdleSinceHint", "t", property_get_idle_since_hint, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
+ SD_BUS_PROPERTY("IdleSinceHintMonotonic", "t", property_get_idle_since_hint, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
+ SD_BUS_PROPERTY("LockedHint", "b", property_get_locked_hint, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
+
+ SD_BUS_METHOD("Terminate", NULL, NULL, bus_session_method_terminate, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("Activate", NULL, NULL, bus_session_method_activate, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("Lock", NULL, NULL, bus_session_method_lock, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("Unlock", NULL, NULL, bus_session_method_lock, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("SetIdleHint", "b", NULL, method_set_idle_hint, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("SetLockedHint", "b", NULL, method_set_locked_hint, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("Kill", "si", NULL, bus_session_method_kill, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("TakeControl", "b", NULL, method_take_control, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("ReleaseControl", NULL, NULL, method_release_control, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("TakeDevice", "uu", "hb", method_take_device, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("ReleaseDevice", "uu", NULL, method_release_device, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("PauseDeviceComplete", "uu", NULL, method_pause_device_complete, SD_BUS_VTABLE_UNPRIVILEGED),
+
+ SD_BUS_SIGNAL("PauseDevice", "uus", 0),
+ SD_BUS_SIGNAL("ResumeDevice", "uuh", 0),
+ SD_BUS_SIGNAL("Lock", NULL, 0),
+ SD_BUS_SIGNAL("Unlock", NULL, 0),
+
+ SD_BUS_VTABLE_END
+};
+
+int session_object_find(sd_bus *bus, const char *path, const char *interface, void *userdata, void **found, sd_bus_error *error) {
+ Manager *m = userdata;
+ Session *session;
+ int r;
+
+ assert(bus);
+ assert(path);
+ assert(interface);
+ assert(found);
+ assert(m);
+
+ if (streq(path, "/org/freedesktop/login1/session/self")) {
+ _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
+ sd_bus_message *message;
+ const char *name;
+
+ message = sd_bus_get_current_message(bus);
+ if (!message)
+ return 0;
+
+ r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_SESSION|SD_BUS_CREDS_AUGMENT, &creds);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_creds_get_session(creds, &name);
+ if (r < 0)
+ return r;
+
+ session = hashmap_get(m->sessions, name);
+ } else {
+ _cleanup_free_ char *e = NULL;
+ const char *p;
+
+ p = startswith(path, "/org/freedesktop/login1/session/");
+ if (!p)
+ return 0;
+
+ e = bus_label_unescape(p);
+ if (!e)
+ return -ENOMEM;
+
+ session = hashmap_get(m->sessions, e);
+ }
+
+ if (!session)
+ return 0;
+
+ *found = session;
+ return 1;
+}
+
+char *session_bus_path(Session *s) {
+ _cleanup_free_ char *t = NULL;
+
+ assert(s);
+
+ t = bus_label_escape(s->id);
+ if (!t)
+ return NULL;
+
+ return strappend("/org/freedesktop/login1/session/", t);
+}
+
+int session_node_enumerator(sd_bus *bus, const char *path, void *userdata, char ***nodes, sd_bus_error *error) {
+ _cleanup_strv_free_ char **l = NULL;
+ sd_bus_message *message;
+ Manager *m = userdata;
+ Session *session;
+ Iterator i;
+ int r;
+
+ assert(bus);
+ assert(path);
+ assert(nodes);
+
+ HASHMAP_FOREACH(session, m->sessions, i) {
+ char *p;
+
+ p = session_bus_path(session);
+ if (!p)
+ return -ENOMEM;
+
+ r = strv_consume(&l, p);
+ if (r < 0)
+ return r;
+ }
+
+ message = sd_bus_get_current_message(bus);
+ if (message) {
+ _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
+ const char *name;
+
+ r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_SESSION|SD_BUS_CREDS_AUGMENT, &creds);
+ if (r >= 0) {
+ r = sd_bus_creds_get_session(creds, &name);
+ if (r >= 0) {
+ session = hashmap_get(m->sessions, name);
+ if (session) {
+ r = strv_extend(&l, "/org/freedesktop/login1/session/self");
+ if (r < 0)
+ return r;
+ }
+ }
+ }
+ }
+
+ *nodes = l;
+ l = NULL;
+
+ return 1;
+}
+
+int session_send_signal(Session *s, bool new_session) {
+ _cleanup_free_ char *p = NULL;
+
+ assert(s);
+
+ p = session_bus_path(s);
+ if (!p)
+ return -ENOMEM;
+
+ return sd_bus_emit_signal(
+ s->manager->bus,
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ new_session ? "SessionNew" : "SessionRemoved",
+ "so", s->id, p);
+}
+
+int session_send_changed(Session *s, const char *properties, ...) {
+ _cleanup_free_ char *p = NULL;
+ char **l;
+
+ assert(s);
+
+ if (!s->started)
+ return 0;
+
+ p = session_bus_path(s);
+ if (!p)
+ return -ENOMEM;
+
+ l = strv_from_stdarg_alloca(properties);
+
+ return sd_bus_emit_properties_changed_strv(s->manager->bus, p, "org.freedesktop.login1.Session", l);
+}
+
+int session_send_lock(Session *s, bool lock) {
+ _cleanup_free_ char *p = NULL;
+
+ assert(s);
+
+ p = session_bus_path(s);
+ if (!p)
+ return -ENOMEM;
+
+ return sd_bus_emit_signal(
+ s->manager->bus,
+ p,
+ "org.freedesktop.login1.Session",
+ lock ? "Lock" : "Unlock",
+ NULL);
+}
+
+int session_send_lock_all(Manager *m, bool lock) {
+ Session *session;
+ Iterator i;
+ int r = 0;
+
+ assert(m);
+
+ HASHMAP_FOREACH(session, m->sessions, i) {
+ int k;
+
+ k = session_send_lock(session, lock);
+ if (k < 0)
+ r = k;
+ }
+
+ return r;
+}
+
+int session_send_create_reply(Session *s, sd_bus_error *error) {
+ _cleanup_(sd_bus_message_unrefp) sd_bus_message *c = NULL;
+ _cleanup_close_ int fifo_fd = -1;
+ _cleanup_free_ char *p = NULL;
+
+ assert(s);
+
+ /* This is called after the session scope and the user service
+ * were successfully created, and finishes where
+ * bus_manager_create_session() left off. */
+
+ if (!s->create_message)
+ return 0;
+
+ if (!sd_bus_error_is_set(error) && (s->scope_job || s->user->service_job))
+ return 0;
+
+ c = s->create_message;
+ s->create_message = NULL;
+
+ if (error)
+ return sd_bus_reply_method_error(c, error);
+
+ fifo_fd = session_create_fifo(s);
+ if (fifo_fd < 0)
+ return fifo_fd;
+
+ /* Update the session state file before we notify the client
+ * about the result. */
+ session_save(s);
+
+ p = session_bus_path(s);
+ if (!p)
+ return -ENOMEM;
+
+ log_debug("Sending reply about created session: "
+ "id=%s object_path=%s uid=%u runtime_path=%s "
+ "session_fd=%d seat=%s vtnr=%u",
+ s->id,
+ p,
+ (uint32_t) s->user->uid,
+ s->user->runtime_path,
+ fifo_fd,
+ s->seat ? s->seat->id : "",
+ (uint32_t) s->vtnr);
+
+ return sd_bus_reply_method_return(
+ c, "soshusub",
+ s->id,
+ p,
+ s->user->runtime_path,
+ fifo_fd,
+ (uint32_t) s->user->uid,
+ s->seat ? s->seat->id : "",
+ (uint32_t) s->vtnr,
+ false);
+}
diff --git a/src/grp-login/systemd-logind/logind-session-device.c b/src/grp-login/systemd-logind/logind-session-device.c
new file mode 100644
index 0000000000..99528488c0
--- /dev/null
+++ b/src/grp-login/systemd-logind/logind-session-device.c
@@ -0,0 +1,482 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2013 David Herrmann
+
+ 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 <string.h>
+#include <sys/ioctl.h>
+#include <sys/types.h>
+
+#include <linux/input.h>
+
+#include <libudev.h>
+
+#include "basic/alloc-util.h"
+#include "basic/fd-util.h"
+#include "basic/missing.h"
+#include "basic/util.h"
+#include "shared/bus-util.h"
+
+#include "logind-session-device.h"
+
+enum SessionDeviceNotifications {
+ SESSION_DEVICE_RESUME,
+ SESSION_DEVICE_TRY_PAUSE,
+ SESSION_DEVICE_PAUSE,
+ SESSION_DEVICE_RELEASE,
+};
+
+static int session_device_notify(SessionDevice *sd, enum SessionDeviceNotifications type) {
+ _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
+ _cleanup_free_ char *path = NULL;
+ const char *t = NULL;
+ uint32_t major, minor;
+ int r;
+
+ assert(sd);
+
+ major = major(sd->dev);
+ minor = minor(sd->dev);
+
+ if (!sd->session->controller)
+ return 0;
+
+ path = session_bus_path(sd->session);
+ if (!path)
+ return -ENOMEM;
+
+ r = sd_bus_message_new_signal(
+ sd->session->manager->bus,
+ &m, path,
+ "org.freedesktop.login1.Session",
+ (type == SESSION_DEVICE_RESUME) ? "ResumeDevice" : "PauseDevice");
+ if (!m)
+ return r;
+
+ r = sd_bus_message_set_destination(m, sd->session->controller);
+ if (r < 0)
+ return r;
+
+ switch (type) {
+ case SESSION_DEVICE_RESUME:
+ r = sd_bus_message_append(m, "uuh", major, minor, sd->fd);
+ if (r < 0)
+ return r;
+ break;
+ case SESSION_DEVICE_TRY_PAUSE:
+ t = "pause";
+ break;
+ case SESSION_DEVICE_PAUSE:
+ t = "force";
+ break;
+ case SESSION_DEVICE_RELEASE:
+ t = "gone";
+ break;
+ default:
+ return -EINVAL;
+ }
+
+ if (t) {
+ r = sd_bus_message_append(m, "uus", major, minor, t);
+ if (r < 0)
+ return r;
+ }
+
+ return sd_bus_send(sd->session->manager->bus, m, NULL);
+}
+
+static int sd_eviocrevoke(int fd) {
+ static bool warned;
+ int r;
+
+ assert(fd >= 0);
+
+ r = ioctl(fd, EVIOCREVOKE, NULL);
+ if (r < 0) {
+ r = -errno;
+ if (r == -EINVAL && !warned) {
+ warned = true;
+ log_warning("kernel does not support evdev-revocation");
+ }
+ }
+
+ return 0;
+}
+
+static int sd_drmsetmaster(int fd) {
+ int r;
+
+ assert(fd >= 0);
+
+ r = ioctl(fd, DRM_IOCTL_SET_MASTER, 0);
+ if (r < 0)
+ return -errno;
+
+ return 0;
+}
+
+static int sd_drmdropmaster(int fd) {
+ int r;
+
+ assert(fd >= 0);
+
+ r = ioctl(fd, DRM_IOCTL_DROP_MASTER, 0);
+ if (r < 0)
+ return -errno;
+
+ return 0;
+}
+
+static int session_device_open(SessionDevice *sd, bool active) {
+ int fd, r;
+
+ assert(sd->type != DEVICE_TYPE_UNKNOWN);
+
+ /* open device and try to get an udev_device from it */
+ fd = open(sd->node, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK);
+ if (fd < 0)
+ return -errno;
+
+ switch (sd->type) {
+ case DEVICE_TYPE_DRM:
+ if (active) {
+ /* Weird legacy DRM semantics might return an error
+ * even though we're master. No way to detect that so
+ * fail at all times and let caller retry in inactive
+ * state. */
+ r = sd_drmsetmaster(fd);
+ if (r < 0) {
+ close_nointr(fd);
+ return r;
+ }
+ } else {
+ /* DRM-Master is granted to the first user who opens a
+ * device automatically (ughh, racy!). Hence, we just
+ * drop DRM-Master in case we were the first. */
+ sd_drmdropmaster(fd);
+ }
+ break;
+ case DEVICE_TYPE_EVDEV:
+ if (!active)
+ sd_eviocrevoke(fd);
+ break;
+ case DEVICE_TYPE_UNKNOWN:
+ default:
+ /* fallback for devices wihout synchronizations */
+ break;
+ }
+
+ return fd;
+}
+
+static int session_device_start(SessionDevice *sd) {
+ int r;
+
+ assert(sd);
+ assert(session_is_active(sd->session));
+
+ if (sd->active)
+ return 0;
+
+ switch (sd->type) {
+ case DEVICE_TYPE_DRM:
+ /* Device is kept open. Simply call drmSetMaster() and hope
+ * there is no-one else. In case it fails, we keep the device
+ * paused. Maybe at some point we have a drmStealMaster(). */
+ r = sd_drmsetmaster(sd->fd);
+ if (r < 0)
+ return r;
+ break;
+ case DEVICE_TYPE_EVDEV:
+ /* Evdev devices are revoked while inactive. Reopen it and we
+ * are fine. */
+ r = session_device_open(sd, true);
+ if (r < 0)
+ return r;
+ close_nointr(sd->fd);
+ sd->fd = r;
+ break;
+ case DEVICE_TYPE_UNKNOWN:
+ default:
+ /* fallback for devices wihout synchronizations */
+ break;
+ }
+
+ sd->active = true;
+ return 0;
+}
+
+static void session_device_stop(SessionDevice *sd) {
+ assert(sd);
+
+ if (!sd->active)
+ return;
+
+ switch (sd->type) {
+ case DEVICE_TYPE_DRM:
+ /* On DRM devices we simply drop DRM-Master but keep it open.
+ * This allows the user to keep resources allocated. The
+ * CAP_SYS_ADMIN restriction to DRM-Master prevents users from
+ * circumventing this. */
+ sd_drmdropmaster(sd->fd);
+ break;
+ case DEVICE_TYPE_EVDEV:
+ /* Revoke access on evdev file-descriptors during deactivation.
+ * This will basically prevent any operations on the fd and
+ * cannot be undone. Good side is: it needs no CAP_SYS_ADMIN
+ * protection this way. */
+ sd_eviocrevoke(sd->fd);
+ break;
+ case DEVICE_TYPE_UNKNOWN:
+ default:
+ /* fallback for devices without synchronization */
+ break;
+ }
+
+ sd->active = false;
+}
+
+static DeviceType detect_device_type(struct udev_device *dev) {
+ const char *sysname, *subsystem;
+ DeviceType type;
+
+ sysname = udev_device_get_sysname(dev);
+ subsystem = udev_device_get_subsystem(dev);
+ type = DEVICE_TYPE_UNKNOWN;
+
+ if (streq_ptr(subsystem, "drm")) {
+ if (startswith(sysname, "card"))
+ type = DEVICE_TYPE_DRM;
+ } else if (streq_ptr(subsystem, "input")) {
+ if (startswith(sysname, "event"))
+ type = DEVICE_TYPE_EVDEV;
+ }
+
+ return type;
+}
+
+static int session_device_verify(SessionDevice *sd) {
+ struct udev_device *dev, *p = NULL;
+ const char *sp, *node;
+ int r;
+
+ dev = udev_device_new_from_devnum(sd->session->manager->udev, 'c', sd->dev);
+ if (!dev)
+ return -ENODEV;
+
+ sp = udev_device_get_syspath(dev);
+ node = udev_device_get_devnode(dev);
+ if (!node) {
+ r = -EINVAL;
+ goto err_dev;
+ }
+
+ /* detect device type so we can find the correct sysfs parent */
+ sd->type = detect_device_type(dev);
+ if (sd->type == DEVICE_TYPE_UNKNOWN) {
+ r = -ENODEV;
+ goto err_dev;
+ } else if (sd->type == DEVICE_TYPE_EVDEV) {
+ /* for evdev devices we need the parent node as device */
+ p = dev;
+ dev = udev_device_get_parent_with_subsystem_devtype(p, "input", NULL);
+ if (!dev) {
+ r = -ENODEV;
+ goto err_dev;
+ }
+ sp = udev_device_get_syspath(dev);
+ } else if (sd->type != DEVICE_TYPE_DRM) {
+ /* Prevent opening unsupported devices. Especially devices of
+ * subsystem "input" must be opened via the evdev node as
+ * we require EVIOCREVOKE. */
+ r = -ENODEV;
+ goto err_dev;
+ }
+
+ /* search for an existing seat device and return it if available */
+ sd->device = hashmap_get(sd->session->manager->devices, sp);
+ if (!sd->device) {
+ /* The caller might have gotten the udev event before we were
+ * able to process it. Hence, fake the "add" event and let the
+ * logind-manager handle the new device. */
+ r = manager_process_seat_device(sd->session->manager, dev);
+ if (r < 0)
+ goto err_dev;
+
+ /* if it's still not available, then the device is invalid */
+ sd->device = hashmap_get(sd->session->manager->devices, sp);
+ if (!sd->device) {
+ r = -ENODEV;
+ goto err_dev;
+ }
+ }
+
+ if (sd->device->seat != sd->session->seat) {
+ r = -EPERM;
+ goto err_dev;
+ }
+
+ sd->node = strdup(node);
+ if (!sd->node) {
+ r = -ENOMEM;
+ goto err_dev;
+ }
+
+ r = 0;
+err_dev:
+ udev_device_unref(p ? : dev);
+ return r;
+}
+
+int session_device_new(Session *s, dev_t dev, SessionDevice **out) {
+ SessionDevice *sd;
+ int r;
+
+ assert(s);
+ assert(out);
+
+ if (!s->seat)
+ return -EPERM;
+
+ sd = new0(SessionDevice, 1);
+ if (!sd)
+ return -ENOMEM;
+
+ sd->session = s;
+ sd->dev = dev;
+ sd->fd = -1;
+ sd->type = DEVICE_TYPE_UNKNOWN;
+
+ r = session_device_verify(sd);
+ if (r < 0)
+ goto error;
+
+ r = hashmap_put(s->devices, &sd->dev, sd);
+ if (r < 0) {
+ r = -ENOMEM;
+ goto error;
+ }
+
+ /* Open the device for the first time. We need a valid fd to pass back
+ * to the caller. If the session is not active, this _might_ immediately
+ * revoke access and thus invalidate the fd. But this is still needed
+ * to pass a valid fd back. */
+ sd->active = session_is_active(s);
+ r = session_device_open(sd, sd->active);
+ if (r < 0) {
+ /* EINVAL _may_ mean a master is active; retry inactive */
+ if (sd->active && r == -EINVAL) {
+ sd->active = false;
+ r = session_device_open(sd, false);
+ }
+ if (r < 0)
+ goto error;
+ }
+ sd->fd = r;
+
+ LIST_PREPEND(sd_by_device, sd->device->session_devices, sd);
+
+ *out = sd;
+ return 0;
+
+error:
+ hashmap_remove(s->devices, &sd->dev);
+ free(sd->node);
+ free(sd);
+ return r;
+}
+
+void session_device_free(SessionDevice *sd) {
+ assert(sd);
+
+ session_device_stop(sd);
+ session_device_notify(sd, SESSION_DEVICE_RELEASE);
+ close_nointr(sd->fd);
+
+ LIST_REMOVE(sd_by_device, sd->device->session_devices, sd);
+
+ hashmap_remove(sd->session->devices, &sd->dev);
+
+ free(sd->node);
+ free(sd);
+}
+
+void session_device_complete_pause(SessionDevice *sd) {
+ SessionDevice *iter;
+ Iterator i;
+
+ if (!sd->active)
+ return;
+
+ session_device_stop(sd);
+
+ /* if not all devices are paused, wait for further completion events */
+ HASHMAP_FOREACH(iter, sd->session->devices, i)
+ if (iter->active)
+ return;
+
+ /* complete any pending session switch */
+ seat_complete_switch(sd->session->seat);
+}
+
+void session_device_resume_all(Session *s) {
+ SessionDevice *sd;
+ Iterator i;
+ int r;
+
+ assert(s);
+
+ HASHMAP_FOREACH(sd, s->devices, i) {
+ if (!sd->active) {
+ r = session_device_start(sd);
+ if (!r)
+ session_device_notify(sd, SESSION_DEVICE_RESUME);
+ }
+ }
+}
+
+void session_device_pause_all(Session *s) {
+ SessionDevice *sd;
+ Iterator i;
+
+ assert(s);
+
+ HASHMAP_FOREACH(sd, s->devices, i) {
+ if (sd->active) {
+ session_device_stop(sd);
+ session_device_notify(sd, SESSION_DEVICE_PAUSE);
+ }
+ }
+}
+
+unsigned int session_device_try_pause_all(Session *s) {
+ SessionDevice *sd;
+ Iterator i;
+ unsigned int num_pending = 0;
+
+ assert(s);
+
+ HASHMAP_FOREACH(sd, s->devices, i) {
+ if (sd->active) {
+ session_device_notify(sd, SESSION_DEVICE_TRY_PAUSE);
+ ++num_pending;
+ }
+ }
+
+ return num_pending;
+}
diff --git a/src/grp-login/systemd-logind/logind-session-device.h b/src/grp-login/systemd-logind/logind-session-device.h
new file mode 100644
index 0000000000..4a22decb1d
--- /dev/null
+++ b/src/grp-login/systemd-logind/logind-session-device.h
@@ -0,0 +1,54 @@
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2013 David Herrmann
+
+ 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 "basic/list.h"
+
+typedef enum DeviceType DeviceType;
+typedef struct SessionDevice SessionDevice;
+
+#include "logind.h"
+
+enum DeviceType {
+ DEVICE_TYPE_UNKNOWN,
+ DEVICE_TYPE_DRM,
+ DEVICE_TYPE_EVDEV,
+};
+
+struct SessionDevice {
+ Session *session;
+ Device *device;
+
+ dev_t dev;
+ char *node;
+ int fd;
+ bool active;
+ DeviceType type;
+
+ LIST_FIELDS(struct SessionDevice, sd_by_device);
+};
+
+int session_device_new(Session *s, dev_t dev, SessionDevice **out);
+void session_device_free(SessionDevice *sd);
+void session_device_complete_pause(SessionDevice *sd);
+
+void session_device_resume_all(Session *s);
+void session_device_pause_all(Session *s);
+unsigned int session_device_try_pause_all(Session *s);
diff --git a/src/grp-login/systemd-logind/logind-session.c b/src/grp-login/systemd-logind/logind-session.c
new file mode 100644
index 0000000000..b08db54068
--- /dev/null
+++ b/src/grp-login/systemd-logind/logind-session.c
@@ -0,0 +1,1275 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ 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 <errno.h>
+#include <fcntl.h>
+#include <signal.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <unistd.h>
+
+#include <linux/kd.h>
+#include <linux/vt.h>
+
+#include <systemd/sd-messages.h>
+
+#include "basic/alloc-util.h"
+#include "basic/audit-util.h"
+#include "basic/escape.h"
+#include "basic/fd-util.h"
+#include "basic/fileio.h"
+#include "basic/formats-util.h"
+#include "basic/io-util.h"
+#include "basic/mkdir.h"
+#include "basic/parse-util.h"
+#include "basic/path-util.h"
+#include "basic/string-table.h"
+#include "basic/terminal-util.h"
+#include "basic/user-util.h"
+#include "basic/util.h"
+#include "sd-bus/bus-error.h"
+#include "shared/bus-util.h"
+
+#include "logind-session.h"
+
+#define RELEASE_USEC (20*USEC_PER_SEC)
+
+static void session_remove_fifo(Session *s);
+
+Session* session_new(Manager *m, const char *id) {
+ Session *s;
+
+ assert(m);
+ assert(id);
+ assert(session_id_valid(id));
+
+ s = new0(Session, 1);
+ if (!s)
+ return NULL;
+
+ s->state_file = strappend("/run/systemd/sessions/", id);
+ if (!s->state_file) {
+ free(s);
+ return NULL;
+ }
+
+ s->devices = hashmap_new(&devt_hash_ops);
+ if (!s->devices) {
+ free(s->state_file);
+ free(s);
+ return NULL;
+ }
+
+ s->id = basename(s->state_file);
+
+ if (hashmap_put(m->sessions, s->id, s) < 0) {
+ hashmap_free(s->devices);
+ free(s->state_file);
+ free(s);
+ return NULL;
+ }
+
+ s->manager = m;
+ s->fifo_fd = -1;
+ s->vtfd = -1;
+
+ return s;
+}
+
+void session_free(Session *s) {
+ SessionDevice *sd;
+
+ assert(s);
+
+ if (s->in_gc_queue)
+ LIST_REMOVE(gc_queue, s->manager->session_gc_queue, s);
+
+ s->timer_event_source = sd_event_source_unref(s->timer_event_source);
+
+ session_remove_fifo(s);
+
+ session_drop_controller(s);
+
+ while ((sd = hashmap_first(s->devices)))
+ session_device_free(sd);
+
+ hashmap_free(s->devices);
+
+ if (s->user) {
+ LIST_REMOVE(sessions_by_user, s->user->sessions, s);
+
+ if (s->user->display == s)
+ s->user->display = NULL;
+ }
+
+ if (s->seat) {
+ if (s->seat->active == s)
+ s->seat->active = NULL;
+ if (s->seat->pending_switch == s)
+ s->seat->pending_switch = NULL;
+
+ seat_evict_position(s->seat, s);
+ LIST_REMOVE(sessions_by_seat, s->seat->sessions, s);
+ }
+
+ if (s->scope) {
+ hashmap_remove(s->manager->session_units, s->scope);
+ free(s->scope);
+ }
+
+ free(s->scope_job);
+
+ sd_bus_message_unref(s->create_message);
+
+ free(s->tty);
+ free(s->display);
+ free(s->remote_host);
+ free(s->remote_user);
+ free(s->service);
+ free(s->desktop);
+
+ hashmap_remove(s->manager->sessions, s->id);
+
+ free(s->state_file);
+ free(s);
+}
+
+void session_set_user(Session *s, User *u) {
+ assert(s);
+ assert(!s->user);
+
+ s->user = u;
+ LIST_PREPEND(sessions_by_user, u->sessions, s);
+}
+
+int session_save(Session *s) {
+ _cleanup_free_ char *temp_path = NULL;
+ _cleanup_fclose_ FILE *f = NULL;
+ int r = 0;
+
+ assert(s);
+
+ if (!s->user)
+ return -ESTALE;
+
+ if (!s->started)
+ return 0;
+
+ r = mkdir_safe_label("/run/systemd/sessions", 0755, 0, 0);
+ if (r < 0)
+ goto fail;
+
+ r = fopen_temporary(s->state_file, &f, &temp_path);
+ if (r < 0)
+ goto fail;
+
+ assert(s->user);
+
+ fchmod(fileno(f), 0644);
+
+ fprintf(f,
+ "# This is private data. Do not parse.\n"
+ "UID="UID_FMT"\n"
+ "USER=%s\n"
+ "ACTIVE=%i\n"
+ "STATE=%s\n"
+ "REMOTE=%i\n",
+ s->user->uid,
+ s->user->name,
+ session_is_active(s),
+ session_state_to_string(session_get_state(s)),
+ s->remote);
+
+ if (s->type >= 0)
+ fprintf(f, "TYPE=%s\n", session_type_to_string(s->type));
+
+ if (s->class >= 0)
+ fprintf(f, "CLASS=%s\n", session_class_to_string(s->class));
+
+ if (s->scope)
+ fprintf(f, "SCOPE=%s\n", s->scope);
+ if (s->scope_job)
+ fprintf(f, "SCOPE_JOB=%s\n", s->scope_job);
+
+ if (s->fifo_path)
+ fprintf(f, "FIFO=%s\n", s->fifo_path);
+
+ if (s->seat)
+ fprintf(f, "SEAT=%s\n", s->seat->id);
+
+ if (s->tty)
+ fprintf(f, "TTY=%s\n", s->tty);
+
+ if (s->display)
+ fprintf(f, "DISPLAY=%s\n", s->display);
+
+ if (s->remote_host) {
+ _cleanup_free_ char *escaped;
+
+ escaped = cescape(s->remote_host);
+ if (!escaped) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ fprintf(f, "REMOTE_HOST=%s\n", escaped);
+ }
+
+ if (s->remote_user) {
+ _cleanup_free_ char *escaped;
+
+ escaped = cescape(s->remote_user);
+ if (!escaped) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ fprintf(f, "REMOTE_USER=%s\n", escaped);
+ }
+
+ if (s->service) {
+ _cleanup_free_ char *escaped;
+
+ escaped = cescape(s->service);
+ if (!escaped) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ fprintf(f, "SERVICE=%s\n", escaped);
+ }
+
+ if (s->desktop) {
+ _cleanup_free_ char *escaped;
+
+
+ escaped = cescape(s->desktop);
+ if (!escaped) {
+ r = -ENOMEM;
+ goto fail;
+ }
+
+ fprintf(f, "DESKTOP=%s\n", escaped);
+ }
+
+ if (s->seat && seat_has_vts(s->seat))
+ fprintf(f, "VTNR=%u\n", s->vtnr);
+
+ if (!s->vtnr)
+ fprintf(f, "POSITION=%u\n", s->position);
+
+ if (s->leader > 0)
+ fprintf(f, "LEADER="PID_FMT"\n", s->leader);
+
+ if (s->audit_id > 0)
+ fprintf(f, "AUDIT=%"PRIu32"\n", s->audit_id);
+
+ if (dual_timestamp_is_set(&s->timestamp))
+ fprintf(f,
+ "REALTIME="USEC_FMT"\n"
+ "MONOTONIC="USEC_FMT"\n",
+ s->timestamp.realtime,
+ s->timestamp.monotonic);
+
+ if (s->controller)
+ fprintf(f, "CONTROLLER=%s\n", s->controller);
+
+ r = fflush_and_check(f);
+ if (r < 0)
+ goto fail;
+
+ if (rename(temp_path, s->state_file) < 0) {
+ r = -errno;
+ goto fail;
+ }
+
+ return 0;
+
+fail:
+ (void) unlink(s->state_file);
+
+ if (temp_path)
+ (void) unlink(temp_path);
+
+ return log_error_errno(r, "Failed to save session data %s: %m", s->state_file);
+}
+
+
+int session_load(Session *s) {
+ _cleanup_free_ char *remote = NULL,
+ *seat = NULL,
+ *vtnr = NULL,
+ *state = NULL,
+ *position = NULL,
+ *leader = NULL,
+ *type = NULL,
+ *class = NULL,
+ *uid = NULL,
+ *realtime = NULL,
+ *monotonic = NULL,
+ *controller = NULL;
+
+ int k, r;
+
+ assert(s);
+
+ r = parse_env_file(s->state_file, NEWLINE,
+ "REMOTE", &remote,
+ "SCOPE", &s->scope,
+ "SCOPE_JOB", &s->scope_job,
+ "FIFO", &s->fifo_path,
+ "SEAT", &seat,
+ "TTY", &s->tty,
+ "DISPLAY", &s->display,
+ "REMOTE_HOST", &s->remote_host,
+ "REMOTE_USER", &s->remote_user,
+ "SERVICE", &s->service,
+ "DESKTOP", &s->desktop,
+ "VTNR", &vtnr,
+ "STATE", &state,
+ "POSITION", &position,
+ "LEADER", &leader,
+ "TYPE", &type,
+ "CLASS", &class,
+ "UID", &uid,
+ "REALTIME", &realtime,
+ "MONOTONIC", &monotonic,
+ "CONTROLLER", &controller,
+ NULL);
+
+ if (r < 0)
+ return log_error_errno(r, "Failed to read %s: %m", s->state_file);
+
+ if (!s->user) {
+ uid_t u;
+ User *user;
+
+ if (!uid) {
+ log_error("UID not specified for session %s", s->id);
+ return -ENOENT;
+ }
+
+ r = parse_uid(uid, &u);
+ if (r < 0) {
+ log_error("Failed to parse UID value %s for session %s.", uid, s->id);
+ return r;
+ }
+
+ user = hashmap_get(s->manager->users, UID_TO_PTR(u));
+ if (!user) {
+ log_error("User of session %s not known.", s->id);
+ return -ENOENT;
+ }
+
+ session_set_user(s, user);
+ }
+
+ if (remote) {
+ k = parse_boolean(remote);
+ if (k >= 0)
+ s->remote = k;
+ }
+
+ if (vtnr)
+ safe_atou(vtnr, &s->vtnr);
+
+ if (seat && !s->seat) {
+ Seat *o;
+
+ o = hashmap_get(s->manager->seats, seat);
+ if (o)
+ r = seat_attach_session(o, s);
+ if (!o || r < 0)
+ log_error("Cannot attach session %s to seat %s", s->id, seat);
+ }
+
+ if (!s->seat || !seat_has_vts(s->seat))
+ s->vtnr = 0;
+
+ if (position && s->seat) {
+ unsigned int npos;
+
+ safe_atou(position, &npos);
+ seat_claim_position(s->seat, s, npos);
+ }
+
+ if (leader) {
+ k = parse_pid(leader, &s->leader);
+ if (k >= 0)
+ audit_session_from_pid(s->leader, &s->audit_id);
+ }
+
+ if (type) {
+ SessionType t;
+
+ t = session_type_from_string(type);
+ if (t >= 0)
+ s->type = t;
+ }
+
+ if (class) {
+ SessionClass c;
+
+ c = session_class_from_string(class);
+ if (c >= 0)
+ s->class = c;
+ }
+
+ if (state && streq(state, "closing"))
+ s->stopping = true;
+
+ if (s->fifo_path) {
+ int fd;
+
+ /* If we open an unopened pipe for reading we will not
+ get an EOF. to trigger an EOF we hence open it for
+ writing, but close it right away which then will
+ trigger the EOF. This will happen immediately if no
+ other process has the FIFO open for writing, i. e.
+ when the session died before logind (re)started. */
+
+ fd = session_create_fifo(s);
+ safe_close(fd);
+ }
+
+ if (realtime)
+ timestamp_deserialize(realtime, &s->timestamp.realtime);
+ if (monotonic)
+ timestamp_deserialize(monotonic, &s->timestamp.monotonic);
+
+ if (controller) {
+ if (bus_name_has_owner(s->manager->bus, controller, NULL) > 0)
+ session_set_controller(s, controller, false);
+ else
+ session_restore_vt(s);
+ }
+
+ return r;
+}
+
+int session_activate(Session *s) {
+ unsigned int num_pending;
+
+ assert(s);
+ assert(s->user);
+
+ if (!s->seat)
+ return -EOPNOTSUPP;
+
+ if (s->seat->active == s)
+ return 0;
+
+ /* on seats with VTs, we let VTs manage session-switching */
+ if (seat_has_vts(s->seat)) {
+ if (!s->vtnr)
+ return -EOPNOTSUPP;
+
+ return chvt(s->vtnr);
+ }
+
+ /* On seats without VTs, we implement session-switching in logind. We
+ * try to pause all session-devices and wait until the session
+ * controller acknowledged them. Once all devices are asleep, we simply
+ * switch the active session and be done.
+ * We save the session we want to switch to in seat->pending_switch and
+ * seat_complete_switch() will perform the final switch. */
+
+ s->seat->pending_switch = s;
+
+ /* if no devices are running, immediately perform the session switch */
+ num_pending = session_device_try_pause_all(s);
+ if (!num_pending)
+ seat_complete_switch(s->seat);
+
+ return 0;
+}
+
+static int session_start_scope(Session *s) {
+ int r;
+
+ assert(s);
+ assert(s->user);
+
+ if (!s->scope) {
+ _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+ char *scope, *job = NULL;
+ const char *description;
+
+ scope = strjoin("session-", s->id, ".scope", NULL);
+ if (!scope)
+ return log_oom();
+
+ description = strjoina("Session ", s->id, " of user ", s->user->name);
+
+ r = manager_start_scope(
+ s->manager,
+ scope,
+ s->leader,
+ s->user->slice,
+ description,
+ "systemd-logind.service",
+ "systemd-user-sessions.service",
+ (uint64_t) -1, /* disable TasksMax= for the scope, rely on the slice setting for it */
+ &error,
+ &job);
+ if (r < 0) {
+ log_error_errno(r, "Failed to start session scope %s: %s", scope, bus_error_message(&error, r));
+ free(scope);
+ return r;
+ } else {
+ s->scope = scope;
+
+ free(s->scope_job);
+ s->scope_job = job;
+ }
+ }
+
+ if (s->scope)
+ (void) hashmap_put(s->manager->session_units, s->scope, s);
+
+ return 0;
+}
+
+int session_start(Session *s) {
+ int r;
+
+ assert(s);
+
+ if (!s->user)
+ return -ESTALE;
+
+ if (s->started)
+ return 0;
+
+ r = user_start(s->user);
+ if (r < 0)
+ return r;
+
+ /* Create cgroup */
+ r = session_start_scope(s);
+ if (r < 0)
+ return r;
+
+ log_struct(s->class == SESSION_BACKGROUND ? LOG_DEBUG : LOG_INFO,
+ LOG_MESSAGE_ID(SD_MESSAGE_SESSION_START),
+ "SESSION_ID=%s", s->id,
+ "USER_ID=%s", s->user->name,
+ "LEADER="PID_FMT, s->leader,
+ LOG_MESSAGE("New session %s of user %s.", s->id, s->user->name),
+ NULL);
+
+ if (!dual_timestamp_is_set(&s->timestamp))
+ dual_timestamp_get(&s->timestamp);
+
+ if (s->seat)
+ seat_read_active_vt(s->seat);
+
+ s->started = true;
+
+ user_elect_display(s->user);
+
+ /* Save data */
+ session_save(s);
+ user_save(s->user);
+ if (s->seat)
+ seat_save(s->seat);
+
+ /* Send signals */
+ session_send_signal(s, true);
+ user_send_changed(s->user, "Sessions", "Display", NULL);
+ if (s->seat) {
+ if (s->seat->active == s)
+ seat_send_changed(s->seat, "Sessions", "ActiveSession", NULL);
+ else
+ seat_send_changed(s->seat, "Sessions", NULL);
+ }
+
+ return 0;
+}
+
+static int session_stop_scope(Session *s, bool force) {
+ _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+ int r;
+
+ assert(s);
+
+ if (!s->scope)
+ return 0;
+
+ /* Let's always abandon the scope first. This tells systemd that we are not interested anymore, and everything
+ * that is left in in the scope is "left-over". Informing systemd about this has the benefit that it will log
+ * when killing any processes left after this point. */
+ r = manager_abandon_scope(s->manager, s->scope, &error);
+ if (r < 0)
+ log_warning_errno(r, "Failed to abandon session scope, ignoring: %s", bus_error_message(&error, r));
+
+ /* Optionally, let's kill everything that's left now. */
+ if (force || manager_shall_kill(s->manager, s->user->name)) {
+ char *job = NULL;
+
+ r = manager_stop_unit(s->manager, s->scope, &error, &job);
+ if (r < 0)
+ return log_error_errno(r, "Failed to stop session scope: %s", bus_error_message(&error, r));
+
+ free(s->scope_job);
+ s->scope_job = job;
+ } else
+ s->scope_job = mfree(s->scope_job);
+
+ return 0;
+}
+
+int session_stop(Session *s, bool force) {
+ int r;
+
+ assert(s);
+
+ if (!s->user)
+ return -ESTALE;
+
+ s->timer_event_source = sd_event_source_unref(s->timer_event_source);
+
+ if (s->seat)
+ seat_evict_position(s->seat, s);
+
+ /* We are going down, don't care about FIFOs anymore */
+ session_remove_fifo(s);
+
+ /* Kill cgroup */
+ r = session_stop_scope(s, force);
+
+ s->stopping = true;
+
+ user_elect_display(s->user);
+
+ session_save(s);
+ user_save(s->user);
+
+ return r;
+}
+
+int session_finalize(Session *s) {
+ SessionDevice *sd;
+
+ assert(s);
+
+ if (!s->user)
+ return -ESTALE;
+
+ if (s->started)
+ log_struct(s->class == SESSION_BACKGROUND ? LOG_DEBUG : LOG_INFO,
+ LOG_MESSAGE_ID(SD_MESSAGE_SESSION_STOP),
+ "SESSION_ID=%s", s->id,
+ "USER_ID=%s", s->user->name,
+ "LEADER="PID_FMT, s->leader,
+ LOG_MESSAGE("Removed session %s.", s->id),
+ NULL);
+
+ s->timer_event_source = sd_event_source_unref(s->timer_event_source);
+
+ if (s->seat)
+ seat_evict_position(s->seat, s);
+
+ /* Kill session devices */
+ while ((sd = hashmap_first(s->devices)))
+ session_device_free(sd);
+
+ (void) unlink(s->state_file);
+ session_add_to_gc_queue(s);
+ user_add_to_gc_queue(s->user);
+
+ if (s->started) {
+ session_send_signal(s, false);
+ s->started = false;
+ }
+
+ if (s->seat) {
+ if (s->seat->active == s)
+ seat_set_active(s->seat, NULL);
+
+ seat_save(s->seat);
+ seat_send_changed(s->seat, "Sessions", NULL);
+ }
+
+ user_save(s->user);
+ user_send_changed(s->user, "Sessions", "Display", NULL);
+
+ return 0;
+}
+
+static int release_timeout_callback(sd_event_source *es, uint64_t usec, void *userdata) {
+ Session *s = userdata;
+
+ assert(es);
+ assert(s);
+
+ session_stop(s, false);
+ return 0;
+}
+
+int session_release(Session *s) {
+ assert(s);
+
+ if (!s->started || s->stopping)
+ return 0;
+
+ if (s->timer_event_source)
+ return 0;
+
+ return sd_event_add_time(s->manager->event,
+ &s->timer_event_source,
+ CLOCK_MONOTONIC,
+ now(CLOCK_MONOTONIC) + RELEASE_USEC, 0,
+ release_timeout_callback, s);
+}
+
+bool session_is_active(Session *s) {
+ assert(s);
+
+ if (!s->seat)
+ return true;
+
+ return s->seat->active == s;
+}
+
+static int get_tty_atime(const char *tty, usec_t *atime) {
+ _cleanup_free_ char *p = NULL;
+ struct stat st;
+
+ assert(tty);
+ assert(atime);
+
+ if (!path_is_absolute(tty)) {
+ p = strappend("/dev/", tty);
+ if (!p)
+ return -ENOMEM;
+
+ tty = p;
+ } else if (!path_startswith(tty, "/dev/"))
+ return -ENOENT;
+
+ if (lstat(tty, &st) < 0)
+ return -errno;
+
+ *atime = timespec_load(&st.st_atim);
+ return 0;
+}
+
+static int get_process_ctty_atime(pid_t pid, usec_t *atime) {
+ _cleanup_free_ char *p = NULL;
+ int r;
+
+ assert(pid > 0);
+ assert(atime);
+
+ r = get_ctty(pid, NULL, &p);
+ if (r < 0)
+ return r;
+
+ return get_tty_atime(p, atime);
+}
+
+int session_get_idle_hint(Session *s, dual_timestamp *t) {
+ usec_t atime = 0, n;
+ int r;
+
+ assert(s);
+
+ /* Explicit idle hint is set */
+ if (s->idle_hint) {
+ if (t)
+ *t = s->idle_hint_timestamp;
+
+ return s->idle_hint;
+ }
+
+ /* Graphical sessions should really implement a real
+ * idle hint logic */
+ if (SESSION_TYPE_IS_GRAPHICAL(s->type))
+ goto dont_know;
+
+ /* For sessions with an explicitly configured tty, let's check
+ * its atime */
+ if (s->tty) {
+ r = get_tty_atime(s->tty, &atime);
+ if (r >= 0)
+ goto found_atime;
+ }
+
+ /* For sessions with a leader but no explicitly configured
+ * tty, let's check the controlling tty of the leader */
+ if (s->leader > 0) {
+ r = get_process_ctty_atime(s->leader, &atime);
+ if (r >= 0)
+ goto found_atime;
+ }
+
+dont_know:
+ if (t)
+ *t = s->idle_hint_timestamp;
+
+ return 0;
+
+found_atime:
+ if (t)
+ dual_timestamp_from_realtime(t, atime);
+
+ n = now(CLOCK_REALTIME);
+
+ if (s->manager->idle_action_usec <= 0)
+ return 0;
+
+ return atime + s->manager->idle_action_usec <= n;
+}
+
+void session_set_idle_hint(Session *s, bool b) {
+ assert(s);
+
+ if (s->idle_hint == b)
+ return;
+
+ s->idle_hint = b;
+ dual_timestamp_get(&s->idle_hint_timestamp);
+
+ session_send_changed(s, "IdleHint", "IdleSinceHint", "IdleSinceHintMonotonic", NULL);
+
+ if (s->seat)
+ seat_send_changed(s->seat, "IdleHint", "IdleSinceHint", "IdleSinceHintMonotonic", NULL);
+
+ user_send_changed(s->user, "IdleHint", "IdleSinceHint", "IdleSinceHintMonotonic", NULL);
+ manager_send_changed(s->manager, "IdleHint", "IdleSinceHint", "IdleSinceHintMonotonic", NULL);
+}
+
+int session_get_locked_hint(Session *s) {
+ assert(s);
+
+ return s->locked_hint;
+}
+
+void session_set_locked_hint(Session *s, bool b) {
+ assert(s);
+
+ if (s->locked_hint == b)
+ return;
+
+ s->locked_hint = b;
+
+ session_send_changed(s, "LockedHint", NULL);
+}
+
+static int session_dispatch_fifo(sd_event_source *es, int fd, uint32_t revents, void *userdata) {
+ Session *s = userdata;
+
+ assert(s);
+ assert(s->fifo_fd == fd);
+
+ /* EOF on the FIFO means the session died abnormally. */
+
+ session_remove_fifo(s);
+ session_stop(s, false);
+
+ return 1;
+}
+
+int session_create_fifo(Session *s) {
+ int r;
+
+ assert(s);
+
+ /* Create FIFO */
+ if (!s->fifo_path) {
+ r = mkdir_safe_label("/run/systemd/sessions", 0755, 0, 0);
+ if (r < 0)
+ return r;
+
+ if (asprintf(&s->fifo_path, "/run/systemd/sessions/%s.ref", s->id) < 0)
+ return -ENOMEM;
+
+ if (mkfifo(s->fifo_path, 0600) < 0 && errno != EEXIST)
+ return -errno;
+ }
+
+ /* Open reading side */
+ if (s->fifo_fd < 0) {
+ s->fifo_fd = open(s->fifo_path, O_RDONLY|O_CLOEXEC|O_NDELAY);
+ if (s->fifo_fd < 0)
+ return -errno;
+
+ }
+
+ if (!s->fifo_event_source) {
+ r = sd_event_add_io(s->manager->event, &s->fifo_event_source, s->fifo_fd, 0, session_dispatch_fifo, s);
+ if (r < 0)
+ return r;
+
+ /* Let's make sure we noticed dead sessions before we process new bus requests (which might create new
+ * sessions). */
+ r = sd_event_source_set_priority(s->fifo_event_source, SD_EVENT_PRIORITY_NORMAL-10);
+ if (r < 0)
+ return r;
+ }
+
+ /* Open writing side */
+ r = open(s->fifo_path, O_WRONLY|O_CLOEXEC|O_NDELAY);
+ if (r < 0)
+ return -errno;
+
+ return r;
+}
+
+static void session_remove_fifo(Session *s) {
+ assert(s);
+
+ s->fifo_event_source = sd_event_source_unref(s->fifo_event_source);
+ s->fifo_fd = safe_close(s->fifo_fd);
+
+ if (s->fifo_path) {
+ unlink(s->fifo_path);
+ s->fifo_path = mfree(s->fifo_path);
+ }
+}
+
+bool session_check_gc(Session *s, bool drop_not_started) {
+ assert(s);
+
+ if (drop_not_started && !s->started)
+ return false;
+
+ if (!s->user)
+ return false;
+
+ if (s->fifo_fd >= 0) {
+ if (pipe_eof(s->fifo_fd) <= 0)
+ return true;
+ }
+
+ if (s->scope_job && manager_job_is_active(s->manager, s->scope_job))
+ return true;
+
+ if (s->scope && manager_unit_is_active(s->manager, s->scope))
+ return true;
+
+ return false;
+}
+
+void session_add_to_gc_queue(Session *s) {
+ assert(s);
+
+ if (s->in_gc_queue)
+ return;
+
+ LIST_PREPEND(gc_queue, s->manager->session_gc_queue, s);
+ s->in_gc_queue = true;
+}
+
+SessionState session_get_state(Session *s) {
+ assert(s);
+
+ /* always check closing first */
+ if (s->stopping || s->timer_event_source)
+ return SESSION_CLOSING;
+
+ if (s->scope_job || s->fifo_fd < 0)
+ return SESSION_OPENING;
+
+ if (session_is_active(s))
+ return SESSION_ACTIVE;
+
+ return SESSION_ONLINE;
+}
+
+int session_kill(Session *s, KillWho who, int signo) {
+ assert(s);
+
+ if (!s->scope)
+ return -ESRCH;
+
+ return manager_kill_unit(s->manager, s->scope, who, signo, NULL);
+}
+
+static int session_open_vt(Session *s) {
+ char path[sizeof("/dev/tty") + DECIMAL_STR_MAX(s->vtnr)];
+
+ if (s->vtnr < 1)
+ return -ENODEV;
+
+ if (s->vtfd >= 0)
+ return s->vtfd;
+
+ sprintf(path, "/dev/tty%u", s->vtnr);
+ s->vtfd = open_terminal(path, O_RDWR | O_CLOEXEC | O_NONBLOCK | O_NOCTTY);
+ if (s->vtfd < 0)
+ return log_error_errno(s->vtfd, "cannot open VT %s of session %s: %m", path, s->id);
+
+ return s->vtfd;
+}
+
+int session_prepare_vt(Session *s) {
+ int vt, r;
+ struct vt_mode mode = { 0 };
+
+ if (s->vtnr < 1)
+ return 0;
+
+ vt = session_open_vt(s);
+ if (vt < 0)
+ return vt;
+
+ r = fchown(vt, s->user->uid, -1);
+ if (r < 0) {
+ r = log_error_errno(errno,
+ "Cannot change owner of /dev/tty%u: %m",
+ s->vtnr);
+ goto error;
+ }
+
+ r = ioctl(vt, KDSKBMODE, K_OFF);
+ if (r < 0) {
+ r = log_error_errno(errno,
+ "Cannot set K_OFF on /dev/tty%u: %m",
+ s->vtnr);
+ goto error;
+ }
+
+ r = ioctl(vt, KDSETMODE, KD_GRAPHICS);
+ if (r < 0) {
+ r = log_error_errno(errno,
+ "Cannot set KD_GRAPHICS on /dev/tty%u: %m",
+ s->vtnr);
+ goto error;
+ }
+
+ /* Oh, thanks to the VT layer, VT_AUTO does not work with KD_GRAPHICS.
+ * So we need a dummy handler here which just acknowledges *all* VT
+ * switch requests. */
+ mode.mode = VT_PROCESS;
+ mode.relsig = SIGRTMIN;
+ mode.acqsig = SIGRTMIN + 1;
+ r = ioctl(vt, VT_SETMODE, &mode);
+ if (r < 0) {
+ r = log_error_errno(errno,
+ "Cannot set VT_PROCESS on /dev/tty%u: %m",
+ s->vtnr);
+ goto error;
+ }
+
+ return 0;
+
+error:
+ session_restore_vt(s);
+ return r;
+}
+
+void session_restore_vt(Session *s) {
+
+ static const struct vt_mode mode = {
+ .mode = VT_AUTO,
+ };
+
+ _cleanup_free_ char *utf8 = NULL;
+ int vt, kb, old_fd;
+
+ /* We need to get a fresh handle to the virtual terminal,
+ * since the old file-descriptor is potentially in a hung-up
+ * state after the controlling process exited; we do a
+ * little dance to avoid having the terminal be available
+ * for reuse before we've cleaned it up.
+ */
+ old_fd = s->vtfd;
+ s->vtfd = -1;
+
+ vt = session_open_vt(s);
+ safe_close(old_fd);
+
+ if (vt < 0)
+ return;
+
+ (void) ioctl(vt, KDSETMODE, KD_TEXT);
+
+ if (read_one_line_file("/sys/module/vt/parameters/default_utf8", &utf8) >= 0 && *utf8 == '1')
+ kb = K_UNICODE;
+ else
+ kb = K_XLATE;
+
+ (void) ioctl(vt, KDSKBMODE, kb);
+
+ (void) ioctl(vt, VT_SETMODE, &mode);
+ (void) fchown(vt, 0, (gid_t) -1);
+
+ s->vtfd = safe_close(s->vtfd);
+}
+
+void session_leave_vt(Session *s) {
+ int r;
+
+ assert(s);
+
+ /* This is called whenever we get a VT-switch signal from the kernel.
+ * We acknowledge all of them unconditionally. Note that session are
+ * free to overwrite those handlers and we only register them for
+ * sessions with controllers. Legacy sessions are not affected.
+ * However, if we switch from a non-legacy to a legacy session, we must
+ * make sure to pause all device before acknowledging the switch. We
+ * process the real switch only after we are notified via sysfs, so the
+ * legacy session might have already started using the devices. If we
+ * don't pause the devices before the switch, we might confuse the
+ * session we switch to. */
+
+ if (s->vtfd < 0)
+ return;
+
+ session_device_pause_all(s);
+ r = ioctl(s->vtfd, VT_RELDISP, 1);
+ if (r < 0)
+ log_debug_errno(errno, "Cannot release VT of session %s: %m", s->id);
+}
+
+bool session_is_controller(Session *s, const char *sender) {
+ assert(s);
+
+ return streq_ptr(s->controller, sender);
+}
+
+static void session_release_controller(Session *s, bool notify) {
+ _cleanup_free_ char *name = NULL;
+ SessionDevice *sd;
+
+ if (!s->controller)
+ return;
+
+ name = s->controller;
+
+ /* By resetting the controller before releasing the devices, we won't
+ * send notification signals. This avoids sending useless notifications
+ * if the controller is released on disconnects. */
+ if (!notify)
+ s->controller = NULL;
+
+ while ((sd = hashmap_first(s->devices)))
+ session_device_free(sd);
+
+ s->controller = NULL;
+ s->track = sd_bus_track_unref(s->track);
+}
+
+static int on_bus_track(sd_bus_track *track, void *userdata) {
+ Session *s = userdata;
+
+ assert(track);
+ assert(s);
+
+ session_drop_controller(s);
+
+ return 0;
+}
+
+int session_set_controller(Session *s, const char *sender, bool force) {
+ _cleanup_free_ char *name = NULL;
+ int r;
+
+ assert(s);
+ assert(sender);
+
+ if (session_is_controller(s, sender))
+ return 0;
+ if (s->controller && !force)
+ return -EBUSY;
+
+ name = strdup(sender);
+ if (!name)
+ return -ENOMEM;
+
+ s->track = sd_bus_track_unref(s->track);
+ r = sd_bus_track_new(s->manager->bus, &s->track, on_bus_track, s);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_track_add_name(s->track, name);
+ if (r < 0)
+ return r;
+
+ /* When setting a session controller, we forcibly mute the VT and set
+ * it into graphics-mode. Applications can override that by changing
+ * VT state after calling TakeControl(). However, this serves as a good
+ * default and well-behaving controllers can now ignore VTs entirely.
+ * Note that we reset the VT on ReleaseControl() and if the controller
+ * exits.
+ * If logind crashes/restarts, we restore the controller during restart
+ * or reset the VT in case it crashed/exited, too. */
+ r = session_prepare_vt(s);
+ if (r < 0) {
+ s->track = sd_bus_track_unref(s->track);
+ return r;
+ }
+
+ session_release_controller(s, true);
+ s->controller = name;
+ name = NULL;
+ session_save(s);
+
+ return 0;
+}
+
+void session_drop_controller(Session *s) {
+ assert(s);
+
+ if (!s->controller)
+ return;
+
+ s->track = sd_bus_track_unref(s->track);
+ session_release_controller(s, false);
+ session_save(s);
+ session_restore_vt(s);
+}
+
+static const char* const session_state_table[_SESSION_STATE_MAX] = {
+ [SESSION_OPENING] = "opening",
+ [SESSION_ONLINE] = "online",
+ [SESSION_ACTIVE] = "active",
+ [SESSION_CLOSING] = "closing"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(session_state, SessionState);
+
+static const char* const session_type_table[_SESSION_TYPE_MAX] = {
+ [SESSION_UNSPECIFIED] = "unspecified",
+ [SESSION_TTY] = "tty",
+ [SESSION_X11] = "x11",
+ [SESSION_WAYLAND] = "wayland",
+ [SESSION_MIR] = "mir",
+ [SESSION_WEB] = "web",
+};
+
+DEFINE_STRING_TABLE_LOOKUP(session_type, SessionType);
+
+static const char* const session_class_table[_SESSION_CLASS_MAX] = {
+ [SESSION_USER] = "user",
+ [SESSION_GREETER] = "greeter",
+ [SESSION_LOCK_SCREEN] = "lock-screen",
+ [SESSION_BACKGROUND] = "background"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(session_class, SessionClass);
+
+static const char* const kill_who_table[_KILL_WHO_MAX] = {
+ [KILL_LEADER] = "leader",
+ [KILL_ALL] = "all"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(kill_who, KillWho);
diff --git a/src/grp-login/systemd-logind/logind-session.h b/src/grp-login/systemd-logind/logind-session.h
new file mode 100644
index 0000000000..976046d847
--- /dev/null
+++ b/src/grp-login/systemd-logind/logind-session.h
@@ -0,0 +1,186 @@
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ 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 "basic/list.h"
+#include "basic/login-util.h"
+
+typedef enum KillWho KillWho;
+typedef struct Session Session;
+
+#include "logind-user.h"
+
+typedef enum SessionState {
+ SESSION_OPENING, /* Session scope is being created */
+ SESSION_ONLINE, /* Logged in */
+ SESSION_ACTIVE, /* Logged in and in the fg */
+ SESSION_CLOSING, /* Logged out, but scope is still there */
+ _SESSION_STATE_MAX,
+ _SESSION_STATE_INVALID = -1
+} SessionState;
+
+typedef enum SessionClass {
+ SESSION_USER,
+ SESSION_GREETER,
+ SESSION_LOCK_SCREEN,
+ SESSION_BACKGROUND,
+ _SESSION_CLASS_MAX,
+ _SESSION_CLASS_INVALID = -1
+} SessionClass;
+
+typedef enum SessionType {
+ SESSION_UNSPECIFIED,
+ SESSION_TTY,
+ SESSION_X11,
+ SESSION_WAYLAND,
+ SESSION_MIR,
+ SESSION_WEB,
+ _SESSION_TYPE_MAX,
+ _SESSION_TYPE_INVALID = -1
+} SessionType;
+
+#define SESSION_TYPE_IS_GRAPHICAL(type) IN_SET(type, SESSION_X11, SESSION_WAYLAND, SESSION_MIR)
+
+enum KillWho {
+ KILL_LEADER,
+ KILL_ALL,
+ _KILL_WHO_MAX,
+ _KILL_WHO_INVALID = -1
+};
+
+struct Session {
+ Manager *manager;
+
+ const char *id;
+ unsigned int position;
+ SessionType type;
+ SessionClass class;
+
+ char *state_file;
+
+ User *user;
+
+ dual_timestamp timestamp;
+
+ char *tty;
+ char *display;
+
+ bool remote;
+ char *remote_user;
+ char *remote_host;
+ char *service;
+ char *desktop;
+
+ char *scope;
+ char *scope_job;
+
+ Seat *seat;
+ unsigned int vtnr;
+ int vtfd;
+
+ pid_t leader;
+ uint32_t audit_id;
+
+ int fifo_fd;
+ char *fifo_path;
+
+ sd_event_source *fifo_event_source;
+
+ bool idle_hint;
+ dual_timestamp idle_hint_timestamp;
+
+ bool locked_hint;
+
+ bool in_gc_queue:1;
+ bool started:1;
+ bool stopping:1;
+
+ sd_bus_message *create_message;
+
+ sd_event_source *timer_event_source;
+
+ char *controller;
+ Hashmap *devices;
+ sd_bus_track *track;
+
+ LIST_FIELDS(Session, sessions_by_user);
+ LIST_FIELDS(Session, sessions_by_seat);
+
+ LIST_FIELDS(Session, gc_queue);
+};
+
+Session *session_new(Manager *m, const char *id);
+void session_free(Session *s);
+void session_set_user(Session *s, User *u);
+bool session_check_gc(Session *s, bool drop_not_started);
+void session_add_to_gc_queue(Session *s);
+int session_activate(Session *s);
+bool session_is_active(Session *s);
+int session_get_idle_hint(Session *s, dual_timestamp *t);
+void session_set_idle_hint(Session *s, bool b);
+int session_get_locked_hint(Session *s);
+void session_set_locked_hint(Session *s, bool b);
+int session_create_fifo(Session *s);
+int session_start(Session *s);
+int session_stop(Session *s, bool force);
+int session_finalize(Session *s);
+int session_release(Session *s);
+int session_save(Session *s);
+int session_load(Session *s);
+int session_kill(Session *s, KillWho who, int signo);
+
+SessionState session_get_state(Session *u);
+
+extern const sd_bus_vtable session_vtable[];
+int session_node_enumerator(sd_bus *bus, const char *path,void *userdata, char ***nodes, sd_bus_error *error);
+int session_object_find(sd_bus *bus, const char *path, const char *interface, void *userdata, void **found, sd_bus_error *error);
+char *session_bus_path(Session *s);
+
+int session_send_signal(Session *s, bool new_session);
+int session_send_changed(Session *s, const char *properties, ...) _sentinel_;
+int session_send_lock(Session *s, bool lock);
+int session_send_lock_all(Manager *m, bool lock);
+
+int session_send_create_reply(Session *s, sd_bus_error *error);
+
+const char* session_state_to_string(SessionState t) _const_;
+SessionState session_state_from_string(const char *s) _pure_;
+
+const char* session_type_to_string(SessionType t) _const_;
+SessionType session_type_from_string(const char *s) _pure_;
+
+const char* session_class_to_string(SessionClass t) _const_;
+SessionClass session_class_from_string(const char *s) _pure_;
+
+const char *kill_who_to_string(KillWho k) _const_;
+KillWho kill_who_from_string(const char *s) _pure_;
+
+int session_prepare_vt(Session *s);
+void session_restore_vt(Session *s);
+void session_leave_vt(Session *s);
+
+bool session_is_controller(Session *s, const char *sender);
+int session_set_controller(Session *s, const char *sender, bool force);
+void session_drop_controller(Session *s);
+
+int bus_session_method_activate(sd_bus_message *message, void *userdata, sd_bus_error *error);
+int bus_session_method_lock(sd_bus_message *message, void *userdata, sd_bus_error *error);
+int bus_session_method_terminate(sd_bus_message *message, void *userdata, sd_bus_error *error);
+int bus_session_method_kill(sd_bus_message *message, void *userdata, sd_bus_error *error);
diff --git a/src/grp-login/systemd-logind/logind-user-dbus.c b/src/grp-login/systemd-logind/logind-user-dbus.c
new file mode 100644
index 0000000000..57d1c857e6
--- /dev/null
+++ b/src/grp-login/systemd-logind/logind-user-dbus.c
@@ -0,0 +1,399 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ 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 <errno.h>
+#include <string.h>
+
+#include "basic/alloc-util.h"
+#include "basic/formats-util.h"
+#include "basic/signal-util.h"
+#include "basic/strv.h"
+#include "basic/user-util.h"
+#include "shared/bus-util.h"
+
+#include "logind-user.h"
+#include "logind.h"
+
+static int property_get_display(
+ sd_bus *bus,
+ const char *path,
+ const char *interface,
+ const char *property,
+ sd_bus_message *reply,
+ void *userdata,
+ sd_bus_error *error) {
+
+ _cleanup_free_ char *p = NULL;
+ User *u = userdata;
+
+ assert(bus);
+ assert(reply);
+ assert(u);
+
+ p = u->display ? session_bus_path(u->display) : strdup("/");
+ if (!p)
+ return -ENOMEM;
+
+ return sd_bus_message_append(reply, "(so)", u->display ? u->display->id : "", p);
+}
+
+static int property_get_state(
+ sd_bus *bus,
+ const char *path,
+ const char *interface,
+ const char *property,
+ sd_bus_message *reply,
+ void *userdata,
+ sd_bus_error *error) {
+
+ User *u = userdata;
+
+ assert(bus);
+ assert(reply);
+ assert(u);
+
+ return sd_bus_message_append(reply, "s", user_state_to_string(user_get_state(u)));
+}
+
+static int property_get_sessions(
+ sd_bus *bus,
+ const char *path,
+ const char *interface,
+ const char *property,
+ sd_bus_message *reply,
+ void *userdata,
+ sd_bus_error *error) {
+
+ User *u = userdata;
+ Session *session;
+ int r;
+
+ assert(bus);
+ assert(reply);
+ assert(u);
+
+ r = sd_bus_message_open_container(reply, 'a', "(so)");
+ if (r < 0)
+ return r;
+
+ LIST_FOREACH(sessions_by_user, session, u->sessions) {
+ _cleanup_free_ char *p = NULL;
+
+ p = session_bus_path(session);
+ if (!p)
+ return -ENOMEM;
+
+ r = sd_bus_message_append(reply, "(so)", session->id, p);
+ if (r < 0)
+ return r;
+
+ }
+
+ return sd_bus_message_close_container(reply);
+}
+
+static int property_get_idle_hint(
+ sd_bus *bus,
+ const char *path,
+ const char *interface,
+ const char *property,
+ sd_bus_message *reply,
+ void *userdata,
+ sd_bus_error *error) {
+
+ User *u = userdata;
+
+ assert(bus);
+ assert(reply);
+ assert(u);
+
+ return sd_bus_message_append(reply, "b", user_get_idle_hint(u, NULL) > 0);
+}
+
+static int property_get_idle_since_hint(
+ sd_bus *bus,
+ const char *path,
+ const char *interface,
+ const char *property,
+ sd_bus_message *reply,
+ void *userdata,
+ sd_bus_error *error) {
+
+ User *u = userdata;
+ dual_timestamp t = DUAL_TIMESTAMP_NULL;
+ uint64_t k;
+
+ assert(bus);
+ assert(reply);
+ assert(u);
+
+ user_get_idle_hint(u, &t);
+ k = streq(property, "IdleSinceHint") ? t.realtime : t.monotonic;
+
+ return sd_bus_message_append(reply, "t", k);
+}
+
+static int property_get_linger(
+ sd_bus *bus,
+ const char *path,
+ const char *interface,
+ const char *property,
+ sd_bus_message *reply,
+ void *userdata,
+ sd_bus_error *error) {
+
+ User *u = userdata;
+ int r;
+
+ assert(bus);
+ assert(reply);
+ assert(u);
+
+ r = user_check_linger_file(u);
+
+ return sd_bus_message_append(reply, "b", r > 0);
+}
+
+int bus_user_method_terminate(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ User *u = userdata;
+ int r;
+
+ assert(message);
+ assert(u);
+
+ r = bus_verify_polkit_async(
+ message,
+ CAP_KILL,
+ "org.freedesktop.login1.manage",
+ NULL,
+ false,
+ u->uid,
+ &u->manager->polkit_registry,
+ error);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ return 1; /* Will call us back */
+
+ r = user_stop(u, true);
+ if (r < 0)
+ return r;
+
+ return sd_bus_reply_method_return(message, NULL);
+}
+
+int bus_user_method_kill(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+ User *u = userdata;
+ int32_t signo;
+ int r;
+
+ assert(message);
+ assert(u);
+
+ r = bus_verify_polkit_async(
+ message,
+ CAP_KILL,
+ "org.freedesktop.login1.manage",
+ NULL,
+ false,
+ u->uid,
+ &u->manager->polkit_registry,
+ error);
+ if (r < 0)
+ return r;
+ if (r == 0)
+ return 1; /* Will call us back */
+
+ r = sd_bus_message_read(message, "i", &signo);
+ if (r < 0)
+ return r;
+
+ if (!SIGNAL_VALID(signo))
+ return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid signal %i", signo);
+
+ r = user_kill(u, signo);
+ if (r < 0)
+ return r;
+
+ return sd_bus_reply_method_return(message, NULL);
+}
+
+const sd_bus_vtable user_vtable[] = {
+ SD_BUS_VTABLE_START(0),
+
+ SD_BUS_PROPERTY("UID", "u", bus_property_get_uid, offsetof(User, uid), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("GID", "u", bus_property_get_gid, offsetof(User, gid), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("Name", "s", NULL, offsetof(User, name), SD_BUS_VTABLE_PROPERTY_CONST),
+ BUS_PROPERTY_DUAL_TIMESTAMP("Timestamp", offsetof(User, timestamp), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("RuntimePath", "s", NULL, offsetof(User, runtime_path), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("Service", "s", NULL, offsetof(User, service), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("Slice", "s", NULL, offsetof(User, slice), SD_BUS_VTABLE_PROPERTY_CONST),
+ SD_BUS_PROPERTY("Display", "(so)", property_get_display, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
+ SD_BUS_PROPERTY("State", "s", property_get_state, 0, 0),
+ SD_BUS_PROPERTY("Sessions", "a(so)", property_get_sessions, 0, 0),
+ SD_BUS_PROPERTY("IdleHint", "b", property_get_idle_hint, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
+ SD_BUS_PROPERTY("IdleSinceHint", "t", property_get_idle_since_hint, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
+ SD_BUS_PROPERTY("IdleSinceHintMonotonic", "t", property_get_idle_since_hint, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
+ SD_BUS_PROPERTY("Linger", "b", property_get_linger, 0, 0),
+
+ SD_BUS_METHOD("Terminate", NULL, NULL, bus_user_method_terminate, SD_BUS_VTABLE_UNPRIVILEGED),
+ SD_BUS_METHOD("Kill", "i", NULL, bus_user_method_kill, SD_BUS_VTABLE_UNPRIVILEGED),
+
+ SD_BUS_VTABLE_END
+};
+
+int user_object_find(sd_bus *bus, const char *path, const char *interface, void *userdata, void **found, sd_bus_error *error) {
+ Manager *m = userdata;
+ uid_t uid;
+ User *user;
+ int r;
+
+ assert(bus);
+ assert(path);
+ assert(interface);
+ assert(found);
+ assert(m);
+
+ if (streq(path, "/org/freedesktop/login1/user/self")) {
+ _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
+ sd_bus_message *message;
+
+ message = sd_bus_get_current_message(bus);
+ if (!message)
+ return 0;
+
+ r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_OWNER_UID|SD_BUS_CREDS_AUGMENT, &creds);
+ if (r < 0)
+ return r;
+
+ r = sd_bus_creds_get_owner_uid(creds, &uid);
+ } else {
+ const char *p;
+
+ p = startswith(path, "/org/freedesktop/login1/user/_");
+ if (!p)
+ return 0;
+
+ r = parse_uid(p, &uid);
+ }
+ if (r < 0)
+ return 0;
+
+ user = hashmap_get(m->users, UID_TO_PTR(uid));
+ if (!user)
+ return 0;
+
+ *found = user;
+ return 1;
+}
+
+char *user_bus_path(User *u) {
+ char *s;
+
+ assert(u);
+
+ if (asprintf(&s, "/org/freedesktop/login1/user/_"UID_FMT, u->uid) < 0)
+ return NULL;
+
+ return s;
+}
+
+int user_node_enumerator(sd_bus *bus, const char *path, void *userdata, char ***nodes, sd_bus_error *error) {
+ _cleanup_strv_free_ char **l = NULL;
+ sd_bus_message *message;
+ Manager *m = userdata;
+ User *user;
+ Iterator i;
+ int r;
+
+ assert(bus);
+ assert(path);
+ assert(nodes);
+
+ HASHMAP_FOREACH(user, m->users, i) {
+ char *p;
+
+ p = user_bus_path(user);
+ if (!p)
+ return -ENOMEM;
+
+ r = strv_consume(&l, p);
+ if (r < 0)
+ return r;
+ }
+
+ message = sd_bus_get_current_message(bus);
+ if (message) {
+ _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
+ uid_t uid;
+
+ r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_OWNER_UID|SD_BUS_CREDS_AUGMENT, &creds);
+ if (r >= 0) {
+ r = sd_bus_creds_get_owner_uid(creds, &uid);
+ if (r >= 0) {
+ user = hashmap_get(m->users, UID_TO_PTR(uid));
+ if (user) {
+ r = strv_extend(&l, "/org/freedesktop/login1/user/self");
+ if (r < 0)
+ return r;
+ }
+ }
+ }
+ }
+
+ *nodes = l;
+ l = NULL;
+
+ return 1;
+}
+
+int user_send_signal(User *u, bool new_user) {
+ _cleanup_free_ char *p = NULL;
+
+ assert(u);
+
+ p = user_bus_path(u);
+ if (!p)
+ return -ENOMEM;
+
+ return sd_bus_emit_signal(
+ u->manager->bus,
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ new_user ? "UserNew" : "UserRemoved",
+ "uo", (uint32_t) u->uid, p);
+}
+
+int user_send_changed(User *u, const char *properties, ...) {
+ _cleanup_free_ char *p = NULL;
+ char **l;
+
+ assert(u);
+
+ if (!u->started)
+ return 0;
+
+ p = user_bus_path(u);
+ if (!p)
+ return -ENOMEM;
+
+ l = strv_from_stdarg_alloca(properties);
+
+ return sd_bus_emit_properties_changed_strv(u->manager->bus, p, "org.freedesktop.login1.User", l);
+}
diff --git a/src/grp-login/systemd-logind/logind-user.c b/src/grp-login/systemd-logind/logind-user.c
new file mode 100644
index 0000000000..5a2750b72b
--- /dev/null
+++ b/src/grp-login/systemd-logind/logind-user.c
@@ -0,0 +1,917 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ 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 <errno.h>
+#include <string.h>
+#include <sys/mount.h>
+#include <unistd.h>
+
+#include "basic/alloc-util.h"
+#include "basic/escape.h"
+#include "basic/fd-util.h"
+#include "basic/fileio.h"
+#include "basic/formats-util.h"
+#include "basic/fs-util.h"
+#include "basic/hashmap.h"
+#include "basic/label.h"
+#include "basic/mkdir.h"
+#include "basic/mount-util.h"
+#include "basic/parse-util.h"
+#include "basic/path-util.h"
+#include "basic/rm-rf.h"
+#include "basic/smack-util.h"
+#include "basic/special.h"
+#include "basic/stdio-util.h"
+#include "basic/string-table.h"
+#include "basic/unit-name.h"
+#include "basic/user-util.h"
+#include "basic/util.h"
+#include "sd-bus/bus-common-errors.h"
+#include "sd-bus/bus-error.h"
+#include "shared/bus-util.h"
+#include "shared/clean-ipc.h"
+#include "shared/conf-parser.h"
+
+#include "logind-user.h"
+
+int user_new(User **out, Manager *m, uid_t uid, gid_t gid, const char *name) {
+ _cleanup_(user_freep) User *u = NULL;
+ char lu[DECIMAL_STR_MAX(uid_t) + 1];
+ int r;
+
+ assert(out);
+ assert(m);
+ assert(name);
+
+ u = new0(User, 1);
+ if (!u)
+ return -ENOMEM;
+
+ u->manager = m;
+ u->uid = uid;
+ u->gid = gid;
+ xsprintf(lu, UID_FMT, uid);
+
+ u->name = strdup(name);
+ if (!u->name)
+ return -ENOMEM;
+
+ if (asprintf(&u->state_file, "/run/systemd/users/"UID_FMT, uid) < 0)
+ return -ENOMEM;
+
+ if (asprintf(&u->runtime_path, "/run/user/"UID_FMT, uid) < 0)
+ return -ENOMEM;
+
+ r = slice_build_subslice(SPECIAL_USER_SLICE, lu, &u->slice);
+ if (r < 0)
+ return r;
+
+ r = unit_name_build("user", lu, ".service", &u->service);
+ if (r < 0)
+ return r;
+
+ r = hashmap_put(m->users, UID_TO_PTR(uid), u);
+ if (r < 0)
+ return r;
+
+ r = hashmap_put(m->user_units, u->slice, u);
+ if (r < 0)
+ return r;
+
+ r = hashmap_put(m->user_units, u->service, u);
+ if (r < 0)
+ return r;
+
+ *out = u;
+ u = NULL;
+ return 0;
+}
+
+User *user_free(User *u) {
+ if (!u)
+ return NULL;
+
+ if (u->in_gc_queue)
+ LIST_REMOVE(gc_queue, u->manager->user_gc_queue, u);
+
+ while (u->sessions)
+ session_free(u->sessions);
+
+ if (u->service)
+ hashmap_remove_value(u->manager->user_units, u->service, u);
+
+ if (u->slice)
+ hashmap_remove_value(u->manager->user_units, u->slice, u);
+
+ hashmap_remove_value(u->manager->users, UID_TO_PTR(u->uid), u);
+
+ u->slice_job = mfree(u->slice_job);
+ u->service_job = mfree(u->service_job);
+
+ u->service = mfree(u->service);
+ u->slice = mfree(u->slice);
+ u->runtime_path = mfree(u->runtime_path);
+ u->state_file = mfree(u->state_file);
+ u->name = mfree(u->name);
+
+ return mfree(u);
+}
+
+static int user_save_internal(User *u) {
+ _cleanup_free_ char *temp_path = NULL;
+ _cleanup_fclose_ FILE *f = NULL;
+ int r;
+
+ assert(u);
+ assert(u->state_file);
+
+ r = mkdir_safe_label("/run/systemd/users", 0755, 0, 0);
+ if (r < 0)
+ goto fail;
+
+ r = fopen_temporary(u->state_file, &f, &temp_path);
+ if (r < 0)
+ goto fail;
+
+ fchmod(fileno(f), 0644);
+
+ fprintf(f,
+ "# This is private data. Do not parse.\n"
+ "NAME=%s\n"
+ "STATE=%s\n",
+ u->name,
+ user_state_to_string(user_get_state(u)));
+
+ /* LEGACY: no-one reads RUNTIME= anymore, drop it at some point */
+ if (u->runtime_path)
+ fprintf(f, "RUNTIME=%s\n", u->runtime_path);
+
+ if (u->service_job)
+ fprintf(f, "SERVICE_JOB=%s\n", u->service_job);
+
+ if (u->slice_job)
+ fprintf(f, "SLICE_JOB=%s\n", u->slice_job);
+
+ if (u->display)
+ fprintf(f, "DISPLAY=%s\n", u->display->id);
+
+ if (dual_timestamp_is_set(&u->timestamp))
+ fprintf(f,
+ "REALTIME="USEC_FMT"\n"
+ "MONOTONIC="USEC_FMT"\n",
+ u->timestamp.realtime,
+ u->timestamp.monotonic);
+
+ if (u->sessions) {
+ Session *i;
+ bool first;
+
+ fputs("SESSIONS=", f);
+ first = true;
+ LIST_FOREACH(sessions_by_user, i, u->sessions) {
+ if (first)
+ first = false;
+ else
+ fputc(' ', f);
+
+ fputs(i->id, f);
+ }
+
+ fputs("\nSEATS=", f);
+ first = true;
+ LIST_FOREACH(sessions_by_user, i, u->sessions) {
+ if (!i->seat)
+ continue;
+
+ if (first)
+ first = false;
+ else
+ fputc(' ', f);
+
+ fputs(i->seat->id, f);
+ }
+
+ fputs("\nACTIVE_SESSIONS=", f);
+ first = true;
+ LIST_FOREACH(sessions_by_user, i, u->sessions) {
+ if (!session_is_active(i))
+ continue;
+
+ if (first)
+ first = false;
+ else
+ fputc(' ', f);
+
+ fputs(i->id, f);
+ }
+
+ fputs("\nONLINE_SESSIONS=", f);
+ first = true;
+ LIST_FOREACH(sessions_by_user, i, u->sessions) {
+ if (session_get_state(i) == SESSION_CLOSING)
+ continue;
+
+ if (first)
+ first = false;
+ else
+ fputc(' ', f);
+
+ fputs(i->id, f);
+ }
+
+ fputs("\nACTIVE_SEATS=", f);
+ first = true;
+ LIST_FOREACH(sessions_by_user, i, u->sessions) {
+ if (!session_is_active(i) || !i->seat)
+ continue;
+
+ if (first)
+ first = false;
+ else
+ fputc(' ', f);
+
+ fputs(i->seat->id, f);
+ }
+
+ fputs("\nONLINE_SEATS=", f);
+ first = true;
+ LIST_FOREACH(sessions_by_user, i, u->sessions) {
+ if (session_get_state(i) == SESSION_CLOSING || !i->seat)
+ continue;
+
+ if (first)
+ first = false;
+ else
+ fputc(' ', f);
+
+ fputs(i->seat->id, f);
+ }
+ fputc('\n', f);
+ }
+
+ r = fflush_and_check(f);
+ if (r < 0)
+ goto fail;
+
+ if (rename(temp_path, u->state_file) < 0) {
+ r = -errno;
+ goto fail;
+ }
+
+ return 0;
+
+fail:
+ (void) unlink(u->state_file);
+
+ if (temp_path)
+ (void) unlink(temp_path);
+
+ return log_error_errno(r, "Failed to save user data %s: %m", u->state_file);
+}
+
+int user_save(User *u) {
+ assert(u);
+
+ if (!u->started)
+ return 0;
+
+ return user_save_internal (u);
+}
+
+int user_load(User *u) {
+ _cleanup_free_ char *display = NULL, *realtime = NULL, *monotonic = NULL;
+ Session *s = NULL;
+ int r;
+
+ assert(u);
+
+ r = parse_env_file(u->state_file, NEWLINE,
+ "SERVICE_JOB", &u->service_job,
+ "SLICE_JOB", &u->slice_job,
+ "DISPLAY", &display,
+ "REALTIME", &realtime,
+ "MONOTONIC", &monotonic,
+ NULL);
+ if (r < 0) {
+ if (r == -ENOENT)
+ return 0;
+
+ return log_error_errno(r, "Failed to read %s: %m", u->state_file);
+ }
+
+ if (display)
+ s = hashmap_get(u->manager->sessions, display);
+
+ if (s && s->display && display_is_local(s->display))
+ u->display = s;
+
+ if (realtime)
+ timestamp_deserialize(realtime, &u->timestamp.realtime);
+ if (monotonic)
+ timestamp_deserialize(monotonic, &u->timestamp.monotonic);
+
+ return r;
+}
+
+static int user_mkdir_runtime_path(User *u) {
+ int r;
+
+ assert(u);
+
+ r = mkdir_safe_label("/run/user", 0755, 0, 0);
+ if (r < 0)
+ return log_error_errno(r, "Failed to create /run/user: %m");
+
+ if (path_is_mount_point(u->runtime_path, 0) <= 0) {
+ _cleanup_free_ char *t = NULL;
+
+ (void) mkdir_label(u->runtime_path, 0700);
+
+ if (mac_smack_use())
+ r = asprintf(&t, "mode=0700,smackfsroot=*,uid=" UID_FMT ",gid=" GID_FMT ",size=%zu", u->uid, u->gid, u->manager->runtime_dir_size);
+ else
+ r = asprintf(&t, "mode=0700,uid=" UID_FMT ",gid=" GID_FMT ",size=%zu", u->uid, u->gid, u->manager->runtime_dir_size);
+ if (r < 0) {
+ r = log_oom();
+ goto fail;
+ }
+
+ r = mount("tmpfs", u->runtime_path, "tmpfs", MS_NODEV|MS_NOSUID, t);
+ if (r < 0) {
+ if (errno != EPERM) {
+ r = log_error_errno(errno, "Failed to mount per-user tmpfs directory %s: %m", u->runtime_path);
+ goto fail;
+ }
+
+ /* Lacking permissions, maybe
+ * CAP_SYS_ADMIN-less container? In this case,
+ * just use a normal directory. */
+
+ r = chmod_and_chown(u->runtime_path, 0700, u->uid, u->gid);
+ if (r < 0) {
+ log_error_errno(r, "Failed to change runtime directory ownership and mode: %m");
+ goto fail;
+ }
+ }
+
+ r = label_fix(u->runtime_path, false, false);
+ if (r < 0)
+ log_warning_errno(r, "Failed to fix label of '%s', ignoring: %m", u->runtime_path);
+ }
+
+ return 0;
+
+fail:
+ /* Try to clean up, but ignore errors */
+ (void) rmdir(u->runtime_path);
+ return r;
+}
+
+static int user_start_slice(User *u) {
+ _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+ const char *description;
+ char *job;
+ int r;
+
+ assert(u);
+
+ u->slice_job = mfree(u->slice_job);
+ description = strjoina("User Slice of ", u->name);
+
+ r = manager_start_slice(
+ u->manager,
+ u->slice,
+ description,
+ "systemd-logind.service",
+ "systemd-user-sessions.service",
+ u->manager->user_tasks_max,
+ &error,
+ &job);
+ if (r >= 0)
+ u->slice_job = job;
+ else if (!sd_bus_error_has_name(&error, BUS_ERROR_UNIT_EXISTS))
+ /* we don't fail due to this, let's try to continue */
+ log_error_errno(r, "Failed to start user slice %s, ignoring: %s (%s)",
+ u->slice, bus_error_message(&error, r), error.name);
+
+ return 0;
+}
+
+static int user_start_service(User *u) {
+ _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+ char *job;
+ int r;
+
+ assert(u);
+
+ u->service_job = mfree(u->service_job);
+
+ r = manager_start_unit(
+ u->manager,
+ u->service,
+ &error,
+ &job);
+ if (r < 0) {
+ /* we don't fail due to this, let's try to continue */
+ log_error_errno(r, "Failed to start user service, ignoring: %s", bus_error_message(&error, r));
+ } else {
+ u->service_job = job;
+ }
+
+ return 0;
+}
+
+int user_start(User *u) {
+ int r;
+
+ assert(u);
+
+ if (u->started && !u->stopping)
+ return 0;
+
+ /*
+ * If u->stopping is set, the user is marked for removal and the slice
+ * and service stop-jobs are queued. We have to clear that flag before
+ * queing the start-jobs again. If they succeed, the user object can be
+ * re-used just fine (pid1 takes care of job-ordering and proper
+ * restart), but if they fail, we want to force another user_stop() so
+ * possibly pending units are stopped.
+ * Note that we don't clear u->started, as we have no clue what state
+ * the user is in on failure here. Hence, we pretend the user is
+ * running so it will be properly taken down by GC. However, we clearly
+ * return an error from user_start() in that case, so no further
+ * reference to the user is taken.
+ */
+ u->stopping = false;
+
+ if (!u->started) {
+ log_debug("New user %s logged in.", u->name);
+
+ /* Make XDG_RUNTIME_DIR */
+ r = user_mkdir_runtime_path(u);
+ if (r < 0)
+ return r;
+ }
+
+ /* Create cgroup */
+ r = user_start_slice(u);
+ if (r < 0)
+ return r;
+
+ /* Save the user data so far, because pam_systemd will read the
+ * XDG_RUNTIME_DIR out of it while starting up systemd --user.
+ * We need to do user_save_internal() because we have not
+ * "officially" started yet. */
+ user_save_internal(u);
+
+ /* Spawn user systemd */
+ r = user_start_service(u);
+ if (r < 0)
+ return r;
+
+ if (!u->started) {
+ if (!dual_timestamp_is_set(&u->timestamp))
+ dual_timestamp_get(&u->timestamp);
+ user_send_signal(u, true);
+ u->started = true;
+ }
+
+ /* Save new user data */
+ user_save(u);
+
+ return 0;
+}
+
+static int user_stop_slice(User *u) {
+ _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+ char *job;
+ int r;
+
+ assert(u);
+
+ r = manager_stop_unit(u->manager, u->slice, &error, &job);
+ if (r < 0) {
+ log_error("Failed to stop user slice: %s", bus_error_message(&error, r));
+ return r;
+ }
+
+ free(u->slice_job);
+ u->slice_job = job;
+
+ return r;
+}
+
+static int user_stop_service(User *u) {
+ _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+ char *job;
+ int r;
+
+ assert(u);
+
+ r = manager_stop_unit(u->manager, u->service, &error, &job);
+ if (r < 0) {
+ log_error("Failed to stop user service: %s", bus_error_message(&error, r));
+ return r;
+ }
+
+ free(u->service_job);
+ u->service_job = job;
+
+ return r;
+}
+
+static int user_remove_runtime_path(User *u) {
+ int r;
+
+ assert(u);
+
+ r = rm_rf(u->runtime_path, 0);
+ if (r < 0)
+ log_error_errno(r, "Failed to remove runtime directory %s: %m", u->runtime_path);
+
+ /* Ignore cases where the directory isn't mounted, as that's
+ * quite possible, if we lacked the permissions to mount
+ * something */
+ r = umount2(u->runtime_path, MNT_DETACH);
+ if (r < 0 && errno != EINVAL && errno != ENOENT)
+ log_error_errno(errno, "Failed to unmount user runtime directory %s: %m", u->runtime_path);
+
+ r = rm_rf(u->runtime_path, REMOVE_ROOT);
+ if (r < 0)
+ log_error_errno(r, "Failed to remove runtime directory %s: %m", u->runtime_path);
+
+ return r;
+}
+
+int user_stop(User *u, bool force) {
+ Session *s;
+ int r = 0, k;
+ assert(u);
+
+ /* Stop jobs have already been queued */
+ if (u->stopping) {
+ user_save(u);
+ return r;
+ }
+
+ LIST_FOREACH(sessions_by_user, s, u->sessions) {
+ k = session_stop(s, force);
+ if (k < 0)
+ r = k;
+ }
+
+ /* Kill systemd */
+ k = user_stop_service(u);
+ if (k < 0)
+ r = k;
+
+ /* Kill cgroup */
+ k = user_stop_slice(u);
+ if (k < 0)
+ r = k;
+
+ u->stopping = true;
+
+ user_save(u);
+
+ return r;
+}
+
+int user_finalize(User *u) {
+ Session *s;
+ int r = 0, k;
+
+ assert(u);
+
+ if (u->started)
+ log_debug("User %s logged out.", u->name);
+
+ LIST_FOREACH(sessions_by_user, s, u->sessions) {
+ k = session_finalize(s);
+ if (k < 0)
+ r = k;
+ }
+
+ /* Kill XDG_RUNTIME_DIR */
+ k = user_remove_runtime_path(u);
+ if (k < 0)
+ r = k;
+
+ /* Clean SysV + POSIX IPC objects */
+ if (u->manager->remove_ipc) {
+ k = clean_ipc(u->uid);
+ if (k < 0)
+ r = k;
+ }
+
+ unlink(u->state_file);
+ user_add_to_gc_queue(u);
+
+ if (u->started) {
+ user_send_signal(u, false);
+ u->started = false;
+ }
+
+ return r;
+}
+
+int user_get_idle_hint(User *u, dual_timestamp *t) {
+ Session *s;
+ bool idle_hint = true;
+ dual_timestamp ts = DUAL_TIMESTAMP_NULL;
+
+ assert(u);
+
+ LIST_FOREACH(sessions_by_user, s, u->sessions) {
+ dual_timestamp k;
+ int ih;
+
+ ih = session_get_idle_hint(s, &k);
+ if (ih < 0)
+ return ih;
+
+ if (!ih) {
+ if (!idle_hint) {
+ if (k.monotonic < ts.monotonic)
+ ts = k;
+ } else {
+ idle_hint = false;
+ ts = k;
+ }
+ } else if (idle_hint) {
+
+ if (k.monotonic > ts.monotonic)
+ ts = k;
+ }
+ }
+
+ if (t)
+ *t = ts;
+
+ return idle_hint;
+}
+
+int user_check_linger_file(User *u) {
+ _cleanup_free_ char *cc = NULL;
+ char *p = NULL;
+
+ cc = cescape(u->name);
+ if (!cc)
+ return -ENOMEM;
+
+ p = strjoina("/var/lib/systemd/linger/", cc);
+
+ return access(p, F_OK) >= 0;
+}
+
+bool user_check_gc(User *u, bool drop_not_started) {
+ assert(u);
+
+ if (drop_not_started && !u->started)
+ return false;
+
+ if (u->sessions)
+ return true;
+
+ if (user_check_linger_file(u) > 0)
+ return true;
+
+ if (u->slice_job && manager_job_is_active(u->manager, u->slice_job))
+ return true;
+
+ if (u->service_job && manager_job_is_active(u->manager, u->service_job))
+ return true;
+
+ return false;
+}
+
+void user_add_to_gc_queue(User *u) {
+ assert(u);
+
+ if (u->in_gc_queue)
+ return;
+
+ LIST_PREPEND(gc_queue, u->manager->user_gc_queue, u);
+ u->in_gc_queue = true;
+}
+
+UserState user_get_state(User *u) {
+ Session *i;
+
+ assert(u);
+
+ if (u->stopping)
+ return USER_CLOSING;
+
+ if (!u->started || u->slice_job || u->service_job)
+ return USER_OPENING;
+
+ if (u->sessions) {
+ bool all_closing = true;
+
+ LIST_FOREACH(sessions_by_user, i, u->sessions) {
+ SessionState state;
+
+ state = session_get_state(i);
+ if (state == SESSION_ACTIVE)
+ return USER_ACTIVE;
+ if (state != SESSION_CLOSING)
+ all_closing = false;
+ }
+
+ return all_closing ? USER_CLOSING : USER_ONLINE;
+ }
+
+ if (user_check_linger_file(u) > 0)
+ return USER_LINGERING;
+
+ return USER_CLOSING;
+}
+
+int user_kill(User *u, int signo) {
+ assert(u);
+
+ return manager_kill_unit(u->manager, u->slice, KILL_ALL, signo, NULL);
+}
+
+static bool elect_display_filter(Session *s) {
+ /* Return true if the session is a candidate for the user’s ‘primary
+ * session’ or ‘display’. */
+ assert(s);
+
+ return (s->class == SESSION_USER && !s->stopping);
+}
+
+static int elect_display_compare(Session *s1, Session *s2) {
+ /* Indexed by SessionType. Lower numbers mean more preferred. */
+ const int type_ranks[_SESSION_TYPE_MAX] = {
+ [SESSION_UNSPECIFIED] = 0,
+ [SESSION_TTY] = -2,
+ [SESSION_X11] = -3,
+ [SESSION_WAYLAND] = -3,
+ [SESSION_MIR] = -3,
+ [SESSION_WEB] = -1,
+ };
+
+ /* Calculate the partial order relationship between s1 and s2,
+ * returning < 0 if s1 is preferred as the user’s ‘primary session’,
+ * 0 if s1 and s2 are equally preferred or incomparable, or > 0 if s2
+ * is preferred.
+ *
+ * s1 or s2 may be NULL. */
+ if (!s1 && !s2)
+ return 0;
+
+ if ((s1 == NULL) != (s2 == NULL))
+ return (s1 == NULL) - (s2 == NULL);
+
+ if (s1->stopping != s2->stopping)
+ return s1->stopping - s2->stopping;
+
+ if ((s1->class != SESSION_USER) != (s2->class != SESSION_USER))
+ return (s1->class != SESSION_USER) - (s2->class != SESSION_USER);
+
+ if ((s1->type == _SESSION_TYPE_INVALID) != (s2->type == _SESSION_TYPE_INVALID))
+ return (s1->type == _SESSION_TYPE_INVALID) - (s2->type == _SESSION_TYPE_INVALID);
+
+ if (s1->type != s2->type)
+ return type_ranks[s1->type] - type_ranks[s2->type];
+
+ return 0;
+}
+
+void user_elect_display(User *u) {
+ Session *s;
+
+ assert(u);
+
+ /* This elects a primary session for each user, which we call
+ * the "display". We try to keep the assignment stable, but we
+ * "upgrade" to better choices. */
+ log_debug("Electing new display for user %s", u->name);
+
+ LIST_FOREACH(sessions_by_user, s, u->sessions) {
+ if (!elect_display_filter(s)) {
+ log_debug("Ignoring session %s", s->id);
+ continue;
+ }
+
+ if (elect_display_compare(s, u->display) < 0) {
+ log_debug("Choosing session %s in preference to %s", s->id, u->display ? u->display->id : "-");
+ u->display = s;
+ }
+ }
+}
+
+static const char* const user_state_table[_USER_STATE_MAX] = {
+ [USER_OFFLINE] = "offline",
+ [USER_OPENING] = "opening",
+ [USER_LINGERING] = "lingering",
+ [USER_ONLINE] = "online",
+ [USER_ACTIVE] = "active",
+ [USER_CLOSING] = "closing"
+};
+
+DEFINE_STRING_TABLE_LOOKUP(user_state, UserState);
+
+int config_parse_tmpfs_size(
+ const char* unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ unsigned section_line,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ size_t *sz = data;
+ int r;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ /* First, try to parse as percentage */
+ r = parse_percent(rvalue);
+ if (r > 0 && r < 100)
+ *sz = physical_memory_scale(r, 100U);
+ else {
+ uint64_t k;
+
+ /* If the passed argument was not a percentage, or out of range, parse as byte size */
+
+ r = parse_size(rvalue, 1024, &k);
+ if (r < 0 || k <= 0 || (uint64_t) (size_t) k != k) {
+ log_syntax(unit, LOG_ERR, filename, line, r, "Failed to parse size value, ignoring: %s", rvalue);
+ return 0;
+ }
+
+ *sz = PAGE_ALIGN((size_t) k);
+ }
+
+ return 0;
+}
+
+int config_parse_user_tasks_max(
+ const char* unit,
+ const char *filename,
+ unsigned line,
+ const char *section,
+ unsigned section_line,
+ const char *lvalue,
+ int ltype,
+ const char *rvalue,
+ void *data,
+ void *userdata) {
+
+ uint64_t *m = data;
+ uint64_t k;
+ int r;
+
+ assert(filename);
+ assert(lvalue);
+ assert(rvalue);
+ assert(data);
+
+ /* First, try to parse as percentage */
+ r = parse_percent(rvalue);
+ if (r > 0 && r < 100)
+ k = system_tasks_max_scale(r, 100U);
+ else {
+
+ /* If the passed argument was not a percentage, or out of range, parse as byte size */
+
+ r = safe_atou64(rvalue, &k);
+ if (r < 0) {
+ log_syntax(unit, LOG_ERR, filename, line, r, "Failed to parse tasks maximum, ignoring: %s", rvalue);
+ return 0;
+ }
+ }
+
+ if (k <= 0 || k >= UINT64_MAX) {
+ log_syntax(unit, LOG_ERR, filename, line, 0, "Tasks maximum out of range, ignoring: %s", rvalue);
+ return 0;
+ }
+
+ *m = k;
+ return 0;
+}
diff --git a/src/grp-login/systemd-logind/logind-user.h b/src/grp-login/systemd-logind/logind-user.h
new file mode 100644
index 0000000000..b23c59fa1d
--- /dev/null
+++ b/src/grp-login/systemd-logind/logind-user.h
@@ -0,0 +1,94 @@
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ 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 "basic/list.h"
+
+typedef struct User User;
+
+#include "logind.h"
+
+typedef enum UserState {
+ USER_OFFLINE, /* Not logged in at all */
+ USER_OPENING, /* Is logging in */
+ USER_LINGERING, /* Lingering has been enabled by the admin for this user */
+ USER_ONLINE, /* User logged in */
+ USER_ACTIVE, /* User logged in and has a session in the fg */
+ USER_CLOSING, /* User logged out, but processes still remain and lingering is not enabled */
+ _USER_STATE_MAX,
+ _USER_STATE_INVALID = -1
+} UserState;
+
+struct User {
+ Manager *manager;
+ uid_t uid;
+ gid_t gid;
+ char *name;
+ char *state_file;
+ char *runtime_path;
+ char *slice;
+ char *service;
+
+ char *service_job;
+ char *slice_job;
+
+ Session *display;
+
+ dual_timestamp timestamp;
+
+ bool in_gc_queue:1;
+ bool started:1;
+ bool stopping:1;
+
+ LIST_HEAD(Session, sessions);
+ LIST_FIELDS(User, gc_queue);
+};
+
+int user_new(User **out, Manager *m, uid_t uid, gid_t gid, const char *name);
+User *user_free(User *u);
+
+DEFINE_TRIVIAL_CLEANUP_FUNC(User *, user_free);
+
+bool user_check_gc(User *u, bool drop_not_started);
+void user_add_to_gc_queue(User *u);
+int user_start(User *u);
+int user_stop(User *u, bool force);
+int user_finalize(User *u);
+UserState user_get_state(User *u);
+int user_get_idle_hint(User *u, dual_timestamp *t);
+int user_save(User *u);
+int user_load(User *u);
+int user_kill(User *u, int signo);
+int user_check_linger_file(User *u);
+void user_elect_display(User *u);
+
+extern const sd_bus_vtable user_vtable[];
+int user_node_enumerator(sd_bus *bus, const char *path, void *userdata, char ***nodes, sd_bus_error *error);
+int user_object_find(sd_bus *bus, const char *path, const char *interface, void *userdata, void **found, sd_bus_error *error);
+char *user_bus_path(User *s);
+
+int user_send_signal(User *u, bool new_user);
+int user_send_changed(User *u, const char *properties, ...) _sentinel_;
+
+const char* user_state_to_string(UserState s) _const_;
+UserState user_state_from_string(const char *s) _pure_;
+
+int bus_user_method_terminate(sd_bus_message *message, void *userdata, sd_bus_error *error);
+int bus_user_method_kill(sd_bus_message *message, void *userdata, sd_bus_error *error);
diff --git a/src/grp-login/systemd-logind/logind-utmp.c b/src/grp-login/systemd-logind/logind-utmp.c
new file mode 100644
index 0000000000..1e97083f78
--- /dev/null
+++ b/src/grp-login/systemd-logind/logind-utmp.c
@@ -0,0 +1,184 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2015 Daniel Mack
+
+ 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 <errno.h>
+#include <pwd.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <systemd/sd-messages.h>
+
+#include "basic/alloc-util.h"
+#include "basic/audit-util.h"
+#include "basic/formats-util.h"
+#include "basic/special.h"
+#include "basic/strv.h"
+#include "basic/unit-name.h"
+#include "basic/user-util.h"
+#include "sd-bus/bus-common-errors.h"
+#include "sd-bus/bus-error.h"
+#include "shared/bus-util.h"
+#include "shared/utmp-wtmp.h"
+
+#include "logind.h"
+
+_const_ static usec_t when_wall(usec_t n, usec_t elapse) {
+
+ usec_t left;
+ unsigned int i;
+ static const int wall_timers[] = {
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
+ 25, 40, 55, 70, 100, 130, 150, 180,
+ };
+
+ /* If the time is already passed, then don't announce */
+ if (n >= elapse)
+ return 0;
+
+ left = elapse - n;
+
+ for (i = 1; i < ELEMENTSOF(wall_timers); i++)
+ if (wall_timers[i] * USEC_PER_MINUTE >= left)
+ return left - wall_timers[i-1] * USEC_PER_MINUTE;
+
+ return left % USEC_PER_HOUR;
+}
+
+bool logind_wall_tty_filter(const char *tty, void *userdata) {
+
+ Manager *m = userdata;
+
+ assert(m);
+
+ if (!startswith(tty, "/dev/") || !m->scheduled_shutdown_tty)
+ return true;
+
+ return !streq(tty + 5, m->scheduled_shutdown_tty);
+}
+
+static int warn_wall(Manager *m, usec_t n) {
+ char date[FORMAT_TIMESTAMP_MAX] = {};
+ _cleanup_free_ char *l = NULL;
+ usec_t left;
+ int r;
+
+ assert(m);
+
+ if (!m->enable_wall_messages)
+ return 0;
+
+ left = m->scheduled_shutdown_timeout > n;
+
+ r = asprintf(&l, "%s%sThe system is going down for %s %s%s!",
+ strempty(m->wall_message),
+ isempty(m->wall_message) ? "" : "\n",
+ m->scheduled_shutdown_type,
+ left ? "at " : "NOW",
+ left ? format_timestamp(date, sizeof(date), m->scheduled_shutdown_timeout) : "");
+ if (r < 0) {
+ log_oom();
+ return 0;
+ }
+
+ utmp_wall(l, uid_to_name(m->scheduled_shutdown_uid),
+ m->scheduled_shutdown_tty, logind_wall_tty_filter, m);
+
+ return 1;
+}
+
+static int wall_message_timeout_handler(
+ sd_event_source *s,
+ uint64_t usec,
+ void *userdata) {
+
+ Manager *m = userdata;
+ usec_t n, next;
+ int r;
+
+ assert(m);
+ assert(s == m->wall_message_timeout_source);
+
+ n = now(CLOCK_REALTIME);
+
+ r = warn_wall(m, n);
+ if (r == 0)
+ return 0;
+
+ next = when_wall(n, m->scheduled_shutdown_timeout);
+ if (next > 0) {
+ r = sd_event_source_set_time(s, n + next);
+ if (r < 0)
+ return log_error_errno(r, "sd_event_source_set_time() failed. %m");
+
+ r = sd_event_source_set_enabled(s, SD_EVENT_ONESHOT);
+ if (r < 0)
+ return log_error_errno(r, "sd_event_source_set_enabled() failed. %m");
+ }
+
+ return 0;
+}
+
+int manager_setup_wall_message_timer(Manager *m) {
+
+ usec_t n, elapse;
+ int r;
+
+ assert(m);
+
+ n = now(CLOCK_REALTIME);
+ elapse = m->scheduled_shutdown_timeout;
+
+ /* wall message handling */
+
+ if (isempty(m->scheduled_shutdown_type)) {
+ warn_wall(m, n);
+ return 0;
+ }
+
+ if (elapse < n)
+ return 0;
+
+ /* Warn immediately if less than 15 minutes are left */
+ if (elapse - n < 15 * USEC_PER_MINUTE) {
+ r = warn_wall(m, n);
+ if (r == 0)
+ return 0;
+ }
+
+ elapse = when_wall(n, elapse);
+ if (elapse == 0)
+ return 0;
+
+ if (m->wall_message_timeout_source) {
+ r = sd_event_source_set_time(m->wall_message_timeout_source, n + elapse);
+ if (r < 0)
+ return log_error_errno(r, "sd_event_source_set_time() failed. %m");
+
+ r = sd_event_source_set_enabled(m->wall_message_timeout_source, SD_EVENT_ONESHOT);
+ if (r < 0)
+ return log_error_errno(r, "sd_event_source_set_enabled() failed. %m");
+ } else {
+ r = sd_event_add_time(m->event, &m->wall_message_timeout_source,
+ CLOCK_REALTIME, n + elapse, 0, wall_message_timeout_handler, m);
+ if (r < 0)
+ return log_error_errno(r, "sd_event_add_time() failed. %m");
+ }
+
+ return 0;
+}
diff --git a/src/grp-login/systemd-logind/logind.c b/src/grp-login/systemd-logind/logind.c
new file mode 100644
index 0000000000..84e23beef0
--- /dev/null
+++ b/src/grp-login/systemd-logind/logind.c
@@ -0,0 +1,1209 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ 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 <errno.h>
+#include <fcntl.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <libudev.h>
+#include <systemd/sd-daemon.h>
+
+#include "basic/alloc-util.h"
+#include "basic/def.h"
+#include "basic/dirent-util.h"
+#include "basic/fd-util.h"
+#include "basic/formats-util.h"
+#include "basic/selinux-util.h"
+#include "basic/signal-util.h"
+#include "basic/strv.h"
+#include "sd-bus/bus-error.h"
+#include "shared/bus-util.h"
+#include "shared/conf-parser.h"
+#include "shared/udev-util.h"
+
+#include "logind.h"
+
+static void manager_free(Manager *m);
+
+static void manager_reset_config(Manager *m) {
+ m->n_autovts = 6;
+ m->reserve_vt = 6;
+ m->remove_ipc = true;
+ m->inhibit_delay_max = 5 * USEC_PER_SEC;
+ m->handle_power_key = HANDLE_POWEROFF;
+ m->handle_suspend_key = HANDLE_SUSPEND;
+ m->handle_hibernate_key = HANDLE_HIBERNATE;
+ m->handle_lid_switch = HANDLE_SUSPEND;
+ m->handle_lid_switch_docked = HANDLE_IGNORE;
+ m->power_key_ignore_inhibited = false;
+ m->suspend_key_ignore_inhibited = false;
+ m->hibernate_key_ignore_inhibited = false;
+ m->lid_switch_ignore_inhibited = true;
+
+ m->holdoff_timeout_usec = 30 * USEC_PER_SEC;
+
+ m->idle_action_usec = 30 * USEC_PER_MINUTE;
+ m->idle_action = HANDLE_IGNORE;
+
+ m->runtime_dir_size = physical_memory_scale(10U, 100U); /* 10% */
+ m->user_tasks_max = system_tasks_max_scale(33U, 100U); /* 33% */
+ m->sessions_max = 8192;
+ m->inhibitors_max = 8192;
+
+ m->kill_user_processes = KILL_USER_PROCESSES;
+
+ m->kill_only_users = strv_free(m->kill_only_users);
+ m->kill_exclude_users = strv_free(m->kill_exclude_users);
+}
+
+static Manager *manager_new(void) {
+ Manager *m;
+ int r;
+
+ m = new0(Manager, 1);
+ if (!m)
+ return NULL;
+
+ m->console_active_fd = -1;
+ m->reserve_vt_fd = -1;
+
+ m->idle_action_not_before_usec = now(CLOCK_MONOTONIC);
+
+ m->devices = hashmap_new(&string_hash_ops);
+ m->seats = hashmap_new(&string_hash_ops);
+ m->sessions = hashmap_new(&string_hash_ops);
+ m->users = hashmap_new(NULL);
+ m->inhibitors = hashmap_new(&string_hash_ops);
+ m->buttons = hashmap_new(&string_hash_ops);
+
+ m->user_units = hashmap_new(&string_hash_ops);
+ m->session_units = hashmap_new(&string_hash_ops);
+
+ if (!m->devices || !m->seats || !m->sessions || !m->users || !m->inhibitors || !m->buttons || !m->user_units || !m->session_units)
+ goto fail;
+
+ m->udev = udev_new();
+ if (!m->udev)
+ goto fail;
+
+ r = sd_event_default(&m->event);
+ if (r < 0)
+ goto fail;
+
+ sd_event_set_watchdog(m->event, true);
+
+ manager_reset_config(m);
+
+ return m;
+
+fail:
+ manager_free(m);
+ return NULL;
+}
+
+static void manager_free(Manager *m) {
+ Session *session;
+ User *u;
+ Device *d;
+ Seat *s;
+ Inhibitor *i;
+ Button *b;
+
+ assert(m);
+
+ while ((session = hashmap_first(m->sessions)))
+ session_free(session);
+
+ while ((u = hashmap_first(m->users)))
+ user_free(u);
+
+ while ((d = hashmap_first(m->devices)))
+ device_free(d);
+
+ while ((s = hashmap_first(m->seats)))
+ seat_free(s);
+
+ while ((i = hashmap_first(m->inhibitors)))
+ inhibitor_free(i);
+
+ while ((b = hashmap_first(m->buttons)))
+ button_free(b);
+
+ hashmap_free(m->devices);
+ hashmap_free(m->seats);
+ hashmap_free(m->sessions);
+ hashmap_free(m->users);
+ hashmap_free(m->inhibitors);
+ hashmap_free(m->buttons);
+
+ hashmap_free(m->user_units);
+ hashmap_free(m->session_units);
+
+ sd_event_source_unref(m->idle_action_event_source);
+ sd_event_source_unref(m->inhibit_timeout_source);
+ sd_event_source_unref(m->scheduled_shutdown_timeout_source);
+ sd_event_source_unref(m->nologin_timeout_source);
+ sd_event_source_unref(m->wall_message_timeout_source);
+
+ sd_event_source_unref(m->console_active_event_source);
+ sd_event_source_unref(m->udev_seat_event_source);
+ sd_event_source_unref(m->udev_device_event_source);
+ sd_event_source_unref(m->udev_vcsa_event_source);
+ sd_event_source_unref(m->udev_button_event_source);
+ sd_event_source_unref(m->lid_switch_ignore_event_source);
+
+ safe_close(m->console_active_fd);
+
+ udev_monitor_unref(m->udev_seat_monitor);
+ udev_monitor_unref(m->udev_device_monitor);
+ udev_monitor_unref(m->udev_vcsa_monitor);
+ udev_monitor_unref(m->udev_button_monitor);
+
+ udev_unref(m->udev);
+
+ if (m->unlink_nologin)
+ (void) unlink("/run/nologin");
+
+ bus_verify_polkit_async_registry_free(m->polkit_registry);
+
+ sd_bus_unref(m->bus);
+ sd_event_unref(m->event);
+
+ safe_close(m->reserve_vt_fd);
+
+ strv_free(m->kill_only_users);
+ strv_free(m->kill_exclude_users);
+
+ free(m->scheduled_shutdown_type);
+ free(m->scheduled_shutdown_tty);
+ free(m->wall_message);
+ free(m->action_job);
+ free(m);
+}
+
+static int manager_enumerate_devices(Manager *m) {
+ struct udev_list_entry *item = NULL, *first = NULL;
+ _cleanup_udev_enumerate_unref_ struct udev_enumerate *e = NULL;
+ int r;
+
+ assert(m);
+
+ /* Loads devices from udev and creates seats for them as
+ * necessary */
+
+ e = udev_enumerate_new(m->udev);
+ if (!e)
+ return -ENOMEM;
+
+ r = udev_enumerate_add_match_tag(e, "master-of-seat");
+ if (r < 0)
+ return r;
+
+ r = udev_enumerate_add_match_is_initialized(e);
+ if (r < 0)
+ return r;
+
+ r = udev_enumerate_scan_devices(e);
+ if (r < 0)
+ return r;
+
+ first = udev_enumerate_get_list_entry(e);
+ udev_list_entry_foreach(item, first) {
+ _cleanup_udev_device_unref_ struct udev_device *d = NULL;
+ int k;
+
+ d = udev_device_new_from_syspath(m->udev, udev_list_entry_get_name(item));
+ if (!d)
+ return -ENOMEM;
+
+ k = manager_process_seat_device(m, d);
+ if (k < 0)
+ r = k;
+ }
+
+ return r;
+}
+
+static int manager_enumerate_buttons(Manager *m) {
+ _cleanup_udev_enumerate_unref_ struct udev_enumerate *e = NULL;
+ struct udev_list_entry *item = NULL, *first = NULL;
+ int r;
+
+ assert(m);
+
+ /* Loads buttons from udev */
+
+ if (m->handle_power_key == HANDLE_IGNORE &&
+ m->handle_suspend_key == HANDLE_IGNORE &&
+ m->handle_hibernate_key == HANDLE_IGNORE &&
+ m->handle_lid_switch == HANDLE_IGNORE &&
+ m->handle_lid_switch_docked == HANDLE_IGNORE)
+ return 0;
+
+ e = udev_enumerate_new(m->udev);
+ if (!e)
+ return -ENOMEM;
+
+ r = udev_enumerate_add_match_subsystem(e, "input");
+ if (r < 0)
+ return r;
+
+ r = udev_enumerate_add_match_tag(e, "power-switch");
+ if (r < 0)
+ return r;
+
+ r = udev_enumerate_add_match_is_initialized(e);
+ if (r < 0)
+ return r;
+
+ r = udev_enumerate_scan_devices(e);
+ if (r < 0)
+ return r;
+
+ first = udev_enumerate_get_list_entry(e);
+ udev_list_entry_foreach(item, first) {
+ _cleanup_udev_device_unref_ struct udev_device *d = NULL;
+ int k;
+
+ d = udev_device_new_from_syspath(m->udev, udev_list_entry_get_name(item));
+ if (!d)
+ return -ENOMEM;
+
+ k = manager_process_button_device(m, d);
+ if (k < 0)
+ r = k;
+ }
+
+ return r;
+}
+
+static int manager_enumerate_seats(Manager *m) {
+ _cleanup_closedir_ DIR *d = NULL;
+ struct dirent *de;
+ int r = 0;
+
+ assert(m);
+
+ /* This loads data about seats stored on disk, but does not
+ * actually create any seats. Removes data of seats that no
+ * longer exist. */
+
+ d = opendir("/run/systemd/seats");
+ if (!d) {
+ if (errno == ENOENT)
+ return 0;
+
+ return log_error_errno(errno, "Failed to open /run/systemd/seats: %m");
+ }
+
+ FOREACH_DIRENT(de, d, return -errno) {
+ Seat *s;
+ int k;
+
+ if (!dirent_is_file(de))
+ continue;
+
+ s = hashmap_get(m->seats, de->d_name);
+ if (!s) {
+ unlinkat(dirfd(d), de->d_name, 0);
+ continue;
+ }
+
+ k = seat_load(s);
+ if (k < 0)
+ r = k;
+ }
+
+ return r;
+}
+
+static int manager_enumerate_linger_users(Manager *m) {
+ _cleanup_closedir_ DIR *d = NULL;
+ struct dirent *de;
+ int r = 0;
+
+ assert(m);
+
+ d = opendir("/var/lib/systemd/linger");
+ if (!d) {
+ if (errno == ENOENT)
+ return 0;
+
+ return log_error_errno(errno, "Failed to open /var/lib/systemd/linger/: %m");
+ }
+
+ FOREACH_DIRENT(de, d, return -errno) {
+ int k;
+
+ if (!dirent_is_file(de))
+ continue;
+
+ k = manager_add_user_by_name(m, de->d_name, NULL);
+ if (k < 0) {
+ log_notice_errno(k, "Couldn't add lingering user %s: %m", de->d_name);
+ r = k;
+ }
+ }
+
+ return r;
+}
+
+static int manager_enumerate_users(Manager *m) {
+ _cleanup_closedir_ DIR *d = NULL;
+ struct dirent *de;
+ int r, k;
+
+ assert(m);
+
+ /* Add lingering users */
+ r = manager_enumerate_linger_users(m);
+
+ /* Read in user data stored on disk */
+ d = opendir("/run/systemd/users");
+ if (!d) {
+ if (errno == ENOENT)
+ return 0;
+
+ return log_error_errno(errno, "Failed to open /run/systemd/users: %m");
+ }
+
+ FOREACH_DIRENT(de, d, return -errno) {
+ User *u;
+
+ if (!dirent_is_file(de))
+ continue;
+
+ k = manager_add_user_by_name(m, de->d_name, &u);
+ if (k < 0) {
+ log_error_errno(k, "Failed to add user by file name %s: %m", de->d_name);
+
+ r = k;
+ continue;
+ }
+
+ user_add_to_gc_queue(u);
+
+ k = user_load(u);
+ if (k < 0)
+ r = k;
+ }
+
+ return r;
+}
+
+static int manager_enumerate_sessions(Manager *m) {
+ _cleanup_closedir_ DIR *d = NULL;
+ struct dirent *de;
+ int r = 0;
+
+ assert(m);
+
+ /* Read in session data stored on disk */
+ d = opendir("/run/systemd/sessions");
+ if (!d) {
+ if (errno == ENOENT)
+ return 0;
+
+ return log_error_errno(errno, "Failed to open /run/systemd/sessions: %m");
+ }
+
+ FOREACH_DIRENT(de, d, return -errno) {
+ struct Session *s;
+ int k;
+
+ if (!dirent_is_file(de))
+ continue;
+
+ if (!session_id_valid(de->d_name)) {
+ log_warning("Invalid session file name '%s', ignoring.", de->d_name);
+ r = -EINVAL;
+ continue;
+ }
+
+ k = manager_add_session(m, de->d_name, &s);
+ if (k < 0) {
+ log_error_errno(k, "Failed to add session by file name %s: %m", de->d_name);
+
+ r = k;
+ continue;
+ }
+
+ session_add_to_gc_queue(s);
+
+ k = session_load(s);
+ if (k < 0)
+ r = k;
+ }
+
+ return r;
+}
+
+static int manager_enumerate_inhibitors(Manager *m) {
+ _cleanup_closedir_ DIR *d = NULL;
+ struct dirent *de;
+ int r = 0;
+
+ assert(m);
+
+ d = opendir("/run/systemd/inhibit");
+ if (!d) {
+ if (errno == ENOENT)
+ return 0;
+
+ return log_error_errno(errno, "Failed to open /run/systemd/inhibit: %m");
+ }
+
+ FOREACH_DIRENT(de, d, return -errno) {
+ int k;
+ Inhibitor *i;
+
+ if (!dirent_is_file(de))
+ continue;
+
+ k = manager_add_inhibitor(m, de->d_name, &i);
+ if (k < 0) {
+ log_notice_errno(k, "Couldn't add inhibitor %s: %m", de->d_name);
+ r = k;
+ continue;
+ }
+
+ k = inhibitor_load(i);
+ if (k < 0)
+ r = k;
+ }
+
+ return r;
+}
+
+static int manager_dispatch_seat_udev(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
+ _cleanup_udev_device_unref_ struct udev_device *d = NULL;
+ Manager *m = userdata;
+
+ assert(m);
+
+ d = udev_monitor_receive_device(m->udev_seat_monitor);
+ if (!d)
+ return -ENOMEM;
+
+ manager_process_seat_device(m, d);
+ return 0;
+}
+
+static int manager_dispatch_device_udev(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
+ _cleanup_udev_device_unref_ struct udev_device *d = NULL;
+ Manager *m = userdata;
+
+ assert(m);
+
+ d = udev_monitor_receive_device(m->udev_device_monitor);
+ if (!d)
+ return -ENOMEM;
+
+ manager_process_seat_device(m, d);
+ return 0;
+}
+
+static int manager_dispatch_vcsa_udev(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
+ _cleanup_udev_device_unref_ struct udev_device *d = NULL;
+ Manager *m = userdata;
+ const char *name;
+
+ assert(m);
+
+ d = udev_monitor_receive_device(m->udev_vcsa_monitor);
+ if (!d)
+ return -ENOMEM;
+
+ name = udev_device_get_sysname(d);
+
+ /* Whenever a VCSA device is removed try to reallocate our
+ * VTs, to make sure our auto VTs never go away. */
+
+ if (name && startswith(name, "vcsa") && streq_ptr(udev_device_get_action(d), "remove"))
+ seat_preallocate_vts(m->seat0);
+
+ return 0;
+}
+
+static int manager_dispatch_button_udev(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
+ _cleanup_udev_device_unref_ struct udev_device *d = NULL;
+ Manager *m = userdata;
+
+ assert(m);
+
+ d = udev_monitor_receive_device(m->udev_button_monitor);
+ if (!d)
+ return -ENOMEM;
+
+ manager_process_button_device(m, d);
+ return 0;
+}
+
+static int manager_dispatch_console(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
+ Manager *m = userdata;
+
+ assert(m);
+ assert(m->seat0);
+ assert(m->console_active_fd == fd);
+
+ seat_read_active_vt(m->seat0);
+ return 0;
+}
+
+static int manager_reserve_vt(Manager *m) {
+ _cleanup_free_ char *p = NULL;
+
+ assert(m);
+
+ if (m->reserve_vt <= 0)
+ return 0;
+
+ if (asprintf(&p, "/dev/tty%u", m->reserve_vt) < 0)
+ return log_oom();
+
+ m->reserve_vt_fd = open(p, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
+ if (m->reserve_vt_fd < 0) {
+
+ /* Don't complain on VT-less systems */
+ if (errno != ENOENT)
+ log_warning_errno(errno, "Failed to pin reserved VT: %m");
+ return -errno;
+ }
+
+ return 0;
+}
+
+static int manager_connect_bus(Manager *m) {
+ _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+ int r;
+
+ assert(m);
+ assert(!m->bus);
+
+ r = sd_bus_default_system(&m->bus);
+ if (r < 0)
+ return log_error_errno(r, "Failed to connect to system bus: %m");
+
+ r = sd_bus_add_object_vtable(m->bus, NULL, "/org/freedesktop/login1", "org.freedesktop.login1.Manager", manager_vtable, m);
+ if (r < 0)
+ return log_error_errno(r, "Failed to add manager object vtable: %m");
+
+ r = sd_bus_add_fallback_vtable(m->bus, NULL, "/org/freedesktop/login1/seat", "org.freedesktop.login1.Seat", seat_vtable, seat_object_find, m);
+ if (r < 0)
+ return log_error_errno(r, "Failed to add seat object vtable: %m");
+
+ r = sd_bus_add_node_enumerator(m->bus, NULL, "/org/freedesktop/login1/seat", seat_node_enumerator, m);
+ if (r < 0)
+ return log_error_errno(r, "Failed to add seat enumerator: %m");
+
+ r = sd_bus_add_fallback_vtable(m->bus, NULL, "/org/freedesktop/login1/session", "org.freedesktop.login1.Session", session_vtable, session_object_find, m);
+ if (r < 0)
+ return log_error_errno(r, "Failed to add session object vtable: %m");
+
+ r = sd_bus_add_node_enumerator(m->bus, NULL, "/org/freedesktop/login1/session", session_node_enumerator, m);
+ if (r < 0)
+ return log_error_errno(r, "Failed to add session enumerator: %m");
+
+ r = sd_bus_add_fallback_vtable(m->bus, NULL, "/org/freedesktop/login1/user", "org.freedesktop.login1.User", user_vtable, user_object_find, m);
+ if (r < 0)
+ return log_error_errno(r, "Failed to add user object vtable: %m");
+
+ r = sd_bus_add_node_enumerator(m->bus, NULL, "/org/freedesktop/login1/user", user_node_enumerator, m);
+ if (r < 0)
+ return log_error_errno(r, "Failed to add user enumerator: %m");
+
+ r = sd_bus_add_match(m->bus,
+ NULL,
+ "type='signal',"
+ "sender='org.freedesktop.systemd1',"
+ "interface='org.freedesktop.systemd1.Manager',"
+ "member='JobRemoved',"
+ "path='/org/freedesktop/systemd1'",
+ match_job_removed, m);
+ if (r < 0)
+ return log_error_errno(r, "Failed to add match for JobRemoved: %m");
+
+ r = sd_bus_add_match(m->bus,
+ NULL,
+ "type='signal',"
+ "sender='org.freedesktop.systemd1',"
+ "interface='org.freedesktop.systemd1.Manager',"
+ "member='UnitRemoved',"
+ "path='/org/freedesktop/systemd1'",
+ match_unit_removed, m);
+ if (r < 0)
+ return log_error_errno(r, "Failed to add match for UnitRemoved: %m");
+
+ r = sd_bus_add_match(m->bus,
+ NULL,
+ "type='signal',"
+ "sender='org.freedesktop.systemd1',"
+ "interface='org.freedesktop.DBus.Properties',"
+ "member='PropertiesChanged'",
+ match_properties_changed, m);
+ if (r < 0)
+ return log_error_errno(r, "Failed to add match for PropertiesChanged: %m");
+
+ r = sd_bus_add_match(m->bus,
+ NULL,
+ "type='signal',"
+ "sender='org.freedesktop.systemd1',"
+ "interface='org.freedesktop.systemd1.Manager',"
+ "member='Reloading',"
+ "path='/org/freedesktop/systemd1'",
+ match_reloading, m);
+ if (r < 0)
+ return log_error_errno(r, "Failed to add match for Reloading: %m");
+
+ r = sd_bus_call_method(
+ m->bus,
+ "org.freedesktop.systemd1",
+ "/org/freedesktop/systemd1",
+ "org.freedesktop.systemd1.Manager",
+ "Subscribe",
+ &error,
+ NULL, NULL);
+ if (r < 0) {
+ log_error("Failed to enable subscription: %s", bus_error_message(&error, r));
+ return r;
+ }
+
+ r = sd_bus_request_name(m->bus, "org.freedesktop.login1", 0);
+ if (r < 0)
+ return log_error_errno(r, "Failed to register name: %m");
+
+ r = sd_bus_attach_event(m->bus, m->event, SD_EVENT_PRIORITY_NORMAL);
+ if (r < 0)
+ return log_error_errno(r, "Failed to attach bus to event loop: %m");
+
+ return 0;
+}
+
+static int manager_vt_switch(sd_event_source *src, const struct signalfd_siginfo *si, void *data) {
+ Manager *m = data;
+ Session *active, *iter;
+
+ /*
+ * We got a VT-switch signal and we have to acknowledge it immediately.
+ * Preferably, we'd just use m->seat0->active->vtfd, but unfortunately,
+ * old user-space might run multiple sessions on a single VT, *sigh*.
+ * Therefore, we have to iterate all sessions and find one with a vtfd
+ * on the requested VT.
+ * As only VTs with active controllers have VT_PROCESS set, our current
+ * notion of the active VT might be wrong (for instance if the switch
+ * happens while we setup VT_PROCESS). Therefore, read the current VT
+ * first and then use s->active->vtnr as reference. Note that this is
+ * not racy, as no further VT-switch can happen as long as we're in
+ * synchronous VT_PROCESS mode.
+ */
+
+ assert(m->seat0);
+ seat_read_active_vt(m->seat0);
+
+ active = m->seat0->active;
+ if (!active || active->vtnr < 1) {
+ log_warning("Received VT_PROCESS signal without a registered session on that VT.");
+ return 0;
+ }
+
+ if (active->vtfd >= 0) {
+ session_leave_vt(active);
+ } else {
+ LIST_FOREACH(sessions_by_seat, iter, m->seat0->sessions) {
+ if (iter->vtnr == active->vtnr && iter->vtfd >= 0) {
+ session_leave_vt(iter);
+ break;
+ }
+ }
+ }
+
+ return 0;
+}
+
+static int manager_connect_console(Manager *m) {
+ int r;
+
+ assert(m);
+ assert(m->console_active_fd < 0);
+
+ /* On certain architectures (S390 and Xen, and containers),
+ /dev/tty0 does not exist, so don't fail if we can't open
+ it. */
+ if (access("/dev/tty0", F_OK) < 0)
+ return 0;
+
+ m->console_active_fd = open("/sys/class/tty/tty0/active", O_RDONLY|O_NOCTTY|O_CLOEXEC);
+ if (m->console_active_fd < 0) {
+
+ /* On some systems the device node /dev/tty0 may exist
+ * even though /sys/class/tty/tty0 does not. */
+ if (errno == ENOENT)
+ return 0;
+
+ return log_error_errno(errno, "Failed to open /sys/class/tty/tty0/active: %m");
+ }
+
+ r = sd_event_add_io(m->event, &m->console_active_event_source, m->console_active_fd, 0, manager_dispatch_console, m);
+ if (r < 0) {
+ log_error("Failed to watch foreground console");
+ return r;
+ }
+
+ /*
+ * SIGRTMIN is used as global VT-release signal, SIGRTMIN + 1 is used
+ * as VT-acquire signal. We ignore any acquire-events (yes, we still
+ * have to provide a valid signal-number for it!) and acknowledge all
+ * release events immediately.
+ */
+
+ if (SIGRTMIN + 1 > SIGRTMAX) {
+ log_error("Not enough real-time signals available: %u-%u", SIGRTMIN, SIGRTMAX);
+ return -EINVAL;
+ }
+
+ assert_se(ignore_signals(SIGRTMIN + 1, -1) >= 0);
+ assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGRTMIN, -1) >= 0);
+
+ r = sd_event_add_signal(m->event, NULL, SIGRTMIN, manager_vt_switch, m);
+ if (r < 0)
+ return r;
+
+ return 0;
+}
+
+static int manager_connect_udev(Manager *m) {
+ int r;
+
+ assert(m);
+ assert(!m->udev_seat_monitor);
+ assert(!m->udev_device_monitor);
+ assert(!m->udev_vcsa_monitor);
+ assert(!m->udev_button_monitor);
+
+ m->udev_seat_monitor = udev_monitor_new_from_netlink(m->udev, "udev");
+ if (!m->udev_seat_monitor)
+ return -ENOMEM;
+
+ r = udev_monitor_filter_add_match_tag(m->udev_seat_monitor, "master-of-seat");
+ if (r < 0)
+ return r;
+
+ r = udev_monitor_enable_receiving(m->udev_seat_monitor);
+ if (r < 0)
+ return r;
+
+ r = sd_event_add_io(m->event, &m->udev_seat_event_source, udev_monitor_get_fd(m->udev_seat_monitor), EPOLLIN, manager_dispatch_seat_udev, m);
+ if (r < 0)
+ return r;
+
+ m->udev_device_monitor = udev_monitor_new_from_netlink(m->udev, "udev");
+ if (!m->udev_device_monitor)
+ return -ENOMEM;
+
+ r = udev_monitor_filter_add_match_subsystem_devtype(m->udev_device_monitor, "input", NULL);
+ if (r < 0)
+ return r;
+
+ r = udev_monitor_filter_add_match_subsystem_devtype(m->udev_device_monitor, "graphics", NULL);
+ if (r < 0)
+ return r;
+
+ r = udev_monitor_filter_add_match_subsystem_devtype(m->udev_device_monitor, "drm", NULL);
+ if (r < 0)
+ return r;
+
+ r = udev_monitor_enable_receiving(m->udev_device_monitor);
+ if (r < 0)
+ return r;
+
+ r = sd_event_add_io(m->event, &m->udev_device_event_source, udev_monitor_get_fd(m->udev_device_monitor), EPOLLIN, manager_dispatch_device_udev, m);
+ if (r < 0)
+ return r;
+
+ /* Don't watch keys if nobody cares */
+ if (m->handle_power_key != HANDLE_IGNORE ||
+ m->handle_suspend_key != HANDLE_IGNORE ||
+ m->handle_hibernate_key != HANDLE_IGNORE ||
+ m->handle_lid_switch != HANDLE_IGNORE ||
+ m->handle_lid_switch_docked != HANDLE_IGNORE) {
+
+ m->udev_button_monitor = udev_monitor_new_from_netlink(m->udev, "udev");
+ if (!m->udev_button_monitor)
+ return -ENOMEM;
+
+ r = udev_monitor_filter_add_match_tag(m->udev_button_monitor, "power-switch");
+ if (r < 0)
+ return r;
+
+ r = udev_monitor_filter_add_match_subsystem_devtype(m->udev_button_monitor, "input", NULL);
+ if (r < 0)
+ return r;
+
+ r = udev_monitor_enable_receiving(m->udev_button_monitor);
+ if (r < 0)
+ return r;
+
+ r = sd_event_add_io(m->event, &m->udev_button_event_source, udev_monitor_get_fd(m->udev_button_monitor), EPOLLIN, manager_dispatch_button_udev, m);
+ if (r < 0)
+ return r;
+ }
+
+ /* Don't bother watching VCSA devices, if nobody cares */
+ if (m->n_autovts > 0 && m->console_active_fd >= 0) {
+
+ m->udev_vcsa_monitor = udev_monitor_new_from_netlink(m->udev, "udev");
+ if (!m->udev_vcsa_monitor)
+ return -ENOMEM;
+
+ r = udev_monitor_filter_add_match_subsystem_devtype(m->udev_vcsa_monitor, "vc", NULL);
+ if (r < 0)
+ return r;
+
+ r = udev_monitor_enable_receiving(m->udev_vcsa_monitor);
+ if (r < 0)
+ return r;
+
+ r = sd_event_add_io(m->event, &m->udev_vcsa_event_source, udev_monitor_get_fd(m->udev_vcsa_monitor), EPOLLIN, manager_dispatch_vcsa_udev, m);
+ if (r < 0)
+ return r;
+ }
+
+ return 0;
+}
+
+static void manager_gc(Manager *m, bool drop_not_started) {
+ Seat *seat;
+ Session *session;
+ User *user;
+
+ assert(m);
+
+ while ((seat = m->seat_gc_queue)) {
+ LIST_REMOVE(gc_queue, m->seat_gc_queue, seat);
+ seat->in_gc_queue = false;
+
+ if (!seat_check_gc(seat, drop_not_started)) {
+ seat_stop(seat, false);
+ seat_free(seat);
+ }
+ }
+
+ while ((session = m->session_gc_queue)) {
+ LIST_REMOVE(gc_queue, m->session_gc_queue, session);
+ session->in_gc_queue = false;
+
+ /* First, if we are not closing yet, initiate stopping */
+ if (!session_check_gc(session, drop_not_started) &&
+ session_get_state(session) != SESSION_CLOSING)
+ session_stop(session, false);
+
+ /* Normally, this should make the session referenced
+ * again, if it doesn't then let's get rid of it
+ * immediately */
+ if (!session_check_gc(session, drop_not_started)) {
+ session_finalize(session);
+ session_free(session);
+ }
+ }
+
+ while ((user = m->user_gc_queue)) {
+ LIST_REMOVE(gc_queue, m->user_gc_queue, user);
+ user->in_gc_queue = false;
+
+ /* First step: queue stop jobs */
+ if (!user_check_gc(user, drop_not_started))
+ user_stop(user, false);
+
+ /* Second step: finalize user */
+ if (!user_check_gc(user, drop_not_started)) {
+ user_finalize(user);
+ user_free(user);
+ }
+ }
+}
+
+static int manager_dispatch_idle_action(sd_event_source *s, uint64_t t, void *userdata) {
+ Manager *m = userdata;
+ struct dual_timestamp since;
+ usec_t n, elapse;
+ int r;
+
+ assert(m);
+
+ if (m->idle_action == HANDLE_IGNORE ||
+ m->idle_action_usec <= 0)
+ return 0;
+
+ n = now(CLOCK_MONOTONIC);
+
+ r = manager_get_idle_hint(m, &since);
+ if (r <= 0)
+ /* Not idle. Let's check if after a timeout it might be idle then. */
+ elapse = n + m->idle_action_usec;
+ else {
+ /* Idle! Let's see if it's time to do something, or if
+ * we shall sleep for longer. */
+
+ if (n >= since.monotonic + m->idle_action_usec &&
+ (m->idle_action_not_before_usec <= 0 || n >= m->idle_action_not_before_usec + m->idle_action_usec)) {
+ log_info("System idle. Taking action.");
+
+ manager_handle_action(m, 0, m->idle_action, false, false);
+ m->idle_action_not_before_usec = n;
+ }
+
+ elapse = MAX(since.monotonic, m->idle_action_not_before_usec) + m->idle_action_usec;
+ }
+
+ if (!m->idle_action_event_source) {
+
+ r = sd_event_add_time(
+ m->event,
+ &m->idle_action_event_source,
+ CLOCK_MONOTONIC,
+ elapse, USEC_PER_SEC*30,
+ manager_dispatch_idle_action, m);
+ if (r < 0)
+ return log_error_errno(r, "Failed to add idle event source: %m");
+
+ r = sd_event_source_set_priority(m->idle_action_event_source, SD_EVENT_PRIORITY_IDLE+10);
+ if (r < 0)
+ return log_error_errno(r, "Failed to set idle event source priority: %m");
+ } else {
+ r = sd_event_source_set_time(m->idle_action_event_source, elapse);
+ if (r < 0)
+ return log_error_errno(r, "Failed to set idle event timer: %m");
+
+ r = sd_event_source_set_enabled(m->idle_action_event_source, SD_EVENT_ONESHOT);
+ if (r < 0)
+ return log_error_errno(r, "Failed to enable idle event timer: %m");
+ }
+
+ return 0;
+}
+
+static int manager_parse_config_file(Manager *m) {
+ assert(m);
+
+ return config_parse_many(PKGSYSCONFDIR "/logind.conf",
+ CONF_PATHS_NULSTR("systemd/logind.conf.d"),
+ "Login\0",
+ config_item_perf_lookup, logind_gperf_lookup,
+ false, m);
+}
+
+static int manager_dispatch_reload_signal(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
+ Manager *m = userdata;
+ int r;
+
+ manager_reset_config(m);
+ r = manager_parse_config_file(m);
+ if (r < 0)
+ log_warning_errno(r, "Failed to parse config file, using defaults: %m");
+ else
+ log_info("Config file reloaded.");
+
+ return 0;
+}
+
+static int manager_startup(Manager *m) {
+ int r;
+ Seat *seat;
+ Session *session;
+ User *user;
+ Button *button;
+ Inhibitor *inhibitor;
+ Iterator i;
+
+ assert(m);
+
+ assert_se(sigprocmask_many(SIG_SETMASK, NULL, SIGHUP, -1) >= 0);
+
+ r = sd_event_add_signal(m->event, NULL, SIGHUP, manager_dispatch_reload_signal, m);
+ if (r < 0)
+ return log_error_errno(r, "Failed to register SIGHUP handler: %m");
+
+ /* Connect to console */
+ r = manager_connect_console(m);
+ if (r < 0)
+ return r;
+
+ /* Connect to udev */
+ r = manager_connect_udev(m);
+ if (r < 0)
+ return log_error_errno(r, "Failed to create udev watchers: %m");
+
+ /* Connect to the bus */
+ r = manager_connect_bus(m);
+ if (r < 0)
+ return r;
+
+ /* Instantiate magic seat 0 */
+ r = manager_add_seat(m, "seat0", &m->seat0);
+ if (r < 0)
+ return log_error_errno(r, "Failed to add seat0: %m");
+
+ r = manager_set_lid_switch_ignore(m, 0 + m->holdoff_timeout_usec);
+ if (r < 0)
+ log_warning_errno(r, "Failed to set up lid switch ignore event source: %m");
+
+ /* Deserialize state */
+ r = manager_enumerate_devices(m);
+ if (r < 0)
+ log_warning_errno(r, "Device enumeration failed: %m");
+
+ r = manager_enumerate_seats(m);
+ if (r < 0)
+ log_warning_errno(r, "Seat enumeration failed: %m");
+
+ r = manager_enumerate_users(m);
+ if (r < 0)
+ log_warning_errno(r, "User enumeration failed: %m");
+
+ r = manager_enumerate_sessions(m);
+ if (r < 0)
+ log_warning_errno(r, "Session enumeration failed: %m");
+
+ r = manager_enumerate_inhibitors(m);
+ if (r < 0)
+ log_warning_errno(r, "Inhibitor enumeration failed: %m");
+
+ r = manager_enumerate_buttons(m);
+ if (r < 0)
+ log_warning_errno(r, "Button enumeration failed: %m");
+
+ /* Remove stale objects before we start them */
+ manager_gc(m, false);
+
+ /* Reserve the special reserved VT */
+ manager_reserve_vt(m);
+
+ /* And start everything */
+ HASHMAP_FOREACH(seat, m->seats, i)
+ seat_start(seat);
+
+ HASHMAP_FOREACH(user, m->users, i)
+ user_start(user);
+
+ HASHMAP_FOREACH(session, m->sessions, i)
+ session_start(session);
+
+ HASHMAP_FOREACH(inhibitor, m->inhibitors, i)
+ inhibitor_start(inhibitor);
+
+ HASHMAP_FOREACH(button, m->buttons, i)
+ button_check_switches(button);
+
+ manager_dispatch_idle_action(NULL, 0, m);
+
+ return 0;
+}
+
+static int manager_run(Manager *m) {
+ int r;
+
+ assert(m);
+
+ for (;;) {
+ r = sd_event_get_state(m->event);
+ if (r < 0)
+ return r;
+ if (r == SD_EVENT_FINISHED)
+ return 0;
+
+ manager_gc(m, true);
+
+ r = manager_dispatch_delayed(m, false);
+ if (r < 0)
+ return r;
+ if (r > 0)
+ continue;
+
+ r = sd_event_run(m->event, (uint64_t) -1);
+ if (r < 0)
+ return r;
+ }
+}
+
+int main(int argc, char *argv[]) {
+ Manager *m = NULL;
+ int r;
+
+ log_set_target(LOG_TARGET_AUTO);
+ log_set_facility(LOG_AUTH);
+ log_parse_environment();
+ log_open();
+
+ umask(0022);
+
+ if (argc != 1) {
+ log_error("This program takes no arguments.");
+ r = -EINVAL;
+ goto finish;
+ }
+
+ r = mac_selinux_init();
+ if (r < 0) {
+ log_error_errno(r, "Could not initialize labelling: %m");
+ goto finish;
+ }
+
+ /* Always create the directories people can create inotify
+ * watches in. Note that some applications might check for the
+ * existence of /run/systemd/seats/ to determine whether
+ * logind is available, so please always make sure this check
+ * stays in. */
+ mkdir_label("/run/systemd/seats", 0755);
+ mkdir_label("/run/systemd/users", 0755);
+ mkdir_label("/run/systemd/sessions", 0755);
+
+ m = manager_new();
+ if (!m) {
+ r = log_oom();
+ goto finish;
+ }
+
+ manager_parse_config_file(m);
+
+ r = manager_startup(m);
+ if (r < 0) {
+ log_error_errno(r, "Failed to fully start up daemon: %m");
+ goto finish;
+ }
+
+ log_debug("systemd-logind running as pid "PID_FMT, getpid());
+
+ sd_notify(false,
+ "READY=1\n"
+ "STATUS=Processing requests...");
+
+ r = manager_run(m);
+
+ log_debug("systemd-logind stopped as pid "PID_FMT, getpid());
+
+finish:
+ sd_notify(false,
+ "STOPPING=1\n"
+ "STATUS=Shutting down...");
+
+ manager_free(m);
+
+ return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
+}
diff --git a/src/grp-login/systemd-logind/logind.conf.in b/src/grp-login/systemd-logind/logind.conf.in
new file mode 100644
index 0000000000..6f720b7708
--- /dev/null
+++ b/src/grp-login/systemd-logind/logind.conf.in
@@ -0,0 +1,37 @@
+# This file is part of systemd.
+#
+# 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.
+#
+# Entries in this file show the compile time defaults.
+# You can change settings by editing this file.
+# Defaults can be restored by simply deleting this file.
+#
+# See logind.conf(5) for details.
+
+[Login]
+#NAutoVTs=6
+#ReserveVT=6
+#KillUserProcesses=@KILL_USER_PROCESSES@
+#KillOnlyUsers=
+#KillExcludeUsers=root
+#InhibitDelayMaxSec=5
+#HandlePowerKey=poweroff
+#HandleSuspendKey=suspend
+#HandleHibernateKey=hibernate
+#HandleLidSwitch=suspend
+#HandleLidSwitchDocked=ignore
+#PowerKeyIgnoreInhibited=no
+#SuspendKeyIgnoreInhibited=no
+#HibernateKeyIgnoreInhibited=no
+#LidSwitchIgnoreInhibited=yes
+#HoldoffTimeoutSec=30s
+#IdleAction=ignore
+#IdleActionSec=30min
+#RuntimeDirectorySize=10%
+#RemoveIPC=yes
+#InhibitorsMax=8192
+#SessionsMax=8192
+#UserTasksMax=33%
diff --git a/src/grp-login/systemd-logind/logind.conf.xml b/src/grp-login/systemd-logind/logind.conf.xml
new file mode 100644
index 0000000000..adba5a4131
--- /dev/null
+++ b/src/grp-login/systemd-logind/logind.conf.xml
@@ -0,0 +1,348 @@
+<?xml version='1.0'?> <!--*- Mode: nxml; nxml-child-indent: 2; indent-tabs-mode: nil -*-->
+<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN"
+ "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd">
+
+<!--
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ 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/>.
+-->
+
+<refentry id="logind.conf" conditional='ENABLE_LOGIND'
+ xmlns:xi="http://www.w3.org/2001/XInclude">
+ <refentryinfo>
+ <title>logind.conf</title>
+ <productname>systemd</productname>
+
+ <authorgroup>
+ <author>
+ <contrib>Developer</contrib>
+ <firstname>Lennart</firstname>
+ <surname>Poettering</surname>
+ <email>lennart@poettering.net</email>
+ </author>
+ </authorgroup>
+ </refentryinfo>
+
+ <refmeta>
+ <refentrytitle>logind.conf</refentrytitle>
+ <manvolnum>5</manvolnum>
+ </refmeta>
+
+ <refnamediv>
+ <refname>logind.conf</refname>
+ <refname>logind.conf.d</refname>
+ <refpurpose>Login manager configuration files</refpurpose>
+ </refnamediv>
+
+ <refsynopsisdiv>
+ <para><filename>/etc/systemd/logind.conf</filename></para>
+ <para><filename>/etc/systemd/logind.conf.d/*.conf</filename></para>
+ <para><filename>/run/systemd/logind.conf.d/*.conf</filename></para>
+ <para><filename>/usr/lib/systemd/logind.conf.d/*.conf</filename></para>
+ </refsynopsisdiv>
+
+ <refsect1>
+ <title>Description</title>
+
+ <para>These files configure various parameters of the systemd
+ login manager,
+ <citerefentry><refentrytitle>systemd-logind.service</refentrytitle><manvolnum>8</manvolnum></citerefentry>.
+ </para>
+ </refsect1>
+
+ <xi:include href="standard-conf.xml" xpointer="main-conf" />
+
+ <refsect1>
+ <title>Options</title>
+
+ <para>All options are configured in the
+ <literal>[Login]</literal> section:</para>
+
+ <variablelist>
+
+ <varlistentry>
+ <term><varname>NAutoVTs=</varname></term>
+
+ <listitem><para>Takes a positive integer. Configures how many
+ virtual terminals (VTs) to allocate by default that, when
+ switched to and are previously unused,
+ <literal>autovt</literal> services are automatically spawned
+ on. These services are instantiated from the template unit
+ <filename>autovt@.service</filename> for the respective VT TTY
+ name, for example, <filename>autovt@tty4.service</filename>.
+ By default, <filename>autovt@.service</filename> is linked to
+ <filename>getty@.service</filename>. In other words, login
+ prompts are started dynamically as the user switches to unused
+ virtual terminals. Hence, this parameter controls how many
+ login <literal>gettys</literal> are available on the VTs. If a
+ VT is already used by some other subsystem (for example, a
+ graphical login), this kind of activation will not be
+ attempted. Note that the VT configured in
+ <varname>ReserveVT=</varname> is always subject to this kind
+ of activation, even if it is not one of the VTs configured
+ with the <varname>NAutoVTs=</varname> directive. Defaults to
+ 6. When set to 0, automatic spawning of
+ <literal>autovt</literal> services is
+ disabled.</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><varname>ReserveVT=</varname></term>
+
+ <listitem><para>Takes a positive integer. Identifies one
+ virtual terminal that shall unconditionally be reserved for
+ <filename>autovt@.service</filename> activation (see above).
+ The VT selected with this option will be marked busy
+ unconditionally, so that no other subsystem will allocate it.
+ This functionality is useful to ensure that, regardless of how
+ many VTs are allocated by other subsystems, one login
+ <literal>getty</literal> is always available. Defaults to 6
+ (in other words, there will always be a
+ <literal>getty</literal> available on Alt-F6.). When set to 0,
+ VT reservation is disabled.</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><varname>KillUserProcesses=</varname></term>
+
+ <listitem><para>Takes a boolean argument. Configures whether the processes of a
+ user should be killed when the user logs out. If true, the scope unit
+ corresponding to the session and all processes inside that scope will be
+ terminated. If false, the scope is "abandoned", see
+ <citerefentry><refentrytitle>systemd.scope</refentrytitle><manvolnum>5</manvolnum></citerefentry>,
+ and processes are not killed. Defaults to <literal>yes</literal>,
+ but see the options <varname>KillOnlyUsers=</varname> and
+ <varname>KillExcludeUsers=</varname> below.</para>
+
+ <para>In addition to session processes, user process may run under the user
+ manager unit <filename>user@.service</filename>. Depending on the linger
+ settings, this may allow users to run processes independent of their login
+ sessions. See the description of <command>enable-linger</command> in
+ <citerefentry><refentrytitle>loginctl</refentrytitle><manvolnum>1</manvolnum></citerefentry>.
+ </para>
+
+ <para>Note that setting <varname>KillUserProcesses=yes</varname>
+ will break tools like
+ <citerefentry project='die-net'><refentrytitle>screen</refentrytitle><manvolnum>1</manvolnum></citerefentry>
+ and
+ <citerefentry project='die-net'><refentrytitle>tmux</refentrytitle><manvolnum>1</manvolnum></citerefentry>,
+ unless they are moved out of the session scope. See example in
+ <citerefentry><refentrytitle>systemd-run</refentrytitle><manvolnum>1</manvolnum></citerefentry>.
+ </para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><varname>KillOnlyUsers=</varname></term>
+ <term><varname>KillExcludeUsers=</varname></term>
+
+ <listitem><para>These settings take space-separated lists of usernames that override
+ the <varname>KillUserProcesses=</varname> setting. A user name may be added to
+ <varname>KillExcludeUsers=</varname> to exclude the processes in the session scopes of
+ that user from being killed even if <varname>KillUserProcesses=yes</varname> is set. If
+ <varname>KillExcludeUsers=</varname> is not set, the <literal>root</literal> user is
+ excluded by default. <varname>KillExcludeUsers=</varname> may be set to an empty value
+ to override this default. If a user is not excluded, <varname>KillOnlyUsers=</varname>
+ is checked next. If this setting is specified, only the session scopes of those users
+ will be killed. Otherwise, users are subject to the
+ <varname>KillUserProcesses=yes</varname> setting.</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><varname>IdleAction=</varname></term>
+
+ <listitem><para>Configures the action to take when the system
+ is idle. Takes one of
+ <literal>ignore</literal>,
+ <literal>poweroff</literal>,
+ <literal>reboot</literal>,
+ <literal>halt</literal>,
+ <literal>kexec</literal>,
+ <literal>suspend</literal>,
+ <literal>hibernate</literal>,
+ <literal>hybrid-sleep</literal>, and
+ <literal>lock</literal>.
+ Defaults to <literal>ignore</literal>.</para>
+
+ <para>Note that this requires that user sessions correctly
+ report the idle status to the system. The system will execute
+ the action after all sessions report that they are idle, no
+ idle inhibitor lock is active, and subsequently, the time
+ configured with <varname>IdleActionSec=</varname> (see below)
+ has expired.</para>
+ </listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><varname>IdleActionSec=</varname></term>
+
+ <listitem><para>Configures the delay after which the action
+ configured in <varname>IdleAction=</varname> (see above) is
+ taken after the system is idle.</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><varname>InhibitDelayMaxSec=</varname></term>
+
+ <listitem><para>Specifies the maximum time a system shutdown
+ or sleep request is delayed due to an inhibitor lock of type
+ <literal>delay</literal> being active before the inhibitor is
+ ignored and the operation executes anyway. Defaults to
+ 5.</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><varname>HandlePowerKey=</varname></term>
+ <term><varname>HandleSuspendKey=</varname></term>
+ <term><varname>HandleHibernateKey=</varname></term>
+ <term><varname>HandleLidSwitch=</varname></term>
+ <term><varname>HandleLidSwitchDocked=</varname></term>
+
+ <listitem><para>Controls whether logind shall handle the
+ system power and sleep keys and the lid switch to trigger
+ actions such as system power-off or suspend. Can be one of
+ <literal>ignore</literal>,
+ <literal>poweroff</literal>,
+ <literal>reboot</literal>,
+ <literal>halt</literal>,
+ <literal>kexec</literal>,
+ <literal>suspend</literal>,
+ <literal>hibernate</literal>,
+ <literal>hybrid-sleep</literal>, and
+ <literal>lock</literal>.
+ If <literal>ignore</literal>, logind will never handle these
+ keys. If <literal>lock</literal>, all running sessions will be
+ screen-locked; otherwise, the specified action will be taken
+ in the respective event. Only input devices with the
+ <literal>power-switch</literal> udev tag will be watched for
+ key/lid switch events. <varname>HandlePowerKey=</varname>
+ defaults to <literal>poweroff</literal>.
+ <varname>HandleSuspendKey=</varname> and
+ <varname>HandleLidSwitch=</varname> default to
+ <literal>suspend</literal>.
+ <varname>HandleLidSwitchDocked=</varname> defaults to
+ <literal>ignore</literal>.
+ <varname>HandleHibernateKey=</varname> defaults to
+ <literal>hibernate</literal>. If the system is inserted in a
+ docking station, or if more than one display is connected, the
+ action specified by <varname>HandleLidSwitchDocked=</varname>
+ occurs; otherwise the <varname>HandleLidSwitch=</varname>
+ action occurs.</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><varname>PowerKeyIgnoreInhibited=</varname></term>
+ <term><varname>SuspendKeyIgnoreInhibited=</varname></term>
+ <term><varname>HibernateKeyIgnoreInhibited=</varname></term>
+ <term><varname>LidSwitchIgnoreInhibited=</varname></term>
+
+ <listitem><para>Controls whether actions triggered by the
+ power and sleep keys and the lid switch are subject to
+ inhibitor locks. These settings take boolean arguments. If
+ <literal>no</literal>, the inhibitor locks taken by
+ applications in order to block the requested operation are
+ respected. If <literal>yes</literal>, the requested operation
+ is executed in any case.
+ <varname>PowerKeyIgnoreInhibited=</varname>,
+ <varname>SuspendKeyIgnoreInhibited=</varname> and
+ <varname>HibernateKeyIgnoreInhibited=</varname> default to
+ <literal>no</literal>.
+ <varname>LidSwitchIgnoreInhibited=</varname> defaults to
+ <literal>yes</literal>. This means that the lid switch does
+ not respect suspend blockers by default, but the power and
+ sleep keys do. </para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><varname>HoldoffTimeoutSec=</varname></term>
+
+ <listitem><para>Specifies the timeout after system startup or
+ system resume in which systemd will hold off on reacting to
+ lid events. This is required for the system to properly
+ detect any hotplugged devices so systemd can ignore lid events
+ if external monitors, or docks, are connected. If set to 0,
+ systemd will always react immediately, possibly before the
+ kernel fully probed all hotplugged devices. This is safe, as
+ long as you do not care for systemd to account for devices
+ that have been plugged or unplugged while the system was off.
+ Defaults to 30s.</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><varname>RuntimeDirectorySize=</varname></term>
+
+ <listitem><para>Sets the size limit on the
+ <varname>$XDG_RUNTIME_DIR</varname> runtime directory for each
+ user who logs in. Takes a size in bytes, optionally suffixed
+ with the usual K, G, M, and T suffixes, to the base 1024
+ (IEC). Alternatively, a numerical percentage suffixed by
+ <literal>%</literal> may be specified, which sets the size
+ limit relative to the amount of physical RAM. Defaults to 10%.
+ Note that this size is a safety limit only. As each runtime
+ directory is a tmpfs file system, it will only consume as much
+ memory as is needed.</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><varname>InhibitorsMax=</varname></term>
+
+ <listitem><para>Controls the maximum number of concurrent inhibitors to permit. Defaults to 8192
+ (8K).</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><varname>SessionsMax=</varname></term>
+
+ <listitem><para>Controls the maximum number of concurrent user sessions to manage. Defaults to 8192
+ (8K). Depending on how the <filename>pam_systemd.so</filename> module is included in the PAM stack
+ configuration, further login sessions will either be refused, or permitted but not tracked by
+ <filename>systemd-logind</filename>.</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><varname>UserTasksMax=</varname></term>
+
+ <listitem><para>Sets the maximum number of OS tasks each user may run concurrently. This controls the
+ <varname>TasksMax=</varname> setting of the per-user slice unit, see
+ <citerefentry><refentrytitle>systemd.resource-control</refentrytitle><manvolnum>5</manvolnum></citerefentry>
+ for details. Defaults to 33%, which equals 10813 with the kernel's defaults on the host, but might be smaller
+ in OS containers.</para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><varname>RemoveIPC=</varname></term>
+
+ <listitem><para>Controls whether System V and POSIX IPC objects belonging to the user shall be removed when the
+ user fully logs out. Takes a boolean argument. If enabled, the user may not consume IPC resources after the
+ last of the user's sessions terminated. This covers System V semaphores, shared memory and message queues, as
+ well as POSIX shared memory and message queues. Note that IPC objects of the root user and other system users
+ are excluded from the effect of this setting. Defaults to <literal>yes</literal>.</para></listitem>
+ </varlistentry>
+
+ </variablelist>
+ </refsect1>
+
+ <refsect1>
+ <title>See Also</title>
+ <para>
+ <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>,
+ <citerefentry><refentrytitle>systemd-logind.service</refentrytitle><manvolnum>8</manvolnum></citerefentry>,
+ <citerefentry><refentrytitle>loginctl</refentrytitle><manvolnum>1</manvolnum></citerefentry>,
+ <citerefentry><refentrytitle>systemd-system.conf</refentrytitle><manvolnum>5</manvolnum></citerefentry>
+ </para>
+ </refsect1>
+
+</refentry>
diff --git a/src/grp-login/systemd-logind/logind.h b/src/grp-login/systemd-logind/logind.h
new file mode 100644
index 0000000000..c637cdfcac
--- /dev/null
+++ b/src/grp-login/systemd-logind/logind.h
@@ -0,0 +1,199 @@
+#pragma once
+
+/***
+ This file is part of systemd.
+
+ Copyright 2011 Lennart Poettering
+
+ 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 <stdbool.h>
+
+#include <libudev.h>
+#include <systemd/sd-bus.h>
+#include <systemd/sd-event.h>
+
+#include "basic/hashmap.h"
+#include "basic/list.h"
+#include "basic/set.h"
+
+typedef struct Manager Manager;
+
+#include "logind-action.h"
+#include "logind-button.h"
+#include "logind-device.h"
+#include "logind-inhibit.h"
+
+struct Manager {
+ sd_event *event;
+ sd_bus *bus;
+
+ Hashmap *devices;
+ Hashmap *seats;
+ Hashmap *sessions;
+ Hashmap *users;
+ Hashmap *inhibitors;
+ Hashmap *buttons;
+
+ LIST_HEAD(Seat, seat_gc_queue);
+ LIST_HEAD(Session, session_gc_queue);
+ LIST_HEAD(User, user_gc_queue);
+
+ struct udev *udev;
+ struct udev_monitor *udev_seat_monitor, *udev_device_monitor, *udev_vcsa_monitor, *udev_button_monitor;
+
+ sd_event_source *console_active_event_source;
+ sd_event_source *udev_seat_event_source;
+ sd_event_source *udev_device_event_source;
+ sd_event_source *udev_vcsa_event_source;
+ sd_event_source *udev_button_event_source;
+
+ int console_active_fd;
+
+ unsigned n_autovts;
+
+ unsigned reserve_vt;
+ int reserve_vt_fd;
+
+ Seat *seat0;
+
+ char **kill_only_users, **kill_exclude_users;
+ bool kill_user_processes;
+
+ unsigned long session_counter;
+ unsigned long inhibit_counter;
+
+ Hashmap *session_units;
+ Hashmap *user_units;
+
+ usec_t inhibit_delay_max;
+
+ /* If an action is currently being executed or is delayed,
+ * this is != 0 and encodes what is being done */
+ InhibitWhat action_what;
+
+ /* If a shutdown/suspend was delayed due to a inhibitor this
+ contains the unit name we are supposed to start after the
+ delay is over */
+ const char *action_unit;
+
+ /* If a shutdown/suspend is currently executed, then this is
+ * the job of it */
+ char *action_job;
+ sd_event_source *inhibit_timeout_source;
+
+ char *scheduled_shutdown_type;
+ usec_t scheduled_shutdown_timeout;
+ sd_event_source *scheduled_shutdown_timeout_source;
+ uid_t scheduled_shutdown_uid;
+ char *scheduled_shutdown_tty;
+ sd_event_source *nologin_timeout_source;
+ bool unlink_nologin;
+
+ char *wall_message;
+ unsigned enable_wall_messages;
+ sd_event_source *wall_message_timeout_source;
+
+ bool shutdown_dry_run;
+
+ sd_event_source *idle_action_event_source;
+ usec_t idle_action_usec;
+ usec_t idle_action_not_before_usec;
+ HandleAction idle_action;
+
+ HandleAction handle_power_key;
+ HandleAction handle_suspend_key;
+ HandleAction handle_hibernate_key;
+ HandleAction handle_lid_switch;
+ HandleAction handle_lid_switch_docked;
+
+ bool power_key_ignore_inhibited;
+ bool suspend_key_ignore_inhibited;
+ bool hibernate_key_ignore_inhibited;
+ bool lid_switch_ignore_inhibited;
+
+ bool remove_ipc;
+
+ Hashmap *polkit_registry;
+
+ usec_t holdoff_timeout_usec;
+ sd_event_source *lid_switch_ignore_event_source;
+
+ size_t runtime_dir_size;
+ uint64_t user_tasks_max;
+ uint64_t sessions_max;
+ uint64_t inhibitors_max;
+};
+
+int manager_add_device(Manager *m, const char *sysfs, bool master, Device **_device);
+int manager_add_button(Manager *m, const char *name, Button **_button);
+int manager_add_seat(Manager *m, const char *id, Seat **_seat);
+int manager_add_session(Manager *m, const char *id, Session **_session);
+int manager_add_user(Manager *m, uid_t uid, gid_t gid, const char *name, User **_user);
+int manager_add_user_by_name(Manager *m, const char *name, User **_user);
+int manager_add_user_by_uid(Manager *m, uid_t uid, User **_user);
+int manager_add_inhibitor(Manager *m, const char* id, Inhibitor **_inhibitor);
+
+int manager_process_seat_device(Manager *m, struct udev_device *d);
+int manager_process_button_device(Manager *m, struct udev_device *d);
+
+int manager_spawn_autovt(Manager *m, unsigned int vtnr);
+
+bool manager_shall_kill(Manager *m, const char *user);
+
+int manager_get_idle_hint(Manager *m, dual_timestamp *t);
+
+int manager_get_user_by_pid(Manager *m, pid_t pid, User **user);
+int manager_get_session_by_pid(Manager *m, pid_t pid, Session **session);
+
+bool manager_is_docked_or_external_displays(Manager *m);
+
+extern const sd_bus_vtable manager_vtable[];
+
+int match_job_removed(sd_bus_message *message, void *userdata, sd_bus_error *error);
+int match_unit_removed(sd_bus_message *message, void *userdata, sd_bus_error *error);
+int match_properties_changed(sd_bus_message *message, void *userdata, sd_bus_error *error);
+int match_reloading(sd_bus_message *message, void *userdata, sd_bus_error *error);
+int match_name_owner_changed(sd_bus_message *message, void *userdata, sd_bus_error *error);
+
+int bus_manager_shutdown_or_sleep_now_or_later(Manager *m, const char *unit_name, InhibitWhat w, sd_bus_error *error);
+
+int manager_send_changed(Manager *manager, const char *property, ...) _sentinel_;
+
+int manager_start_slice(Manager *manager, const char *slice, const char *description, const char *after, const char *after2, uint64_t tasks_max, sd_bus_error *error, char **job);
+int manager_start_scope(Manager *manager, const char *scope, pid_t pid, const char *slice, const char *description, const char *after, const char *after2, uint64_t tasks_max, sd_bus_error *error, char **job);
+int manager_start_unit(Manager *manager, const char *unit, sd_bus_error *error, char **job);
+int manager_stop_unit(Manager *manager, const char *unit, sd_bus_error *error, char **job);
+int manager_abandon_scope(Manager *manager, const char *scope, sd_bus_error *error);
+int manager_kill_unit(Manager *manager, const char *unit, KillWho who, int signo, sd_bus_error *error);
+int manager_unit_is_active(Manager *manager, const char *unit);
+int manager_job_is_active(Manager *manager, const char *path);
+
+/* gperf lookup function */
+const struct ConfigPerfItem* logind_gperf_lookup(const char *key, unsigned length);
+
+int manager_set_lid_switch_ignore(Manager *m, usec_t until);
+
+int config_parse_tmpfs_size(const char *unit, const char *filename, unsigned line, const char *section, unsigned section_line, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+int config_parse_user_tasks_max(const char *unit, const char *filename, unsigned line, const char *section, unsigned section_line, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata);
+
+int manager_get_session_from_creds(Manager *m, sd_bus_message *message, const char *name, sd_bus_error *error, Session **ret);
+int manager_get_user_from_creds(Manager *m, sd_bus_message *message, uid_t uid, sd_bus_error *error, User **ret);
+int manager_get_seat_from_creds(Manager *m, sd_bus_message *message, const char *name, sd_bus_error *error, Seat **ret);
+
+int manager_setup_wall_message_timer(Manager *m);
+bool logind_wall_tty_filter(const char *tty, void *userdata);
+
+int manager_dispatch_delayed(Manager *manager, bool timeout);
diff --git a/src/grp-login/systemd-logind/org.freedesktop.login1.conf b/src/grp-login/systemd-logind/org.freedesktop.login1.conf
new file mode 100644
index 0000000000..c89e40457e
--- /dev/null
+++ b/src/grp-login/systemd-logind/org.freedesktop.login1.conf
@@ -0,0 +1,274 @@
+<?xml version="1.0"?> <!--*-nxml-*-->
+<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN"
+ "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
+
+<!--
+ This file is part of systemd.
+
+ 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.
+-->
+
+<busconfig>
+
+ <policy user="root">
+ <allow own="org.freedesktop.login1"/>
+ <allow send_destination="org.freedesktop.login1"/>
+ <allow receive_sender="org.freedesktop.login1"/>
+ </policy>
+
+ <policy context="default">
+ <deny send_destination="org.freedesktop.login1"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.DBus.Introspectable"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.DBus.Peer"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.DBus.Properties"
+ send_member="Get"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.DBus.Properties"
+ send_member="GetAll"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="GetSession"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="GetSessionByPID"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="GetUser"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="GetUserByPID"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="GetSeat"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="ListSessions"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="ListUsers"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="ListSeats"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="ListInhibitors"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="Inhibit"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="SetUserLinger"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="ActivateSession"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="ActivateSessionOnSeat"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="LockSession"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="UnlockSession"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="LockSessions"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="UnlockSessions"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="KillSession"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="KillUser"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="TerminateSession"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="TerminateUser"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="TerminateSeat"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="PowerOff"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="Reboot"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="Suspend"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="Hibernate"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="HybridSleep"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="CanPowerOff"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="CanReboot"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="CanSuspend"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="CanHibernate"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="CanHybridSleep"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="ScheduleShutdown"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="CancelScheduledShutdown"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="CanRebootToFirmwareSetup"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="SetRebootToFirmwareSetup"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="SetWallMessage"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="AttachDevice"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Manager"
+ send_member="FlushDevices"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Seat"
+ send_member="Terminate"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Seat"
+ send_member="ActivateSession"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Seat"
+ send_member="SwitchTo"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Seat"
+ send_member="SwitchToPrevious"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Seat"
+ send_member="SwitchToNext"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Session"
+ send_member="Terminate"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Session"
+ send_member="Activate"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Session"
+ send_member="Lock"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Session"
+ send_member="Unlock"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Session"
+ send_member="SetIdleHint"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Session"
+ send_member="SetLockedHint"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Session"
+ send_member="Kill"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Session"
+ send_member="TakeControl"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Session"
+ send_member="ReleaseControl"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Session"
+ send_member="TakeDevice"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Session"
+ send_member="ReleaseDevice"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.Session"
+ send_member="PauseDeviceComplete"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.User"
+ send_member="Terminate"/>
+
+ <allow send_destination="org.freedesktop.login1"
+ send_interface="org.freedesktop.login1.User"
+ send_member="Kill"/>
+
+ <allow receive_sender="org.freedesktop.login1"/>
+ </policy>
+
+</busconfig>
diff --git a/src/grp-login/systemd-logind/org.freedesktop.login1.policy.in b/src/grp-login/systemd-logind/org.freedesktop.login1.policy.in
new file mode 100644
index 0000000000..66cbce393c
--- /dev/null
+++ b/src/grp-login/systemd-logind/org.freedesktop.login1.policy.in
@@ -0,0 +1,325 @@
+<?xml version="1.0" encoding="UTF-8"?> <!--*-nxml-*-->
+<!DOCTYPE policyconfig PUBLIC "-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN"
+ "http://www.freedesktop.org/standards/PolicyKit/1/policyconfig.dtd">
+
+<!--
+ This file is part of systemd.
+
+ 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.
+-->
+
+<policyconfig>
+
+ <vendor>The systemd Project</vendor>
+ <vendor_url>http://www.freedesktop.org/wiki/Software/systemd</vendor_url>
+
+ <action id="org.freedesktop.login1.inhibit-block-shutdown">
+ <_description>Allow applications to inhibit system shutdown</_description>
+ <_message>Authentication is required for an application to inhibit system shutdown.</_message>
+ <defaults>
+ <allow_any>no</allow_any>
+ <allow_inactive>yes</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.imply">org.freedesktop.login1.inhibit-delay-shutdown org.freedesktop.login1.inhibit-block-sleep org.freedesktop.login1.inhibit-delay-sleep org.freedesktop.login1.inhibit-block-idle</annotate>
+ </action>
+
+ <action id="org.freedesktop.login1.inhibit-delay-shutdown">
+ <_description>Allow applications to delay system shutdown</_description>
+ <_message>Authentication is required for an application to delay system shutdown.</_message>
+ <defaults>
+ <allow_any>yes</allow_any>
+ <allow_inactive>yes</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.imply">org.freedesktop.login1.inhibit-delay-sleep</annotate>
+ </action>
+
+ <action id="org.freedesktop.login1.inhibit-block-sleep">
+ <_description>Allow applications to inhibit system sleep</_description>
+ <_message>Authentication is required for an application to inhibit system sleep.</_message>
+ <defaults>
+ <allow_any>no</allow_any>
+ <allow_inactive>yes</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.imply">org.freedesktop.login1.inhibit-delay-sleep org.freedesktop.login1.inhibit-block-idle</annotate>
+ </action>
+
+ <action id="org.freedesktop.login1.inhibit-delay-sleep">
+ <_description>Allow applications to delay system sleep</_description>
+ <_message>Authentication is required for an application to delay system sleep.</_message>
+ <defaults>
+ <allow_any>yes</allow_any>
+ <allow_inactive>yes</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ </action>
+
+ <action id="org.freedesktop.login1.inhibit-block-idle">
+ <_description>Allow applications to inhibit automatic system suspend</_description>
+ <_message>Authentication is required for an application to inhibit automatic system suspend.</_message>
+ <defaults>
+ <allow_any>yes</allow_any>
+ <allow_inactive>yes</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ </action>
+
+ <action id="org.freedesktop.login1.inhibit-handle-power-key">
+ <_description>Allow applications to inhibit system handling of the power key</_description>
+ <_message>Authentication is required for an application to inhibit system handling of the power key.</_message>
+ <defaults>
+ <allow_any>no</allow_any>
+ <allow_inactive>yes</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.imply">org.freedesktop.login1.inhibit-handle-suspend-key org.freedesktop.login1.inhibit-handle-hibernate-key org.freedesktop.login1.inhibit-handle-lid-switch</annotate>
+ </action>
+
+ <action id="org.freedesktop.login1.inhibit-handle-suspend-key">
+ <_description>Allow applications to inhibit system handling of the suspend key</_description>
+ <_message>Authentication is required for an application to inhibit system handling of the suspend key.</_message>
+ <defaults>
+ <allow_any>no</allow_any>
+ <allow_inactive>yes</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.imply">org.freedesktop.login1.inhibit-handle-hibernate-key org.freedesktop.login1.inhibit-handle-lid-switch</annotate>
+ </action>
+
+ <action id="org.freedesktop.login1.inhibit-handle-hibernate-key">
+ <_description>Allow applications to inhibit system handling of the hibernate key</_description>
+ <_message>Authentication is required for an application to inhibit system handling of the hibernate key.</_message>
+ <defaults>
+ <allow_any>no</allow_any>
+ <allow_inactive>yes</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ </action>
+
+ <action id="org.freedesktop.login1.inhibit-handle-lid-switch">
+ <_description>Allow applications to inhibit system handling of the lid switch</_description>
+ <_message>Authentication is required for an application to inhibit system handling of the lid switch.</_message>
+ <defaults>
+ <allow_any>no</allow_any>
+ <allow_inactive>yes</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ </action>
+
+ <action id="org.freedesktop.login1.set-self-linger">
+ <_description>Allow non-logged-in user to run programs</_description>
+ <_message>Explicit request is required to run programs as a non-logged-in user.</_message>
+ <defaults>
+ <allow_any>yes</allow_any>
+ <allow_inactive>yes</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ </action>
+
+ <action id="org.freedesktop.login1.set-user-linger">
+ <_description>Allow non-logged-in users to run programs</_description>
+ <_message>Authentication is required to run programs as a non-logged-in user.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>auth_admin_keep</allow_active>
+ </defaults>
+ </action>
+
+ <action id="org.freedesktop.login1.attach-device">
+ <_description>Allow attaching devices to seats</_description>
+ <_message>Authentication is required for attaching a device to a seat.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>auth_admin_keep</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.imply">org.freedesktop.login1.flush-devices</annotate>
+ </action>
+
+ <action id="org.freedesktop.login1.flush-devices">
+ <_description>Flush device to seat attachments</_description>
+ <_message>Authentication is required for resetting how devices are attached to seats.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>auth_admin_keep</allow_active>
+ </defaults>
+ </action>
+
+ <action id="org.freedesktop.login1.power-off">
+ <_description>Power off the system</_description>
+ <_message>Authentication is required for powering off the system.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.imply">org.freedesktop.login1.set-wall-message</annotate>
+ </action>
+
+ <action id="org.freedesktop.login1.power-off-multiple-sessions">
+ <_description>Power off the system while other users are logged in</_description>
+ <_message>Authentication is required for powering off the system while other users are logged in.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.imply">org.freedesktop.login1.power-off</annotate>
+ </action>
+
+ <action id="org.freedesktop.login1.power-off-ignore-inhibit">
+ <_description>Power off the system while an application asked to inhibit it</_description>
+ <_message>Authentication is required for powering off the system while an application asked to inhibit it.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>auth_admin_keep</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.imply">org.freedesktop.login1.power-off</annotate>
+ </action>
+
+ <action id="org.freedesktop.login1.reboot">
+ <_description>Reboot the system</_description>
+ <_message>Authentication is required for rebooting the system.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.imply">org.freedesktop.login1.set-wall-message</annotate>
+ </action>
+
+ <action id="org.freedesktop.login1.reboot-multiple-sessions">
+ <_description>Reboot the system while other users are logged in</_description>
+ <_message>Authentication is required for rebooting the system while other users are logged in.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.imply">org.freedesktop.login1.reboot</annotate>
+ </action>
+
+ <action id="org.freedesktop.login1.reboot-ignore-inhibit">
+ <_description>Reboot the system while an application asked to inhibit it</_description>
+ <_message>Authentication is required for rebooting the system while an application asked to inhibit it.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>auth_admin_keep</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.imply">org.freedesktop.login1.reboot</annotate>
+ </action>
+
+ <action id="org.freedesktop.login1.suspend">
+ <_description>Suspend the system</_description>
+ <_message>Authentication is required for suspending the system.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ </action>
+
+ <action id="org.freedesktop.login1.suspend-multiple-sessions">
+ <_description>Suspend the system while other users are logged in</_description>
+ <_message>Authentication is required for suspending the system while other users are logged in.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.imply">org.freedesktop.login1.suspend</annotate>
+ </action>
+
+ <action id="org.freedesktop.login1.suspend-ignore-inhibit">
+ <_description>Suspend the system while an application asked to inhibit it</_description>
+ <_message>Authentication is required for suspending the system while an application asked to inhibit it.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>auth_admin_keep</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.imply">org.freedesktop.login1.suspend</annotate>
+ </action>
+
+ <action id="org.freedesktop.login1.hibernate">
+ <_description>Hibernate the system</_description>
+ <_message>Authentication is required for hibernating the system.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ </action>
+
+ <action id="org.freedesktop.login1.hibernate-multiple-sessions">
+ <_description>Hibernate the system while other users are logged in</_description>
+ <_message>Authentication is required for hibernating the system while other users are logged in.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.imply">org.freedesktop.login1.hibernate</annotate>
+ </action>
+
+ <action id="org.freedesktop.login1.hibernate-ignore-inhibit">
+ <_description>Hibernate the system while an application asked to inhibit it</_description>
+ <_message>Authentication is required for hibernating the system while an application asked to inhibit it.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>auth_admin_keep</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.imply">org.freedesktop.login1.hibernate</annotate>
+ </action>
+
+ <action id="org.freedesktop.login1.manage">
+ <_description>Manage active sessions, users and seats</_description>
+ <_message>Authentication is required for managing active sessions, users and seats.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>auth_admin_keep</allow_active>
+ </defaults>
+ </action>
+
+ <action id="org.freedesktop.login1.lock-sessions">
+ <_description>Lock or unlock active sessions</_description>
+ <_message>Authentication is required to lock or unlock active sessions.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>auth_admin_keep</allow_active>
+ </defaults>
+ </action>
+
+ <action id="org.freedesktop.login1.set-reboot-to-firmware-setup">
+ <_description>Allow indication to the firmware to boot to setup interface</_description>
+ <_message>Authentication is required to indicate to the firmware to boot to setup interface.</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>auth_admin_keep</allow_active>
+ </defaults>
+ </action>
+
+ <action id="org.freedesktop.login1.set-wall-message">
+ <_description>Set a wall message</_description>
+ <_message>Authentication is required to set a wall message</_message>
+ <defaults>
+ <allow_any>auth_admin_keep</allow_any>
+ <allow_inactive>auth_admin_keep</allow_inactive>
+ <allow_active>auth_admin_keep</allow_active>
+ </defaults>
+ </action>
+
+</policyconfig>
diff --git a/src/grp-login/systemd-logind/org.freedesktop.login1.service b/src/grp-login/systemd-logind/org.freedesktop.login1.service
new file mode 100644
index 0000000000..762dae2bb3
--- /dev/null
+++ b/src/grp-login/systemd-logind/org.freedesktop.login1.service
@@ -0,0 +1,12 @@
+# This file is part of systemd.
+#
+# 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.
+
+[D-BUS Service]
+Name=org.freedesktop.login1
+Exec=/bin/false
+User=root
+SystemdService=dbus-org.freedesktop.login1.service
diff --git a/src/grp-login/systemd-logind/systemd-logind.service.in b/src/grp-login/systemd-logind/systemd-logind.service.in
new file mode 100644
index 0000000000..bee08d011f
--- /dev/null
+++ b/src/grp-login/systemd-logind/systemd-logind.service.in
@@ -0,0 +1,33 @@
+# This file is part of systemd.
+#
+# 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.
+
+[Unit]
+Description=Login Service
+Documentation=man:systemd-logind.service(8) man:logind.conf(5)
+Documentation=http://www.freedesktop.org/wiki/Software/systemd/logind
+Documentation=http://www.freedesktop.org/wiki/Software/systemd/multiseat
+Wants=user.slice
+After=nss-user-lookup.target user.slice
+
+# Ask for the dbus socket. If running over kdbus, the socket will
+# not be actually used.
+Wants=dbus.socket
+After=dbus.socket
+
+[Service]
+ExecStart=@rootlibexecdir@/systemd-logind
+Restart=always
+RestartSec=0
+BusName=org.freedesktop.login1
+CapabilityBoundingSet=CAP_SYS_ADMIN CAP_MAC_ADMIN CAP_AUDIT_CONTROL CAP_CHOWN CAP_KILL CAP_DAC_READ_SEARCH CAP_DAC_OVERRIDE CAP_FOWNER CAP_SYS_TTY_CONFIG
+WatchdogSec=3min
+MemoryDenyWriteExecute=yes
+SystemCallFilter=~@clock @cpu-emulation @debug @keyring @module @obsolete @raw-io
+
+# Increase the default a bit in order to allow many simultaneous
+# logins since we keep one fd open per session.
+LimitNOFILE=16384
diff --git a/src/grp-login/systemd-logind/systemd-logind.service.xml b/src/grp-login/systemd-logind/systemd-logind.service.xml
new file mode 100644
index 0000000000..5733e42cd1
--- /dev/null
+++ b/src/grp-login/systemd-logind/systemd-logind.service.xml
@@ -0,0 +1,121 @@
+<?xml version='1.0'?> <!--*-nxml-*-->
+<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN"
+ "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd">
+
+<!--
+ This file is part of systemd.
+
+ Copyright 2010 Lennart Poettering
+
+ 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/>.
+-->
+
+<refentry id="systemd-logind.service" conditional='ENABLE_LOGIND'>
+
+ <refentryinfo>
+ <title>systemd-logind.service</title>
+ <productname>systemd</productname>
+
+ <authorgroup>
+ <author>
+ <contrib>Developer</contrib>
+ <firstname>Lennart</firstname>
+ <surname>Poettering</surname>
+ <email>lennart@poettering.net</email>
+ </author>
+ </authorgroup>
+ </refentryinfo>
+
+ <refmeta>
+ <refentrytitle>systemd-logind.service</refentrytitle>
+ <manvolnum>8</manvolnum>
+ </refmeta>
+
+ <refnamediv>
+ <refname>systemd-logind.service</refname>
+ <refname>systemd-logind</refname>
+ <refpurpose>Login manager</refpurpose>
+ </refnamediv>
+
+ <refsynopsisdiv>
+ <para><filename>systemd-logind.service</filename></para>
+ <para><filename>/usr/lib/systemd/systemd-logind</filename></para>
+ </refsynopsisdiv>
+
+ <refsect1>
+ <title>Description</title>
+
+ <para><command>systemd-logind</command> is a system service that
+ manages user logins. It is responsible for:</para>
+
+ <itemizedlist>
+ <listitem><para>Keeping track of users and sessions, their
+ processes and their idle state</para></listitem>
+
+ <listitem><para>Providing PolicyKit-based access for users to
+ operations such as system shutdown or sleep</para></listitem>
+
+ <listitem><para>Implementing a shutdown/sleep inhibition logic
+ for applications</para></listitem>
+
+ <listitem><para>Handling of power/sleep hardware
+ keys</para></listitem>
+
+ <listitem><para>Multi-seat management</para></listitem>
+
+ <listitem><para>Session switch management</para></listitem>
+
+ <listitem><para>Device access management for
+ users</para></listitem>
+
+ <listitem><para>Automatic spawning of text logins (gettys) on
+ virtual console activation and user runtime directory
+ management</para></listitem>
+ </itemizedlist>
+
+ <para>User sessions are registered in logind via the
+ <citerefentry><refentrytitle>pam_systemd</refentrytitle><manvolnum>8</manvolnum></citerefentry>
+ PAM module.</para>
+
+ <para>See
+ <citerefentry><refentrytitle>logind.conf</refentrytitle><manvolnum>5</manvolnum></citerefentry>
+ for information about the configuration of this service.</para>
+
+ <para>See <ulink
+ url="http://www.freedesktop.org/wiki/Software/systemd/multiseat">Multi-Seat
+ on Linux</ulink> for an introduction into basic concepts of logind
+ such as users, sessions and seats.</para>
+
+ <para>See the <ulink
+ url="http://www.freedesktop.org/wiki/Software/systemd/logind">
+ logind D-Bus API Documentation</ulink> for information about the
+ APIs <filename>systemd-logind</filename> provides.</para>
+
+ <para>For more information on the inhibition logic see the <ulink
+ url="http://www.freedesktop.org/wiki/Software/systemd/inhibit">Inhibitor
+ Lock Developer Documentation</ulink>.</para>
+ </refsect1>
+
+ <refsect1>
+ <title>See Also</title>
+ <para>
+ <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>,
+ <citerefentry><refentrytitle>systemd-user-sessions.service</refentrytitle><manvolnum>8</manvolnum></citerefentry>,
+ <citerefentry><refentrytitle>loginctl</refentrytitle><manvolnum>1</manvolnum></citerefentry>,
+ <citerefentry><refentrytitle>logind.conf</refentrytitle><manvolnum>5</manvolnum></citerefentry>,
+ <citerefentry><refentrytitle>pam_systemd</refentrytitle><manvolnum>8</manvolnum></citerefentry>
+ </para>
+ </refsect1>
+
+</refentry>
diff --git a/src/grp-login/systemd-logind/systemd-user.pam.m4 b/src/grp-login/systemd-logind/systemd-user.pam.m4
new file mode 100644
index 0000000000..f188a8e548
--- /dev/null
+++ b/src/grp-login/systemd-logind/systemd-user.pam.m4
@@ -0,0 +1,12 @@
+# This file is part of systemd.
+#
+# Used by systemd --user instances.
+
+account include system-auth
+
+m4_ifdef(`HAVE_SELINUX',
+session required pam_selinux.so close
+session required pam_selinux.so nottys open
+)m4_dnl
+session required pam_loginuid.so
+session include system-auth
diff --git a/src/grp-login/systemd-logind/user.slice b/src/grp-login/systemd-logind/user.slice
new file mode 100644
index 0000000000..9fa6284c12
--- /dev/null
+++ b/src/grp-login/systemd-logind/user.slice
@@ -0,0 +1,11 @@
+# This file is part of systemd.
+#
+# 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.
+
+[Unit]
+Description=User and Session Slice
+Documentation=man:systemd.special(7)
+Before=slices.target
diff --git a/src/grp-login/test-inhibit.c b/src/grp-login/test-inhibit.c
new file mode 100644
index 0000000000..2451d56446
--- /dev/null
+++ b/src/grp-login/test-inhibit.c
@@ -0,0 +1,112 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2012 Lennart Poettering
+
+ 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 <unistd.h>
+
+#include <systemd/sd-bus.h>
+
+#include "basic/fd-util.h"
+#include "basic/macro.h"
+#include "basic/util.h"
+#include "shared/bus-util.h"
+
+static int inhibit(sd_bus *bus, const char *what) {
+ _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
+ _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+ const char *who = "Test Tool", *reason = "Just because!", *mode = "block";
+ int fd;
+ int r;
+
+ r = sd_bus_call_method(bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "Inhibit",
+ &error,
+ &reply,
+ "ssss", what, who, reason, mode);
+ assert_se(r >= 0);
+
+ r = sd_bus_message_read_basic(reply, SD_BUS_TYPE_UNIX_FD, &fd);
+ assert_se(r >= 0);
+ assert_se(fd >= 0);
+
+ return dup(fd);
+}
+
+static void print_inhibitors(sd_bus *bus) {
+ _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
+ _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+ const char *what, *who, *why, *mode;
+ uint32_t uid, pid;
+ unsigned n = 0;
+ int r;
+
+ r = sd_bus_call_method(bus,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ "ListInhibitors",
+ &error,
+ &reply,
+ "");
+ assert_se(r >= 0);
+
+ r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ssssuu)");
+ assert_se(r >= 0);
+
+ while ((r = sd_bus_message_read(reply, "(ssssuu)", &what, &who, &why, &mode, &uid, &pid)) > 0) {
+ printf("what=<%s> who=<%s> why=<%s> mode=<%s> uid=<%"PRIu32"> pid=<%"PRIu32">\n",
+ what, who, why, mode, uid, pid);
+
+ n++;
+ }
+ assert_se(r >= 0);
+
+ printf("%u inhibitors\n", n);
+}
+
+int main(int argc, char*argv[]) {
+ _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
+ int fd1, fd2;
+ int r;
+
+ r = sd_bus_open_system(&bus);
+ assert_se(r >= 0);
+
+ print_inhibitors(bus);
+
+ fd1 = inhibit(bus, "sleep");
+ assert_se(fd1 >= 0);
+ print_inhibitors(bus);
+
+ fd2 = inhibit(bus, "idle:shutdown");
+ assert_se(fd2 >= 0);
+ print_inhibitors(bus);
+
+ safe_close(fd1);
+ sleep(1);
+ print_inhibitors(bus);
+
+ safe_close(fd2);
+ sleep(1);
+ print_inhibitors(bus);
+
+ return 0;
+}
diff --git a/src/grp-login/test-login-shared.c b/src/grp-login/test-login-shared.c
new file mode 100644
index 0000000000..5a9329f7ee
--- /dev/null
+++ b/src/grp-login/test-login-shared.c
@@ -0,0 +1,39 @@
+/***
+ This file is part of systemd.
+
+ Copyright 2013 Zbigniew Jędrzejewski-Szmek
+
+ 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 "basic/login-util.h"
+#include "basic/macro.h"
+
+static void test_session_id_valid(void) {
+ assert_se(session_id_valid("c1"));
+ assert_se(session_id_valid("1234"));
+
+ assert_se(!session_id_valid("1-2"));
+ assert_se(!session_id_valid(""));
+ assert_se(!session_id_valid("\tid"));
+}
+
+int main(int argc, char* argv[]) {
+ log_parse_environment();
+ log_open();
+
+ test_session_id_valid();
+
+ return 0;
+}
diff --git a/src/grp-login/test-login-tables.c b/src/grp-login/test-login-tables.c
new file mode 100644
index 0000000000..3f2f4f3054
--- /dev/null
+++ b/src/grp-login/test-login-tables.c
@@ -0,0 +1,34 @@
+/***
+ This file is part of systemd
+
+ Copyright 2013 Zbigniew Jędrzejewski-Szmek
+
+ 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 "logind-action.h"
+#include "logind-session.h"
+#include "shared/test-tables.h"
+
+int main(int argc, char **argv) {
+ test_table(handle_action, HANDLE_ACTION);
+ test_table(inhibit_mode, INHIBIT_MODE);
+ test_table(kill_who, KILL_WHO);
+ test_table(session_class, SESSION_CLASS);
+ test_table(session_state, SESSION_STATE);
+ test_table(session_type, SESSION_TYPE);
+ test_table(user_state, USER_STATE);
+
+ return EXIT_SUCCESS;
+}