]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/login/logind-core.c
Merge pull request #13909 from poettering/env-copy-pid
[thirdparty/systemd.git] / src / login / logind-core.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <fcntl.h>
4 #include <pwd.h>
5 #include <sys/ioctl.h>
6 #include <sys/types.h>
7 #include <linux/vt.h>
8 #if ENABLE_UTMP
9 #include <utmpx.h>
10 #endif
11
12 #include "sd-device.h"
13
14 #include "alloc-util.h"
15 #include "bus-error.h"
16 #include "bus-util.h"
17 #include "cgroup-util.h"
18 #include "conf-parser.h"
19 #include "device-util.h"
20 #include "errno-util.h"
21 #include "fd-util.h"
22 #include "limits-util.h"
23 #include "logind.h"
24 #include "parse-util.h"
25 #include "path-util.h"
26 #include "process-util.h"
27 #include "strv.h"
28 #include "terminal-util.h"
29 #include "udev-util.h"
30 #include "user-util.h"
31
32 void manager_reset_config(Manager *m) {
33 assert(m);
34
35 m->n_autovts = 6;
36 m->reserve_vt = 6;
37 m->remove_ipc = true;
38 m->inhibit_delay_max = 5 * USEC_PER_SEC;
39 m->user_stop_delay = 10 * USEC_PER_SEC;
40
41 m->handle_power_key = HANDLE_POWEROFF;
42 m->handle_suspend_key = HANDLE_SUSPEND;
43 m->handle_hibernate_key = HANDLE_HIBERNATE;
44 m->handle_lid_switch = HANDLE_SUSPEND;
45 m->handle_lid_switch_ep = _HANDLE_ACTION_INVALID;
46 m->handle_lid_switch_docked = HANDLE_IGNORE;
47 m->power_key_ignore_inhibited = false;
48 m->suspend_key_ignore_inhibited = false;
49 m->hibernate_key_ignore_inhibited = false;
50 m->lid_switch_ignore_inhibited = true;
51
52 m->holdoff_timeout_usec = 30 * USEC_PER_SEC;
53
54 m->idle_action_usec = 30 * USEC_PER_MINUTE;
55 m->idle_action = HANDLE_IGNORE;
56
57 m->runtime_dir_size = physical_memory_scale(10U, 100U); /* 10% */
58 m->user_tasks_max = system_tasks_max_scale(DEFAULT_USER_TASKS_MAX_PERCENTAGE, 100U); /* 33% */
59 m->sessions_max = 8192;
60 m->inhibitors_max = 8192;
61
62 m->kill_user_processes = KILL_USER_PROCESSES;
63
64 m->kill_only_users = strv_free(m->kill_only_users);
65 m->kill_exclude_users = strv_free(m->kill_exclude_users);
66 }
67
68 int manager_parse_config_file(Manager *m) {
69 assert(m);
70
71 return config_parse_many_nulstr(PKGSYSCONFDIR "/logind.conf",
72 CONF_PATHS_NULSTR("systemd/logind.conf.d"),
73 "Login\0",
74 config_item_perf_lookup, logind_gperf_lookup,
75 CONFIG_PARSE_WARN, m);
76 }
77
78 int manager_add_device(Manager *m, const char *sysfs, bool master, Device **ret_device) {
79 Device *d;
80
81 assert(m);
82 assert(sysfs);
83
84 d = hashmap_get(m->devices, sysfs);
85 if (d)
86 /* we support adding master-flags, but not removing them */
87 d->master = d->master || master;
88 else {
89 d = device_new(m, sysfs, master);
90 if (!d)
91 return -ENOMEM;
92 }
93
94 if (ret_device)
95 *ret_device = d;
96
97 return 0;
98 }
99
100 int manager_add_seat(Manager *m, const char *id, Seat **ret_seat) {
101 Seat *s;
102 int r;
103
104 assert(m);
105 assert(id);
106
107 s = hashmap_get(m->seats, id);
108 if (!s) {
109 r = seat_new(&s, m, id);
110 if (r < 0)
111 return r;
112 }
113
114 if (ret_seat)
115 *ret_seat = s;
116
117 return 0;
118 }
119
120 int manager_add_session(Manager *m, const char *id, Session **ret_session) {
121 Session *s;
122 int r;
123
124 assert(m);
125 assert(id);
126
127 s = hashmap_get(m->sessions, id);
128 if (!s) {
129 r = session_new(&s, m, id);
130 if (r < 0)
131 return r;
132 }
133
134 if (ret_session)
135 *ret_session = s;
136
137 return 0;
138 }
139
140 int manager_add_user(
141 Manager *m,
142 uid_t uid,
143 gid_t gid,
144 const char *name,
145 const char *home,
146 User **ret_user) {
147
148 User *u;
149 int r;
150
151 assert(m);
152 assert(name);
153
154 u = hashmap_get(m->users, UID_TO_PTR(uid));
155 if (!u) {
156 r = user_new(&u, m, uid, gid, name, home);
157 if (r < 0)
158 return r;
159 }
160
161 if (ret_user)
162 *ret_user = u;
163
164 return 0;
165 }
166
167 int manager_add_user_by_name(
168 Manager *m,
169 const char *name,
170 User **ret_user) {
171
172 const char *home = NULL;
173 uid_t uid;
174 gid_t gid;
175 int r;
176
177 assert(m);
178 assert(name);
179
180 r = get_user_creds(&name, &uid, &gid, &home, NULL, 0);
181 if (r < 0)
182 return r;
183
184 return manager_add_user(m, uid, gid, name, home, ret_user);
185 }
186
187 int manager_add_user_by_uid(Manager *m, uid_t uid, User **ret_user) {
188 struct passwd *p;
189
190 assert(m);
191
192 errno = 0;
193 p = getpwuid(uid);
194 if (!p)
195 return errno_or_else(ENOENT);
196
197 return manager_add_user(m, uid, p->pw_gid, p->pw_name, p->pw_dir, ret_user);
198 }
199
200 int manager_add_inhibitor(Manager *m, const char* id, Inhibitor **ret) {
201 Inhibitor *i;
202 int r;
203
204 assert(m);
205 assert(id);
206
207 i = hashmap_get(m->inhibitors, id);
208 if (!i) {
209 r = inhibitor_new(&i, m, id);
210 if (r < 0)
211 return r;
212 }
213
214 if (ret)
215 *ret = i;
216
217 return 0;
218 }
219
220 int manager_add_button(Manager *m, const char *name, Button **ret_button) {
221 Button *b;
222
223 assert(m);
224 assert(name);
225
226 b = hashmap_get(m->buttons, name);
227 if (!b) {
228 b = button_new(m, name);
229 if (!b)
230 return -ENOMEM;
231 }
232
233 if (ret_button)
234 *ret_button = b;
235
236 return 0;
237 }
238
239 int manager_process_seat_device(Manager *m, sd_device *d) {
240 Device *device;
241 int r;
242
243 assert(m);
244
245 if (device_for_action(d, DEVICE_ACTION_REMOVE)) {
246 const char *syspath;
247
248 r = sd_device_get_syspath(d, &syspath);
249 if (r < 0)
250 return 0;
251
252 device = hashmap_get(m->devices, syspath);
253 if (!device)
254 return 0;
255
256 seat_add_to_gc_queue(device->seat);
257 device_free(device);
258
259 } else {
260 const char *sn, *syspath;
261 bool master;
262 Seat *seat;
263
264 if (sd_device_get_property_value(d, "ID_SEAT", &sn) < 0 || isempty(sn))
265 sn = "seat0";
266
267 if (!seat_name_is_valid(sn)) {
268 log_device_warning(d, "Device with invalid seat name %s found, ignoring.", sn);
269 return 0;
270 }
271
272 seat = hashmap_get(m->seats, sn);
273 master = sd_device_has_tag(d, "master-of-seat") > 0;
274
275 /* Ignore non-master devices for unknown seats */
276 if (!master && !seat)
277 return 0;
278
279 r = sd_device_get_syspath(d, &syspath);
280 if (r < 0)
281 return r;
282
283 r = manager_add_device(m, syspath, master, &device);
284 if (r < 0)
285 return r;
286
287 if (!seat) {
288 r = manager_add_seat(m, sn, &seat);
289 if (r < 0) {
290 if (!device->seat)
291 device_free(device);
292
293 return r;
294 }
295 }
296
297 device_attach(device, seat);
298 seat_start(seat);
299 }
300
301 return 0;
302 }
303
304 int manager_process_button_device(Manager *m, sd_device *d) {
305 const char *sysname;
306 Button *b;
307 int r;
308
309 assert(m);
310
311 r = sd_device_get_sysname(d, &sysname);
312 if (r < 0)
313 return r;
314
315 if (device_for_action(d, DEVICE_ACTION_REMOVE)) {
316
317 b = hashmap_get(m->buttons, sysname);
318 if (!b)
319 return 0;
320
321 button_free(b);
322
323 } else {
324 const char *sn;
325
326 r = manager_add_button(m, sysname, &b);
327 if (r < 0)
328 return r;
329
330 if (sd_device_get_property_value(d, "ID_SEAT", &sn) < 0 || isempty(sn))
331 sn = "seat0";
332
333 button_set_seat(b, sn);
334
335 r = button_open(b);
336 if (r < 0) /* event device doesn't have any keys or switches relevant to us? (or any other error
337 * opening the device?) let's close the button again. */
338 button_free(b);
339 }
340
341 return 0;
342 }
343
344 int manager_get_session_by_pid(Manager *m, pid_t pid, Session **ret) {
345 _cleanup_free_ char *unit = NULL;
346 Session *s;
347 int r;
348
349 assert(m);
350
351 if (!pid_is_valid(pid))
352 return -EINVAL;
353
354 s = hashmap_get(m->sessions_by_leader, PID_TO_PTR(pid));
355 if (!s) {
356 r = cg_pid_get_unit(pid, &unit);
357 if (r >= 0)
358 s = hashmap_get(m->session_units, unit);
359 }
360
361 if (ret)
362 *ret = s;
363
364 return !!s;
365 }
366
367 int manager_get_user_by_pid(Manager *m, pid_t pid, User **ret) {
368 _cleanup_free_ char *unit = NULL;
369 User *u = NULL;
370 int r;
371
372 assert(m);
373
374 if (!pid_is_valid(pid))
375 return -EINVAL;
376
377 r = cg_pid_get_slice(pid, &unit);
378 if (r >= 0)
379 u = hashmap_get(m->user_units, unit);
380
381 if (ret)
382 *ret = u;
383
384 return !!u;
385 }
386
387 int manager_get_idle_hint(Manager *m, dual_timestamp *t) {
388 Session *s;
389 bool idle_hint;
390 dual_timestamp ts = DUAL_TIMESTAMP_NULL;
391 Iterator i;
392
393 assert(m);
394
395 idle_hint = !manager_is_inhibited(m, INHIBIT_IDLE, INHIBIT_BLOCK, t, false, false, 0, NULL);
396
397 HASHMAP_FOREACH(s, m->sessions, i) {
398 dual_timestamp k;
399 int ih;
400
401 ih = session_get_idle_hint(s, &k);
402 if (ih < 0)
403 return ih;
404
405 if (!ih) {
406 if (!idle_hint) {
407 if (k.monotonic < ts.monotonic)
408 ts = k;
409 } else {
410 idle_hint = false;
411 ts = k;
412 }
413 } else if (idle_hint) {
414
415 if (k.monotonic > ts.monotonic)
416 ts = k;
417 }
418 }
419
420 if (t)
421 *t = ts;
422
423 return idle_hint;
424 }
425
426 bool manager_shall_kill(Manager *m, const char *user) {
427 assert(m);
428 assert(user);
429
430 if (!m->kill_exclude_users && streq(user, "root"))
431 return false;
432
433 if (strv_contains(m->kill_exclude_users, user))
434 return false;
435
436 if (!strv_isempty(m->kill_only_users))
437 return strv_contains(m->kill_only_users, user);
438
439 return m->kill_user_processes;
440 }
441
442 int config_parse_n_autovts(
443 const char *unit,
444 const char *filename,
445 unsigned line,
446 const char *section,
447 unsigned section_line,
448 const char *lvalue,
449 int ltype,
450 const char *rvalue,
451 void *data,
452 void *userdata) {
453
454 unsigned *n = data;
455 unsigned o;
456 int r;
457
458 assert(filename);
459 assert(lvalue);
460 assert(rvalue);
461 assert(data);
462
463 r = safe_atou(rvalue, &o);
464 if (r < 0) {
465 log_syntax(unit, LOG_ERR, filename, line, r, "Failed to parse number of autovts, ignoring: %s", rvalue);
466 return 0;
467 }
468
469 if (o > 15) {
470 log_syntax(unit, LOG_ERR, filename, line, r, "A maximum of 15 autovts are supported, ignoring: %s", rvalue);
471 return 0;
472 }
473
474 *n = o;
475 return 0;
476 }
477
478 static int vt_is_busy(unsigned vtnr) {
479 struct vt_stat vt_stat;
480 int r = 0;
481 _cleanup_close_ int fd;
482
483 assert(vtnr >= 1);
484
485 /* VT_GETSTATE "cannot return state for more than 16 VTs, since v_state is short" */
486 assert(vtnr <= 15);
487
488 /* We explicitly open /dev/tty1 here instead of /dev/tty0. If
489 * we'd open the latter we'd open the foreground tty which
490 * hence would be unconditionally busy. By opening /dev/tty1
491 * we avoid this. Since tty1 is special and needs to be an
492 * explicitly loaded getty or DM this is safe. */
493
494 fd = open_terminal("/dev/tty1", O_RDWR|O_NOCTTY|O_CLOEXEC);
495 if (fd < 0)
496 return -errno;
497
498 if (ioctl(fd, VT_GETSTATE, &vt_stat) < 0)
499 r = -errno;
500 else
501 r = !!(vt_stat.v_state & (1 << vtnr));
502
503 return r;
504 }
505
506 int manager_spawn_autovt(Manager *m, unsigned vtnr) {
507 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
508 char name[sizeof("autovt@tty.service") + DECIMAL_STR_MAX(unsigned)];
509 int r;
510
511 assert(m);
512 assert(vtnr >= 1);
513
514 if (vtnr > m->n_autovts &&
515 vtnr != m->reserve_vt)
516 return 0;
517
518 if (vtnr != m->reserve_vt) {
519 /* If this is the reserved TTY, we'll start the getty
520 * on it in any case, but otherwise only if it is not
521 * busy. */
522
523 r = vt_is_busy(vtnr);
524 if (r < 0)
525 return r;
526 else if (r > 0)
527 return -EBUSY;
528 }
529
530 snprintf(name, sizeof(name), "autovt@tty%u.service", vtnr);
531 r = sd_bus_call_method(
532 m->bus,
533 "org.freedesktop.systemd1",
534 "/org/freedesktop/systemd1",
535 "org.freedesktop.systemd1.Manager",
536 "StartUnit",
537 &error,
538 NULL,
539 "ss", name, "fail");
540 if (r < 0)
541 return log_error_errno(r, "Failed to start %s: %s", name, bus_error_message(&error, r));
542
543 return 0;
544 }
545
546 bool manager_is_lid_closed(Manager *m) {
547 Iterator i;
548 Button *b;
549
550 HASHMAP_FOREACH(b, m->buttons, i)
551 if (b->lid_closed)
552 return true;
553
554 return false;
555 }
556
557 static bool manager_is_docked(Manager *m) {
558 Iterator i;
559 Button *b;
560
561 HASHMAP_FOREACH(b, m->buttons, i)
562 if (b->docked)
563 return true;
564
565 return false;
566 }
567
568 static int manager_count_external_displays(Manager *m) {
569 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
570 sd_device *d;
571 int r, n = 0;
572
573 r = sd_device_enumerator_new(&e);
574 if (r < 0)
575 return r;
576
577 r = sd_device_enumerator_allow_uninitialized(e);
578 if (r < 0)
579 return r;
580
581 r = sd_device_enumerator_add_match_subsystem(e, "drm", true);
582 if (r < 0)
583 return r;
584
585 FOREACH_DEVICE(e, d) {
586 const char *status, *enabled, *dash, *nn, *subsys;
587 sd_device *p;
588
589 if (sd_device_get_parent(d, &p) < 0)
590 continue;
591
592 /* If the parent shares the same subsystem as the
593 * device we are looking at then it is a connector,
594 * which is what we are interested in. */
595 if (sd_device_get_subsystem(p, &subsys) < 0 || !streq(subsys, "drm"))
596 continue;
597
598 if (sd_device_get_sysname(d, &nn) < 0)
599 continue;
600
601 /* Ignore internal displays: the type is encoded in the sysfs name, as the second dash separated item
602 * (the first is the card name, the last the connector number). We implement a blacklist of external
603 * displays here, rather than a whitelist of internal ones, to ensure we don't block suspends too
604 * eagerly. */
605 dash = strchr(nn, '-');
606 if (!dash)
607 continue;
608
609 dash++;
610 if (!STARTSWITH_SET(dash,
611 "VGA-", "DVI-I-", "DVI-D-", "DVI-A-"
612 "Composite-", "SVIDEO-", "Component-",
613 "DIN-", "DP-", "HDMI-A-", "HDMI-B-", "TV-"))
614 continue;
615
616 /* Ignore ports that are not enabled */
617 if (sd_device_get_sysattr_value(d, "enabled", &enabled) < 0 || !streq(enabled, "enabled"))
618 continue;
619
620 /* We count any connector which is not explicitly
621 * "disconnected" as connected. */
622 if (sd_device_get_sysattr_value(d, "status", &status) < 0 || !streq(status, "disconnected"))
623 n++;
624 }
625
626 return n;
627 }
628
629 bool manager_is_docked_or_external_displays(Manager *m) {
630 int n;
631
632 /* If we are docked don't react to lid closing */
633 if (manager_is_docked(m)) {
634 log_debug("System is docked.");
635 return true;
636 }
637
638 /* If we have more than one display connected,
639 * assume that we are docked. */
640 n = manager_count_external_displays(m);
641 if (n < 0)
642 log_warning_errno(n, "Display counting failed: %m");
643 else if (n >= 1) {
644 log_debug("External (%i) displays connected.", n);
645 return true;
646 }
647
648 return false;
649 }
650
651 bool manager_is_on_external_power(void) {
652 int r;
653
654 /* For now we only check for AC power, but 'external power' can apply to anything that isn't an internal
655 * battery */
656 r = on_ac_power();
657 if (r < 0)
658 log_warning_errno(r, "Failed to read AC power status: %m");
659
660 return r != 0; /* Treat failure as 'on AC' */
661 }
662
663 bool manager_all_buttons_ignored(Manager *m) {
664 assert(m);
665
666 if (m->handle_power_key != HANDLE_IGNORE)
667 return false;
668 if (m->handle_suspend_key != HANDLE_IGNORE)
669 return false;
670 if (m->handle_hibernate_key != HANDLE_IGNORE)
671 return false;
672 if (m->handle_lid_switch != HANDLE_IGNORE)
673 return false;
674 if (!IN_SET(m->handle_lid_switch_ep, _HANDLE_ACTION_INVALID, HANDLE_IGNORE))
675 return false;
676 if (m->handle_lid_switch_docked != HANDLE_IGNORE)
677 return false;
678
679 return true;
680 }
681
682 int manager_read_utmp(Manager *m) {
683 #if ENABLE_UTMP
684 int r;
685
686 assert(m);
687
688 if (utmpxname(_PATH_UTMPX) < 0)
689 return log_error_errno(errno, "Failed to set utmp path to " _PATH_UTMPX ": %m");
690
691 setutxent();
692
693 for (;;) {
694 _cleanup_free_ char *t = NULL;
695 struct utmpx *u;
696 const char *c;
697 Session *s;
698
699 errno = 0;
700 u = getutxent();
701 if (!u) {
702 if (errno != 0)
703 log_warning_errno(errno, "Failed to read " _PATH_UTMPX ", ignoring: %m");
704 r = 0;
705 break;
706 }
707
708 if (u->ut_type != USER_PROCESS)
709 continue;
710
711 if (!pid_is_valid(u->ut_pid))
712 continue;
713
714 t = strndup(u->ut_line, sizeof(u->ut_line));
715 if (!t) {
716 r = log_oom();
717 break;
718 }
719
720 c = path_startswith(t, "/dev/");
721 if (c) {
722 r = free_and_strdup(&t, c);
723 if (r < 0) {
724 log_oom();
725 break;
726 }
727 }
728
729 if (isempty(t))
730 continue;
731
732 s = hashmap_get(m->sessions_by_leader, PID_TO_PTR(u->ut_pid));
733 if (!s)
734 continue;
735
736 if (s->tty_validity == TTY_FROM_UTMP && !streq_ptr(s->tty, t)) {
737 /* This may happen on multiplexed SSH connection (i.e. 'SSH connection sharing'). In
738 * this case PAM and utmp sessions don't match. In such a case let's invalidate the TTY
739 * information and never acquire it again. */
740
741 s->tty = mfree(s->tty);
742 s->tty_validity = TTY_UTMP_INCONSISTENT;
743 log_debug("Session '%s' has inconsistent TTY information, dropping TTY information.", s->id);
744 continue;
745 }
746
747 /* Never override what we figured out once */
748 if (s->tty || s->tty_validity >= 0)
749 continue;
750
751 s->tty = TAKE_PTR(t);
752 s->tty_validity = TTY_FROM_UTMP;
753 log_debug("Acquired TTY information '%s' from utmp for session '%s'.", s->tty, s->id);
754 }
755
756 endutxent();
757 return r;
758 #else
759 return 0;
760 #endif
761 }
762
763 #if ENABLE_UTMP
764 static int manager_dispatch_utmp(sd_event_source *s, const struct inotify_event *event, void *userdata) {
765 Manager *m = userdata;
766
767 assert(m);
768
769 /* If there's indication the file itself might have been removed or became otherwise unavailable, then let's
770 * reestablish the watch on whatever there's now. */
771 if ((event->mask & (IN_ATTRIB|IN_DELETE_SELF|IN_MOVE_SELF|IN_Q_OVERFLOW|IN_UNMOUNT)) != 0)
772 manager_connect_utmp(m);
773
774 (void) manager_read_utmp(m);
775 return 0;
776 }
777 #endif
778
779 void manager_connect_utmp(Manager *m) {
780 #if ENABLE_UTMP
781 sd_event_source *s = NULL;
782 int r;
783
784 assert(m);
785
786 /* Watch utmp for changes via inotify. We do this to deal with tools such as ssh, which will register the PAM
787 * session early, and acquire a TTY only much later for the connection. Thus during PAM the TTY won't be known
788 * yet. ssh will register itself with utmp when it finally acquired the TTY. Hence, let's make use of this, and
789 * watch utmp for the TTY asynchronously. We use the PAM session's leader PID as key, to find the right entry.
790 *
791 * Yes, relying on utmp is pretty ugly, but it's good enough for informational purposes, as well as idle
792 * detection (which, for tty sessions, relies on the TTY used) */
793
794 r = sd_event_add_inotify(m->event, &s, _PATH_UTMPX, IN_MODIFY|IN_MOVE_SELF|IN_DELETE_SELF|IN_ATTRIB, manager_dispatch_utmp, m);
795 if (r < 0)
796 log_full_errno(r == -ENOENT ? LOG_DEBUG: LOG_WARNING, r, "Failed to create inotify watch on " _PATH_UTMPX ", ignoring: %m");
797 else {
798 r = sd_event_source_set_priority(s, SD_EVENT_PRIORITY_IDLE);
799 if (r < 0)
800 log_warning_errno(r, "Failed to adjust utmp event source priority, ignoring: %m");
801
802 (void) sd_event_source_set_description(s, "utmp");
803 }
804
805 sd_event_source_unref(m->utmp_event_source);
806 m->utmp_event_source = s;
807 #endif
808 }
809
810 void manager_reconnect_utmp(Manager *m) {
811 #if ENABLE_UTMP
812 assert(m);
813
814 if (m->utmp_event_source)
815 return;
816
817 manager_connect_utmp(m);
818 #endif
819 }