1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
11 #include "alloc-util.h"
12 #include "bus-error.h"
13 #include "bus-locator.h"
14 #include "bus-log-control-api.h"
15 #include "bus-polkit.h"
16 #include "cgroup-util.h"
17 #include "common-signal.h"
18 #include "constants.h"
19 #include "daemon-util.h"
20 #include "device-util.h"
21 #include "devnum-util.h"
22 #include "dirent-util.h"
25 #include "format-util.h"
27 #include "logind-dbus.h"
28 #include "logind-seat-dbus.h"
29 #include "logind-session-dbus.h"
30 #include "logind-user-dbus.h"
32 #include "main-func.h"
33 #include "mkdir-label.h"
34 #include "parse-util.h"
35 #include "process-util.h"
36 #include "selinux-util.h"
37 #include "service-util.h"
38 #include "signal-util.h"
40 #include "terminal-util.h"
41 #include "udev-util.h"
42 #include "user-util.h"
44 static Manager
* manager_free(Manager
*m
);
45 DEFINE_TRIVIAL_CLEANUP_FUNC(Manager
*, manager_free
);
47 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(device_hash_ops
, char, string_hash_func
, string_compare_func
, Device
, device_free
);
48 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(seat_hash_ops
, char, string_hash_func
, string_compare_func
, Seat
, seat_free
);
49 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(session_hash_ops
, char, string_hash_func
, string_compare_func
, Session
, session_free
);
50 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(user_hash_ops
, void, trivial_hash_func
, trivial_compare_func
, User
, user_free
);
51 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(inhibitor_hash_ops
, char, string_hash_func
, string_compare_func
, Inhibitor
, inhibitor_free
);
52 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(button_hash_ops
, char, string_hash_func
, string_compare_func
, Button
, button_free
);
54 static int manager_new(Manager
**ret
) {
55 _cleanup_(manager_freep
) Manager
*m
= NULL
;
65 .console_active_fd
= -EBADF
,
66 .reserve_vt_fd
= -EBADF
,
67 .enable_wall_messages
= true,
68 .idle_action_not_before_usec
= now(CLOCK_MONOTONIC
),
69 .scheduled_shutdown_action
= _HANDLE_ACTION_INVALID
,
71 .devices
= hashmap_new(&device_hash_ops
),
72 .seats
= hashmap_new(&seat_hash_ops
),
73 .sessions
= hashmap_new(&session_hash_ops
),
74 .users
= hashmap_new(&user_hash_ops
),
75 .inhibitors
= hashmap_new(&inhibitor_hash_ops
),
76 .buttons
= hashmap_new(&button_hash_ops
),
78 .user_units
= hashmap_new(&string_hash_ops
),
79 .session_units
= hashmap_new(&string_hash_ops
),
82 if (!m
->devices
|| !m
->seats
|| !m
->sessions
|| !m
->users
|| !m
->inhibitors
|| !m
->buttons
|| !m
->user_units
|| !m
->session_units
)
85 r
= sd_event_default(&m
->event
);
89 r
= sd_event_add_signal(m
->event
, NULL
, SIGINT
, NULL
, NULL
);
93 r
= sd_event_add_signal(m
->event
, NULL
, SIGTERM
, NULL
, NULL
);
97 r
= sd_event_add_signal(m
->event
, NULL
, SIGRTMIN
+18, sigrtmin18_handler
, NULL
);
101 r
= sd_event_add_memory_pressure(m
->event
, NULL
, NULL
, NULL
);
103 log_debug_errno(r
, "Failed allocate memory pressure event source, ignoring: %m");
105 (void) sd_event_set_watchdog(m
->event
, true);
107 manager_reset_config(m
);
113 static Manager
* manager_free(Manager
*m
) {
117 hashmap_free(m
->devices
);
118 hashmap_free(m
->seats
);
119 hashmap_free(m
->sessions
);
121 /* All records should have been removed by session_free */
122 assert(hashmap_isempty(m
->sessions_by_leader
));
123 hashmap_free(m
->sessions_by_leader
);
125 hashmap_free(m
->users
);
126 hashmap_free(m
->inhibitors
);
127 hashmap_free(m
->buttons
);
128 hashmap_free(m
->brightness_writers
);
130 hashmap_free(m
->user_units
);
131 hashmap_free(m
->session_units
);
133 sd_event_source_unref(m
->idle_action_event_source
);
134 sd_event_source_unref(m
->inhibit_timeout_source
);
135 sd_event_source_unref(m
->scheduled_shutdown_timeout_source
);
136 sd_event_source_unref(m
->nologin_timeout_source
);
137 sd_event_source_unref(m
->wall_message_timeout_source
);
139 sd_event_source_unref(m
->console_active_event_source
);
140 sd_event_source_unref(m
->lid_switch_ignore_event_source
);
142 sd_event_source_unref(m
->reboot_key_long_press_event_source
);
145 sd_event_source_unref(m
->utmp_event_source
);
148 safe_close(m
->console_active_fd
);
150 sd_device_monitor_unref(m
->device_seat_monitor
);
151 sd_device_monitor_unref(m
->device_monitor
);
152 sd_device_monitor_unref(m
->device_vcsa_monitor
);
153 sd_device_monitor_unref(m
->device_button_monitor
);
155 if (m
->unlink_nologin
)
156 (void) unlink_or_warn("/run/nologin");
158 hashmap_free(m
->polkit_registry
);
160 sd_bus_flush_close_unref(m
->bus
);
161 sd_event_unref(m
->event
);
163 safe_close(m
->reserve_vt_fd
);
165 strv_free(m
->kill_only_users
);
166 strv_free(m
->kill_exclude_users
);
168 free(m
->scheduled_shutdown_tty
);
169 free(m
->wall_message
);
172 strv_free(m
->efi_boot_loader_entries
);
173 free(m
->efi_loader_entry_one_shot
);
178 static int manager_enumerate_devices(Manager
*m
) {
179 _cleanup_(sd_device_enumerator_unrefp
) sd_device_enumerator
*e
= NULL
;
184 /* Loads devices from udev and creates seats for them as
187 r
= sd_device_enumerator_new(&e
);
191 r
= sd_device_enumerator_add_match_tag(e
, "master-of-seat");
198 RET_GATHER(r
, manager_process_seat_device(m
, d
));
203 static int manager_enumerate_buttons(Manager
*m
) {
204 _cleanup_(sd_device_enumerator_unrefp
) sd_device_enumerator
*e
= NULL
;
209 /* Loads buttons from udev */
211 if (manager_all_buttons_ignored(m
))
214 r
= sd_device_enumerator_new(&e
);
218 r
= sd_device_enumerator_add_match_subsystem(e
, "input", true);
222 r
= sd_device_enumerator_add_match_tag(e
, "power-switch");
229 RET_GATHER(r
, manager_process_button_device(m
, d
));
234 static int manager_enumerate_seats(Manager
*m
) {
235 _cleanup_closedir_
DIR *d
= NULL
;
240 /* This loads data about seats stored on disk, but does not
241 * actually create any seats. Removes data of seats that no
244 d
= opendir("/run/systemd/seats");
249 return log_error_errno(errno
, "Failed to open /run/systemd/seats/: %m");
252 FOREACH_DIRENT(de
, d
, return -errno
) {
255 if (!dirent_is_file(de
))
258 s
= hashmap_get(m
->seats
, de
->d_name
);
260 if (unlinkat(dirfd(d
), de
->d_name
, 0) < 0)
261 log_warning_errno(errno
, "Failed to remove /run/systemd/seats/%s, ignoring: %m",
266 RET_GATHER(r
, seat_load(s
));
272 static int manager_enumerate_linger_users(Manager
*m
) {
273 _cleanup_closedir_
DIR *d
= NULL
;
278 d
= opendir("/var/lib/systemd/linger");
283 return log_error_errno(errno
, "Failed to open /var/lib/systemd/linger/: %m");
286 FOREACH_DIRENT(de
, d
, return -errno
) {
287 _cleanup_free_
char *n
= NULL
;
290 if (!dirent_is_file(de
))
293 k
= cunescape(de
->d_name
, 0, &n
);
295 RET_GATHER(r
, log_warning_errno(k
, "Failed to unescape username '%s', ignoring: %m", de
->d_name
));
299 k
= manager_add_user_by_name(m
, n
, NULL
);
301 RET_GATHER(r
, log_warning_errno(k
, "Couldn't add lingering user %s, ignoring: %m", de
->d_name
));
307 static int manager_enumerate_users(Manager
*m
) {
308 _cleanup_closedir_
DIR *d
= NULL
;
313 /* Add lingering users */
314 r
= manager_enumerate_linger_users(m
);
316 /* Read in user data stored on disk */
317 d
= opendir("/run/systemd/users");
322 return log_error_errno(errno
, "Failed to open /run/systemd/users/: %m");
325 FOREACH_DIRENT(de
, d
, return -errno
) {
330 if (!dirent_is_file(de
))
333 k
= parse_uid(de
->d_name
, &uid
);
335 RET_GATHER(r
, log_warning_errno(k
, "Failed to parse filename /run/systemd/users/%s as UID, ignoring: %m", de
->d_name
));
339 k
= manager_add_user_by_uid(m
, uid
, &u
);
341 RET_GATHER(r
, log_warning_errno(k
, "Failed to add user by filename %s, ignoring: %m", de
->d_name
));
345 user_add_to_gc_queue(u
);
347 RET_GATHER(r
, user_load(u
));
353 static int parse_fdname(const char *fdname
, char **ret_session_id
, dev_t
*ret_devno
) {
354 _cleanup_strv_free_
char **parts
= NULL
;
355 _cleanup_free_
char *id
= NULL
;
358 assert(ret_session_id
);
361 parts
= strv_split(fdname
, "-");
365 if (_unlikely_(!streq(parts
[0], "session")))
368 id
= strdup(parts
[1]);
372 if (streq(parts
[2], "leader")) {
373 *ret_session_id
= TAKE_PTR(id
);
379 if (_unlikely_(!streq(parts
[2], "device")))
382 unsigned major
, minor
;
384 r
= safe_atou(parts
[3], &major
);
388 r
= safe_atou(parts
[4], &minor
);
392 *ret_session_id
= TAKE_PTR(id
);
393 *ret_devno
= makedev(major
, minor
);
398 static int deliver_session_device_fd(Session
*s
, const char *fdname
, int fd
, dev_t devno
) {
407 if (fstat(fd
, &st
) < 0)
408 /* The device is allowed to go away at a random point, in which case fstat() failing is
410 return log_debug_errno(errno
, "Failed to stat device fd '%s' for session '%s': %m",
413 if (!S_ISCHR(st
.st_mode
) || st
.st_rdev
!= devno
)
414 return log_debug_errno(SYNTHETIC_ERRNO(ENODEV
),
415 "Device fd '%s' doesn't point to the expected character device node.",
418 sd
= hashmap_get(s
->devices
, &devno
);
420 /* Weird, we got an fd for a session device which wasn't recorded in the session state
422 return log_warning_errno(SYNTHETIC_ERRNO(ENODEV
),
423 "Got session device fd '%s' [" DEVNUM_FORMAT_STR
"], but not present in session state.",
424 fdname
, DEVNUM_FORMAT_VAL(devno
));
426 log_debug("Attaching session device fd '%s' [" DEVNUM_FORMAT_STR
"] to session '%s'.",
427 fdname
, DEVNUM_FORMAT_VAL(devno
), s
->id
);
429 session_device_attach_fd(sd
, fd
, s
->was_active
);
433 static int deliver_session_leader_fd_consume(Session
*s
, const char *fdname
, int fd
) {
434 _cleanup_(pidref_done
) PidRef leader_fdstore
= PIDREF_NULL
;
441 if (!pid_is_valid(s
->deserialized_pid
)) {
442 r
= log_warning_errno(SYNTHETIC_ERRNO(EOWNERDEAD
),
443 "Got leader pidfd for session '%s', but LEADER= is not set, refusing.",
448 if (!s
->leader_fd_saved
)
449 log_warning("Got leader pidfd for session '%s', but not recorded in session state, proceeding anyway.",
452 assert(!pidref_is_set(&s
->leader
));
454 r
= pidref_set_pidfd_take(&leader_fdstore
, fd
);
457 log_debug_errno(r
, "Leader of session '%s' is gone while deserializing.", s
->id
);
459 log_warning_errno(r
, "Failed to create reference to leader of session '%s': %m", s
->id
);
463 if (leader_fdstore
.pid
!= s
->deserialized_pid
)
464 log_warning("Leader from pidfd (" PID_FMT
") doesn't match with LEADER=" PID_FMT
" for session '%s', proceeding anyway.",
465 leader_fdstore
.pid
, s
->deserialized_pid
, s
->id
);
467 r
= session_set_leader_consume(s
, TAKE_PIDREF(leader_fdstore
));
469 return log_warning_errno(r
, "Failed to attach leader pidfd for session '%s': %m", s
->id
);
474 close_and_notify_warn(fd
, fdname
);
478 static int manager_attach_session_fd_one_consume(Manager
*m
, const char *fdname
, int fd
) {
479 _cleanup_free_
char *id
= NULL
;
480 dev_t devno
= 0; /* Explicit initialization to appease gcc */
488 r
= parse_fdname(fdname
, &id
, &devno
);
490 log_warning_errno(r
, "Failed to parse stored fd name '%s': %m", fdname
);
494 s
= hashmap_get(m
->sessions
, id
);
496 /* If the session doesn't exist anymore, let's simply close this fd. */
497 r
= log_debug_errno(SYNTHETIC_ERRNO(ENXIO
),
498 "Cannot attach fd '%s' to unknown session '%s', ignoring.", fdname
, id
);
503 r
= deliver_session_device_fd(s
, fdname
, fd
, devno
);
509 /* Takes ownership of fd on both success and failure */
510 return deliver_session_leader_fd_consume(s
, fdname
, fd
);
513 close_and_notify_warn(fd
, fdname
);
517 static int manager_enumerate_sessions(Manager
*m
) {
518 _cleanup_strv_free_
char **fdnames
= NULL
;
519 _cleanup_closedir_
DIR *d
= NULL
;
524 /* Read in session data stored on disk */
525 d
= opendir("/run/systemd/sessions");
530 return log_error_errno(errno
, "Failed to open /run/systemd/sessions/: %m");
533 FOREACH_DIRENT(de
, d
, return -errno
) {
537 if (!dirent_is_file(de
))
540 k
= manager_add_session(m
, de
->d_name
, &s
);
542 RET_GATHER(r
, log_warning_errno(k
, "Failed to add session by filename %s, ignoring: %m", de
->d_name
));
546 session_add_to_gc_queue(s
);
550 RET_GATHER(r
, log_warning_errno(k
, "Failed to deserialize session '%s', ignoring: %m", s
->id
));
553 n
= sd_listen_fds_with_names(/* unset_environment = */ true, &fdnames
);
555 return log_error_errno(n
, "Failed to acquire passed fd list: %m");
557 for (int i
= 0; i
< n
; i
++) {
558 int fd
= SD_LISTEN_FDS_START
+ i
;
560 RET_GATHER(r
, manager_attach_session_fd_one_consume(m
, fdnames
[i
], fd
));
566 static int manager_enumerate_inhibitors(Manager
*m
) {
567 _cleanup_closedir_
DIR *d
= NULL
;
572 d
= opendir("/run/systemd/inhibit");
577 return log_error_errno(errno
, "Failed to open /run/systemd/inhibit/: %m");
580 FOREACH_DIRENT(de
, d
, return -errno
) {
584 if (!dirent_is_file(de
))
587 k
= manager_add_inhibitor(m
, de
->d_name
, &i
);
589 RET_GATHER(r
, log_warning_errno(k
, "Couldn't add inhibitor %s, ignoring: %m", de
->d_name
));
593 RET_GATHER(r
, inhibitor_load(i
));
599 static int manager_dispatch_seat_udev(sd_device_monitor
*monitor
, sd_device
*device
, void *userdata
) {
600 Manager
*m
= ASSERT_PTR(userdata
);
604 manager_process_seat_device(m
, device
);
608 static int manager_dispatch_device_udev(sd_device_monitor
*monitor
, sd_device
*device
, void *userdata
) {
609 Manager
*m
= ASSERT_PTR(userdata
);
613 manager_process_seat_device(m
, device
);
617 static int manager_dispatch_vcsa_udev(sd_device_monitor
*monitor
, sd_device
*device
, void *userdata
) {
618 Manager
*m
= ASSERT_PTR(userdata
);
623 /* Whenever a VCSA device is removed try to reallocate our
624 * VTs, to make sure our auto VTs never go away. */
626 if (sd_device_get_sysname(device
, &name
) >= 0 &&
627 startswith(name
, "vcsa") &&
628 device_for_action(device
, SD_DEVICE_REMOVE
))
629 seat_preallocate_vts(m
->seat0
);
634 static int manager_dispatch_button_udev(sd_device_monitor
*monitor
, sd_device
*device
, void *userdata
) {
635 Manager
*m
= ASSERT_PTR(userdata
);
639 manager_process_button_device(m
, device
);
643 static int manager_dispatch_console(sd_event_source
*s
, int fd
, uint32_t revents
, void *userdata
) {
644 Manager
*m
= ASSERT_PTR(userdata
);
647 assert(m
->console_active_fd
== fd
);
649 seat_read_active_vt(m
->seat0
);
653 static int manager_reserve_vt(Manager
*m
) {
654 _cleanup_free_
char *p
= NULL
;
658 if (m
->reserve_vt
<= 0)
661 if (asprintf(&p
, "/dev/tty%u", m
->reserve_vt
) < 0)
664 m
->reserve_vt_fd
= open(p
, O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
665 if (m
->reserve_vt_fd
< 0) {
667 /* Don't complain on VT-less systems */
669 log_warning_errno(errno
, "Failed to pin reserved VT: %m");
676 static int manager_connect_bus(Manager
*m
) {
682 r
= sd_bus_default_system(&m
->bus
);
684 return log_error_errno(r
, "Failed to connect to system bus: %m");
686 r
= bus_add_implementation(m
->bus
, &manager_object
, m
);
690 r
= bus_log_control_api_register(m
->bus
);
694 r
= bus_match_signal_async(m
->bus
, NULL
, bus_systemd_mgr
, "JobRemoved", match_job_removed
, NULL
, m
);
696 return log_error_errno(r
, "Failed to request match for JobRemoved: %m");
698 r
= bus_match_signal_async(m
->bus
, NULL
, bus_systemd_mgr
, "UnitRemoved", match_unit_removed
, NULL
, m
);
700 return log_error_errno(r
, "Failed to request match for UnitRemoved: %m");
702 r
= sd_bus_match_signal_async(
705 "org.freedesktop.systemd1",
707 "org.freedesktop.DBus.Properties",
709 match_properties_changed
, NULL
, m
);
711 return log_error_errno(r
, "Failed to request match for PropertiesChanged: %m");
713 r
= bus_match_signal_async(m
->bus
, NULL
, bus_systemd_mgr
, "Reloading", match_reloading
, NULL
, m
);
715 return log_error_errno(r
, "Failed to request match for Reloading: %m");
717 r
= bus_call_method_async(m
->bus
, NULL
, bus_systemd_mgr
, "Subscribe", NULL
, NULL
, NULL
);
719 return log_error_errno(r
, "Failed to enable subscription: %m");
721 r
= sd_bus_request_name_async(m
->bus
, NULL
, "org.freedesktop.login1", 0, NULL
, NULL
);
723 return log_error_errno(r
, "Failed to request name: %m");
725 r
= sd_bus_attach_event(m
->bus
, m
->event
, SD_EVENT_PRIORITY_NORMAL
);
727 return log_error_errno(r
, "Failed to attach bus to event loop: %m");
732 static int manager_vt_switch(sd_event_source
*src
, const struct signalfd_siginfo
*si
, void *data
) {
733 Manager
*m
= ASSERT_PTR(data
);
737 * We got a VT-switch signal and we have to acknowledge it immediately.
738 * Preferably, we'd just use m->seat0->active->vtfd, but unfortunately,
739 * old user-space might run multiple sessions on a single VT, *sigh*.
740 * Therefore, we have to iterate all sessions and find one with a vtfd
741 * on the requested VT.
742 * As only VTs with active controllers have VT_PROCESS set, our current
743 * notion of the active VT might be wrong (for instance if the switch
744 * happens while we setup VT_PROCESS). Therefore, read the current VT
745 * first and then use s->active->vtnr as reference. Note that this is
746 * not racy, as no further VT-switch can happen as long as we're in
747 * synchronous VT_PROCESS mode.
752 seat_read_active_vt(m
->seat0
);
754 active
= m
->seat0
->active
;
755 if (!active
|| active
->vtnr
< 1) {
756 _cleanup_close_
int fd
= -EBADF
;
759 /* We are requested to acknowledge the VT-switch signal by the kernel but
760 * there's no registered sessions for the current VT. Normally this
761 * shouldn't happen but something wrong might have happened when we tried
762 * to release the VT. Better be safe than sorry, and try to release the VT
763 * one more time otherwise the user will be locked with the current VT. */
765 log_warning("Received VT_PROCESS signal without a registered session, restoring VT.");
767 /* At this point we only have the kernel mapping for referring to the current VT. */
768 fd
= open_terminal("/dev/tty0", O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
770 log_warning_errno(fd
, "Failed to open current VT, ignoring: %m");
774 r
= vt_release(fd
, /* restore = */ true);
776 log_warning_errno(r
, "Failed to release current VT, ignoring: %m");
781 if (active
->vtfd
>= 0)
782 session_leave_vt(active
);
784 LIST_FOREACH(sessions_by_seat
, iter
, m
->seat0
->sessions
)
785 if (iter
->vtnr
== active
->vtnr
&& iter
->vtfd
>= 0) {
786 session_leave_vt(iter
);
793 static int manager_connect_console(Manager
*m
) {
797 assert(m
->console_active_fd
< 0);
799 /* On certain systems (such as S390, Xen, and containers) /dev/tty0 does not exist (as there is no VC), so
800 * don't fail if we can't open it. */
802 if (access("/dev/tty0", F_OK
) < 0)
805 m
->console_active_fd
= open("/sys/class/tty/tty0/active", O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
806 if (m
->console_active_fd
< 0) {
808 /* On some systems /dev/tty0 may exist even though /sys/class/tty/tty0 does not. These are broken, but
809 * common. Let's complain but continue anyway. */
810 if (errno
== ENOENT
) {
811 log_warning_errno(errno
, "System has /dev/tty0 but not /sys/class/tty/tty0/active which is broken, ignoring: %m");
815 return log_error_errno(errno
, "Failed to open /sys/class/tty/tty0/active: %m");
818 r
= sd_event_add_io(m
->event
, &m
->console_active_event_source
, m
->console_active_fd
, 0, manager_dispatch_console
, m
);
820 return log_error_errno(r
, "Failed to watch foreground console: %m");
823 * SIGRTMIN is used as global VT-release signal, SIGRTMIN + 1 is used
824 * as VT-acquire signal. We ignore any acquire-events (yes, we still
825 * have to provide a valid signal-number for it!) and acknowledge all
826 * release events immediately.
829 if (SIGRTMIN
+ 1 > SIGRTMAX
)
830 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
831 "Not enough real-time signals available: %i-%i",
834 assert_se(ignore_signals(SIGRTMIN
+ 1) >= 0);
835 assert_se(sigprocmask_many(SIG_BLOCK
, NULL
, SIGRTMIN
, -1) >= 0);
837 r
= sd_event_add_signal(m
->event
, NULL
, SIGRTMIN
, manager_vt_switch
, m
);
839 return log_error_errno(r
, "Failed to subscribe to signal: %m");
844 static int manager_connect_udev(Manager
*m
) {
848 assert(!m
->device_seat_monitor
);
849 assert(!m
->device_monitor
);
850 assert(!m
->device_vcsa_monitor
);
851 assert(!m
->device_button_monitor
);
853 r
= sd_device_monitor_new(&m
->device_seat_monitor
);
857 r
= sd_device_monitor_filter_add_match_tag(m
->device_seat_monitor
, "master-of-seat");
861 r
= sd_device_monitor_attach_event(m
->device_seat_monitor
, m
->event
);
865 r
= sd_device_monitor_start(m
->device_seat_monitor
, manager_dispatch_seat_udev
, m
);
869 (void) sd_device_monitor_set_description(m
->device_seat_monitor
, "seat");
871 r
= sd_device_monitor_new(&m
->device_monitor
);
875 r
= sd_device_monitor_filter_add_match_subsystem_devtype(m
->device_monitor
, "input", NULL
);
879 r
= sd_device_monitor_filter_add_match_subsystem_devtype(m
->device_monitor
, "graphics", NULL
);
883 r
= sd_device_monitor_filter_add_match_subsystem_devtype(m
->device_monitor
, "drm", NULL
);
887 r
= sd_device_monitor_attach_event(m
->device_monitor
, m
->event
);
891 r
= sd_device_monitor_start(m
->device_monitor
, manager_dispatch_device_udev
, m
);
895 (void) sd_device_monitor_set_description(m
->device_monitor
, "input,graphics,drm");
897 /* Don't watch keys if nobody cares */
898 if (!manager_all_buttons_ignored(m
)) {
899 r
= sd_device_monitor_new(&m
->device_button_monitor
);
903 r
= sd_device_monitor_filter_add_match_tag(m
->device_button_monitor
, "power-switch");
907 r
= sd_device_monitor_filter_add_match_subsystem_devtype(m
->device_button_monitor
, "input", NULL
);
911 r
= sd_device_monitor_attach_event(m
->device_button_monitor
, m
->event
);
915 r
= sd_device_monitor_start(m
->device_button_monitor
, manager_dispatch_button_udev
, m
);
919 (void) sd_device_monitor_set_description(m
->device_button_monitor
, "button");
922 /* Don't bother watching VCSA devices, if nobody cares */
923 if (m
->n_autovts
> 0 && m
->console_active_fd
>= 0) {
925 r
= sd_device_monitor_new(&m
->device_vcsa_monitor
);
929 r
= sd_device_monitor_filter_add_match_subsystem_devtype(m
->device_vcsa_monitor
, "vc", NULL
);
933 r
= sd_device_monitor_attach_event(m
->device_vcsa_monitor
, m
->event
);
937 r
= sd_device_monitor_start(m
->device_vcsa_monitor
, manager_dispatch_vcsa_udev
, m
);
941 (void) sd_device_monitor_set_description(m
->device_vcsa_monitor
, "vcsa");
947 static void manager_gc(Manager
*m
, bool drop_not_started
) {
954 while ((seat
= LIST_POP(gc_queue
, m
->seat_gc_queue
))) {
955 seat
->in_gc_queue
= false;
957 if (seat_may_gc(seat
, drop_not_started
)) {
958 seat_stop(seat
, /* force = */ false);
963 while ((session
= LIST_POP(gc_queue
, m
->session_gc_queue
))) {
964 session
->in_gc_queue
= false;
966 /* First, if we are not closing yet, initiate stopping. */
967 if (session_may_gc(session
, drop_not_started
) &&
968 session_get_state(session
) != SESSION_CLOSING
)
969 (void) session_stop(session
, /* force = */ false);
971 /* Normally, this should make the session referenced again, if it doesn't then let's get rid
972 * of it immediately. */
973 if (session_may_gc(session
, drop_not_started
)) {
974 (void) session_finalize(session
);
975 session_free(session
);
979 while ((user
= LIST_POP(gc_queue
, m
->user_gc_queue
))) {
980 user
->in_gc_queue
= false;
982 /* First step: queue stop jobs */
983 if (user_may_gc(user
, drop_not_started
))
984 (void) user_stop(user
, false);
986 /* Second step: finalize user */
987 if (user_may_gc(user
, drop_not_started
)) {
988 (void) user_finalize(user
);
994 static int manager_dispatch_idle_action(sd_event_source
*s
, uint64_t t
, void *userdata
) {
995 Manager
*m
= ASSERT_PTR(userdata
);
996 struct dual_timestamp since
;
1000 if (m
->idle_action
== HANDLE_IGNORE
||
1001 m
->idle_action_usec
<= 0)
1004 n
= now(CLOCK_MONOTONIC
);
1006 r
= manager_get_idle_hint(m
, &since
);
1008 /* Not idle. Let's check if after a timeout it might be idle then. */
1009 elapse
= n
+ m
->idle_action_usec
;
1010 m
->was_idle
= false;
1013 /* Idle! Let's see if it's time to do something, or if
1014 * we shall sleep for longer. */
1016 if (n
>= since
.monotonic
+ m
->idle_action_usec
&&
1017 (m
->idle_action_not_before_usec
<= 0 || n
>= m
->idle_action_not_before_usec
+ m
->idle_action_usec
)) {
1018 bool is_edge
= false;
1020 /* We weren't idle previously or some activity happened while we were sleeping, and now we are
1021 * idle. Let's remember that for the next time and make this an edge transition. */
1022 if (!m
->was_idle
|| since
.monotonic
>= m
->idle_action_not_before_usec
) {
1027 if (m
->idle_action
== HANDLE_LOCK
&& !is_edge
)
1028 /* We are idle and we were before so we are actually not taking any action. */
1029 log_debug("System idle.");
1031 log_info("System idle. Will %s now.", handle_action_verb_to_string(m
->idle_action
));
1033 manager_handle_action(m
, 0, m
->idle_action
, false, is_edge
);
1034 m
->idle_action_not_before_usec
= n
;
1037 elapse
= MAX(since
.monotonic
, m
->idle_action_not_before_usec
) + m
->idle_action_usec
;
1040 if (!m
->idle_action_event_source
) {
1042 r
= sd_event_add_time(
1044 &m
->idle_action_event_source
,
1046 elapse
, MIN(USEC_PER_SEC
*30, m
->idle_action_usec
), /* accuracy of 30s, but don't have an accuracy lower than the idle action timeout */
1047 manager_dispatch_idle_action
, m
);
1049 return log_error_errno(r
, "Failed to add idle event source: %m");
1051 r
= sd_event_source_set_priority(m
->idle_action_event_source
, SD_EVENT_PRIORITY_IDLE
+10);
1053 return log_error_errno(r
, "Failed to set idle event source priority: %m");
1055 r
= sd_event_source_set_time(m
->idle_action_event_source
, elapse
);
1057 return log_error_errno(r
, "Failed to set idle event timer: %m");
1059 r
= sd_event_source_set_enabled(m
->idle_action_event_source
, SD_EVENT_ONESHOT
);
1061 return log_error_errno(r
, "Failed to enable idle event timer: %m");
1067 static int manager_dispatch_reload_signal(sd_event_source
*s
, const struct signalfd_siginfo
*si
, void *userdata
) {
1068 Manager
*m
= userdata
;
1071 (void) sd_notifyf(/* unset= */ false,
1073 "STATUS=Reloading configuration...\n"
1074 "MONOTONIC_USEC=" USEC_FMT
, now(CLOCK_MONOTONIC
));
1076 manager_reset_config(m
);
1077 r
= manager_parse_config_file(m
);
1079 log_warning_errno(r
, "Failed to parse config file, using defaults: %m");
1081 log_info("Config file reloaded.");
1083 (void) sd_notify(/* unset= */ false, NOTIFY_READY
);
1087 static int manager_startup(Manager
*m
) {
1093 Inhibitor
*inhibitor
;
1097 r
= sd_event_add_signal(m
->event
, NULL
, SIGHUP
, manager_dispatch_reload_signal
, m
);
1099 return log_error_errno(r
, "Failed to register SIGHUP handler: %m");
1101 /* Connect to utmp */
1102 manager_connect_utmp(m
);
1104 /* Connect to console */
1105 r
= manager_connect_console(m
);
1109 /* Connect to udev */
1110 r
= manager_connect_udev(m
);
1112 return log_error_errno(r
, "Failed to create udev watchers: %m");
1114 /* Connect to the bus */
1115 r
= manager_connect_bus(m
);
1119 /* Instantiate magic seat 0 */
1120 r
= manager_add_seat(m
, "seat0", &m
->seat0
);
1122 return log_error_errno(r
, "Failed to add seat0: %m");
1124 r
= manager_set_lid_switch_ignore(m
, 0 + m
->holdoff_timeout_usec
);
1126 log_warning_errno(r
, "Failed to set up lid switch ignore event source: %m");
1128 /* Deserialize state */
1129 r
= manager_enumerate_devices(m
);
1131 log_warning_errno(r
, "Device enumeration failed: %m");
1133 r
= manager_enumerate_seats(m
);
1135 log_warning_errno(r
, "Seat enumeration failed: %m");
1137 r
= manager_enumerate_users(m
);
1139 log_warning_errno(r
, "User enumeration failed: %m");
1141 r
= manager_enumerate_sessions(m
);
1143 log_warning_errno(r
, "Session enumeration failed: %m");
1145 r
= manager_enumerate_inhibitors(m
);
1147 log_warning_errno(r
, "Inhibitor enumeration failed: %m");
1149 r
= manager_enumerate_buttons(m
);
1151 log_warning_errno(r
, "Button enumeration failed: %m");
1153 manager_load_scheduled_shutdown(m
);
1155 /* Remove stale objects before we start them */
1156 manager_gc(m
, false);
1158 /* Reserve the special reserved VT */
1159 manager_reserve_vt(m
);
1161 /* Read in utmp if it exists */
1162 manager_read_utmp(m
);
1164 /* And start everything */
1165 HASHMAP_FOREACH(seat
, m
->seats
)
1166 (void) seat_start(seat
);
1168 HASHMAP_FOREACH(user
, m
->users
)
1169 (void) user_start(user
);
1171 HASHMAP_FOREACH(session
, m
->sessions
)
1172 (void) session_start(session
, NULL
, NULL
);
1174 HASHMAP_FOREACH(inhibitor
, m
->inhibitors
) {
1175 (void) inhibitor_start(inhibitor
);
1177 /* Let's see if the inhibitor is dead now, then remove it */
1178 if (inhibitor_is_orphan(inhibitor
)) {
1179 inhibitor_stop(inhibitor
);
1180 inhibitor_free(inhibitor
);
1184 HASHMAP_FOREACH(button
, m
->buttons
)
1185 button_check_switches(button
);
1187 manager_dispatch_idle_action(NULL
, 0, m
);
1192 static int manager_run(Manager
*m
) {
1198 r
= sd_event_get_state(m
->event
);
1201 if (r
== SD_EVENT_FINISHED
)
1204 manager_gc(m
, true);
1206 r
= manager_dispatch_delayed(m
, false);
1212 r
= sd_event_run(m
->event
, UINT64_MAX
);
1218 static int run(int argc
, char *argv
[]) {
1219 _cleanup_(manager_freep
) Manager
*m
= NULL
;
1220 _unused_
_cleanup_(notify_on_cleanup
) const char *notify_message
= NULL
;
1223 log_set_facility(LOG_AUTH
);
1226 r
= service_parse_argv("systemd-logind.service",
1227 "Manager for user logins and devices and privileged operations.",
1228 BUS_IMPLEMENTATIONS(&manager_object
,
1229 &log_control_object
),
1240 /* Always create the directories people can create inotify watches in. Note that some applications
1241 * might check for the existence of /run/systemd/seats/ to determine whether logind is available, so
1242 * please always make sure these directories are created early on and unconditionally. */
1243 (void) mkdir_label("/run/systemd/seats", 0755);
1244 (void) mkdir_label("/run/systemd/users", 0755);
1245 (void) mkdir_label("/run/systemd/sessions", 0755);
1247 assert_se(sigprocmask_many(SIG_BLOCK
, NULL
, SIGHUP
, SIGTERM
, SIGINT
, SIGCHLD
, SIGRTMIN
+18, -1) >= 0);
1249 r
= manager_new(&m
);
1251 return log_error_errno(r
, "Failed to allocate manager object: %m");
1253 (void) manager_parse_config_file(m
);
1255 r
= manager_startup(m
);
1257 return log_error_errno(r
, "Failed to fully start up daemon: %m");
1259 notify_message
= notify_start(NOTIFY_READY
, NOTIFY_STOPPING
);
1260 return manager_run(m
);
1263 DEFINE_MAIN_FUNCTION(run
);