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");
197 FOREACH_DEVICE(e
, d
) {
198 if (device_is_processed(d
) <= 0)
200 RET_GATHER(r
, manager_process_seat_device(m
, d
));
206 static int manager_enumerate_buttons(Manager
*m
) {
207 _cleanup_(sd_device_enumerator_unrefp
) sd_device_enumerator
*e
= NULL
;
212 /* Loads buttons from udev */
214 if (manager_all_buttons_ignored(m
))
217 r
= sd_device_enumerator_new(&e
);
221 r
= sd_device_enumerator_add_match_subsystem(e
, "input", true);
225 r
= sd_device_enumerator_add_match_tag(e
, "power-switch");
231 FOREACH_DEVICE(e
, d
) {
232 if (device_is_processed(d
) <= 0)
234 RET_GATHER(r
, manager_process_button_device(m
, d
));
240 static int manager_enumerate_seats(Manager
*m
) {
241 _cleanup_closedir_
DIR *d
= NULL
;
246 /* This loads data about seats stored on disk, but does not
247 * actually create any seats. Removes data of seats that no
250 d
= opendir("/run/systemd/seats");
255 return log_error_errno(errno
, "Failed to open /run/systemd/seats/: %m");
258 FOREACH_DIRENT(de
, d
, return -errno
) {
261 if (!dirent_is_file(de
))
264 s
= hashmap_get(m
->seats
, de
->d_name
);
266 if (unlinkat(dirfd(d
), de
->d_name
, 0) < 0)
267 log_warning_errno(errno
, "Failed to remove /run/systemd/seats/%s, ignoring: %m",
272 RET_GATHER(r
, seat_load(s
));
278 static int manager_enumerate_linger_users(Manager
*m
) {
279 _cleanup_closedir_
DIR *d
= NULL
;
284 d
= opendir("/var/lib/systemd/linger");
289 return log_error_errno(errno
, "Failed to open /var/lib/systemd/linger/: %m");
292 FOREACH_DIRENT(de
, d
, return -errno
) {
293 _cleanup_free_
char *n
= NULL
;
296 if (!dirent_is_file(de
))
299 k
= cunescape(de
->d_name
, 0, &n
);
301 RET_GATHER(r
, log_warning_errno(k
, "Failed to unescape username '%s', ignoring: %m", de
->d_name
));
305 k
= manager_add_user_by_name(m
, n
, NULL
);
307 RET_GATHER(r
, log_warning_errno(k
, "Couldn't add lingering user %s, ignoring: %m", de
->d_name
));
313 static int manager_enumerate_users(Manager
*m
) {
314 _cleanup_closedir_
DIR *d
= NULL
;
319 /* Add lingering users */
320 r
= manager_enumerate_linger_users(m
);
322 /* Read in user data stored on disk */
323 d
= opendir("/run/systemd/users");
328 return log_error_errno(errno
, "Failed to open /run/systemd/users/: %m");
331 FOREACH_DIRENT(de
, d
, return -errno
) {
336 if (!dirent_is_file(de
))
339 k
= parse_uid(de
->d_name
, &uid
);
341 RET_GATHER(r
, log_warning_errno(k
, "Failed to parse filename /run/systemd/users/%s as UID, ignoring: %m", de
->d_name
));
345 k
= manager_add_user_by_uid(m
, uid
, &u
);
347 RET_GATHER(r
, log_warning_errno(k
, "Failed to add user by filename %s, ignoring: %m", de
->d_name
));
351 user_add_to_gc_queue(u
);
353 RET_GATHER(r
, user_load(u
));
359 static int parse_fdname(const char *fdname
, char **ret_session_id
, dev_t
*ret_devno
) {
360 _cleanup_strv_free_
char **parts
= NULL
;
361 _cleanup_free_
char *id
= NULL
;
364 assert(ret_session_id
);
367 parts
= strv_split(fdname
, "-");
371 if (_unlikely_(!streq(parts
[0], "session")))
374 id
= strdup(parts
[1]);
378 if (streq(parts
[2], "leader")) {
379 *ret_session_id
= TAKE_PTR(id
);
385 if (_unlikely_(!streq(parts
[2], "device")))
388 unsigned major
, minor
;
390 r
= safe_atou(parts
[3], &major
);
394 r
= safe_atou(parts
[4], &minor
);
398 *ret_session_id
= TAKE_PTR(id
);
399 *ret_devno
= makedev(major
, minor
);
404 static int deliver_session_device_fd(Session
*s
, const char *fdname
, int fd
, dev_t devno
) {
413 if (fstat(fd
, &st
) < 0)
414 /* The device is allowed to go away at a random point, in which case fstat() failing is
416 return log_debug_errno(errno
, "Failed to stat device fd '%s' for session '%s': %m",
419 if (!S_ISCHR(st
.st_mode
) || st
.st_rdev
!= devno
)
420 return log_debug_errno(SYNTHETIC_ERRNO(ENODEV
),
421 "Device fd '%s' doesn't point to the expected character device node.",
424 sd
= hashmap_get(s
->devices
, &devno
);
426 /* Weird, we got an fd for a session device which wasn't recorded in the session state
428 return log_warning_errno(SYNTHETIC_ERRNO(ENODEV
),
429 "Got session device fd '%s' [" DEVNUM_FORMAT_STR
"], but not present in session state.",
430 fdname
, DEVNUM_FORMAT_VAL(devno
));
432 log_debug("Attaching session device fd '%s' [" DEVNUM_FORMAT_STR
"] to session '%s'.",
433 fdname
, DEVNUM_FORMAT_VAL(devno
), s
->id
);
435 session_device_attach_fd(sd
, fd
, s
->was_active
);
439 static int deliver_session_leader_fd_consume(Session
*s
, const char *fdname
, int fd
) {
440 _cleanup_(pidref_done
) PidRef leader_fdstore
= PIDREF_NULL
;
447 if (!pid_is_valid(s
->deserialized_pid
)) {
448 r
= log_warning_errno(SYNTHETIC_ERRNO(EOWNERDEAD
),
449 "Got leader pidfd for session '%s', but LEADER= is not set, refusing.",
454 if (!s
->leader_fd_saved
)
455 log_warning("Got leader pidfd for session '%s', but not recorded in session state, proceeding anyway.",
458 assert(!pidref_is_set(&s
->leader
));
460 r
= pidref_set_pidfd_take(&leader_fdstore
, fd
);
463 log_debug_errno(r
, "Leader of session '%s' is gone while deserializing.", s
->id
);
465 log_warning_errno(r
, "Failed to create reference to leader of session '%s': %m", s
->id
);
469 if (leader_fdstore
.pid
!= s
->deserialized_pid
)
470 log_warning("Leader from pidfd (" PID_FMT
") doesn't match with LEADER=" PID_FMT
" for session '%s', proceeding anyway.",
471 leader_fdstore
.pid
, s
->deserialized_pid
, s
->id
);
473 r
= session_set_leader_consume(s
, TAKE_PIDREF(leader_fdstore
));
475 return log_warning_errno(r
, "Failed to attach leader pidfd for session '%s': %m", s
->id
);
480 close_and_notify_warn(fd
, fdname
);
484 static int manager_attach_session_fd_one_consume(Manager
*m
, const char *fdname
, int fd
) {
485 _cleanup_free_
char *id
= NULL
;
486 dev_t devno
= 0; /* Explicit initialization to appease gcc */
494 r
= parse_fdname(fdname
, &id
, &devno
);
496 log_warning_errno(r
, "Failed to parse stored fd name '%s': %m", fdname
);
500 s
= hashmap_get(m
->sessions
, id
);
502 /* If the session doesn't exist anymore, let's simply close this fd. */
503 r
= log_debug_errno(SYNTHETIC_ERRNO(ENXIO
),
504 "Cannot attach fd '%s' to unknown session '%s', ignoring.", fdname
, id
);
509 r
= deliver_session_device_fd(s
, fdname
, fd
, devno
);
515 /* Takes ownership of fd on both success and failure */
516 return deliver_session_leader_fd_consume(s
, fdname
, fd
);
519 close_and_notify_warn(fd
, fdname
);
523 static int manager_enumerate_sessions(Manager
*m
) {
524 _cleanup_strv_free_
char **fdnames
= NULL
;
525 _cleanup_closedir_
DIR *d
= NULL
;
530 /* Read in session data stored on disk */
531 d
= opendir("/run/systemd/sessions");
536 return log_error_errno(errno
, "Failed to open /run/systemd/sessions/: %m");
539 FOREACH_DIRENT(de
, d
, return -errno
) {
543 if (!dirent_is_file(de
))
546 k
= manager_add_session(m
, de
->d_name
, &s
);
548 RET_GATHER(r
, log_warning_errno(k
, "Failed to add session by filename %s, ignoring: %m", de
->d_name
));
552 session_add_to_gc_queue(s
);
556 RET_GATHER(r
, log_warning_errno(k
, "Failed to deserialize session '%s', ignoring: %m", s
->id
));
559 n
= sd_listen_fds_with_names(/* unset_environment = */ true, &fdnames
);
561 return log_error_errno(n
, "Failed to acquire passed fd list: %m");
563 for (int i
= 0; i
< n
; i
++) {
564 int fd
= SD_LISTEN_FDS_START
+ i
;
566 RET_GATHER(r
, manager_attach_session_fd_one_consume(m
, fdnames
[i
], fd
));
572 static int manager_enumerate_inhibitors(Manager
*m
) {
573 _cleanup_closedir_
DIR *d
= NULL
;
578 d
= opendir("/run/systemd/inhibit");
583 return log_error_errno(errno
, "Failed to open /run/systemd/inhibit/: %m");
586 FOREACH_DIRENT(de
, d
, return -errno
) {
590 if (!dirent_is_file(de
))
593 k
= manager_add_inhibitor(m
, de
->d_name
, &i
);
595 RET_GATHER(r
, log_warning_errno(k
, "Couldn't add inhibitor %s, ignoring: %m", de
->d_name
));
599 RET_GATHER(r
, inhibitor_load(i
));
605 static int manager_dispatch_seat_udev(sd_device_monitor
*monitor
, sd_device
*device
, void *userdata
) {
606 Manager
*m
= ASSERT_PTR(userdata
);
610 manager_process_seat_device(m
, device
);
614 static int manager_dispatch_device_udev(sd_device_monitor
*monitor
, sd_device
*device
, void *userdata
) {
615 Manager
*m
= ASSERT_PTR(userdata
);
619 manager_process_seat_device(m
, device
);
623 static int manager_dispatch_vcsa_udev(sd_device_monitor
*monitor
, sd_device
*device
, void *userdata
) {
624 Manager
*m
= ASSERT_PTR(userdata
);
629 /* Whenever a VCSA device is removed try to reallocate our
630 * VTs, to make sure our auto VTs never go away. */
632 if (sd_device_get_sysname(device
, &name
) >= 0 &&
633 startswith(name
, "vcsa") &&
634 device_for_action(device
, SD_DEVICE_REMOVE
))
635 seat_preallocate_vts(m
->seat0
);
640 static int manager_dispatch_button_udev(sd_device_monitor
*monitor
, sd_device
*device
, void *userdata
) {
641 Manager
*m
= ASSERT_PTR(userdata
);
645 manager_process_button_device(m
, device
);
649 static int manager_dispatch_console(sd_event_source
*s
, int fd
, uint32_t revents
, void *userdata
) {
650 Manager
*m
= ASSERT_PTR(userdata
);
653 assert(m
->console_active_fd
== fd
);
655 seat_read_active_vt(m
->seat0
);
659 static int manager_reserve_vt(Manager
*m
) {
660 _cleanup_free_
char *p
= NULL
;
664 if (m
->reserve_vt
<= 0)
667 if (asprintf(&p
, "/dev/tty%u", m
->reserve_vt
) < 0)
670 m
->reserve_vt_fd
= open(p
, O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
671 if (m
->reserve_vt_fd
< 0) {
673 /* Don't complain on VT-less systems */
675 log_warning_errno(errno
, "Failed to pin reserved VT: %m");
682 static int manager_connect_bus(Manager
*m
) {
688 r
= sd_bus_default_system(&m
->bus
);
690 return log_error_errno(r
, "Failed to connect to system bus: %m");
692 r
= bus_add_implementation(m
->bus
, &manager_object
, m
);
696 r
= bus_log_control_api_register(m
->bus
);
700 r
= bus_match_signal_async(m
->bus
, NULL
, bus_systemd_mgr
, "JobRemoved", match_job_removed
, NULL
, m
);
702 return log_error_errno(r
, "Failed to request match for JobRemoved: %m");
704 r
= bus_match_signal_async(m
->bus
, NULL
, bus_systemd_mgr
, "UnitRemoved", match_unit_removed
, NULL
, m
);
706 return log_error_errno(r
, "Failed to request match for UnitRemoved: %m");
708 r
= sd_bus_match_signal_async(
711 "org.freedesktop.systemd1",
713 "org.freedesktop.DBus.Properties",
715 match_properties_changed
, NULL
, m
);
717 return log_error_errno(r
, "Failed to request match for PropertiesChanged: %m");
719 r
= bus_match_signal_async(m
->bus
, NULL
, bus_systemd_mgr
, "Reloading", match_reloading
, NULL
, m
);
721 return log_error_errno(r
, "Failed to request match for Reloading: %m");
723 r
= bus_call_method_async(m
->bus
, NULL
, bus_systemd_mgr
, "Subscribe", NULL
, NULL
, NULL
);
725 return log_error_errno(r
, "Failed to enable subscription: %m");
727 r
= sd_bus_request_name_async(m
->bus
, NULL
, "org.freedesktop.login1", 0, NULL
, NULL
);
729 return log_error_errno(r
, "Failed to request name: %m");
731 r
= sd_bus_attach_event(m
->bus
, m
->event
, SD_EVENT_PRIORITY_NORMAL
);
733 return log_error_errno(r
, "Failed to attach bus to event loop: %m");
738 static int manager_vt_switch(sd_event_source
*src
, const struct signalfd_siginfo
*si
, void *data
) {
739 Manager
*m
= ASSERT_PTR(data
);
743 * We got a VT-switch signal and we have to acknowledge it immediately.
744 * Preferably, we'd just use m->seat0->active->vtfd, but unfortunately,
745 * old user-space might run multiple sessions on a single VT, *sigh*.
746 * Therefore, we have to iterate all sessions and find one with a vtfd
747 * on the requested VT.
748 * As only VTs with active controllers have VT_PROCESS set, our current
749 * notion of the active VT might be wrong (for instance if the switch
750 * happens while we setup VT_PROCESS). Therefore, read the current VT
751 * first and then use s->active->vtnr as reference. Note that this is
752 * not racy, as no further VT-switch can happen as long as we're in
753 * synchronous VT_PROCESS mode.
758 seat_read_active_vt(m
->seat0
);
760 active
= m
->seat0
->active
;
761 if (!active
|| active
->vtnr
< 1) {
762 _cleanup_close_
int fd
= -EBADF
;
765 /* We are requested to acknowledge the VT-switch signal by the kernel but
766 * there's no registered sessions for the current VT. Normally this
767 * shouldn't happen but something wrong might have happened when we tried
768 * to release the VT. Better be safe than sorry, and try to release the VT
769 * one more time otherwise the user will be locked with the current VT. */
771 log_warning("Received VT_PROCESS signal without a registered session, restoring VT.");
773 /* At this point we only have the kernel mapping for referring to the current VT. */
774 fd
= open_terminal("/dev/tty0", O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
776 log_warning_errno(fd
, "Failed to open current VT, ignoring: %m");
780 r
= vt_release(fd
, /* restore = */ true);
782 log_warning_errno(r
, "Failed to release current VT, ignoring: %m");
787 if (active
->vtfd
>= 0)
788 session_leave_vt(active
);
790 LIST_FOREACH(sessions_by_seat
, iter
, m
->seat0
->sessions
)
791 if (iter
->vtnr
== active
->vtnr
&& iter
->vtfd
>= 0) {
792 session_leave_vt(iter
);
799 static int manager_connect_console(Manager
*m
) {
803 assert(m
->console_active_fd
< 0);
805 /* On certain systems (such as S390, Xen, and containers) /dev/tty0 does not exist (as there is no VC), so
806 * don't fail if we can't open it. */
808 if (access("/dev/tty0", F_OK
) < 0)
811 m
->console_active_fd
= open("/sys/class/tty/tty0/active", O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
812 if (m
->console_active_fd
< 0) {
814 /* On some systems /dev/tty0 may exist even though /sys/class/tty/tty0 does not. These are broken, but
815 * common. Let's complain but continue anyway. */
816 if (errno
== ENOENT
) {
817 log_warning_errno(errno
, "System has /dev/tty0 but not /sys/class/tty/tty0/active which is broken, ignoring: %m");
821 return log_error_errno(errno
, "Failed to open /sys/class/tty/tty0/active: %m");
824 r
= sd_event_add_io(m
->event
, &m
->console_active_event_source
, m
->console_active_fd
, 0, manager_dispatch_console
, m
);
826 return log_error_errno(r
, "Failed to watch foreground console: %m");
829 * SIGRTMIN is used as global VT-release signal, SIGRTMIN + 1 is used
830 * as VT-acquire signal. We ignore any acquire-events (yes, we still
831 * have to provide a valid signal-number for it!) and acknowledge all
832 * release events immediately.
835 if (SIGRTMIN
+ 1 > SIGRTMAX
)
836 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
837 "Not enough real-time signals available: %i-%i",
840 assert_se(ignore_signals(SIGRTMIN
+ 1) >= 0);
841 assert_se(sigprocmask_many(SIG_BLOCK
, NULL
, SIGRTMIN
) >= 0);
843 r
= sd_event_add_signal(m
->event
, NULL
, SIGRTMIN
, manager_vt_switch
, m
);
845 return log_error_errno(r
, "Failed to subscribe to signal: %m");
850 static int manager_connect_udev(Manager
*m
) {
854 assert(!m
->device_seat_monitor
);
855 assert(!m
->device_monitor
);
856 assert(!m
->device_vcsa_monitor
);
857 assert(!m
->device_button_monitor
);
859 r
= sd_device_monitor_new(&m
->device_seat_monitor
);
863 r
= sd_device_monitor_filter_add_match_tag(m
->device_seat_monitor
, "master-of-seat");
867 r
= sd_device_monitor_attach_event(m
->device_seat_monitor
, m
->event
);
871 r
= sd_device_monitor_start(m
->device_seat_monitor
, manager_dispatch_seat_udev
, m
);
875 (void) sd_device_monitor_set_description(m
->device_seat_monitor
, "seat");
877 r
= sd_device_monitor_new(&m
->device_monitor
);
881 r
= sd_device_monitor_filter_add_match_subsystem_devtype(m
->device_monitor
, "input", NULL
);
885 r
= sd_device_monitor_filter_add_match_subsystem_devtype(m
->device_monitor
, "graphics", NULL
);
889 r
= sd_device_monitor_filter_add_match_subsystem_devtype(m
->device_monitor
, "drm", NULL
);
893 r
= sd_device_monitor_attach_event(m
->device_monitor
, m
->event
);
897 r
= sd_device_monitor_start(m
->device_monitor
, manager_dispatch_device_udev
, m
);
901 (void) sd_device_monitor_set_description(m
->device_monitor
, "input,graphics,drm");
903 /* Don't watch keys if nobody cares */
904 if (!manager_all_buttons_ignored(m
)) {
905 r
= sd_device_monitor_new(&m
->device_button_monitor
);
909 r
= sd_device_monitor_filter_add_match_tag(m
->device_button_monitor
, "power-switch");
913 r
= sd_device_monitor_filter_add_match_subsystem_devtype(m
->device_button_monitor
, "input", NULL
);
917 r
= sd_device_monitor_attach_event(m
->device_button_monitor
, m
->event
);
921 r
= sd_device_monitor_start(m
->device_button_monitor
, manager_dispatch_button_udev
, m
);
925 (void) sd_device_monitor_set_description(m
->device_button_monitor
, "button");
928 /* Don't bother watching VCSA devices, if nobody cares */
929 if (m
->n_autovts
> 0 && m
->console_active_fd
>= 0) {
931 r
= sd_device_monitor_new(&m
->device_vcsa_monitor
);
935 r
= sd_device_monitor_filter_add_match_subsystem_devtype(m
->device_vcsa_monitor
, "vc", NULL
);
939 r
= sd_device_monitor_attach_event(m
->device_vcsa_monitor
, m
->event
);
943 r
= sd_device_monitor_start(m
->device_vcsa_monitor
, manager_dispatch_vcsa_udev
, m
);
947 (void) sd_device_monitor_set_description(m
->device_vcsa_monitor
, "vcsa");
953 static void manager_gc(Manager
*m
, bool drop_not_started
) {
960 while ((seat
= LIST_POP(gc_queue
, m
->seat_gc_queue
))) {
961 seat
->in_gc_queue
= false;
963 if (seat_may_gc(seat
, drop_not_started
)) {
964 seat_stop(seat
, /* force = */ false);
969 while ((session
= LIST_POP(gc_queue
, m
->session_gc_queue
))) {
970 session
->in_gc_queue
= false;
972 /* First, if we are not closing yet, initiate stopping. */
973 if (session_may_gc(session
, drop_not_started
) &&
974 session_get_state(session
) != SESSION_CLOSING
)
975 (void) session_stop(session
, /* force = */ false);
977 /* Normally, this should make the session referenced again, if it doesn't then let's get rid
978 * of it immediately. */
979 if (session_may_gc(session
, drop_not_started
)) {
980 (void) session_finalize(session
);
981 session_free(session
);
985 while ((user
= LIST_POP(gc_queue
, m
->user_gc_queue
))) {
986 user
->in_gc_queue
= false;
988 /* First step: queue stop jobs */
989 if (user_may_gc(user
, drop_not_started
))
990 (void) user_stop(user
, false);
992 /* Second step: finalize user */
993 if (user_may_gc(user
, drop_not_started
)) {
994 (void) user_finalize(user
);
1000 static int manager_dispatch_idle_action(sd_event_source
*s
, uint64_t t
, void *userdata
) {
1001 Manager
*m
= ASSERT_PTR(userdata
);
1002 struct dual_timestamp since
;
1006 if (m
->idle_action
== HANDLE_IGNORE
||
1007 m
->idle_action_usec
<= 0)
1010 n
= now(CLOCK_MONOTONIC
);
1012 r
= manager_get_idle_hint(m
, &since
);
1014 /* Not idle. Let's check if after a timeout it might be idle then. */
1015 elapse
= n
+ m
->idle_action_usec
;
1016 m
->was_idle
= false;
1019 /* Idle! Let's see if it's time to do something, or if
1020 * we shall sleep for longer. */
1022 if (n
>= since
.monotonic
+ m
->idle_action_usec
&&
1023 (m
->idle_action_not_before_usec
<= 0 || n
>= m
->idle_action_not_before_usec
+ m
->idle_action_usec
)) {
1024 bool is_edge
= false;
1026 /* We weren't idle previously or some activity happened while we were sleeping, and now we are
1027 * idle. Let's remember that for the next time and make this an edge transition. */
1028 if (!m
->was_idle
|| since
.monotonic
>= m
->idle_action_not_before_usec
) {
1033 if (m
->idle_action
== HANDLE_LOCK
&& !is_edge
)
1034 /* We are idle and we were before so we are actually not taking any action. */
1035 log_debug("System idle.");
1037 log_info("System idle. Will %s now.", handle_action_verb_to_string(m
->idle_action
));
1039 manager_handle_action(m
, 0, m
->idle_action
, false, is_edge
);
1040 m
->idle_action_not_before_usec
= n
;
1043 elapse
= MAX(since
.monotonic
, m
->idle_action_not_before_usec
) + m
->idle_action_usec
;
1046 if (!m
->idle_action_event_source
) {
1048 r
= sd_event_add_time(
1050 &m
->idle_action_event_source
,
1052 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 */
1053 manager_dispatch_idle_action
, m
);
1055 return log_error_errno(r
, "Failed to add idle event source: %m");
1057 r
= sd_event_source_set_priority(m
->idle_action_event_source
, SD_EVENT_PRIORITY_IDLE
+10);
1059 return log_error_errno(r
, "Failed to set idle event source priority: %m");
1061 r
= sd_event_source_set_time(m
->idle_action_event_source
, elapse
);
1063 return log_error_errno(r
, "Failed to set idle event timer: %m");
1065 r
= sd_event_source_set_enabled(m
->idle_action_event_source
, SD_EVENT_ONESHOT
);
1067 return log_error_errno(r
, "Failed to enable idle event timer: %m");
1073 static int manager_dispatch_reload_signal(sd_event_source
*s
, const struct signalfd_siginfo
*si
, void *userdata
) {
1074 Manager
*m
= userdata
;
1077 (void) notify_reloading();
1079 manager_reset_config(m
);
1080 r
= manager_parse_config_file(m
);
1082 log_warning_errno(r
, "Failed to parse config file, using defaults: %m");
1084 log_info("Config file reloaded.");
1086 (void) sd_notify(/* unset= */ false, NOTIFY_READY
);
1090 static int manager_startup(Manager
*m
) {
1096 Inhibitor
*inhibitor
;
1100 r
= sd_event_add_signal(m
->event
, NULL
, SIGHUP
, manager_dispatch_reload_signal
, m
);
1102 return log_error_errno(r
, "Failed to register SIGHUP handler: %m");
1104 /* Connect to utmp */
1105 manager_connect_utmp(m
);
1107 /* Connect to console */
1108 r
= manager_connect_console(m
);
1112 /* Connect to udev */
1113 r
= manager_connect_udev(m
);
1115 return log_error_errno(r
, "Failed to create udev watchers: %m");
1117 /* Connect to the bus */
1118 r
= manager_connect_bus(m
);
1122 /* Instantiate magic seat 0 */
1123 r
= manager_add_seat(m
, "seat0", &m
->seat0
);
1125 return log_error_errno(r
, "Failed to add seat0: %m");
1127 r
= manager_set_lid_switch_ignore(m
, 0 + m
->holdoff_timeout_usec
);
1129 log_warning_errno(r
, "Failed to set up lid switch ignore event source: %m");
1131 /* Deserialize state */
1132 r
= manager_enumerate_devices(m
);
1134 log_warning_errno(r
, "Device enumeration failed: %m");
1136 r
= manager_enumerate_seats(m
);
1138 log_warning_errno(r
, "Seat enumeration failed: %m");
1140 r
= manager_enumerate_users(m
);
1142 log_warning_errno(r
, "User enumeration failed: %m");
1144 r
= manager_enumerate_sessions(m
);
1146 log_warning_errno(r
, "Session enumeration failed: %m");
1148 r
= manager_enumerate_inhibitors(m
);
1150 log_warning_errno(r
, "Inhibitor enumeration failed: %m");
1152 r
= manager_enumerate_buttons(m
);
1154 log_warning_errno(r
, "Button enumeration failed: %m");
1156 manager_load_scheduled_shutdown(m
);
1158 /* Remove stale objects before we start them */
1159 manager_gc(m
, false);
1161 /* Reserve the special reserved VT */
1162 manager_reserve_vt(m
);
1164 /* Read in utmp if it exists */
1165 manager_read_utmp(m
);
1167 /* And start everything */
1168 HASHMAP_FOREACH(seat
, m
->seats
)
1169 (void) seat_start(seat
);
1171 HASHMAP_FOREACH(user
, m
->users
)
1172 (void) user_start(user
);
1174 HASHMAP_FOREACH(session
, m
->sessions
)
1175 (void) session_start(session
, NULL
, NULL
);
1177 HASHMAP_FOREACH(inhibitor
, m
->inhibitors
) {
1178 (void) inhibitor_start(inhibitor
);
1180 /* Let's see if the inhibitor is dead now, then remove it */
1181 if (inhibitor_is_orphan(inhibitor
)) {
1182 inhibitor_stop(inhibitor
);
1183 inhibitor_free(inhibitor
);
1187 HASHMAP_FOREACH(button
, m
->buttons
)
1188 button_check_switches(button
);
1190 manager_dispatch_idle_action(NULL
, 0, m
);
1195 static int manager_run(Manager
*m
) {
1201 r
= sd_event_get_state(m
->event
);
1204 if (r
== SD_EVENT_FINISHED
)
1207 manager_gc(m
, true);
1209 r
= manager_dispatch_delayed(m
, false);
1215 r
= sd_event_run(m
->event
, UINT64_MAX
);
1221 static int run(int argc
, char *argv
[]) {
1222 _cleanup_(manager_freep
) Manager
*m
= NULL
;
1223 _unused_
_cleanup_(notify_on_cleanup
) const char *notify_message
= NULL
;
1226 log_set_facility(LOG_AUTH
);
1229 r
= service_parse_argv("systemd-logind.service",
1230 "Manager for user logins and devices and privileged operations.",
1231 BUS_IMPLEMENTATIONS(&manager_object
,
1232 &log_control_object
),
1243 /* Always create the directories people can create inotify watches in. Note that some applications
1244 * might check for the existence of /run/systemd/seats/ to determine whether logind is available, so
1245 * please always make sure these directories are created early on and unconditionally. */
1246 (void) mkdir_label("/run/systemd/seats", 0755);
1247 (void) mkdir_label("/run/systemd/users", 0755);
1248 (void) mkdir_label("/run/systemd/sessions", 0755);
1250 assert_se(sigprocmask_many(SIG_BLOCK
, NULL
, SIGHUP
, SIGTERM
, SIGINT
, SIGCHLD
, SIGRTMIN
+18) >= 0);
1252 r
= manager_new(&m
);
1254 return log_error_errno(r
, "Failed to allocate manager object: %m");
1256 (void) manager_parse_config_file(m
);
1258 r
= manager_startup(m
);
1260 return log_error_errno(r
, "Failed to fully start up daemon: %m");
1262 notify_message
= notify_start(NOTIFY_READY
, NOTIFY_STOPPING
);
1263 return manager_run(m
);
1266 DEFINE_MAIN_FUNCTION(run
);