]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/login/logind.c
tree-wide: refuse enumerated device with ID_PROCESSING=1
[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 if (device_is_processed(d) <= 0)
199 continue;
200 RET_GATHER(r, manager_process_seat_device(m, d));
201 }
202
203 return r;
204 }
205
206 static int manager_enumerate_buttons(Manager *m) {
207 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
208 int r;
209
210 assert(m);
211
212 /* Loads buttons from udev */
213
214 if (manager_all_buttons_ignored(m))
215 return 0;
216
217 r = sd_device_enumerator_new(&e);
218 if (r < 0)
219 return r;
220
221 r = sd_device_enumerator_add_match_subsystem(e, "input", true);
222 if (r < 0)
223 return r;
224
225 r = sd_device_enumerator_add_match_tag(e, "power-switch");
226 if (r < 0)
227 return r;
228
229 r = 0;
230
231 FOREACH_DEVICE(e, d) {
232 if (device_is_processed(d) <= 0)
233 continue;
234 RET_GATHER(r, manager_process_button_device(m, d));
235 }
236
237 return r;
238 }
239
240 static int manager_enumerate_seats(Manager *m) {
241 _cleanup_closedir_ DIR *d = NULL;
242 int r = 0;
243
244 assert(m);
245
246 /* This loads data about seats stored on disk, but does not
247 * actually create any seats. Removes data of seats that no
248 * longer exist. */
249
250 d = opendir("/run/systemd/seats");
251 if (!d) {
252 if (errno == ENOENT)
253 return 0;
254
255 return log_error_errno(errno, "Failed to open /run/systemd/seats/: %m");
256 }
257
258 FOREACH_DIRENT(de, d, return -errno) {
259 Seat *s;
260
261 if (!dirent_is_file(de))
262 continue;
263
264 s = hashmap_get(m->seats, de->d_name);
265 if (!s) {
266 if (unlinkat(dirfd(d), de->d_name, 0) < 0)
267 log_warning_errno(errno, "Failed to remove /run/systemd/seats/%s, ignoring: %m",
268 de->d_name);
269 continue;
270 }
271
272 RET_GATHER(r, seat_load(s));
273 }
274
275 return r;
276 }
277
278 static int manager_enumerate_linger_users(Manager *m) {
279 _cleanup_closedir_ DIR *d = NULL;
280 int r = 0;
281
282 assert(m);
283
284 d = opendir("/var/lib/systemd/linger");
285 if (!d) {
286 if (errno == ENOENT)
287 return 0;
288
289 return log_error_errno(errno, "Failed to open /var/lib/systemd/linger/: %m");
290 }
291
292 FOREACH_DIRENT(de, d, return -errno) {
293 _cleanup_free_ char *n = NULL;
294 int k;
295
296 if (!dirent_is_file(de))
297 continue;
298
299 k = cunescape(de->d_name, 0, &n);
300 if (k < 0) {
301 RET_GATHER(r, log_warning_errno(k, "Failed to unescape username '%s', ignoring: %m", de->d_name));
302 continue;
303 }
304
305 k = manager_add_user_by_name(m, n, NULL);
306 if (k < 0)
307 RET_GATHER(r, log_warning_errno(k, "Couldn't add lingering user %s, ignoring: %m", de->d_name));
308 }
309
310 return r;
311 }
312
313 static int manager_enumerate_users(Manager *m) {
314 _cleanup_closedir_ DIR *d = NULL;
315 int r;
316
317 assert(m);
318
319 /* Add lingering users */
320 r = manager_enumerate_linger_users(m);
321
322 /* Read in user data stored on disk */
323 d = opendir("/run/systemd/users");
324 if (!d) {
325 if (errno == ENOENT)
326 return 0;
327
328 return log_error_errno(errno, "Failed to open /run/systemd/users/: %m");
329 }
330
331 FOREACH_DIRENT(de, d, return -errno) {
332 User *u;
333 uid_t uid;
334 int k;
335
336 if (!dirent_is_file(de))
337 continue;
338
339 k = parse_uid(de->d_name, &uid);
340 if (k < 0) {
341 RET_GATHER(r, log_warning_errno(k, "Failed to parse filename /run/systemd/users/%s as UID, ignoring: %m", de->d_name));
342 continue;
343 }
344
345 k = manager_add_user_by_uid(m, uid, &u);
346 if (k < 0) {
347 RET_GATHER(r, log_warning_errno(k, "Failed to add user by filename %s, ignoring: %m", de->d_name));
348 continue;
349 }
350
351 user_add_to_gc_queue(u);
352
353 RET_GATHER(r, user_load(u));
354 }
355
356 return r;
357 }
358
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;
362 int r;
363
364 assert(ret_session_id);
365 assert(ret_devno);
366
367 parts = strv_split(fdname, "-");
368 if (!parts)
369 return -ENOMEM;
370
371 if (_unlikely_(!streq(parts[0], "session")))
372 return -EINVAL;
373
374 id = strdup(parts[1]);
375 if (!id)
376 return -ENOMEM;
377
378 if (streq(parts[2], "leader")) {
379 *ret_session_id = TAKE_PTR(id);
380 *ret_devno = 0;
381
382 return 0;
383 }
384
385 if (_unlikely_(!streq(parts[2], "device")))
386 return -EINVAL;
387
388 unsigned major, minor;
389
390 r = safe_atou(parts[3], &major);
391 if (r < 0)
392 return r;
393
394 r = safe_atou(parts[4], &minor);
395 if (r < 0)
396 return r;
397
398 *ret_session_id = TAKE_PTR(id);
399 *ret_devno = makedev(major, minor);
400
401 return 0;
402 }
403
404 static int deliver_session_device_fd(Session *s, const char *fdname, int fd, dev_t devno) {
405 SessionDevice *sd;
406 struct stat st;
407
408 assert(s);
409 assert(fdname);
410 assert(fd >= 0);
411 assert(devno > 0);
412
413 if (fstat(fd, &st) < 0)
414 /* The device is allowed to go away at a random point, in which case fstat() failing is
415 * expected. */
416 return log_debug_errno(errno, "Failed to stat device fd '%s' for session '%s': %m",
417 fdname, s->id);
418
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.",
422 fdname);
423
424 sd = hashmap_get(s->devices, &devno);
425 if (!sd)
426 /* Weird, we got an fd for a session device which wasn't recorded in the session state
427 * file... */
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));
431
432 log_debug("Attaching session device fd '%s' [" DEVNUM_FORMAT_STR "] to session '%s'.",
433 fdname, DEVNUM_FORMAT_VAL(devno), s->id);
434
435 session_device_attach_fd(sd, fd, s->was_active);
436 return 0;
437 }
438
439 static int deliver_session_leader_fd_consume(Session *s, const char *fdname, int fd) {
440 _cleanup_(pidref_done) PidRef leader_fdstore = PIDREF_NULL;
441 int r;
442
443 assert(s);
444 assert(fdname);
445 assert(fd >= 0);
446
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.",
450 s->id);
451 goto fail_close;
452 }
453
454 if (!s->leader_fd_saved)
455 log_warning("Got leader pidfd for session '%s', but not recorded in session state, proceeding anyway.",
456 s->id);
457 else
458 assert(!pidref_is_set(&s->leader));
459
460 r = pidref_set_pidfd_take(&leader_fdstore, fd);
461 if (r < 0) {
462 if (r == -ESRCH)
463 log_debug_errno(r, "Leader of session '%s' is gone while deserializing.", s->id);
464 else
465 log_warning_errno(r, "Failed to create reference to leader of session '%s': %m", s->id);
466 goto fail_close;
467 }
468
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);
472
473 r = session_set_leader_consume(s, TAKE_PIDREF(leader_fdstore));
474 if (r < 0)
475 return log_warning_errno(r, "Failed to attach leader pidfd for session '%s': %m", s->id);
476
477 return 0;
478
479 fail_close:
480 close_and_notify_warn(fd, fdname);
481 return r;
482 }
483
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 */
487 Session *s;
488 int r;
489
490 assert(m);
491 assert(fdname);
492 assert(fd >= 0);
493
494 r = parse_fdname(fdname, &id, &devno);
495 if (r < 0) {
496 log_warning_errno(r, "Failed to parse stored fd name '%s': %m", fdname);
497 goto fail_close;
498 }
499
500 s = hashmap_get(m->sessions, id);
501 if (!s) {
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);
505 goto fail_close;
506 }
507
508 if (devno > 0) {
509 r = deliver_session_device_fd(s, fdname, fd, devno);
510 if (r < 0)
511 goto fail_close;
512 return 0;
513 }
514
515 /* Takes ownership of fd on both success and failure */
516 return deliver_session_leader_fd_consume(s, fdname, fd);
517
518 fail_close:
519 close_and_notify_warn(fd, fdname);
520 return r;
521 }
522
523 static int manager_enumerate_sessions(Manager *m) {
524 _cleanup_strv_free_ char **fdnames = NULL;
525 _cleanup_closedir_ DIR *d = NULL;
526 int r = 0, n;
527
528 assert(m);
529
530 /* Read in session data stored on disk */
531 d = opendir("/run/systemd/sessions");
532 if (!d) {
533 if (errno == ENOENT)
534 return 0;
535
536 return log_error_errno(errno, "Failed to open /run/systemd/sessions/: %m");
537 }
538
539 FOREACH_DIRENT(de, d, return -errno) {
540 Session *s;
541 int k;
542
543 if (!dirent_is_file(de))
544 continue;
545
546 k = manager_add_session(m, de->d_name, &s);
547 if (k < 0) {
548 RET_GATHER(r, log_warning_errno(k, "Failed to add session by filename %s, ignoring: %m", de->d_name));
549 continue;
550 }
551
552 session_add_to_gc_queue(s);
553
554 k = session_load(s);
555 if (k < 0)
556 RET_GATHER(r, log_warning_errno(k, "Failed to deserialize session '%s', ignoring: %m", s->id));
557 }
558
559 n = sd_listen_fds_with_names(/* unset_environment = */ true, &fdnames);
560 if (n < 0)
561 return log_error_errno(n, "Failed to acquire passed fd list: %m");
562
563 for (int i = 0; i < n; i++) {
564 int fd = SD_LISTEN_FDS_START + i;
565
566 RET_GATHER(r, manager_attach_session_fd_one_consume(m, fdnames[i], fd));
567 }
568
569 return r;
570 }
571
572 static int manager_enumerate_inhibitors(Manager *m) {
573 _cleanup_closedir_ DIR *d = NULL;
574 int r = 0;
575
576 assert(m);
577
578 d = opendir("/run/systemd/inhibit");
579 if (!d) {
580 if (errno == ENOENT)
581 return 0;
582
583 return log_error_errno(errno, "Failed to open /run/systemd/inhibit/: %m");
584 }
585
586 FOREACH_DIRENT(de, d, return -errno) {
587 Inhibitor *i;
588 int k;
589
590 if (!dirent_is_file(de))
591 continue;
592
593 k = manager_add_inhibitor(m, de->d_name, &i);
594 if (k < 0) {
595 RET_GATHER(r, log_warning_errno(k, "Couldn't add inhibitor %s, ignoring: %m", de->d_name));
596 continue;
597 }
598
599 RET_GATHER(r, inhibitor_load(i));
600 }
601
602 return r;
603 }
604
605 static int manager_dispatch_seat_udev(sd_device_monitor *monitor, sd_device *device, void *userdata) {
606 Manager *m = ASSERT_PTR(userdata);
607
608 assert(device);
609
610 manager_process_seat_device(m, device);
611 return 0;
612 }
613
614 static int manager_dispatch_device_udev(sd_device_monitor *monitor, sd_device *device, void *userdata) {
615 Manager *m = ASSERT_PTR(userdata);
616
617 assert(device);
618
619 manager_process_seat_device(m, device);
620 return 0;
621 }
622
623 static int manager_dispatch_vcsa_udev(sd_device_monitor *monitor, sd_device *device, void *userdata) {
624 Manager *m = ASSERT_PTR(userdata);
625 const char *name;
626
627 assert(device);
628
629 /* Whenever a VCSA device is removed try to reallocate our
630 * VTs, to make sure our auto VTs never go away. */
631
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);
636
637 return 0;
638 }
639
640 static int manager_dispatch_button_udev(sd_device_monitor *monitor, sd_device *device, void *userdata) {
641 Manager *m = ASSERT_PTR(userdata);
642
643 assert(device);
644
645 manager_process_button_device(m, device);
646 return 0;
647 }
648
649 static int manager_dispatch_console(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
650 Manager *m = ASSERT_PTR(userdata);
651
652 assert(m->seat0);
653 assert(m->console_active_fd == fd);
654
655 seat_read_active_vt(m->seat0);
656 return 0;
657 }
658
659 static int manager_reserve_vt(Manager *m) {
660 _cleanup_free_ char *p = NULL;
661
662 assert(m);
663
664 if (m->reserve_vt <= 0)
665 return 0;
666
667 if (asprintf(&p, "/dev/tty%u", m->reserve_vt) < 0)
668 return log_oom();
669
670 m->reserve_vt_fd = open(p, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
671 if (m->reserve_vt_fd < 0) {
672
673 /* Don't complain on VT-less systems */
674 if (errno != ENOENT)
675 log_warning_errno(errno, "Failed to pin reserved VT: %m");
676 return -errno;
677 }
678
679 return 0;
680 }
681
682 static int manager_connect_bus(Manager *m) {
683 int r;
684
685 assert(m);
686 assert(!m->bus);
687
688 r = sd_bus_default_system(&m->bus);
689 if (r < 0)
690 return log_error_errno(r, "Failed to connect to system bus: %m");
691
692 r = bus_add_implementation(m->bus, &manager_object, m);
693 if (r < 0)
694 return r;
695
696 r = bus_log_control_api_register(m->bus);
697 if (r < 0)
698 return r;
699
700 r = bus_match_signal_async(m->bus, NULL, bus_systemd_mgr, "JobRemoved", match_job_removed, NULL, m);
701 if (r < 0)
702 return log_error_errno(r, "Failed to request match for JobRemoved: %m");
703
704 r = bus_match_signal_async(m->bus, NULL, bus_systemd_mgr, "UnitRemoved", match_unit_removed, NULL, m);
705 if (r < 0)
706 return log_error_errno(r, "Failed to request match for UnitRemoved: %m");
707
708 r = sd_bus_match_signal_async(
709 m->bus,
710 NULL,
711 "org.freedesktop.systemd1",
712 NULL,
713 "org.freedesktop.DBus.Properties",
714 "PropertiesChanged",
715 match_properties_changed, NULL, m);
716 if (r < 0)
717 return log_error_errno(r, "Failed to request match for PropertiesChanged: %m");
718
719 r = bus_match_signal_async(m->bus, NULL, bus_systemd_mgr, "Reloading", match_reloading, NULL, m);
720 if (r < 0)
721 return log_error_errno(r, "Failed to request match for Reloading: %m");
722
723 r = bus_call_method_async(m->bus, NULL, bus_systemd_mgr, "Subscribe", NULL, NULL, NULL);
724 if (r < 0)
725 return log_error_errno(r, "Failed to enable subscription: %m");
726
727 r = sd_bus_request_name_async(m->bus, NULL, "org.freedesktop.login1", 0, NULL, NULL);
728 if (r < 0)
729 return log_error_errno(r, "Failed to request name: %m");
730
731 r = sd_bus_attach_event(m->bus, m->event, SD_EVENT_PRIORITY_NORMAL);
732 if (r < 0)
733 return log_error_errno(r, "Failed to attach bus to event loop: %m");
734
735 return 0;
736 }
737
738 static int manager_vt_switch(sd_event_source *src, const struct signalfd_siginfo *si, void *data) {
739 Manager *m = ASSERT_PTR(data);
740 Session *active;
741
742 /*
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.
754 */
755
756 assert(m->seat0);
757
758 seat_read_active_vt(m->seat0);
759
760 active = m->seat0->active;
761 if (!active || active->vtnr < 1) {
762 _cleanup_close_ int fd = -EBADF;
763 int r;
764
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. */
770
771 log_warning("Received VT_PROCESS signal without a registered session, restoring VT.");
772
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);
775 if (fd < 0) {
776 log_warning_errno(fd, "Failed to open current VT, ignoring: %m");
777 return 0;
778 }
779
780 r = vt_release(fd, /* restore = */ true);
781 if (r < 0)
782 log_warning_errno(r, "Failed to release current VT, ignoring: %m");
783
784 return 0;
785 }
786
787 if (active->vtfd >= 0)
788 session_leave_vt(active);
789 else
790 LIST_FOREACH(sessions_by_seat, iter, m->seat0->sessions)
791 if (iter->vtnr == active->vtnr && iter->vtfd >= 0) {
792 session_leave_vt(iter);
793 break;
794 }
795
796 return 0;
797 }
798
799 static int manager_connect_console(Manager *m) {
800 int r;
801
802 assert(m);
803 assert(m->console_active_fd < 0);
804
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. */
807
808 if (access("/dev/tty0", F_OK) < 0)
809 return 0;
810
811 m->console_active_fd = open("/sys/class/tty/tty0/active", O_RDONLY|O_NOCTTY|O_CLOEXEC);
812 if (m->console_active_fd < 0) {
813
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");
818 return 0;
819 }
820
821 return log_error_errno(errno, "Failed to open /sys/class/tty/tty0/active: %m");
822 }
823
824 r = sd_event_add_io(m->event, &m->console_active_event_source, m->console_active_fd, 0, manager_dispatch_console, m);
825 if (r < 0)
826 return log_error_errno(r, "Failed to watch foreground console: %m");
827
828 /*
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.
833 */
834
835 if (SIGRTMIN + 1 > SIGRTMAX)
836 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
837 "Not enough real-time signals available: %i-%i",
838 SIGRTMIN, SIGRTMAX);
839
840 assert_se(ignore_signals(SIGRTMIN + 1) >= 0);
841 assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGRTMIN) >= 0);
842
843 r = sd_event_add_signal(m->event, NULL, SIGRTMIN, manager_vt_switch, m);
844 if (r < 0)
845 return log_error_errno(r, "Failed to subscribe to signal: %m");
846
847 return 0;
848 }
849
850 static int manager_connect_udev(Manager *m) {
851 int r;
852
853 assert(m);
854 assert(!m->device_seat_monitor);
855 assert(!m->device_monitor);
856 assert(!m->device_vcsa_monitor);
857 assert(!m->device_button_monitor);
858
859 r = sd_device_monitor_new(&m->device_seat_monitor);
860 if (r < 0)
861 return r;
862
863 r = sd_device_monitor_filter_add_match_tag(m->device_seat_monitor, "master-of-seat");
864 if (r < 0)
865 return r;
866
867 r = sd_device_monitor_attach_event(m->device_seat_monitor, m->event);
868 if (r < 0)
869 return r;
870
871 r = sd_device_monitor_start(m->device_seat_monitor, manager_dispatch_seat_udev, m);
872 if (r < 0)
873 return r;
874
875 (void) sd_device_monitor_set_description(m->device_seat_monitor, "seat");
876
877 r = sd_device_monitor_new(&m->device_monitor);
878 if (r < 0)
879 return r;
880
881 r = sd_device_monitor_filter_add_match_subsystem_devtype(m->device_monitor, "input", NULL);
882 if (r < 0)
883 return r;
884
885 r = sd_device_monitor_filter_add_match_subsystem_devtype(m->device_monitor, "graphics", NULL);
886 if (r < 0)
887 return r;
888
889 r = sd_device_monitor_filter_add_match_subsystem_devtype(m->device_monitor, "drm", NULL);
890 if (r < 0)
891 return r;
892
893 r = sd_device_monitor_attach_event(m->device_monitor, m->event);
894 if (r < 0)
895 return r;
896
897 r = sd_device_monitor_start(m->device_monitor, manager_dispatch_device_udev, m);
898 if (r < 0)
899 return r;
900
901 (void) sd_device_monitor_set_description(m->device_monitor, "input,graphics,drm");
902
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);
906 if (r < 0)
907 return r;
908
909 r = sd_device_monitor_filter_add_match_tag(m->device_button_monitor, "power-switch");
910 if (r < 0)
911 return r;
912
913 r = sd_device_monitor_filter_add_match_subsystem_devtype(m->device_button_monitor, "input", NULL);
914 if (r < 0)
915 return r;
916
917 r = sd_device_monitor_attach_event(m->device_button_monitor, m->event);
918 if (r < 0)
919 return r;
920
921 r = sd_device_monitor_start(m->device_button_monitor, manager_dispatch_button_udev, m);
922 if (r < 0)
923 return r;
924
925 (void) sd_device_monitor_set_description(m->device_button_monitor, "button");
926 }
927
928 /* Don't bother watching VCSA devices, if nobody cares */
929 if (m->n_autovts > 0 && m->console_active_fd >= 0) {
930
931 r = sd_device_monitor_new(&m->device_vcsa_monitor);
932 if (r < 0)
933 return r;
934
935 r = sd_device_monitor_filter_add_match_subsystem_devtype(m->device_vcsa_monitor, "vc", NULL);
936 if (r < 0)
937 return r;
938
939 r = sd_device_monitor_attach_event(m->device_vcsa_monitor, m->event);
940 if (r < 0)
941 return r;
942
943 r = sd_device_monitor_start(m->device_vcsa_monitor, manager_dispatch_vcsa_udev, m);
944 if (r < 0)
945 return r;
946
947 (void) sd_device_monitor_set_description(m->device_vcsa_monitor, "vcsa");
948 }
949
950 return 0;
951 }
952
953 static void manager_gc(Manager *m, bool drop_not_started) {
954 Seat *seat;
955 Session *session;
956 User *user;
957
958 assert(m);
959
960 while ((seat = LIST_POP(gc_queue, m->seat_gc_queue))) {
961 seat->in_gc_queue = false;
962
963 if (seat_may_gc(seat, drop_not_started)) {
964 seat_stop(seat, /* force = */ false);
965 seat_free(seat);
966 }
967 }
968
969 while ((session = LIST_POP(gc_queue, m->session_gc_queue))) {
970 session->in_gc_queue = false;
971
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);
976
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);
982 }
983 }
984
985 while ((user = LIST_POP(gc_queue, m->user_gc_queue))) {
986 user->in_gc_queue = false;
987
988 /* First step: queue stop jobs */
989 if (user_may_gc(user, drop_not_started))
990 (void) user_stop(user, false);
991
992 /* Second step: finalize user */
993 if (user_may_gc(user, drop_not_started)) {
994 (void) user_finalize(user);
995 user_free(user);
996 }
997 }
998 }
999
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;
1003 usec_t n, elapse;
1004 int r;
1005
1006 if (m->idle_action == HANDLE_IGNORE ||
1007 m->idle_action_usec <= 0)
1008 return 0;
1009
1010 n = now(CLOCK_MONOTONIC);
1011
1012 r = manager_get_idle_hint(m, &since);
1013 if (r <= 0) {
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;
1017 } else {
1018
1019 /* Idle! Let's see if it's time to do something, or if
1020 * we shall sleep for longer. */
1021
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;
1025
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) {
1029 is_edge = true;
1030 m->was_idle = true;
1031 }
1032
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.");
1036 else
1037 log_info("System idle. Will %s now.", handle_action_verb_to_string(m->idle_action));
1038
1039 manager_handle_action(m, 0, m->idle_action, false, is_edge);
1040 m->idle_action_not_before_usec = n;
1041 }
1042
1043 elapse = MAX(since.monotonic, m->idle_action_not_before_usec) + m->idle_action_usec;
1044 }
1045
1046 if (!m->idle_action_event_source) {
1047
1048 r = sd_event_add_time(
1049 m->event,
1050 &m->idle_action_event_source,
1051 CLOCK_MONOTONIC,
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);
1054 if (r < 0)
1055 return log_error_errno(r, "Failed to add idle event source: %m");
1056
1057 r = sd_event_source_set_priority(m->idle_action_event_source, SD_EVENT_PRIORITY_IDLE+10);
1058 if (r < 0)
1059 return log_error_errno(r, "Failed to set idle event source priority: %m");
1060 } else {
1061 r = sd_event_source_set_time(m->idle_action_event_source, elapse);
1062 if (r < 0)
1063 return log_error_errno(r, "Failed to set idle event timer: %m");
1064
1065 r = sd_event_source_set_enabled(m->idle_action_event_source, SD_EVENT_ONESHOT);
1066 if (r < 0)
1067 return log_error_errno(r, "Failed to enable idle event timer: %m");
1068 }
1069
1070 return 0;
1071 }
1072
1073 static int manager_dispatch_reload_signal(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
1074 Manager *m = userdata;
1075 int r;
1076
1077 (void) notify_reloading();
1078
1079 manager_reset_config(m);
1080 r = manager_parse_config_file(m);
1081 if (r < 0)
1082 log_warning_errno(r, "Failed to parse config file, using defaults: %m");
1083 else
1084 log_info("Config file reloaded.");
1085
1086 (void) sd_notify(/* unset= */ false, NOTIFY_READY);
1087 return 0;
1088 }
1089
1090 static int manager_startup(Manager *m) {
1091 int r;
1092 Seat *seat;
1093 Session *session;
1094 User *user;
1095 Button *button;
1096 Inhibitor *inhibitor;
1097
1098 assert(m);
1099
1100 r = sd_event_add_signal(m->event, NULL, SIGHUP, manager_dispatch_reload_signal, m);
1101 if (r < 0)
1102 return log_error_errno(r, "Failed to register SIGHUP handler: %m");
1103
1104 /* Connect to utmp */
1105 manager_connect_utmp(m);
1106
1107 /* Connect to console */
1108 r = manager_connect_console(m);
1109 if (r < 0)
1110 return r;
1111
1112 /* Connect to udev */
1113 r = manager_connect_udev(m);
1114 if (r < 0)
1115 return log_error_errno(r, "Failed to create udev watchers: %m");
1116
1117 /* Connect to the bus */
1118 r = manager_connect_bus(m);
1119 if (r < 0)
1120 return r;
1121
1122 /* Instantiate magic seat 0 */
1123 r = manager_add_seat(m, "seat0", &m->seat0);
1124 if (r < 0)
1125 return log_error_errno(r, "Failed to add seat0: %m");
1126
1127 r = manager_set_lid_switch_ignore(m, 0 + m->holdoff_timeout_usec);
1128 if (r < 0)
1129 log_warning_errno(r, "Failed to set up lid switch ignore event source: %m");
1130
1131 /* Deserialize state */
1132 r = manager_enumerate_devices(m);
1133 if (r < 0)
1134 log_warning_errno(r, "Device enumeration failed: %m");
1135
1136 r = manager_enumerate_seats(m);
1137 if (r < 0)
1138 log_warning_errno(r, "Seat enumeration failed: %m");
1139
1140 r = manager_enumerate_users(m);
1141 if (r < 0)
1142 log_warning_errno(r, "User enumeration failed: %m");
1143
1144 r = manager_enumerate_sessions(m);
1145 if (r < 0)
1146 log_warning_errno(r, "Session enumeration failed: %m");
1147
1148 r = manager_enumerate_inhibitors(m);
1149 if (r < 0)
1150 log_warning_errno(r, "Inhibitor enumeration failed: %m");
1151
1152 r = manager_enumerate_buttons(m);
1153 if (r < 0)
1154 log_warning_errno(r, "Button enumeration failed: %m");
1155
1156 manager_load_scheduled_shutdown(m);
1157
1158 /* Remove stale objects before we start them */
1159 manager_gc(m, false);
1160
1161 /* Reserve the special reserved VT */
1162 manager_reserve_vt(m);
1163
1164 /* Read in utmp if it exists */
1165 manager_read_utmp(m);
1166
1167 /* And start everything */
1168 HASHMAP_FOREACH(seat, m->seats)
1169 (void) seat_start(seat);
1170
1171 HASHMAP_FOREACH(user, m->users)
1172 (void) user_start(user);
1173
1174 HASHMAP_FOREACH(session, m->sessions)
1175 (void) session_start(session, NULL, NULL);
1176
1177 HASHMAP_FOREACH(inhibitor, m->inhibitors) {
1178 (void) inhibitor_start(inhibitor);
1179
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);
1184 }
1185 }
1186
1187 HASHMAP_FOREACH(button, m->buttons)
1188 button_check_switches(button);
1189
1190 manager_dispatch_idle_action(NULL, 0, m);
1191
1192 return 0;
1193 }
1194
1195 static int manager_run(Manager *m) {
1196 int r;
1197
1198 assert(m);
1199
1200 for (;;) {
1201 r = sd_event_get_state(m->event);
1202 if (r < 0)
1203 return r;
1204 if (r == SD_EVENT_FINISHED)
1205 return 0;
1206
1207 manager_gc(m, true);
1208
1209 r = manager_dispatch_delayed(m, false);
1210 if (r < 0)
1211 return r;
1212 if (r > 0)
1213 continue;
1214
1215 r = sd_event_run(m->event, UINT64_MAX);
1216 if (r < 0)
1217 return r;
1218 }
1219 }
1220
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;
1224 int r;
1225
1226 log_set_facility(LOG_AUTH);
1227 log_setup();
1228
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),
1233 argc, argv);
1234 if (r <= 0)
1235 return r;
1236
1237 umask(0022);
1238
1239 r = mac_init();
1240 if (r < 0)
1241 return r;
1242
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);
1249
1250 assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGHUP, SIGTERM, SIGINT, SIGCHLD, SIGRTMIN+18) >= 0);
1251
1252 r = manager_new(&m);
1253 if (r < 0)
1254 return log_error_errno(r, "Failed to allocate manager object: %m");
1255
1256 (void) manager_parse_config_file(m);
1257
1258 r = manager_startup(m);
1259 if (r < 0)
1260 return log_error_errno(r, "Failed to fully start up daemon: %m");
1261
1262 notify_message = notify_start(NOTIFY_READY, NOTIFY_STOPPING);
1263 return manager_run(m);
1264 }
1265
1266 DEFINE_MAIN_FUNCTION(run);