]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/login/logind.c
pam_systemd: always check if session is busy
[thirdparty/systemd.git] / src / login / logind.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <sys/types.h>
6 #include <unistd.h>
7
8 #include "sd-daemon.h"
9 #include "sd-device.h"
10
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"
23 #include "escape.h"
24 #include "fd-util.h"
25 #include "format-util.h"
26 #include "fs-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"
31 #include "logind.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"
39 #include "strv.h"
40 #include "terminal-util.h"
41 #include "udev-util.h"
42 #include "user-util.h"
43
44 static Manager* manager_free(Manager *m);
45 DEFINE_TRIVIAL_CLEANUP_FUNC(Manager*, manager_free);
46
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);
53
54 static int manager_new(Manager **ret) {
55 _cleanup_(manager_freep) Manager *m = NULL;
56 int r;
57
58 assert(ret);
59
60 m = new(Manager, 1);
61 if (!m)
62 return -ENOMEM;
63
64 *m = (Manager) {
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,
70
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),
77
78 .user_units = hashmap_new(&string_hash_ops),
79 .session_units = hashmap_new(&string_hash_ops),
80 };
81
82 if (!m->devices || !m->seats || !m->sessions || !m->users || !m->inhibitors || !m->buttons || !m->user_units || !m->session_units)
83 return -ENOMEM;
84
85 r = sd_event_default(&m->event);
86 if (r < 0)
87 return r;
88
89 r = sd_event_add_signal(m->event, NULL, SIGINT, NULL, NULL);
90 if (r < 0)
91 return r;
92
93 r = sd_event_add_signal(m->event, NULL, SIGTERM, NULL, NULL);
94 if (r < 0)
95 return r;
96
97 r = sd_event_add_signal(m->event, NULL, SIGRTMIN+18, sigrtmin18_handler, NULL);
98 if (r < 0)
99 return r;
100
101 r = sd_event_add_memory_pressure(m->event, NULL, NULL, NULL);
102 if (r < 0)
103 log_debug_errno(r, "Failed allocate memory pressure event source, ignoring: %m");
104
105 (void) sd_event_set_watchdog(m->event, true);
106
107 manager_reset_config(m);
108
109 *ret = TAKE_PTR(m);
110 return 0;
111 }
112
113 static Manager* manager_free(Manager *m) {
114 if (!m)
115 return NULL;
116
117 hashmap_free(m->devices);
118 hashmap_free(m->seats);
119 hashmap_free(m->sessions);
120
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);
124
125 hashmap_free(m->users);
126 hashmap_free(m->inhibitors);
127 hashmap_free(m->buttons);
128 hashmap_free(m->brightness_writers);
129
130 hashmap_free(m->user_units);
131 hashmap_free(m->session_units);
132
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);
138
139 sd_event_source_unref(m->console_active_event_source);
140 sd_event_source_unref(m->lid_switch_ignore_event_source);
141
142 sd_event_source_unref(m->reboot_key_long_press_event_source);
143
144 #if ENABLE_UTMP
145 sd_event_source_unref(m->utmp_event_source);
146 #endif
147
148 safe_close(m->console_active_fd);
149
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);
154
155 if (m->unlink_nologin)
156 (void) unlink_or_warn("/run/nologin");
157
158 hashmap_free(m->polkit_registry);
159
160 sd_bus_flush_close_unref(m->bus);
161 sd_event_unref(m->event);
162
163 safe_close(m->reserve_vt_fd);
164
165 strv_free(m->kill_only_users);
166 strv_free(m->kill_exclude_users);
167
168 free(m->scheduled_shutdown_tty);
169 free(m->wall_message);
170 free(m->action_job);
171
172 strv_free(m->efi_boot_loader_entries);
173 free(m->efi_loader_entry_one_shot);
174
175 return mfree(m);
176 }
177
178 static int manager_enumerate_devices(Manager *m) {
179 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
180 int r;
181
182 assert(m);
183
184 /* Loads devices from udev and creates seats for them as
185 * necessary */
186
187 r = sd_device_enumerator_new(&e);
188 if (r < 0)
189 return r;
190
191 r = sd_device_enumerator_add_match_tag(e, "master-of-seat");
192 if (r < 0)
193 return r;
194
195 r = 0;
196
197 FOREACH_DEVICE(e, d)
198 RET_GATHER(r, manager_process_seat_device(m, d));
199
200 return r;
201 }
202
203 static int manager_enumerate_buttons(Manager *m) {
204 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
205 int r;
206
207 assert(m);
208
209 /* Loads buttons from udev */
210
211 if (manager_all_buttons_ignored(m))
212 return 0;
213
214 r = sd_device_enumerator_new(&e);
215 if (r < 0)
216 return r;
217
218 r = sd_device_enumerator_add_match_subsystem(e, "input", true);
219 if (r < 0)
220 return r;
221
222 r = sd_device_enumerator_add_match_tag(e, "power-switch");
223 if (r < 0)
224 return r;
225
226 r = 0;
227
228 FOREACH_DEVICE(e, d)
229 RET_GATHER(r, manager_process_button_device(m, d));
230
231 return r;
232 }
233
234 static int manager_enumerate_seats(Manager *m) {
235 _cleanup_closedir_ DIR *d = NULL;
236 int r = 0;
237
238 assert(m);
239
240 /* This loads data about seats stored on disk, but does not
241 * actually create any seats. Removes data of seats that no
242 * longer exist. */
243
244 d = opendir("/run/systemd/seats");
245 if (!d) {
246 if (errno == ENOENT)
247 return 0;
248
249 return log_error_errno(errno, "Failed to open /run/systemd/seats/: %m");
250 }
251
252 FOREACH_DIRENT(de, d, return -errno) {
253 Seat *s;
254
255 if (!dirent_is_file(de))
256 continue;
257
258 s = hashmap_get(m->seats, de->d_name);
259 if (!s) {
260 if (unlinkat(dirfd(d), de->d_name, 0) < 0)
261 log_warning_errno(errno, "Failed to remove /run/systemd/seats/%s, ignoring: %m",
262 de->d_name);
263 continue;
264 }
265
266 RET_GATHER(r, seat_load(s));
267 }
268
269 return r;
270 }
271
272 static int manager_enumerate_linger_users(Manager *m) {
273 _cleanup_closedir_ DIR *d = NULL;
274 int r = 0;
275
276 assert(m);
277
278 d = opendir("/var/lib/systemd/linger");
279 if (!d) {
280 if (errno == ENOENT)
281 return 0;
282
283 return log_error_errno(errno, "Failed to open /var/lib/systemd/linger/: %m");
284 }
285
286 FOREACH_DIRENT(de, d, return -errno) {
287 _cleanup_free_ char *n = NULL;
288 int k;
289
290 if (!dirent_is_file(de))
291 continue;
292
293 k = cunescape(de->d_name, 0, &n);
294 if (k < 0) {
295 RET_GATHER(r, log_warning_errno(k, "Failed to unescape username '%s', ignoring: %m", de->d_name));
296 continue;
297 }
298
299 k = manager_add_user_by_name(m, n, NULL);
300 if (k < 0)
301 RET_GATHER(r, log_warning_errno(k, "Couldn't add lingering user %s, ignoring: %m", de->d_name));
302 }
303
304 return r;
305 }
306
307 static int manager_enumerate_users(Manager *m) {
308 _cleanup_closedir_ DIR *d = NULL;
309 int r;
310
311 assert(m);
312
313 /* Add lingering users */
314 r = manager_enumerate_linger_users(m);
315
316 /* Read in user data stored on disk */
317 d = opendir("/run/systemd/users");
318 if (!d) {
319 if (errno == ENOENT)
320 return 0;
321
322 return log_error_errno(errno, "Failed to open /run/systemd/users/: %m");
323 }
324
325 FOREACH_DIRENT(de, d, return -errno) {
326 User *u;
327 uid_t uid;
328 int k;
329
330 if (!dirent_is_file(de))
331 continue;
332
333 k = parse_uid(de->d_name, &uid);
334 if (k < 0) {
335 RET_GATHER(r, log_warning_errno(k, "Failed to parse filename /run/systemd/users/%s as UID, ignoring: %m", de->d_name));
336 continue;
337 }
338
339 k = manager_add_user_by_uid(m, uid, &u);
340 if (k < 0) {
341 RET_GATHER(r, log_warning_errno(k, "Failed to add user by filename %s, ignoring: %m", de->d_name));
342 continue;
343 }
344
345 user_add_to_gc_queue(u);
346
347 RET_GATHER(r, user_load(u));
348 }
349
350 return r;
351 }
352
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;
356 int r;
357
358 assert(ret_session_id);
359 assert(ret_devno);
360
361 parts = strv_split(fdname, "-");
362 if (!parts)
363 return -ENOMEM;
364
365 if (_unlikely_(!streq(parts[0], "session")))
366 return -EINVAL;
367
368 id = strdup(parts[1]);
369 if (!id)
370 return -ENOMEM;
371
372 if (streq(parts[2], "leader")) {
373 *ret_session_id = TAKE_PTR(id);
374 *ret_devno = 0;
375
376 return 0;
377 }
378
379 if (_unlikely_(!streq(parts[2], "device")))
380 return -EINVAL;
381
382 unsigned major, minor;
383
384 r = safe_atou(parts[3], &major);
385 if (r < 0)
386 return r;
387
388 r = safe_atou(parts[4], &minor);
389 if (r < 0)
390 return r;
391
392 *ret_session_id = TAKE_PTR(id);
393 *ret_devno = makedev(major, minor);
394
395 return 0;
396 }
397
398 static int deliver_session_device_fd(Session *s, const char *fdname, int fd, dev_t devno) {
399 SessionDevice *sd;
400 struct stat st;
401
402 assert(s);
403 assert(fdname);
404 assert(fd >= 0);
405 assert(devno > 0);
406
407 if (fstat(fd, &st) < 0)
408 /* The device is allowed to go away at a random point, in which case fstat() failing is
409 * expected. */
410 return log_debug_errno(errno, "Failed to stat device fd '%s' for session '%s': %m",
411 fdname, s->id);
412
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.",
416 fdname);
417
418 sd = hashmap_get(s->devices, &devno);
419 if (!sd)
420 /* Weird, we got an fd for a session device which wasn't recorded in the session state
421 * file... */
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));
425
426 log_debug("Attaching session device fd '%s' [" DEVNUM_FORMAT_STR "] to session '%s'.",
427 fdname, DEVNUM_FORMAT_VAL(devno), s->id);
428
429 session_device_attach_fd(sd, fd, s->was_active);
430 return 0;
431 }
432
433 static int deliver_session_leader_fd_consume(Session *s, const char *fdname, int fd) {
434 _cleanup_(pidref_done) PidRef leader_fdstore = PIDREF_NULL;
435 int r;
436
437 assert(s);
438 assert(fdname);
439 assert(fd >= 0);
440
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.",
444 s->id);
445 goto fail_close;
446 }
447
448 if (!s->leader_fd_saved)
449 log_warning("Got leader pidfd for session '%s', but not recorded in session state, proceeding anyway.",
450 s->id);
451 else
452 assert(!pidref_is_set(&s->leader));
453
454 r = pidref_set_pidfd_take(&leader_fdstore, fd);
455 if (r < 0) {
456 if (r == -ESRCH)
457 log_debug_errno(r, "Leader of session '%s' is gone while deserializing.", s->id);
458 else
459 log_warning_errno(r, "Failed to create reference to leader of session '%s': %m", s->id);
460 goto fail_close;
461 }
462
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);
466
467 r = session_set_leader_consume(s, TAKE_PIDREF(leader_fdstore));
468 if (r < 0)
469 return log_warning_errno(r, "Failed to attach leader pidfd for session '%s': %m", s->id);
470
471 return 0;
472
473 fail_close:
474 close_and_notify_warn(fd, fdname);
475 return r;
476 }
477
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 */
481 Session *s;
482 int r;
483
484 assert(m);
485 assert(fdname);
486 assert(fd >= 0);
487
488 r = parse_fdname(fdname, &id, &devno);
489 if (r < 0) {
490 log_warning_errno(r, "Failed to parse stored fd name '%s': %m", fdname);
491 goto fail_close;
492 }
493
494 s = hashmap_get(m->sessions, id);
495 if (!s) {
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);
499 goto fail_close;
500 }
501
502 if (devno > 0) {
503 r = deliver_session_device_fd(s, fdname, fd, devno);
504 if (r < 0)
505 goto fail_close;
506 return 0;
507 }
508
509 /* Takes ownership of fd on both success and failure */
510 return deliver_session_leader_fd_consume(s, fdname, fd);
511
512 fail_close:
513 close_and_notify_warn(fd, fdname);
514 return r;
515 }
516
517 static int manager_enumerate_sessions(Manager *m) {
518 _cleanup_strv_free_ char **fdnames = NULL;
519 _cleanup_closedir_ DIR *d = NULL;
520 int r = 0, n;
521
522 assert(m);
523
524 /* Read in session data stored on disk */
525 d = opendir("/run/systemd/sessions");
526 if (!d) {
527 if (errno == ENOENT)
528 return 0;
529
530 return log_error_errno(errno, "Failed to open /run/systemd/sessions/: %m");
531 }
532
533 FOREACH_DIRENT(de, d, return -errno) {
534 Session *s;
535 int k;
536
537 if (!dirent_is_file(de))
538 continue;
539
540 k = manager_add_session(m, de->d_name, &s);
541 if (k < 0) {
542 RET_GATHER(r, log_warning_errno(k, "Failed to add session by filename %s, ignoring: %m", de->d_name));
543 continue;
544 }
545
546 session_add_to_gc_queue(s);
547
548 k = session_load(s);
549 if (k < 0)
550 RET_GATHER(r, log_warning_errno(k, "Failed to deserialize session '%s', ignoring: %m", s->id));
551 }
552
553 n = sd_listen_fds_with_names(/* unset_environment = */ true, &fdnames);
554 if (n < 0)
555 return log_error_errno(n, "Failed to acquire passed fd list: %m");
556
557 for (int i = 0; i < n; i++) {
558 int fd = SD_LISTEN_FDS_START + i;
559
560 RET_GATHER(r, manager_attach_session_fd_one_consume(m, fdnames[i], fd));
561 }
562
563 return r;
564 }
565
566 static int manager_enumerate_inhibitors(Manager *m) {
567 _cleanup_closedir_ DIR *d = NULL;
568 int r = 0;
569
570 assert(m);
571
572 d = opendir("/run/systemd/inhibit");
573 if (!d) {
574 if (errno == ENOENT)
575 return 0;
576
577 return log_error_errno(errno, "Failed to open /run/systemd/inhibit/: %m");
578 }
579
580 FOREACH_DIRENT(de, d, return -errno) {
581 Inhibitor *i;
582 int k;
583
584 if (!dirent_is_file(de))
585 continue;
586
587 k = manager_add_inhibitor(m, de->d_name, &i);
588 if (k < 0) {
589 RET_GATHER(r, log_warning_errno(k, "Couldn't add inhibitor %s, ignoring: %m", de->d_name));
590 continue;
591 }
592
593 RET_GATHER(r, inhibitor_load(i));
594 }
595
596 return r;
597 }
598
599 static int manager_dispatch_seat_udev(sd_device_monitor *monitor, sd_device *device, void *userdata) {
600 Manager *m = ASSERT_PTR(userdata);
601
602 assert(device);
603
604 manager_process_seat_device(m, device);
605 return 0;
606 }
607
608 static int manager_dispatch_device_udev(sd_device_monitor *monitor, sd_device *device, void *userdata) {
609 Manager *m = ASSERT_PTR(userdata);
610
611 assert(device);
612
613 manager_process_seat_device(m, device);
614 return 0;
615 }
616
617 static int manager_dispatch_vcsa_udev(sd_device_monitor *monitor, sd_device *device, void *userdata) {
618 Manager *m = ASSERT_PTR(userdata);
619 const char *name;
620
621 assert(device);
622
623 /* Whenever a VCSA device is removed try to reallocate our
624 * VTs, to make sure our auto VTs never go away. */
625
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);
630
631 return 0;
632 }
633
634 static int manager_dispatch_button_udev(sd_device_monitor *monitor, sd_device *device, void *userdata) {
635 Manager *m = ASSERT_PTR(userdata);
636
637 assert(device);
638
639 manager_process_button_device(m, device);
640 return 0;
641 }
642
643 static int manager_dispatch_console(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
644 Manager *m = ASSERT_PTR(userdata);
645
646 assert(m->seat0);
647 assert(m->console_active_fd == fd);
648
649 seat_read_active_vt(m->seat0);
650 return 0;
651 }
652
653 static int manager_reserve_vt(Manager *m) {
654 _cleanup_free_ char *p = NULL;
655
656 assert(m);
657
658 if (m->reserve_vt <= 0)
659 return 0;
660
661 if (asprintf(&p, "/dev/tty%u", m->reserve_vt) < 0)
662 return log_oom();
663
664 m->reserve_vt_fd = open(p, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
665 if (m->reserve_vt_fd < 0) {
666
667 /* Don't complain on VT-less systems */
668 if (errno != ENOENT)
669 log_warning_errno(errno, "Failed to pin reserved VT: %m");
670 return -errno;
671 }
672
673 return 0;
674 }
675
676 static int manager_connect_bus(Manager *m) {
677 int r;
678
679 assert(m);
680 assert(!m->bus);
681
682 r = sd_bus_default_system(&m->bus);
683 if (r < 0)
684 return log_error_errno(r, "Failed to connect to system bus: %m");
685
686 r = bus_add_implementation(m->bus, &manager_object, m);
687 if (r < 0)
688 return r;
689
690 r = bus_log_control_api_register(m->bus);
691 if (r < 0)
692 return r;
693
694 r = bus_match_signal_async(m->bus, NULL, bus_systemd_mgr, "JobRemoved", match_job_removed, NULL, m);
695 if (r < 0)
696 return log_error_errno(r, "Failed to request match for JobRemoved: %m");
697
698 r = bus_match_signal_async(m->bus, NULL, bus_systemd_mgr, "UnitRemoved", match_unit_removed, NULL, m);
699 if (r < 0)
700 return log_error_errno(r, "Failed to request match for UnitRemoved: %m");
701
702 r = sd_bus_match_signal_async(
703 m->bus,
704 NULL,
705 "org.freedesktop.systemd1",
706 NULL,
707 "org.freedesktop.DBus.Properties",
708 "PropertiesChanged",
709 match_properties_changed, NULL, m);
710 if (r < 0)
711 return log_error_errno(r, "Failed to request match for PropertiesChanged: %m");
712
713 r = bus_match_signal_async(m->bus, NULL, bus_systemd_mgr, "Reloading", match_reloading, NULL, m);
714 if (r < 0)
715 return log_error_errno(r, "Failed to request match for Reloading: %m");
716
717 r = bus_call_method_async(m->bus, NULL, bus_systemd_mgr, "Subscribe", NULL, NULL, NULL);
718 if (r < 0)
719 return log_error_errno(r, "Failed to enable subscription: %m");
720
721 r = sd_bus_request_name_async(m->bus, NULL, "org.freedesktop.login1", 0, NULL, NULL);
722 if (r < 0)
723 return log_error_errno(r, "Failed to request name: %m");
724
725 r = sd_bus_attach_event(m->bus, m->event, SD_EVENT_PRIORITY_NORMAL);
726 if (r < 0)
727 return log_error_errno(r, "Failed to attach bus to event loop: %m");
728
729 return 0;
730 }
731
732 static int manager_vt_switch(sd_event_source *src, const struct signalfd_siginfo *si, void *data) {
733 Manager *m = ASSERT_PTR(data);
734 Session *active;
735
736 /*
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.
748 */
749
750 assert(m->seat0);
751
752 seat_read_active_vt(m->seat0);
753
754 active = m->seat0->active;
755 if (!active || active->vtnr < 1) {
756 _cleanup_close_ int fd = -EBADF;
757 int r;
758
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. */
764
765 log_warning("Received VT_PROCESS signal without a registered session, restoring VT.");
766
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);
769 if (fd < 0) {
770 log_warning_errno(fd, "Failed to open current VT, ignoring: %m");
771 return 0;
772 }
773
774 r = vt_release(fd, /* restore = */ true);
775 if (r < 0)
776 log_warning_errno(r, "Failed to release current VT, ignoring: %m");
777
778 return 0;
779 }
780
781 if (active->vtfd >= 0)
782 session_leave_vt(active);
783 else
784 LIST_FOREACH(sessions_by_seat, iter, m->seat0->sessions)
785 if (iter->vtnr == active->vtnr && iter->vtfd >= 0) {
786 session_leave_vt(iter);
787 break;
788 }
789
790 return 0;
791 }
792
793 static int manager_connect_console(Manager *m) {
794 int r;
795
796 assert(m);
797 assert(m->console_active_fd < 0);
798
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. */
801
802 if (access("/dev/tty0", F_OK) < 0)
803 return 0;
804
805 m->console_active_fd = open("/sys/class/tty/tty0/active", O_RDONLY|O_NOCTTY|O_CLOEXEC);
806 if (m->console_active_fd < 0) {
807
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");
812 return 0;
813 }
814
815 return log_error_errno(errno, "Failed to open /sys/class/tty/tty0/active: %m");
816 }
817
818 r = sd_event_add_io(m->event, &m->console_active_event_source, m->console_active_fd, 0, manager_dispatch_console, m);
819 if (r < 0)
820 return log_error_errno(r, "Failed to watch foreground console: %m");
821
822 /*
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.
827 */
828
829 if (SIGRTMIN + 1 > SIGRTMAX)
830 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
831 "Not enough real-time signals available: %i-%i",
832 SIGRTMIN, SIGRTMAX);
833
834 assert_se(ignore_signals(SIGRTMIN + 1) >= 0);
835 assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGRTMIN, -1) >= 0);
836
837 r = sd_event_add_signal(m->event, NULL, SIGRTMIN, manager_vt_switch, m);
838 if (r < 0)
839 return log_error_errno(r, "Failed to subscribe to signal: %m");
840
841 return 0;
842 }
843
844 static int manager_connect_udev(Manager *m) {
845 int r;
846
847 assert(m);
848 assert(!m->device_seat_monitor);
849 assert(!m->device_monitor);
850 assert(!m->device_vcsa_monitor);
851 assert(!m->device_button_monitor);
852
853 r = sd_device_monitor_new(&m->device_seat_monitor);
854 if (r < 0)
855 return r;
856
857 r = sd_device_monitor_filter_add_match_tag(m->device_seat_monitor, "master-of-seat");
858 if (r < 0)
859 return r;
860
861 r = sd_device_monitor_attach_event(m->device_seat_monitor, m->event);
862 if (r < 0)
863 return r;
864
865 r = sd_device_monitor_start(m->device_seat_monitor, manager_dispatch_seat_udev, m);
866 if (r < 0)
867 return r;
868
869 (void) sd_device_monitor_set_description(m->device_seat_monitor, "seat");
870
871 r = sd_device_monitor_new(&m->device_monitor);
872 if (r < 0)
873 return r;
874
875 r = sd_device_monitor_filter_add_match_subsystem_devtype(m->device_monitor, "input", NULL);
876 if (r < 0)
877 return r;
878
879 r = sd_device_monitor_filter_add_match_subsystem_devtype(m->device_monitor, "graphics", NULL);
880 if (r < 0)
881 return r;
882
883 r = sd_device_monitor_filter_add_match_subsystem_devtype(m->device_monitor, "drm", NULL);
884 if (r < 0)
885 return r;
886
887 r = sd_device_monitor_attach_event(m->device_monitor, m->event);
888 if (r < 0)
889 return r;
890
891 r = sd_device_monitor_start(m->device_monitor, manager_dispatch_device_udev, m);
892 if (r < 0)
893 return r;
894
895 (void) sd_device_monitor_set_description(m->device_monitor, "input,graphics,drm");
896
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);
900 if (r < 0)
901 return r;
902
903 r = sd_device_monitor_filter_add_match_tag(m->device_button_monitor, "power-switch");
904 if (r < 0)
905 return r;
906
907 r = sd_device_monitor_filter_add_match_subsystem_devtype(m->device_button_monitor, "input", NULL);
908 if (r < 0)
909 return r;
910
911 r = sd_device_monitor_attach_event(m->device_button_monitor, m->event);
912 if (r < 0)
913 return r;
914
915 r = sd_device_monitor_start(m->device_button_monitor, manager_dispatch_button_udev, m);
916 if (r < 0)
917 return r;
918
919 (void) sd_device_monitor_set_description(m->device_button_monitor, "button");
920 }
921
922 /* Don't bother watching VCSA devices, if nobody cares */
923 if (m->n_autovts > 0 && m->console_active_fd >= 0) {
924
925 r = sd_device_monitor_new(&m->device_vcsa_monitor);
926 if (r < 0)
927 return r;
928
929 r = sd_device_monitor_filter_add_match_subsystem_devtype(m->device_vcsa_monitor, "vc", NULL);
930 if (r < 0)
931 return r;
932
933 r = sd_device_monitor_attach_event(m->device_vcsa_monitor, m->event);
934 if (r < 0)
935 return r;
936
937 r = sd_device_monitor_start(m->device_vcsa_monitor, manager_dispatch_vcsa_udev, m);
938 if (r < 0)
939 return r;
940
941 (void) sd_device_monitor_set_description(m->device_vcsa_monitor, "vcsa");
942 }
943
944 return 0;
945 }
946
947 static void manager_gc(Manager *m, bool drop_not_started) {
948 Seat *seat;
949 Session *session;
950 User *user;
951
952 assert(m);
953
954 while ((seat = LIST_POP(gc_queue, m->seat_gc_queue))) {
955 seat->in_gc_queue = false;
956
957 if (seat_may_gc(seat, drop_not_started)) {
958 seat_stop(seat, /* force = */ false);
959 seat_free(seat);
960 }
961 }
962
963 while ((session = LIST_POP(gc_queue, m->session_gc_queue))) {
964 session->in_gc_queue = false;
965
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);
970
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);
976 }
977 }
978
979 while ((user = LIST_POP(gc_queue, m->user_gc_queue))) {
980 user->in_gc_queue = false;
981
982 /* First step: queue stop jobs */
983 if (user_may_gc(user, drop_not_started))
984 (void) user_stop(user, false);
985
986 /* Second step: finalize user */
987 if (user_may_gc(user, drop_not_started)) {
988 (void) user_finalize(user);
989 user_free(user);
990 }
991 }
992 }
993
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;
997 usec_t n, elapse;
998 int r;
999
1000 if (m->idle_action == HANDLE_IGNORE ||
1001 m->idle_action_usec <= 0)
1002 return 0;
1003
1004 n = now(CLOCK_MONOTONIC);
1005
1006 r = manager_get_idle_hint(m, &since);
1007 if (r <= 0) {
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;
1011 } else {
1012
1013 /* Idle! Let's see if it's time to do something, or if
1014 * we shall sleep for longer. */
1015
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;
1019
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) {
1023 is_edge = true;
1024 m->was_idle = true;
1025 }
1026
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.");
1030 else
1031 log_info("System idle. Will %s now.", handle_action_verb_to_string(m->idle_action));
1032
1033 manager_handle_action(m, 0, m->idle_action, false, is_edge);
1034 m->idle_action_not_before_usec = n;
1035 }
1036
1037 elapse = MAX(since.monotonic, m->idle_action_not_before_usec) + m->idle_action_usec;
1038 }
1039
1040 if (!m->idle_action_event_source) {
1041
1042 r = sd_event_add_time(
1043 m->event,
1044 &m->idle_action_event_source,
1045 CLOCK_MONOTONIC,
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);
1048 if (r < 0)
1049 return log_error_errno(r, "Failed to add idle event source: %m");
1050
1051 r = sd_event_source_set_priority(m->idle_action_event_source, SD_EVENT_PRIORITY_IDLE+10);
1052 if (r < 0)
1053 return log_error_errno(r, "Failed to set idle event source priority: %m");
1054 } else {
1055 r = sd_event_source_set_time(m->idle_action_event_source, elapse);
1056 if (r < 0)
1057 return log_error_errno(r, "Failed to set idle event timer: %m");
1058
1059 r = sd_event_source_set_enabled(m->idle_action_event_source, SD_EVENT_ONESHOT);
1060 if (r < 0)
1061 return log_error_errno(r, "Failed to enable idle event timer: %m");
1062 }
1063
1064 return 0;
1065 }
1066
1067 static int manager_dispatch_reload_signal(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
1068 Manager *m = userdata;
1069 int r;
1070
1071 (void) sd_notifyf(/* unset= */ false,
1072 "RELOADING=1\n"
1073 "STATUS=Reloading configuration...\n"
1074 "MONOTONIC_USEC=" USEC_FMT, now(CLOCK_MONOTONIC));
1075
1076 manager_reset_config(m);
1077 r = manager_parse_config_file(m);
1078 if (r < 0)
1079 log_warning_errno(r, "Failed to parse config file, using defaults: %m");
1080 else
1081 log_info("Config file reloaded.");
1082
1083 (void) sd_notify(/* unset= */ false, NOTIFY_READY);
1084 return 0;
1085 }
1086
1087 static int manager_startup(Manager *m) {
1088 int r;
1089 Seat *seat;
1090 Session *session;
1091 User *user;
1092 Button *button;
1093 Inhibitor *inhibitor;
1094
1095 assert(m);
1096
1097 r = sd_event_add_signal(m->event, NULL, SIGHUP, manager_dispatch_reload_signal, m);
1098 if (r < 0)
1099 return log_error_errno(r, "Failed to register SIGHUP handler: %m");
1100
1101 /* Connect to utmp */
1102 manager_connect_utmp(m);
1103
1104 /* Connect to console */
1105 r = manager_connect_console(m);
1106 if (r < 0)
1107 return r;
1108
1109 /* Connect to udev */
1110 r = manager_connect_udev(m);
1111 if (r < 0)
1112 return log_error_errno(r, "Failed to create udev watchers: %m");
1113
1114 /* Connect to the bus */
1115 r = manager_connect_bus(m);
1116 if (r < 0)
1117 return r;
1118
1119 /* Instantiate magic seat 0 */
1120 r = manager_add_seat(m, "seat0", &m->seat0);
1121 if (r < 0)
1122 return log_error_errno(r, "Failed to add seat0: %m");
1123
1124 r = manager_set_lid_switch_ignore(m, 0 + m->holdoff_timeout_usec);
1125 if (r < 0)
1126 log_warning_errno(r, "Failed to set up lid switch ignore event source: %m");
1127
1128 /* Deserialize state */
1129 r = manager_enumerate_devices(m);
1130 if (r < 0)
1131 log_warning_errno(r, "Device enumeration failed: %m");
1132
1133 r = manager_enumerate_seats(m);
1134 if (r < 0)
1135 log_warning_errno(r, "Seat enumeration failed: %m");
1136
1137 r = manager_enumerate_users(m);
1138 if (r < 0)
1139 log_warning_errno(r, "User enumeration failed: %m");
1140
1141 r = manager_enumerate_sessions(m);
1142 if (r < 0)
1143 log_warning_errno(r, "Session enumeration failed: %m");
1144
1145 r = manager_enumerate_inhibitors(m);
1146 if (r < 0)
1147 log_warning_errno(r, "Inhibitor enumeration failed: %m");
1148
1149 r = manager_enumerate_buttons(m);
1150 if (r < 0)
1151 log_warning_errno(r, "Button enumeration failed: %m");
1152
1153 manager_load_scheduled_shutdown(m);
1154
1155 /* Remove stale objects before we start them */
1156 manager_gc(m, false);
1157
1158 /* Reserve the special reserved VT */
1159 manager_reserve_vt(m);
1160
1161 /* Read in utmp if it exists */
1162 manager_read_utmp(m);
1163
1164 /* And start everything */
1165 HASHMAP_FOREACH(seat, m->seats)
1166 (void) seat_start(seat);
1167
1168 HASHMAP_FOREACH(user, m->users)
1169 (void) user_start(user);
1170
1171 HASHMAP_FOREACH(session, m->sessions)
1172 (void) session_start(session, NULL, NULL);
1173
1174 HASHMAP_FOREACH(inhibitor, m->inhibitors) {
1175 (void) inhibitor_start(inhibitor);
1176
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);
1181 }
1182 }
1183
1184 HASHMAP_FOREACH(button, m->buttons)
1185 button_check_switches(button);
1186
1187 manager_dispatch_idle_action(NULL, 0, m);
1188
1189 return 0;
1190 }
1191
1192 static int manager_run(Manager *m) {
1193 int r;
1194
1195 assert(m);
1196
1197 for (;;) {
1198 r = sd_event_get_state(m->event);
1199 if (r < 0)
1200 return r;
1201 if (r == SD_EVENT_FINISHED)
1202 return 0;
1203
1204 manager_gc(m, true);
1205
1206 r = manager_dispatch_delayed(m, false);
1207 if (r < 0)
1208 return r;
1209 if (r > 0)
1210 continue;
1211
1212 r = sd_event_run(m->event, UINT64_MAX);
1213 if (r < 0)
1214 return r;
1215 }
1216 }
1217
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;
1221 int r;
1222
1223 log_set_facility(LOG_AUTH);
1224 log_setup();
1225
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),
1230 argc, argv);
1231 if (r <= 0)
1232 return r;
1233
1234 umask(0022);
1235
1236 r = mac_init();
1237 if (r < 0)
1238 return r;
1239
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);
1246
1247 assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGHUP, SIGTERM, SIGINT, SIGCHLD, SIGRTMIN+18, -1) >= 0);
1248
1249 r = manager_new(&m);
1250 if (r < 0)
1251 return log_error_errno(r, "Failed to allocate manager object: %m");
1252
1253 (void) manager_parse_config_file(m);
1254
1255 r = manager_startup(m);
1256 if (r < 0)
1257 return log_error_errno(r, "Failed to fully start up daemon: %m");
1258
1259 notify_message = notify_start(NOTIFY_READY, NOTIFY_STOPPING);
1260 return manager_run(m);
1261 }
1262
1263 DEFINE_MAIN_FUNCTION(run);