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 "daemon-util.h"
18 #include "def.h"
19 #include "device-util.h"
20 #include "dirent-util.h"
21 #include "fd-util.h"
22 #include "format-util.h"
23 #include "fs-util.h"
24 #include "logind-dbus.h"
25 #include "logind-seat-dbus.h"
26 #include "logind-session-dbus.h"
27 #include "logind-user-dbus.h"
28 #include "logind.h"
29 #include "main-func.h"
30 #include "mkdir-label.h"
31 #include "parse-util.h"
32 #include "process-util.h"
33 #include "selinux-util.h"
34 #include "service-util.h"
35 #include "signal-util.h"
36 #include "strv.h"
37 #include "terminal-util.h"
38 #include "udev-util.h"
39 #include "user-util.h"
40
41 static Manager* manager_unref(Manager *m);
42 DEFINE_TRIVIAL_CLEANUP_FUNC(Manager*, manager_unref);
43
manager_new(Manager ** ret)44 static int manager_new(Manager **ret) {
45 _cleanup_(manager_unrefp) Manager *m = NULL;
46 int r;
47
48 assert(ret);
49
50 m = new(Manager, 1);
51 if (!m)
52 return -ENOMEM;
53
54 *m = (Manager) {
55 .console_active_fd = -1,
56 .reserve_vt_fd = -1,
57 .enable_wall_messages = true,
58 .idle_action_not_before_usec = now(CLOCK_MONOTONIC),
59 };
60
61 m->devices = hashmap_new(&string_hash_ops);
62 m->seats = hashmap_new(&string_hash_ops);
63 m->sessions = hashmap_new(&string_hash_ops);
64 m->sessions_by_leader = hashmap_new(NULL);
65 m->users = hashmap_new(NULL);
66 m->inhibitors = hashmap_new(&string_hash_ops);
67 m->buttons = hashmap_new(&string_hash_ops);
68
69 m->user_units = hashmap_new(&string_hash_ops);
70 m->session_units = hashmap_new(&string_hash_ops);
71
72 if (!m->devices || !m->seats || !m->sessions || !m->sessions_by_leader || !m->users || !m->inhibitors || !m->buttons || !m->user_units || !m->session_units)
73 return -ENOMEM;
74
75 r = sd_event_default(&m->event);
76 if (r < 0)
77 return r;
78
79 r = sd_event_add_signal(m->event, NULL, SIGINT, NULL, NULL);
80 if (r < 0)
81 return r;
82
83 r = sd_event_add_signal(m->event, NULL, SIGTERM, NULL, NULL);
84 if (r < 0)
85 return r;
86
87 (void) sd_event_set_watchdog(m->event, true);
88
89 manager_reset_config(m);
90
91 *ret = TAKE_PTR(m);
92 return 0;
93 }
94
manager_unref(Manager * m)95 static Manager* manager_unref(Manager *m) {
96 Session *session;
97 User *u;
98 Device *d;
99 Seat *s;
100 Inhibitor *i;
101 Button *b;
102
103 if (!m)
104 return NULL;
105
106 while ((session = hashmap_first(m->sessions)))
107 session_free(session);
108
109 while ((u = hashmap_first(m->users)))
110 user_free(u);
111
112 while ((d = hashmap_first(m->devices)))
113 device_free(d);
114
115 while ((s = hashmap_first(m->seats)))
116 seat_free(s);
117
118 while ((i = hashmap_first(m->inhibitors)))
119 inhibitor_free(i);
120
121 while ((b = hashmap_first(m->buttons)))
122 button_free(b);
123
124 hashmap_free(m->devices);
125 hashmap_free(m->seats);
126 hashmap_free(m->sessions);
127 hashmap_free(m->sessions_by_leader);
128 hashmap_free(m->users);
129 hashmap_free(m->inhibitors);
130 hashmap_free(m->buttons);
131 hashmap_free(m->brightness_writers);
132
133 hashmap_free(m->user_units);
134 hashmap_free(m->session_units);
135
136 sd_event_source_unref(m->idle_action_event_source);
137 sd_event_source_unref(m->inhibit_timeout_source);
138 sd_event_source_unref(m->scheduled_shutdown_timeout_source);
139 sd_event_source_unref(m->nologin_timeout_source);
140 sd_event_source_unref(m->wall_message_timeout_source);
141
142 sd_event_source_unref(m->console_active_event_source);
143 sd_event_source_unref(m->lid_switch_ignore_event_source);
144
145 sd_event_source_unref(m->reboot_key_long_press_event_source);
146
147 #if ENABLE_UTMP
148 sd_event_source_unref(m->utmp_event_source);
149 #endif
150
151 safe_close(m->console_active_fd);
152
153 sd_device_monitor_unref(m->device_seat_monitor);
154 sd_device_monitor_unref(m->device_monitor);
155 sd_device_monitor_unref(m->device_vcsa_monitor);
156 sd_device_monitor_unref(m->device_button_monitor);
157
158 if (m->unlink_nologin)
159 (void) unlink_or_warn("/run/nologin");
160
161 bus_verify_polkit_async_registry_free(m->polkit_registry);
162
163 sd_bus_flush_close_unref(m->bus);
164 sd_event_unref(m->event);
165
166 safe_close(m->reserve_vt_fd);
167
168 strv_free(m->kill_only_users);
169 strv_free(m->kill_exclude_users);
170
171 free(m->scheduled_shutdown_tty);
172 free(m->wall_message);
173 free(m->action_job);
174
175 strv_free(m->efi_boot_loader_entries);
176 free(m->efi_loader_entry_one_shot);
177
178 return mfree(m);
179 }
180
manager_enumerate_devices(Manager * m)181 static int manager_enumerate_devices(Manager *m) {
182 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
183 sd_device *d;
184 int r;
185
186 assert(m);
187
188 /* Loads devices from udev and creates seats for them as
189 * necessary */
190
191 r = sd_device_enumerator_new(&e);
192 if (r < 0)
193 return r;
194
195 r = sd_device_enumerator_add_match_tag(e, "master-of-seat");
196 if (r < 0)
197 return r;
198
199 FOREACH_DEVICE(e, d) {
200 int k;
201
202 k = manager_process_seat_device(m, d);
203 if (k < 0)
204 r = k;
205 }
206
207 return r;
208 }
209
manager_enumerate_buttons(Manager * m)210 static int manager_enumerate_buttons(Manager *m) {
211 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
212 sd_device *d;
213 int r;
214
215 assert(m);
216
217 /* Loads buttons from udev */
218
219 if (manager_all_buttons_ignored(m))
220 return 0;
221
222 r = sd_device_enumerator_new(&e);
223 if (r < 0)
224 return r;
225
226 r = sd_device_enumerator_add_match_subsystem(e, "input", true);
227 if (r < 0)
228 return r;
229
230 r = sd_device_enumerator_add_match_tag(e, "power-switch");
231 if (r < 0)
232 return r;
233
234 FOREACH_DEVICE(e, d) {
235 int k;
236
237 k = manager_process_button_device(m, d);
238 if (k < 0)
239 r = k;
240 }
241
242 return r;
243 }
244
manager_enumerate_seats(Manager * m)245 static int manager_enumerate_seats(Manager *m) {
246 _cleanup_closedir_ DIR *d = NULL;
247 int r = 0;
248
249 assert(m);
250
251 /* This loads data about seats stored on disk, but does not
252 * actually create any seats. Removes data of seats that no
253 * longer exist. */
254
255 d = opendir("/run/systemd/seats");
256 if (!d) {
257 if (errno == ENOENT)
258 return 0;
259
260 return log_error_errno(errno, "Failed to open /run/systemd/seats: %m");
261 }
262
263 FOREACH_DIRENT(de, d, return -errno) {
264 Seat *s;
265 int k;
266
267 if (!dirent_is_file(de))
268 continue;
269
270 s = hashmap_get(m->seats, de->d_name);
271 if (!s) {
272 if (unlinkat(dirfd(d), de->d_name, 0) < 0)
273 log_warning_errno(errno, "Failed to remove /run/systemd/seats/%s, ignoring: %m",
274 de->d_name);
275 continue;
276 }
277
278 k = seat_load(s);
279 if (k < 0)
280 r = k;
281 }
282
283 return r;
284 }
285
manager_enumerate_linger_users(Manager * m)286 static int manager_enumerate_linger_users(Manager *m) {
287 _cleanup_closedir_ DIR *d = NULL;
288 int r = 0;
289
290 assert(m);
291
292 d = opendir("/var/lib/systemd/linger");
293 if (!d) {
294 if (errno == ENOENT)
295 return 0;
296
297 return log_error_errno(errno, "Failed to open /var/lib/systemd/linger/: %m");
298 }
299
300 FOREACH_DIRENT(de, d, return -errno) {
301 int k;
302
303 if (!dirent_is_file(de))
304 continue;
305
306 k = manager_add_user_by_name(m, de->d_name, NULL);
307 if (k < 0)
308 r = log_warning_errno(k, "Couldn't add lingering user %s, ignoring: %m", de->d_name);
309 }
310
311 return r;
312 }
313
manager_enumerate_users(Manager * m)314 static int manager_enumerate_users(Manager *m) {
315 _cleanup_closedir_ DIR *d = NULL;
316 int r, k;
317
318 assert(m);
319
320 /* Add lingering users */
321 r = manager_enumerate_linger_users(m);
322
323 /* Read in user data stored on disk */
324 d = opendir("/run/systemd/users");
325 if (!d) {
326 if (errno == ENOENT)
327 return 0;
328
329 return log_error_errno(errno, "Failed to open /run/systemd/users: %m");
330 }
331
332 FOREACH_DIRENT(de, d, return -errno) {
333 User *u;
334 uid_t uid;
335
336 if (!dirent_is_file(de))
337 continue;
338
339 k = parse_uid(de->d_name, &uid);
340 if (k < 0) {
341 r = log_warning_errno(k, "Failed to parse filename /run/systemd/users/%s as UID.", de->d_name);
342 continue;
343 }
344
345 k = manager_add_user_by_uid(m, uid, &u);
346 if (k < 0) {
347 r = log_warning_errno(k, "Failed to add user by file name %s, ignoring: %m", de->d_name);
348 continue;
349 }
350
351 user_add_to_gc_queue(u);
352
353 k = user_load(u);
354 if (k < 0)
355 r = k;
356 }
357
358 return r;
359 }
360
parse_fdname(const char * fdname,char ** session_id,dev_t * dev)361 static int parse_fdname(const char *fdname, char **session_id, dev_t *dev) {
362 _cleanup_strv_free_ char **parts = NULL;
363 _cleanup_free_ char *id = NULL;
364 unsigned major, minor;
365 int r;
366
367 parts = strv_split(fdname, "-");
368 if (!parts)
369 return -ENOMEM;
370 if (strv_length(parts) != 5)
371 return -EINVAL;
372
373 if (!streq(parts[0], "session"))
374 return -EINVAL;
375
376 id = strdup(parts[1]);
377 if (!id)
378 return -ENOMEM;
379
380 if (!streq(parts[2], "device"))
381 return -EINVAL;
382
383 r = safe_atou(parts[3], &major);
384 if (r < 0)
385 return r;
386 r = safe_atou(parts[4], &minor);
387 if (r < 0)
388 return r;
389
390 *dev = makedev(major, minor);
391 *session_id = TAKE_PTR(id);
392
393 return 0;
394 }
395
deliver_fd(Manager * m,const char * fdname,int fd)396 static int deliver_fd(Manager *m, const char *fdname, int fd) {
397 _cleanup_free_ char *id = NULL;
398 SessionDevice *sd;
399 struct stat st;
400 Session *s;
401 dev_t dev;
402 int r;
403
404 assert(m);
405 assert(fd >= 0);
406
407 r = parse_fdname(fdname, &id, &dev);
408 if (r < 0)
409 return log_debug_errno(r, "Failed to parse fd name %s: %m", fdname);
410
411 s = hashmap_get(m->sessions, id);
412 if (!s)
413 /* If the session doesn't exist anymore, the associated session device attached to this fd
414 * doesn't either. Let's simply close this fd. */
415 return log_debug_errno(SYNTHETIC_ERRNO(ENXIO), "Failed to attach fd for unknown session: %s", id);
416
417 if (fstat(fd, &st) < 0)
418 /* The device is allowed to go away at a random point, in which case fstat() failing is
419 * expected. */
420 return log_debug_errno(errno, "Failed to stat device fd for session %s: %m", id);
421
422 if (!S_ISCHR(st.st_mode) || st.st_rdev != dev)
423 return log_debug_errno(SYNTHETIC_ERRNO(ENODEV), "Device fd doesn't point to the expected character device node");
424
425 sd = hashmap_get(s->devices, &dev);
426 if (!sd)
427 /* Weird, we got an fd for a session device which wasn't recorded in the session state
428 * file... */
429 return log_warning_errno(SYNTHETIC_ERRNO(ENODEV), "Got fd for missing session device [%u:%u] in session %s",
430 major(dev), minor(dev), s->id);
431
432 log_debug("Attaching fd to session device [%u:%u] for session %s",
433 major(dev), minor(dev), s->id);
434
435 session_device_attach_fd(sd, fd, s->was_active);
436 return 0;
437 }
438
manager_attach_fds(Manager * m)439 static int manager_attach_fds(Manager *m) {
440 _cleanup_strv_free_ char **fdnames = NULL;
441 int r, n;
442
443 /* Upon restart, PID1 will send us back all fds of session devices that we previously opened. Each
444 * file descriptor is associated with a given session. The session ids are passed through FDNAMES. */
445
446 n = sd_listen_fds_with_names(true, &fdnames);
447 if (n < 0)
448 return log_warning_errno(n, "Failed to acquire passed fd list: %m");
449 if (n == 0)
450 return 0;
451
452 for (int i = 0; i < n; i++) {
453 int fd = SD_LISTEN_FDS_START + i;
454
455 if (deliver_fd(m, fdnames[i], fd) >= 0)
456 continue;
457
458 /* Hmm, we couldn't deliver the fd to any session device object? If so, let's close the fd */
459 safe_close(fd);
460
461 /* Remove from fdstore as well */
462 r = sd_notifyf(false,
463 "FDSTOREREMOVE=1\n"
464 "FDNAME=%s", fdnames[i]);
465 if (r < 0)
466 log_warning_errno(r, "Failed to remove file descriptor from the store, ignoring: %m");
467 }
468
469 return 0;
470 }
471
manager_enumerate_sessions(Manager * m)472 static int manager_enumerate_sessions(Manager *m) {
473 _cleanup_closedir_ DIR *d = NULL;
474 int r = 0, k;
475
476 assert(m);
477
478 /* Read in session data stored on disk */
479 d = opendir("/run/systemd/sessions");
480 if (!d) {
481 if (errno == ENOENT)
482 return 0;
483
484 return log_error_errno(errno, "Failed to open /run/systemd/sessions: %m");
485 }
486
487 FOREACH_DIRENT(de, d, return -errno) {
488 struct Session *s;
489
490 if (!dirent_is_file(de))
491 continue;
492
493 k = manager_add_session(m, de->d_name, &s);
494 if (k < 0) {
495 r = log_warning_errno(k, "Failed to add session by file name %s, ignoring: %m", de->d_name);
496 continue;
497 }
498
499 session_add_to_gc_queue(s);
500
501 k = session_load(s);
502 if (k < 0)
503 r = k;
504 }
505
506 /* We might be restarted and PID1 could have sent us back the session device fds we previously
507 * saved. */
508 (void) manager_attach_fds(m);
509
510 return r;
511 }
512
manager_enumerate_inhibitors(Manager * m)513 static int manager_enumerate_inhibitors(Manager *m) {
514 _cleanup_closedir_ DIR *d = NULL;
515 int r = 0;
516
517 assert(m);
518
519 d = opendir("/run/systemd/inhibit");
520 if (!d) {
521 if (errno == ENOENT)
522 return 0;
523
524 return log_error_errno(errno, "Failed to open /run/systemd/inhibit: %m");
525 }
526
527 FOREACH_DIRENT(de, d, return -errno) {
528 int k;
529 Inhibitor *i;
530
531 if (!dirent_is_file(de))
532 continue;
533
534 k = manager_add_inhibitor(m, de->d_name, &i);
535 if (k < 0) {
536 r = log_warning_errno(k, "Couldn't add inhibitor %s, ignoring: %m", de->d_name);
537 continue;
538 }
539
540 k = inhibitor_load(i);
541 if (k < 0)
542 r = k;
543 }
544
545 return r;
546 }
547
manager_dispatch_seat_udev(sd_device_monitor * monitor,sd_device * device,void * userdata)548 static int manager_dispatch_seat_udev(sd_device_monitor *monitor, sd_device *device, void *userdata) {
549 Manager *m = userdata;
550
551 assert(m);
552 assert(device);
553
554 manager_process_seat_device(m, device);
555 return 0;
556 }
557
manager_dispatch_device_udev(sd_device_monitor * monitor,sd_device * device,void * userdata)558 static int manager_dispatch_device_udev(sd_device_monitor *monitor, sd_device *device, void *userdata) {
559 Manager *m = userdata;
560
561 assert(m);
562 assert(device);
563
564 manager_process_seat_device(m, device);
565 return 0;
566 }
567
manager_dispatch_vcsa_udev(sd_device_monitor * monitor,sd_device * device,void * userdata)568 static int manager_dispatch_vcsa_udev(sd_device_monitor *monitor, sd_device *device, void *userdata) {
569 Manager *m = userdata;
570 const char *name;
571
572 assert(m);
573 assert(device);
574
575 /* Whenever a VCSA device is removed try to reallocate our
576 * VTs, to make sure our auto VTs never go away. */
577
578 if (sd_device_get_sysname(device, &name) >= 0 &&
579 startswith(name, "vcsa") &&
580 device_for_action(device, SD_DEVICE_REMOVE))
581 seat_preallocate_vts(m->seat0);
582
583 return 0;
584 }
585
manager_dispatch_button_udev(sd_device_monitor * monitor,sd_device * device,void * userdata)586 static int manager_dispatch_button_udev(sd_device_monitor *monitor, sd_device *device, void *userdata) {
587 Manager *m = userdata;
588
589 assert(m);
590 assert(device);
591
592 manager_process_button_device(m, device);
593 return 0;
594 }
595
manager_dispatch_console(sd_event_source * s,int fd,uint32_t revents,void * userdata)596 static int manager_dispatch_console(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
597 Manager *m = userdata;
598
599 assert(m);
600 assert(m->seat0);
601 assert(m->console_active_fd == fd);
602
603 seat_read_active_vt(m->seat0);
604 return 0;
605 }
606
manager_reserve_vt(Manager * m)607 static int manager_reserve_vt(Manager *m) {
608 _cleanup_free_ char *p = NULL;
609
610 assert(m);
611
612 if (m->reserve_vt <= 0)
613 return 0;
614
615 if (asprintf(&p, "/dev/tty%u", m->reserve_vt) < 0)
616 return log_oom();
617
618 m->reserve_vt_fd = open(p, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
619 if (m->reserve_vt_fd < 0) {
620
621 /* Don't complain on VT-less systems */
622 if (errno != ENOENT)
623 log_warning_errno(errno, "Failed to pin reserved VT: %m");
624 return -errno;
625 }
626
627 return 0;
628 }
629
manager_connect_bus(Manager * m)630 static int manager_connect_bus(Manager *m) {
631 int r;
632
633 assert(m);
634 assert(!m->bus);
635
636 r = sd_bus_default_system(&m->bus);
637 if (r < 0)
638 return log_error_errno(r, "Failed to connect to system bus: %m");
639
640 r = bus_add_implementation(m->bus, &manager_object, m);
641 if (r < 0)
642 return r;
643
644 r = bus_log_control_api_register(m->bus);
645 if (r < 0)
646 return r;
647
648 r = bus_match_signal_async(m->bus, NULL, bus_systemd_mgr, "JobRemoved", match_job_removed, NULL, m);
649 if (r < 0)
650 return log_error_errno(r, "Failed to request match for JobRemoved: %m");
651
652 r = bus_match_signal_async(m->bus, NULL, bus_systemd_mgr, "UnitRemoved", match_unit_removed, NULL, m);
653 if (r < 0)
654 return log_error_errno(r, "Failed to request match for UnitRemoved: %m");
655
656 r = sd_bus_match_signal_async(
657 m->bus,
658 NULL,
659 "org.freedesktop.systemd1",
660 NULL,
661 "org.freedesktop.DBus.Properties",
662 "PropertiesChanged",
663 match_properties_changed, NULL, m);
664 if (r < 0)
665 return log_error_errno(r, "Failed to request match for PropertiesChanged: %m");
666
667 r = bus_match_signal_async(m->bus, NULL, bus_systemd_mgr, "Reloading", match_reloading, NULL, m);
668 if (r < 0)
669 return log_error_errno(r, "Failed to request match for Reloading: %m");
670
671 r = bus_call_method_async(m->bus, NULL, bus_systemd_mgr, "Subscribe", NULL, NULL, NULL);
672 if (r < 0)
673 return log_error_errno(r, "Failed to enable subscription: %m");
674
675 r = sd_bus_request_name_async(m->bus, NULL, "org.freedesktop.login1", 0, NULL, NULL);
676 if (r < 0)
677 return log_error_errno(r, "Failed to request name: %m");
678
679 r = sd_bus_attach_event(m->bus, m->event, SD_EVENT_PRIORITY_NORMAL);
680 if (r < 0)
681 return log_error_errno(r, "Failed to attach bus to event loop: %m");
682
683 return 0;
684 }
685
manager_vt_switch(sd_event_source * src,const struct signalfd_siginfo * si,void * data)686 static int manager_vt_switch(sd_event_source *src, const struct signalfd_siginfo *si, void *data) {
687 Manager *m = data;
688 Session *active;
689
690 /*
691 * We got a VT-switch signal and we have to acknowledge it immediately.
692 * Preferably, we'd just use m->seat0->active->vtfd, but unfortunately,
693 * old user-space might run multiple sessions on a single VT, *sigh*.
694 * Therefore, we have to iterate all sessions and find one with a vtfd
695 * on the requested VT.
696 * As only VTs with active controllers have VT_PROCESS set, our current
697 * notion of the active VT might be wrong (for instance if the switch
698 * happens while we setup VT_PROCESS). Therefore, read the current VT
699 * first and then use s->active->vtnr as reference. Note that this is
700 * not racy, as no further VT-switch can happen as long as we're in
701 * synchronous VT_PROCESS mode.
702 */
703
704 assert(m->seat0);
705 seat_read_active_vt(m->seat0);
706
707 active = m->seat0->active;
708 if (!active || active->vtnr < 1) {
709 _cleanup_close_ int fd = -1;
710 int r;
711
712 /* We are requested to acknowledge the VT-switch signal by the kernel but
713 * there's no registered sessions for the current VT. Normally this
714 * shouldn't happen but something wrong might have happened when we tried
715 * to release the VT. Better be safe than sorry, and try to release the VT
716 * one more time otherwise the user will be locked with the current VT. */
717
718 log_warning("Received VT_PROCESS signal without a registered session, restoring VT.");
719
720 /* At this point we only have the kernel mapping for referring to the
721 * current VT. */
722 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
723 if (fd < 0) {
724 log_warning_errno(fd, "Failed to open, ignoring: %m");
725 return 0;
726 }
727
728 r = vt_release(fd, true);
729 if (r < 0)
730 log_warning_errno(r, "Failed to release VT, ignoring: %m");
731
732 return 0;
733 }
734
735 if (active->vtfd >= 0)
736 session_leave_vt(active);
737 else
738 LIST_FOREACH(sessions_by_seat, iter, m->seat0->sessions)
739 if (iter->vtnr == active->vtnr && iter->vtfd >= 0) {
740 session_leave_vt(iter);
741 break;
742 }
743
744 return 0;
745 }
746
manager_connect_console(Manager * m)747 static int manager_connect_console(Manager *m) {
748 int r;
749
750 assert(m);
751 assert(m->console_active_fd < 0);
752
753 /* On certain systems (such as S390, Xen, and containers) /dev/tty0 does not exist (as there is no VC), so
754 * don't fail if we can't open it. */
755
756 if (access("/dev/tty0", F_OK) < 0)
757 return 0;
758
759 m->console_active_fd = open("/sys/class/tty/tty0/active", O_RDONLY|O_NOCTTY|O_CLOEXEC);
760 if (m->console_active_fd < 0) {
761
762 /* On some systems /dev/tty0 may exist even though /sys/class/tty/tty0 does not. These are broken, but
763 * common. Let's complain but continue anyway. */
764 if (errno == ENOENT) {
765 log_warning_errno(errno, "System has /dev/tty0 but not /sys/class/tty/tty0/active which is broken, ignoring: %m");
766 return 0;
767 }
768
769 return log_error_errno(errno, "Failed to open /sys/class/tty/tty0/active: %m");
770 }
771
772 r = sd_event_add_io(m->event, &m->console_active_event_source, m->console_active_fd, 0, manager_dispatch_console, m);
773 if (r < 0)
774 return log_error_errno(r, "Failed to watch foreground console: %m");
775
776 /*
777 * SIGRTMIN is used as global VT-release signal, SIGRTMIN + 1 is used
778 * as VT-acquire signal. We ignore any acquire-events (yes, we still
779 * have to provide a valid signal-number for it!) and acknowledge all
780 * release events immediately.
781 */
782
783 if (SIGRTMIN + 1 > SIGRTMAX)
784 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
785 "Not enough real-time signals available: %u-%u",
786 SIGRTMIN, SIGRTMAX);
787
788 assert_se(ignore_signals(SIGRTMIN + 1) >= 0);
789 assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGRTMIN, -1) >= 0);
790
791 r = sd_event_add_signal(m->event, NULL, SIGRTMIN, manager_vt_switch, m);
792 if (r < 0)
793 return log_error_errno(r, "Failed to subscribe to signal: %m");
794
795 return 0;
796 }
797
manager_connect_udev(Manager * m)798 static int manager_connect_udev(Manager *m) {
799 int r;
800
801 assert(m);
802 assert(!m->device_seat_monitor);
803 assert(!m->device_monitor);
804 assert(!m->device_vcsa_monitor);
805 assert(!m->device_button_monitor);
806
807 r = sd_device_monitor_new(&m->device_seat_monitor);
808 if (r < 0)
809 return r;
810
811 r = sd_device_monitor_filter_add_match_tag(m->device_seat_monitor, "master-of-seat");
812 if (r < 0)
813 return r;
814
815 r = sd_device_monitor_attach_event(m->device_seat_monitor, m->event);
816 if (r < 0)
817 return r;
818
819 r = sd_device_monitor_start(m->device_seat_monitor, manager_dispatch_seat_udev, m);
820 if (r < 0)
821 return r;
822
823 (void) sd_event_source_set_description(sd_device_monitor_get_event_source(m->device_seat_monitor), "logind-seat-monitor");
824
825 r = sd_device_monitor_new(&m->device_monitor);
826 if (r < 0)
827 return r;
828
829 r = sd_device_monitor_filter_add_match_subsystem_devtype(m->device_monitor, "input", NULL);
830 if (r < 0)
831 return r;
832
833 r = sd_device_monitor_filter_add_match_subsystem_devtype(m->device_monitor, "graphics", NULL);
834 if (r < 0)
835 return r;
836
837 r = sd_device_monitor_filter_add_match_subsystem_devtype(m->device_monitor, "drm", NULL);
838 if (r < 0)
839 return r;
840
841 r = sd_device_monitor_attach_event(m->device_monitor, m->event);
842 if (r < 0)
843 return r;
844
845 r = sd_device_monitor_start(m->device_monitor, manager_dispatch_device_udev, m);
846 if (r < 0)
847 return r;
848
849 (void) sd_event_source_set_description(sd_device_monitor_get_event_source(m->device_monitor), "logind-device-monitor");
850
851 /* Don't watch keys if nobody cares */
852 if (!manager_all_buttons_ignored(m)) {
853 r = sd_device_monitor_new(&m->device_button_monitor);
854 if (r < 0)
855 return r;
856
857 r = sd_device_monitor_filter_add_match_tag(m->device_button_monitor, "power-switch");
858 if (r < 0)
859 return r;
860
861 r = sd_device_monitor_filter_add_match_subsystem_devtype(m->device_button_monitor, "input", NULL);
862 if (r < 0)
863 return r;
864
865 r = sd_device_monitor_attach_event(m->device_button_monitor, m->event);
866 if (r < 0)
867 return r;
868
869 r = sd_device_monitor_start(m->device_button_monitor, manager_dispatch_button_udev, m);
870 if (r < 0)
871 return r;
872
873 (void) sd_event_source_set_description(sd_device_monitor_get_event_source(m->device_button_monitor), "logind-button-monitor");
874 }
875
876 /* Don't bother watching VCSA devices, if nobody cares */
877 if (m->n_autovts > 0 && m->console_active_fd >= 0) {
878
879 r = sd_device_monitor_new(&m->device_vcsa_monitor);
880 if (r < 0)
881 return r;
882
883 r = sd_device_monitor_filter_add_match_subsystem_devtype(m->device_vcsa_monitor, "vc", NULL);
884 if (r < 0)
885 return r;
886
887 r = sd_device_monitor_attach_event(m->device_vcsa_monitor, m->event);
888 if (r < 0)
889 return r;
890
891 r = sd_device_monitor_start(m->device_vcsa_monitor, manager_dispatch_vcsa_udev, m);
892 if (r < 0)
893 return r;
894
895 (void) sd_event_source_set_description(sd_device_monitor_get_event_source(m->device_vcsa_monitor), "logind-vcsa-monitor");
896 }
897
898 return 0;
899 }
900
manager_gc(Manager * m,bool drop_not_started)901 static void manager_gc(Manager *m, bool drop_not_started) {
902 Seat *seat;
903 Session *session;
904 User *user;
905
906 assert(m);
907
908 while ((seat = m->seat_gc_queue)) {
909 LIST_REMOVE(gc_queue, m->seat_gc_queue, seat);
910 seat->in_gc_queue = false;
911
912 if (seat_may_gc(seat, drop_not_started)) {
913 seat_stop(seat, /* force = */ false);
914 seat_free(seat);
915 }
916 }
917
918 while ((session = m->session_gc_queue)) {
919 LIST_REMOVE(gc_queue, m->session_gc_queue, session);
920 session->in_gc_queue = false;
921
922 /* First, if we are not closing yet, initiate stopping. */
923 if (session_may_gc(session, drop_not_started) &&
924 session_get_state(session) != SESSION_CLOSING)
925 (void) session_stop(session, /* force = */ false);
926
927 /* Normally, this should make the session referenced again, if it doesn't then let's get rid
928 * of it immediately. */
929 if (session_may_gc(session, drop_not_started)) {
930 (void) session_finalize(session);
931 session_free(session);
932 }
933 }
934
935 while ((user = m->user_gc_queue)) {
936 LIST_REMOVE(gc_queue, m->user_gc_queue, user);
937 user->in_gc_queue = false;
938
939 /* First step: queue stop jobs */
940 if (user_may_gc(user, drop_not_started))
941 (void) user_stop(user, false);
942
943 /* Second step: finalize user */
944 if (user_may_gc(user, drop_not_started)) {
945 (void) user_finalize(user);
946 user_free(user);
947 }
948 }
949 }
950
manager_dispatch_idle_action(sd_event_source * s,uint64_t t,void * userdata)951 static int manager_dispatch_idle_action(sd_event_source *s, uint64_t t, void *userdata) {
952 Manager *m = userdata;
953 struct dual_timestamp since;
954 usec_t n, elapse;
955 int r;
956
957 assert(m);
958
959 if (m->idle_action == HANDLE_IGNORE ||
960 m->idle_action_usec <= 0)
961 return 0;
962
963 n = now(CLOCK_MONOTONIC);
964
965 r = manager_get_idle_hint(m, &since);
966 if (r <= 0)
967 /* Not idle. Let's check if after a timeout it might be idle then. */
968 elapse = n + m->idle_action_usec;
969 else {
970 /* Idle! Let's see if it's time to do something, or if
971 * we shall sleep for longer. */
972
973 if (n >= since.monotonic + m->idle_action_usec &&
974 (m->idle_action_not_before_usec <= 0 || n >= m->idle_action_not_before_usec + m->idle_action_usec)) {
975 log_info("System idle. Doing %s operation.", handle_action_to_string(m->idle_action));
976
977 manager_handle_action(m, 0, m->idle_action, false, false);
978 m->idle_action_not_before_usec = n;
979 }
980
981 elapse = MAX(since.monotonic, m->idle_action_not_before_usec) + m->idle_action_usec;
982 }
983
984 if (!m->idle_action_event_source) {
985
986 r = sd_event_add_time(
987 m->event,
988 &m->idle_action_event_source,
989 CLOCK_MONOTONIC,
990 elapse, USEC_PER_SEC*30,
991 manager_dispatch_idle_action, m);
992 if (r < 0)
993 return log_error_errno(r, "Failed to add idle event source: %m");
994
995 r = sd_event_source_set_priority(m->idle_action_event_source, SD_EVENT_PRIORITY_IDLE+10);
996 if (r < 0)
997 return log_error_errno(r, "Failed to set idle event source priority: %m");
998 } else {
999 r = sd_event_source_set_time(m->idle_action_event_source, elapse);
1000 if (r < 0)
1001 return log_error_errno(r, "Failed to set idle event timer: %m");
1002
1003 r = sd_event_source_set_enabled(m->idle_action_event_source, SD_EVENT_ONESHOT);
1004 if (r < 0)
1005 return log_error_errno(r, "Failed to enable idle event timer: %m");
1006 }
1007
1008 return 0;
1009 }
1010
manager_dispatch_reload_signal(sd_event_source * s,const struct signalfd_siginfo * si,void * userdata)1011 static int manager_dispatch_reload_signal(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
1012 Manager *m = userdata;
1013 int r;
1014
1015 manager_reset_config(m);
1016 r = manager_parse_config_file(m);
1017 if (r < 0)
1018 log_warning_errno(r, "Failed to parse config file, using defaults: %m");
1019 else
1020 log_info("Config file reloaded.");
1021
1022 return 0;
1023 }
1024
manager_startup(Manager * m)1025 static int manager_startup(Manager *m) {
1026 int r;
1027 Seat *seat;
1028 Session *session;
1029 User *user;
1030 Button *button;
1031 Inhibitor *inhibitor;
1032
1033 assert(m);
1034
1035 r = sd_event_add_signal(m->event, NULL, SIGHUP, manager_dispatch_reload_signal, m);
1036 if (r < 0)
1037 return log_error_errno(r, "Failed to register SIGHUP handler: %m");
1038
1039 /* Connect to utmp */
1040 manager_connect_utmp(m);
1041
1042 /* Connect to console */
1043 r = manager_connect_console(m);
1044 if (r < 0)
1045 return r;
1046
1047 /* Connect to udev */
1048 r = manager_connect_udev(m);
1049 if (r < 0)
1050 return log_error_errno(r, "Failed to create udev watchers: %m");
1051
1052 /* Connect to the bus */
1053 r = manager_connect_bus(m);
1054 if (r < 0)
1055 return r;
1056
1057 /* Instantiate magic seat 0 */
1058 r = manager_add_seat(m, "seat0", &m->seat0);
1059 if (r < 0)
1060 return log_error_errno(r, "Failed to add seat0: %m");
1061
1062 r = manager_set_lid_switch_ignore(m, 0 + m->holdoff_timeout_usec);
1063 if (r < 0)
1064 log_warning_errno(r, "Failed to set up lid switch ignore event source: %m");
1065
1066 /* Deserialize state */
1067 r = manager_enumerate_devices(m);
1068 if (r < 0)
1069 log_warning_errno(r, "Device enumeration failed: %m");
1070
1071 r = manager_enumerate_seats(m);
1072 if (r < 0)
1073 log_warning_errno(r, "Seat enumeration failed: %m");
1074
1075 r = manager_enumerate_users(m);
1076 if (r < 0)
1077 log_warning_errno(r, "User enumeration failed: %m");
1078
1079 r = manager_enumerate_sessions(m);
1080 if (r < 0)
1081 log_warning_errno(r, "Session enumeration failed: %m");
1082
1083 r = manager_enumerate_inhibitors(m);
1084 if (r < 0)
1085 log_warning_errno(r, "Inhibitor enumeration failed: %m");
1086
1087 r = manager_enumerate_buttons(m);
1088 if (r < 0)
1089 log_warning_errno(r, "Button enumeration failed: %m");
1090
1091 manager_load_scheduled_shutdown(m);
1092
1093 /* Remove stale objects before we start them */
1094 manager_gc(m, false);
1095
1096 /* Reserve the special reserved VT */
1097 manager_reserve_vt(m);
1098
1099 /* Read in utmp if it exists */
1100 manager_read_utmp(m);
1101
1102 /* And start everything */
1103 HASHMAP_FOREACH(seat, m->seats)
1104 (void) seat_start(seat);
1105
1106 HASHMAP_FOREACH(user, m->users)
1107 (void) user_start(user);
1108
1109 HASHMAP_FOREACH(session, m->sessions)
1110 (void) session_start(session, NULL, NULL);
1111
1112 HASHMAP_FOREACH(inhibitor, m->inhibitors) {
1113 (void) inhibitor_start(inhibitor);
1114
1115 /* Let's see if the inhibitor is dead now, then remove it */
1116 if (inhibitor_is_orphan(inhibitor)) {
1117 inhibitor_stop(inhibitor);
1118 inhibitor_free(inhibitor);
1119 }
1120 }
1121
1122 HASHMAP_FOREACH(button, m->buttons)
1123 button_check_switches(button);
1124
1125 manager_dispatch_idle_action(NULL, 0, m);
1126
1127 return 0;
1128 }
1129
manager_run(Manager * m)1130 static int manager_run(Manager *m) {
1131 int r;
1132
1133 assert(m);
1134
1135 for (;;) {
1136 r = sd_event_get_state(m->event);
1137 if (r < 0)
1138 return r;
1139 if (r == SD_EVENT_FINISHED)
1140 return 0;
1141
1142 manager_gc(m, true);
1143
1144 r = manager_dispatch_delayed(m, false);
1145 if (r < 0)
1146 return r;
1147 if (r > 0)
1148 continue;
1149
1150 r = sd_event_run(m->event, UINT64_MAX);
1151 if (r < 0)
1152 return r;
1153 }
1154 }
1155
run(int argc,char * argv[])1156 static int run(int argc, char *argv[]) {
1157 _cleanup_(manager_unrefp) Manager *m = NULL;
1158 _unused_ _cleanup_(notify_on_cleanup) const char *notify_message = NULL;
1159 int r;
1160
1161 log_set_facility(LOG_AUTH);
1162 log_setup();
1163
1164 r = service_parse_argv("systemd-logind.service",
1165 "Manager for user logins and devices and privileged operations.",
1166 BUS_IMPLEMENTATIONS(&manager_object,
1167 &log_control_object),
1168 argc, argv);
1169 if (r <= 0)
1170 return r;
1171
1172 umask(0022);
1173
1174 r = mac_selinux_init();
1175 if (r < 0)
1176 return r;
1177
1178 /* Always create the directories people can create inotify watches in. Note that some applications
1179 * might check for the existence of /run/systemd/seats/ to determine whether logind is available, so
1180 * please always make sure these directories are created early on and unconditionally. */
1181 (void) mkdir_label("/run/systemd/seats", 0755);
1182 (void) mkdir_label("/run/systemd/users", 0755);
1183 (void) mkdir_label("/run/systemd/sessions", 0755);
1184
1185 assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGHUP, SIGTERM, SIGINT, SIGCHLD, -1) >= 0);
1186
1187 r = manager_new(&m);
1188 if (r < 0)
1189 return log_error_errno(r, "Failed to allocate manager object: %m");
1190
1191 (void) manager_parse_config_file(m);
1192
1193 r = manager_startup(m);
1194 if (r < 0)
1195 return log_error_errno(r, "Failed to fully start up daemon: %m");
1196
1197 notify_message = notify_start(NOTIFY_READY, NOTIFY_STOPPING);
1198 return manager_run(m);
1199 }
1200
1201 DEFINE_MAIN_FUNCTION(run);
1202