]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/login/logind-session.c
terminal-util: introduce vt_release() helper
[thirdparty/systemd.git] / src / login / logind-session.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <linux/kd.h>
6 #include <linux/vt.h>
7 #include <signal.h>
8 #include <stdio_ext.h>
9 #include <string.h>
10 #include <sys/ioctl.h>
11 #include <unistd.h>
12
13 #include "sd-messages.h"
14
15 #include "alloc-util.h"
16 #include "audit-util.h"
17 #include "bus-error.h"
18 #include "bus-util.h"
19 #include "escape.h"
20 #include "fd-util.h"
21 #include "fileio.h"
22 #include "format-util.h"
23 #include "io-util.h"
24 #include "logind-session.h"
25 #include "mkdir.h"
26 #include "parse-util.h"
27 #include "path-util.h"
28 #include "process-util.h"
29 #include "serialize.h"
30 #include "string-table.h"
31 #include "strv.h"
32 #include "terminal-util.h"
33 #include "user-util.h"
34 #include "util.h"
35
36 #define RELEASE_USEC (20*USEC_PER_SEC)
37
38 static void session_remove_fifo(Session *s);
39 static void session_restore_vt(Session *s);
40
41 int session_new(Session **ret, Manager *m, const char *id) {
42 _cleanup_(session_freep) Session *s = NULL;
43 int r;
44
45 assert(ret);
46 assert(m);
47 assert(id);
48
49 if (!session_id_valid(id))
50 return -EINVAL;
51
52 s = new(Session, 1);
53 if (!s)
54 return -ENOMEM;
55
56 *s = (Session) {
57 .manager = m,
58 .fifo_fd = -1,
59 .vtfd = -1,
60 .audit_id = AUDIT_SESSION_INVALID,
61 .tty_validity = _TTY_VALIDITY_INVALID,
62 };
63
64 s->state_file = strappend("/run/systemd/sessions/", id);
65 if (!s->state_file)
66 return -ENOMEM;
67
68 s->id = basename(s->state_file);
69
70 s->devices = hashmap_new(&devt_hash_ops);
71 if (!s->devices)
72 return -ENOMEM;
73
74 r = hashmap_put(m->sessions, s->id, s);
75 if (r < 0)
76 return r;
77
78 *ret = TAKE_PTR(s);
79 return 0;
80 }
81
82 Session* session_free(Session *s) {
83 SessionDevice *sd;
84
85 if (!s)
86 return NULL;
87
88 if (s->in_gc_queue)
89 LIST_REMOVE(gc_queue, s->manager->session_gc_queue, s);
90
91 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
92
93 session_remove_fifo(s);
94
95 session_drop_controller(s);
96
97 while ((sd = hashmap_first(s->devices)))
98 session_device_free(sd);
99
100 hashmap_free(s->devices);
101
102 if (s->user) {
103 LIST_REMOVE(sessions_by_user, s->user->sessions, s);
104
105 if (s->user->display == s)
106 s->user->display = NULL;
107
108 user_update_last_session_timer(s->user);
109 }
110
111 if (s->seat) {
112 if (s->seat->active == s)
113 s->seat->active = NULL;
114 if (s->seat->pending_switch == s)
115 s->seat->pending_switch = NULL;
116
117 seat_evict_position(s->seat, s);
118 LIST_REMOVE(sessions_by_seat, s->seat->sessions, s);
119 }
120
121 if (s->scope) {
122 hashmap_remove(s->manager->session_units, s->scope);
123 free(s->scope);
124 }
125
126 if (pid_is_valid(s->leader))
127 (void) hashmap_remove_value(s->manager->sessions_by_leader, PID_TO_PTR(s->leader), s);
128
129 free(s->scope_job);
130
131 sd_bus_message_unref(s->create_message);
132
133 free(s->tty);
134 free(s->display);
135 free(s->remote_host);
136 free(s->remote_user);
137 free(s->service);
138 free(s->desktop);
139
140 hashmap_remove(s->manager->sessions, s->id);
141
142 free(s->state_file);
143
144 return mfree(s);
145 }
146
147 void session_set_user(Session *s, User *u) {
148 assert(s);
149 assert(!s->user);
150
151 s->user = u;
152 LIST_PREPEND(sessions_by_user, u->sessions, s);
153
154 user_update_last_session_timer(u);
155 }
156
157 int session_set_leader(Session *s, pid_t pid) {
158 int r;
159
160 assert(s);
161
162 if (!pid_is_valid(pid))
163 return -EINVAL;
164
165 if (s->leader == pid)
166 return 0;
167
168 r = hashmap_put(s->manager->sessions_by_leader, PID_TO_PTR(pid), s);
169 if (r < 0)
170 return r;
171
172 if (pid_is_valid(s->leader))
173 (void) hashmap_remove_value(s->manager->sessions_by_leader, PID_TO_PTR(s->leader), s);
174
175 s->leader = pid;
176 (void) audit_session_from_pid(pid, &s->audit_id);
177
178 return 1;
179 }
180
181 static void session_save_devices(Session *s, FILE *f) {
182 SessionDevice *sd;
183 Iterator i;
184
185 if (!hashmap_isempty(s->devices)) {
186 fprintf(f, "DEVICES=");
187 HASHMAP_FOREACH(sd, s->devices, i)
188 fprintf(f, "%u:%u ", major(sd->dev), minor(sd->dev));
189 fprintf(f, "\n");
190 }
191 }
192
193 int session_save(Session *s) {
194 _cleanup_free_ char *temp_path = NULL;
195 _cleanup_fclose_ FILE *f = NULL;
196 int r = 0;
197
198 assert(s);
199
200 if (!s->user)
201 return -ESTALE;
202
203 if (!s->started)
204 return 0;
205
206 r = mkdir_safe_label("/run/systemd/sessions", 0755, 0, 0, MKDIR_WARN_MODE);
207 if (r < 0)
208 goto fail;
209
210 r = fopen_temporary(s->state_file, &f, &temp_path);
211 if (r < 0)
212 goto fail;
213
214 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
215 (void) fchmod(fileno(f), 0644);
216
217 fprintf(f,
218 "# This is private data. Do not parse.\n"
219 "UID="UID_FMT"\n"
220 "USER=%s\n"
221 "ACTIVE=%i\n"
222 "IS_DISPLAY=%i\n"
223 "STATE=%s\n"
224 "REMOTE=%i\n",
225 s->user->uid,
226 s->user->name,
227 session_is_active(s),
228 s->user->display == s,
229 session_state_to_string(session_get_state(s)),
230 s->remote);
231
232 if (s->type >= 0)
233 fprintf(f, "TYPE=%s\n", session_type_to_string(s->type));
234
235 if (s->class >= 0)
236 fprintf(f, "CLASS=%s\n", session_class_to_string(s->class));
237
238 if (s->scope)
239 fprintf(f, "SCOPE=%s\n", s->scope);
240 if (s->scope_job)
241 fprintf(f, "SCOPE_JOB=%s\n", s->scope_job);
242
243 if (s->fifo_path)
244 fprintf(f, "FIFO=%s\n", s->fifo_path);
245
246 if (s->seat)
247 fprintf(f, "SEAT=%s\n", s->seat->id);
248
249 if (s->tty)
250 fprintf(f, "TTY=%s\n", s->tty);
251
252 if (s->tty_validity >= 0)
253 fprintf(f, "TTY_VALIDITY=%s\n", tty_validity_to_string(s->tty_validity));
254
255 if (s->display)
256 fprintf(f, "DISPLAY=%s\n", s->display);
257
258 if (s->remote_host) {
259 _cleanup_free_ char *escaped;
260
261 escaped = cescape(s->remote_host);
262 if (!escaped) {
263 r = -ENOMEM;
264 goto fail;
265 }
266
267 fprintf(f, "REMOTE_HOST=%s\n", escaped);
268 }
269
270 if (s->remote_user) {
271 _cleanup_free_ char *escaped;
272
273 escaped = cescape(s->remote_user);
274 if (!escaped) {
275 r = -ENOMEM;
276 goto fail;
277 }
278
279 fprintf(f, "REMOTE_USER=%s\n", escaped);
280 }
281
282 if (s->service) {
283 _cleanup_free_ char *escaped;
284
285 escaped = cescape(s->service);
286 if (!escaped) {
287 r = -ENOMEM;
288 goto fail;
289 }
290
291 fprintf(f, "SERVICE=%s\n", escaped);
292 }
293
294 if (s->desktop) {
295 _cleanup_free_ char *escaped;
296
297 escaped = cescape(s->desktop);
298 if (!escaped) {
299 r = -ENOMEM;
300 goto fail;
301 }
302
303 fprintf(f, "DESKTOP=%s\n", escaped);
304 }
305
306 if (s->seat && seat_has_vts(s->seat))
307 fprintf(f, "VTNR=%u\n", s->vtnr);
308
309 if (!s->vtnr)
310 fprintf(f, "POSITION=%u\n", s->position);
311
312 if (pid_is_valid(s->leader))
313 fprintf(f, "LEADER="PID_FMT"\n", s->leader);
314
315 if (audit_session_is_valid(s->audit_id))
316 fprintf(f, "AUDIT=%"PRIu32"\n", s->audit_id);
317
318 if (dual_timestamp_is_set(&s->timestamp))
319 fprintf(f,
320 "REALTIME="USEC_FMT"\n"
321 "MONOTONIC="USEC_FMT"\n",
322 s->timestamp.realtime,
323 s->timestamp.monotonic);
324
325 if (s->controller) {
326 fprintf(f, "CONTROLLER=%s\n", s->controller);
327 session_save_devices(s, f);
328 }
329
330 r = fflush_and_check(f);
331 if (r < 0)
332 goto fail;
333
334 if (rename(temp_path, s->state_file) < 0) {
335 r = -errno;
336 goto fail;
337 }
338
339 return 0;
340
341 fail:
342 (void) unlink(s->state_file);
343
344 if (temp_path)
345 (void) unlink(temp_path);
346
347 return log_error_errno(r, "Failed to save session data %s: %m", s->state_file);
348 }
349
350 static int session_load_devices(Session *s, const char *devices) {
351 const char *p;
352 int r = 0;
353
354 assert(s);
355
356 for (p = devices;;) {
357 _cleanup_free_ char *word = NULL;
358 SessionDevice *sd;
359 dev_t dev;
360 int k;
361
362 k = extract_first_word(&p, &word, NULL, 0);
363 if (k == 0)
364 break;
365 if (k < 0) {
366 r = k;
367 break;
368 }
369
370 k = parse_dev(word, &dev);
371 if (k < 0) {
372 r = k;
373 continue;
374 }
375
376 /* The file descriptors for loaded devices will be reattached later. */
377 k = session_device_new(s, dev, false, &sd);
378 if (k < 0)
379 r = k;
380 }
381
382 if (r < 0)
383 log_error_errno(r, "Loading session devices for session %s failed: %m", s->id);
384
385 return r;
386 }
387
388 int session_load(Session *s) {
389 _cleanup_free_ char *remote = NULL,
390 *seat = NULL,
391 *tty_validity = NULL,
392 *vtnr = NULL,
393 *state = NULL,
394 *position = NULL,
395 *leader = NULL,
396 *type = NULL,
397 *class = NULL,
398 *uid = NULL,
399 *realtime = NULL,
400 *monotonic = NULL,
401 *controller = NULL,
402 *active = NULL,
403 *devices = NULL,
404 *is_display = NULL;
405
406 int k, r;
407
408 assert(s);
409
410 r = parse_env_file(NULL, s->state_file,
411 "REMOTE", &remote,
412 "SCOPE", &s->scope,
413 "SCOPE_JOB", &s->scope_job,
414 "FIFO", &s->fifo_path,
415 "SEAT", &seat,
416 "TTY", &s->tty,
417 "TTY_VALIDITY", &tty_validity,
418 "DISPLAY", &s->display,
419 "REMOTE_HOST", &s->remote_host,
420 "REMOTE_USER", &s->remote_user,
421 "SERVICE", &s->service,
422 "DESKTOP", &s->desktop,
423 "VTNR", &vtnr,
424 "STATE", &state,
425 "POSITION", &position,
426 "LEADER", &leader,
427 "TYPE", &type,
428 "CLASS", &class,
429 "UID", &uid,
430 "REALTIME", &realtime,
431 "MONOTONIC", &monotonic,
432 "CONTROLLER", &controller,
433 "ACTIVE", &active,
434 "DEVICES", &devices,
435 "IS_DISPLAY", &is_display);
436
437 if (r < 0)
438 return log_error_errno(r, "Failed to read %s: %m", s->state_file);
439
440 if (!s->user) {
441 uid_t u;
442 User *user;
443
444 if (!uid) {
445 log_error("UID not specified for session %s", s->id);
446 return -ENOENT;
447 }
448
449 r = parse_uid(uid, &u);
450 if (r < 0) {
451 log_error("Failed to parse UID value %s for session %s.", uid, s->id);
452 return r;
453 }
454
455 user = hashmap_get(s->manager->users, UID_TO_PTR(u));
456 if (!user) {
457 log_error("User of session %s not known.", s->id);
458 return -ENOENT;
459 }
460
461 session_set_user(s, user);
462 }
463
464 if (remote) {
465 k = parse_boolean(remote);
466 if (k >= 0)
467 s->remote = k;
468 }
469
470 if (vtnr)
471 safe_atou(vtnr, &s->vtnr);
472
473 if (seat && !s->seat) {
474 Seat *o;
475
476 o = hashmap_get(s->manager->seats, seat);
477 if (o)
478 r = seat_attach_session(o, s);
479 if (!o || r < 0)
480 log_error("Cannot attach session %s to seat %s", s->id, seat);
481 }
482
483 if (!s->seat || !seat_has_vts(s->seat))
484 s->vtnr = 0;
485
486 if (position && s->seat) {
487 unsigned npos;
488
489 safe_atou(position, &npos);
490 seat_claim_position(s->seat, s, npos);
491 }
492
493 if (tty_validity) {
494 TTYValidity v;
495
496 v = tty_validity_from_string(tty_validity);
497 if (v < 0)
498 log_debug("Failed to parse TTY validity: %s", tty_validity);
499 else
500 s->tty_validity = v;
501 }
502
503 if (leader) {
504 pid_t pid;
505
506 r = parse_pid(leader, &pid);
507 if (r < 0)
508 log_debug_errno(r, "Failed to parse leader PID of session: %s", leader);
509 else {
510 r = session_set_leader(s, pid);
511 if (r < 0)
512 log_warning_errno(r, "Failed to set session leader PID, ignoring: %m");
513 }
514 }
515
516 if (type) {
517 SessionType t;
518
519 t = session_type_from_string(type);
520 if (t >= 0)
521 s->type = t;
522 }
523
524 if (class) {
525 SessionClass c;
526
527 c = session_class_from_string(class);
528 if (c >= 0)
529 s->class = c;
530 }
531
532 if (state && streq(state, "closing"))
533 s->stopping = true;
534
535 if (s->fifo_path) {
536 int fd;
537
538 /* If we open an unopened pipe for reading we will not
539 get an EOF. to trigger an EOF we hence open it for
540 writing, but close it right away which then will
541 trigger the EOF. This will happen immediately if no
542 other process has the FIFO open for writing, i. e.
543 when the session died before logind (re)started. */
544
545 fd = session_create_fifo(s);
546 safe_close(fd);
547 }
548
549 if (realtime)
550 (void) deserialize_usec(realtime, &s->timestamp.realtime);
551 if (monotonic)
552 (void) deserialize_usec(monotonic, &s->timestamp.monotonic);
553
554 if (active) {
555 k = parse_boolean(active);
556 if (k >= 0)
557 s->was_active = k;
558 }
559
560 if (is_display) {
561 /* Note that when enumerating users are loaded before sessions, hence the display session to use is
562 * something we have to store along with the session and not the user, as in that case we couldn't
563 * apply it at the time we load the user. */
564
565 k = parse_boolean(is_display);
566 if (k < 0)
567 log_warning_errno(k, "Failed to parse IS_DISPLAY session property: %m");
568 else if (k > 0)
569 s->user->display = s;
570 }
571
572 if (controller) {
573 if (bus_name_has_owner(s->manager->bus, controller, NULL) > 0) {
574 session_set_controller(s, controller, false, false);
575 session_load_devices(s, devices);
576 } else
577 session_restore_vt(s);
578 }
579
580 return r;
581 }
582
583 int session_activate(Session *s) {
584 unsigned num_pending;
585
586 assert(s);
587 assert(s->user);
588
589 if (!s->seat)
590 return -EOPNOTSUPP;
591
592 if (s->seat->active == s)
593 return 0;
594
595 /* on seats with VTs, we let VTs manage session-switching */
596 if (seat_has_vts(s->seat)) {
597 if (s->vtnr == 0)
598 return -EOPNOTSUPP;
599
600 return chvt(s->vtnr);
601 }
602
603 /* On seats without VTs, we implement session-switching in logind. We
604 * try to pause all session-devices and wait until the session
605 * controller acknowledged them. Once all devices are asleep, we simply
606 * switch the active session and be done.
607 * We save the session we want to switch to in seat->pending_switch and
608 * seat_complete_switch() will perform the final switch. */
609
610 s->seat->pending_switch = s;
611
612 /* if no devices are running, immediately perform the session switch */
613 num_pending = session_device_try_pause_all(s);
614 if (!num_pending)
615 seat_complete_switch(s->seat);
616
617 return 0;
618 }
619
620 static int session_start_scope(Session *s, sd_bus_message *properties, sd_bus_error *error) {
621 int r;
622
623 assert(s);
624 assert(s->user);
625
626 if (!s->scope) {
627 _cleanup_free_ char *scope = NULL;
628 const char *description;
629
630 s->scope_job = mfree(s->scope_job);
631
632 scope = strjoin("session-", s->id, ".scope");
633 if (!scope)
634 return log_oom();
635
636 description = strjoina("Session ", s->id, " of user ", s->user->name);
637
638 r = manager_start_scope(
639 s->manager,
640 scope,
641 s->leader,
642 s->user->slice,
643 description,
644 STRV_MAKE(s->user->runtime_dir_service, s->user->service), /* These two have StopWhenUnneeded= set, hence add a dep towards them */
645 STRV_MAKE("systemd-logind.service", "systemd-user-sessions.service", s->user->runtime_dir_service, s->user->service), /* And order us after some more */
646 s->user->home,
647 properties,
648 error,
649 &s->scope_job);
650 if (r < 0)
651 return log_error_errno(r, "Failed to start session scope %s: %s", scope, bus_error_message(error, r));
652
653 s->scope = TAKE_PTR(scope);
654 }
655
656 if (s->scope)
657 (void) hashmap_put(s->manager->session_units, s->scope, s);
658
659 return 0;
660 }
661
662 int session_start(Session *s, sd_bus_message *properties, sd_bus_error *error) {
663 int r;
664
665 assert(s);
666
667 if (!s->user)
668 return -ESTALE;
669
670 if (s->stopping)
671 return -EINVAL;
672
673 if (s->started)
674 return 0;
675
676 r = user_start(s->user);
677 if (r < 0)
678 return r;
679
680 r = session_start_scope(s, properties, error);
681 if (r < 0)
682 return r;
683
684 log_struct(s->class == SESSION_BACKGROUND ? LOG_DEBUG : LOG_INFO,
685 "MESSAGE_ID=" SD_MESSAGE_SESSION_START_STR,
686 "SESSION_ID=%s", s->id,
687 "USER_ID=%s", s->user->name,
688 "LEADER="PID_FMT, s->leader,
689 LOG_MESSAGE("New session %s of user %s.", s->id, s->user->name));
690
691 if (!dual_timestamp_is_set(&s->timestamp))
692 dual_timestamp_get(&s->timestamp);
693
694 if (s->seat)
695 seat_read_active_vt(s->seat);
696
697 s->started = true;
698
699 user_elect_display(s->user);
700
701 /* Save data */
702 session_save(s);
703 user_save(s->user);
704 if (s->seat)
705 seat_save(s->seat);
706
707 /* Send signals */
708 session_send_signal(s, true);
709 user_send_changed(s->user, "Display", NULL);
710 if (s->seat) {
711 if (s->seat->active == s)
712 seat_send_changed(s->seat, "ActiveSession", NULL);
713 }
714
715 return 0;
716 }
717
718 static int session_stop_scope(Session *s, bool force) {
719 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
720 int r;
721
722 assert(s);
723
724 if (!s->scope)
725 return 0;
726
727 /* Let's always abandon the scope first. This tells systemd that we are not interested anymore, and everything
728 * that is left in the scope is "left-over". Informing systemd about this has the benefit that it will log
729 * when killing any processes left after this point. */
730 r = manager_abandon_scope(s->manager, s->scope, &error);
731 if (r < 0) {
732 log_warning_errno(r, "Failed to abandon session scope, ignoring: %s", bus_error_message(&error, r));
733 sd_bus_error_free(&error);
734 }
735
736 s->scope_job = mfree(s->scope_job);
737
738 /* Optionally, let's kill everything that's left now. */
739 if (force || manager_shall_kill(s->manager, s->user->name)) {
740
741 r = manager_stop_unit(s->manager, s->scope, &error, &s->scope_job);
742 if (r < 0) {
743 if (force)
744 return log_error_errno(r, "Failed to stop session scope: %s", bus_error_message(&error, r));
745
746 log_warning_errno(r, "Failed to stop session scope, ignoring: %s", bus_error_message(&error, r));
747 }
748 } else {
749
750 /* With no killing, this session is allowed to persist in "closing" state indefinitely.
751 * Therefore session stop and session removal may be two distinct events.
752 * Session stop is quite significant on its own, let's log it. */
753 log_struct(s->class == SESSION_BACKGROUND ? LOG_DEBUG : LOG_INFO,
754 "SESSION_ID=%s", s->id,
755 "USER_ID=%s", s->user->name,
756 "LEADER="PID_FMT, s->leader,
757 LOG_MESSAGE("Session %s logged out. Waiting for processes to exit.", s->id));
758 }
759
760 return 0;
761 }
762
763 int session_stop(Session *s, bool force) {
764 int r;
765
766 assert(s);
767
768 /* This is called whenever we begin with tearing down a session record. It's called in four cases: explicit API
769 * request via the bus (either directly for the session object or for the seat or user object this session
770 * belongs to; 'force' is true), or due to automatic GC (i.e. scope vanished; 'force' is false), or because the
771 * session FIFO saw an EOF ('force' is false), or because the release timer hit ('force' is false). */
772
773 if (!s->user)
774 return -ESTALE;
775 if (!s->started)
776 return 0;
777 if (s->stopping)
778 return 0;
779
780 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
781
782 if (s->seat)
783 seat_evict_position(s->seat, s);
784
785 /* We are going down, don't care about FIFOs anymore */
786 session_remove_fifo(s);
787
788 /* Kill cgroup */
789 r = session_stop_scope(s, force);
790
791 s->stopping = true;
792
793 user_elect_display(s->user);
794
795 session_save(s);
796 user_save(s->user);
797
798 return r;
799 }
800
801 int session_finalize(Session *s) {
802 SessionDevice *sd;
803
804 assert(s);
805
806 if (!s->user)
807 return -ESTALE;
808
809 if (s->started)
810 log_struct(s->class == SESSION_BACKGROUND ? LOG_DEBUG : LOG_INFO,
811 "MESSAGE_ID=" SD_MESSAGE_SESSION_STOP_STR,
812 "SESSION_ID=%s", s->id,
813 "USER_ID=%s", s->user->name,
814 "LEADER="PID_FMT, s->leader,
815 LOG_MESSAGE("Removed session %s.", s->id));
816
817 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
818
819 if (s->seat)
820 seat_evict_position(s->seat, s);
821
822 /* Kill session devices */
823 while ((sd = hashmap_first(s->devices)))
824 session_device_free(sd);
825
826 (void) unlink(s->state_file);
827 session_add_to_gc_queue(s);
828 user_add_to_gc_queue(s->user);
829
830 if (s->started) {
831 session_send_signal(s, false);
832 s->started = false;
833 }
834
835 if (s->seat) {
836 if (s->seat->active == s)
837 seat_set_active(s->seat, NULL);
838
839 seat_save(s->seat);
840 }
841
842 user_save(s->user);
843 user_send_changed(s->user, "Display", NULL);
844
845 return 0;
846 }
847
848 static int release_timeout_callback(sd_event_source *es, uint64_t usec, void *userdata) {
849 Session *s = userdata;
850
851 assert(es);
852 assert(s);
853
854 session_stop(s, false);
855 return 0;
856 }
857
858 int session_release(Session *s) {
859 assert(s);
860
861 if (!s->started || s->stopping)
862 return 0;
863
864 if (s->timer_event_source)
865 return 0;
866
867 return sd_event_add_time(s->manager->event,
868 &s->timer_event_source,
869 CLOCK_MONOTONIC,
870 usec_add(now(CLOCK_MONOTONIC), RELEASE_USEC), 0,
871 release_timeout_callback, s);
872 }
873
874 bool session_is_active(Session *s) {
875 assert(s);
876
877 if (!s->seat)
878 return true;
879
880 return s->seat->active == s;
881 }
882
883 static int get_tty_atime(const char *tty, usec_t *atime) {
884 _cleanup_free_ char *p = NULL;
885 struct stat st;
886
887 assert(tty);
888 assert(atime);
889
890 if (!path_is_absolute(tty)) {
891 p = strappend("/dev/", tty);
892 if (!p)
893 return -ENOMEM;
894
895 tty = p;
896 } else if (!path_startswith(tty, "/dev/"))
897 return -ENOENT;
898
899 if (lstat(tty, &st) < 0)
900 return -errno;
901
902 *atime = timespec_load(&st.st_atim);
903 return 0;
904 }
905
906 static int get_process_ctty_atime(pid_t pid, usec_t *atime) {
907 _cleanup_free_ char *p = NULL;
908 int r;
909
910 assert(pid > 0);
911 assert(atime);
912
913 r = get_ctty(pid, NULL, &p);
914 if (r < 0)
915 return r;
916
917 return get_tty_atime(p, atime);
918 }
919
920 int session_get_idle_hint(Session *s, dual_timestamp *t) {
921 usec_t atime = 0, n;
922 int r;
923
924 assert(s);
925
926 /* Explicit idle hint is set */
927 if (s->idle_hint) {
928 if (t)
929 *t = s->idle_hint_timestamp;
930
931 return s->idle_hint;
932 }
933
934 /* Graphical sessions should really implement a real
935 * idle hint logic */
936 if (SESSION_TYPE_IS_GRAPHICAL(s->type))
937 goto dont_know;
938
939 /* For sessions with an explicitly configured tty, let's check
940 * its atime */
941 if (s->tty) {
942 r = get_tty_atime(s->tty, &atime);
943 if (r >= 0)
944 goto found_atime;
945 }
946
947 /* For sessions with a leader but no explicitly configured
948 * tty, let's check the controlling tty of the leader */
949 if (pid_is_valid(s->leader)) {
950 r = get_process_ctty_atime(s->leader, &atime);
951 if (r >= 0)
952 goto found_atime;
953 }
954
955 dont_know:
956 if (t)
957 *t = s->idle_hint_timestamp;
958
959 return 0;
960
961 found_atime:
962 if (t)
963 dual_timestamp_from_realtime(t, atime);
964
965 n = now(CLOCK_REALTIME);
966
967 if (s->manager->idle_action_usec <= 0)
968 return 0;
969
970 return atime + s->manager->idle_action_usec <= n;
971 }
972
973 void session_set_idle_hint(Session *s, bool b) {
974 assert(s);
975
976 if (s->idle_hint == b)
977 return;
978
979 s->idle_hint = b;
980 dual_timestamp_get(&s->idle_hint_timestamp);
981
982 session_send_changed(s, "IdleHint", "IdleSinceHint", "IdleSinceHintMonotonic", NULL);
983
984 if (s->seat)
985 seat_send_changed(s->seat, "IdleHint", "IdleSinceHint", "IdleSinceHintMonotonic", NULL);
986
987 user_send_changed(s->user, "IdleHint", "IdleSinceHint", "IdleSinceHintMonotonic", NULL);
988 manager_send_changed(s->manager, "IdleHint", "IdleSinceHint", "IdleSinceHintMonotonic", NULL);
989 }
990
991 int session_get_locked_hint(Session *s) {
992 assert(s);
993
994 return s->locked_hint;
995 }
996
997 void session_set_locked_hint(Session *s, bool b) {
998 assert(s);
999
1000 if (s->locked_hint == b)
1001 return;
1002
1003 s->locked_hint = b;
1004
1005 session_send_changed(s, "LockedHint", NULL);
1006 }
1007
1008 static int session_dispatch_fifo(sd_event_source *es, int fd, uint32_t revents, void *userdata) {
1009 Session *s = userdata;
1010
1011 assert(s);
1012 assert(s->fifo_fd == fd);
1013
1014 /* EOF on the FIFO means the session died abnormally. */
1015
1016 session_remove_fifo(s);
1017 session_stop(s, false);
1018
1019 return 1;
1020 }
1021
1022 int session_create_fifo(Session *s) {
1023 int r;
1024
1025 assert(s);
1026
1027 /* Create FIFO */
1028 if (!s->fifo_path) {
1029 r = mkdir_safe_label("/run/systemd/sessions", 0755, 0, 0, MKDIR_WARN_MODE);
1030 if (r < 0)
1031 return r;
1032
1033 s->fifo_path = strjoin("/run/systemd/sessions/", s->id, ".ref");
1034 if (!s->fifo_path)
1035 return -ENOMEM;
1036
1037 if (mkfifo(s->fifo_path, 0600) < 0 && errno != EEXIST)
1038 return -errno;
1039 }
1040
1041 /* Open reading side */
1042 if (s->fifo_fd < 0) {
1043 s->fifo_fd = open(s->fifo_path, O_RDONLY|O_CLOEXEC|O_NONBLOCK);
1044 if (s->fifo_fd < 0)
1045 return -errno;
1046 }
1047
1048 if (!s->fifo_event_source) {
1049 r = sd_event_add_io(s->manager->event, &s->fifo_event_source, s->fifo_fd, 0, session_dispatch_fifo, s);
1050 if (r < 0)
1051 return r;
1052
1053 /* Let's make sure we noticed dead sessions before we process new bus requests (which might create new
1054 * sessions). */
1055 r = sd_event_source_set_priority(s->fifo_event_source, SD_EVENT_PRIORITY_NORMAL-10);
1056 if (r < 0)
1057 return r;
1058 }
1059
1060 /* Open writing side */
1061 r = open(s->fifo_path, O_WRONLY|O_CLOEXEC|O_NONBLOCK);
1062 if (r < 0)
1063 return -errno;
1064
1065 return r;
1066 }
1067
1068 static void session_remove_fifo(Session *s) {
1069 assert(s);
1070
1071 s->fifo_event_source = sd_event_source_unref(s->fifo_event_source);
1072 s->fifo_fd = safe_close(s->fifo_fd);
1073
1074 if (s->fifo_path) {
1075 (void) unlink(s->fifo_path);
1076 s->fifo_path = mfree(s->fifo_path);
1077 }
1078 }
1079
1080 bool session_may_gc(Session *s, bool drop_not_started) {
1081 int r;
1082
1083 assert(s);
1084
1085 if (drop_not_started && !s->started)
1086 return true;
1087
1088 if (!s->user)
1089 return true;
1090
1091 if (s->fifo_fd >= 0) {
1092 if (pipe_eof(s->fifo_fd) <= 0)
1093 return false;
1094 }
1095
1096 if (s->scope_job) {
1097 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1098
1099 r = manager_job_is_active(s->manager, s->scope_job, &error);
1100 if (r < 0)
1101 log_debug_errno(r, "Failed to determine whether job '%s' is pending, ignoring: %s", s->scope_job, bus_error_message(&error, r));
1102 if (r != 0)
1103 return false;
1104 }
1105
1106 if (s->scope) {
1107 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1108
1109 r = manager_unit_is_active(s->manager, s->scope, &error);
1110 if (r < 0)
1111 log_debug_errno(r, "Failed to determine whether unit '%s' is active, ignoring: %s", s->scope, bus_error_message(&error, r));
1112 if (r != 0)
1113 return false;
1114 }
1115
1116 return true;
1117 }
1118
1119 void session_add_to_gc_queue(Session *s) {
1120 assert(s);
1121
1122 if (s->in_gc_queue)
1123 return;
1124
1125 LIST_PREPEND(gc_queue, s->manager->session_gc_queue, s);
1126 s->in_gc_queue = true;
1127 }
1128
1129 SessionState session_get_state(Session *s) {
1130 assert(s);
1131
1132 /* always check closing first */
1133 if (s->stopping || s->timer_event_source)
1134 return SESSION_CLOSING;
1135
1136 if (s->scope_job || s->fifo_fd < 0)
1137 return SESSION_OPENING;
1138
1139 if (session_is_active(s))
1140 return SESSION_ACTIVE;
1141
1142 return SESSION_ONLINE;
1143 }
1144
1145 int session_kill(Session *s, KillWho who, int signo) {
1146 assert(s);
1147
1148 if (!s->scope)
1149 return -ESRCH;
1150
1151 return manager_kill_unit(s->manager, s->scope, who, signo, NULL);
1152 }
1153
1154 static int session_open_vt(Session *s) {
1155 char path[sizeof("/dev/tty") + DECIMAL_STR_MAX(s->vtnr)];
1156
1157 if (s->vtnr < 1)
1158 return -ENODEV;
1159
1160 if (s->vtfd >= 0)
1161 return s->vtfd;
1162
1163 sprintf(path, "/dev/tty%u", s->vtnr);
1164 s->vtfd = open_terminal(path, O_RDWR | O_CLOEXEC | O_NONBLOCK | O_NOCTTY);
1165 if (s->vtfd < 0)
1166 return log_error_errno(s->vtfd, "cannot open VT %s of session %s: %m", path, s->id);
1167
1168 return s->vtfd;
1169 }
1170
1171 int session_prepare_vt(Session *s) {
1172 int vt, r;
1173 struct vt_mode mode = { 0 };
1174
1175 if (s->vtnr < 1)
1176 return 0;
1177
1178 vt = session_open_vt(s);
1179 if (vt < 0)
1180 return vt;
1181
1182 r = fchown(vt, s->user->uid, -1);
1183 if (r < 0) {
1184 r = log_error_errno(errno,
1185 "Cannot change owner of /dev/tty%u: %m",
1186 s->vtnr);
1187 goto error;
1188 }
1189
1190 r = ioctl(vt, KDSKBMODE, K_OFF);
1191 if (r < 0) {
1192 r = log_error_errno(errno,
1193 "Cannot set K_OFF on /dev/tty%u: %m",
1194 s->vtnr);
1195 goto error;
1196 }
1197
1198 r = ioctl(vt, KDSETMODE, KD_GRAPHICS);
1199 if (r < 0) {
1200 r = log_error_errno(errno,
1201 "Cannot set KD_GRAPHICS on /dev/tty%u: %m",
1202 s->vtnr);
1203 goto error;
1204 }
1205
1206 /* Oh, thanks to the VT layer, VT_AUTO does not work with KD_GRAPHICS.
1207 * So we need a dummy handler here which just acknowledges *all* VT
1208 * switch requests. */
1209 mode.mode = VT_PROCESS;
1210 mode.relsig = SIGRTMIN;
1211 mode.acqsig = SIGRTMIN + 1;
1212 r = ioctl(vt, VT_SETMODE, &mode);
1213 if (r < 0) {
1214 r = log_error_errno(errno,
1215 "Cannot set VT_PROCESS on /dev/tty%u: %m",
1216 s->vtnr);
1217 goto error;
1218 }
1219
1220 return 0;
1221
1222 error:
1223 session_restore_vt(s);
1224 return r;
1225 }
1226
1227 static void session_restore_vt(Session *s) {
1228 pid_t pid;
1229 int r;
1230
1231 if (s->vtnr < 1)
1232 return;
1233
1234 if (s->vtfd < 0)
1235 return;
1236
1237 /* The virtual terminal can potentially be entering in hung-up state at any time
1238 * depending on when the controlling process exits.
1239 *
1240 * If the controlling process exits while we're restoring the virtual terminal,
1241 * the VT will enter in hung-up state and we'll fail at restoring it. To prevent
1242 * this case, we kick off the current controlling process (if any) in a child
1243 * process so logind doesn't play around with tty ownership.
1244 *
1245 * If the controlling process already exited, getting a fresh handle to the
1246 * virtual terminal reset the hung-up state. */
1247 r = safe_fork("(logind)", FORK_REOPEN_LOG|FORK_CLOSE_ALL_FDS|FORK_RESET_SIGNALS|FORK_WAIT|FORK_LOG, &pid);
1248 if (r == 0) {
1249 char path[sizeof("/dev/tty") + DECIMAL_STR_MAX(s->vtnr)];
1250 int vt;
1251
1252 /* We must be a session leader in order to become the controlling process. */
1253 pid = setsid();
1254 if (pid < 0) {
1255 log_error_errno(errno, "Failed to become session leader: %m");
1256 _exit(EXIT_FAILURE);
1257 }
1258
1259 sprintf(path, "/dev/tty%u", s->vtnr);
1260 vt = acquire_terminal(path, ACQUIRE_TERMINAL_FORCE, USEC_INFINITY);
1261 if (vt < 0) {
1262 log_error_errno(vt, "Cannot acquire VT %s of session %s: %m", path, s->id);
1263 _exit(EXIT_FAILURE);
1264 }
1265
1266 r = vt_restore(vt);
1267 if (r < 0)
1268 log_warning_errno(r, "Failed to restore VT, ignoring: %m");
1269
1270 /* Give up and release the controlling terminal. */
1271 safe_close(vt);
1272 _exit(EXIT_SUCCESS);
1273 }
1274
1275 /* Close the fd in any cases. */
1276 s->vtfd = safe_close(s->vtfd);
1277 }
1278
1279 void session_leave_vt(Session *s) {
1280 int r;
1281
1282 assert(s);
1283
1284 /* This is called whenever we get a VT-switch signal from the kernel.
1285 * We acknowledge all of them unconditionally. Note that session are
1286 * free to overwrite those handlers and we only register them for
1287 * sessions with controllers. Legacy sessions are not affected.
1288 * However, if we switch from a non-legacy to a legacy session, we must
1289 * make sure to pause all device before acknowledging the switch. We
1290 * process the real switch only after we are notified via sysfs, so the
1291 * legacy session might have already started using the devices. If we
1292 * don't pause the devices before the switch, we might confuse the
1293 * session we switch to. */
1294
1295 if (s->vtfd < 0)
1296 return;
1297
1298 session_device_pause_all(s);
1299 r = vt_release(s->vtfd, false);
1300 if (r < 0)
1301 log_debug_errno(r, "Cannot release VT of session %s: %m", s->id);
1302 }
1303
1304 bool session_is_controller(Session *s, const char *sender) {
1305 assert(s);
1306
1307 return streq_ptr(s->controller, sender);
1308 }
1309
1310 static void session_release_controller(Session *s, bool notify) {
1311 _cleanup_free_ char *name = NULL;
1312 SessionDevice *sd;
1313
1314 if (!s->controller)
1315 return;
1316
1317 name = s->controller;
1318
1319 /* By resetting the controller before releasing the devices, we won't
1320 * send notification signals. This avoids sending useless notifications
1321 * if the controller is released on disconnects. */
1322 if (!notify)
1323 s->controller = NULL;
1324
1325 while ((sd = hashmap_first(s->devices)))
1326 session_device_free(sd);
1327
1328 s->controller = NULL;
1329 s->track = sd_bus_track_unref(s->track);
1330 }
1331
1332 static int on_bus_track(sd_bus_track *track, void *userdata) {
1333 Session *s = userdata;
1334
1335 assert(track);
1336 assert(s);
1337
1338 session_drop_controller(s);
1339
1340 return 0;
1341 }
1342
1343 int session_set_controller(Session *s, const char *sender, bool force, bool prepare) {
1344 _cleanup_free_ char *name = NULL;
1345 int r;
1346
1347 assert(s);
1348 assert(sender);
1349
1350 if (session_is_controller(s, sender))
1351 return 0;
1352 if (s->controller && !force)
1353 return -EBUSY;
1354
1355 name = strdup(sender);
1356 if (!name)
1357 return -ENOMEM;
1358
1359 s->track = sd_bus_track_unref(s->track);
1360 r = sd_bus_track_new(s->manager->bus, &s->track, on_bus_track, s);
1361 if (r < 0)
1362 return r;
1363
1364 r = sd_bus_track_add_name(s->track, name);
1365 if (r < 0)
1366 return r;
1367
1368 /* When setting a session controller, we forcibly mute the VT and set
1369 * it into graphics-mode. Applications can override that by changing
1370 * VT state after calling TakeControl(). However, this serves as a good
1371 * default and well-behaving controllers can now ignore VTs entirely.
1372 * Note that we reset the VT on ReleaseControl() and if the controller
1373 * exits.
1374 * If logind crashes/restarts, we restore the controller during restart
1375 * (without preparing the VT since the controller has probably overridden
1376 * VT state by now) or reset the VT in case it crashed/exited, too. */
1377 if (prepare) {
1378 r = session_prepare_vt(s);
1379 if (r < 0) {
1380 s->track = sd_bus_track_unref(s->track);
1381 return r;
1382 }
1383 }
1384
1385 session_release_controller(s, true);
1386 s->controller = TAKE_PTR(name);
1387 session_save(s);
1388
1389 return 0;
1390 }
1391
1392 void session_drop_controller(Session *s) {
1393 assert(s);
1394
1395 if (!s->controller)
1396 return;
1397
1398 s->track = sd_bus_track_unref(s->track);
1399 session_release_controller(s, false);
1400 session_save(s);
1401 session_restore_vt(s);
1402 }
1403
1404 static const char* const session_state_table[_SESSION_STATE_MAX] = {
1405 [SESSION_OPENING] = "opening",
1406 [SESSION_ONLINE] = "online",
1407 [SESSION_ACTIVE] = "active",
1408 [SESSION_CLOSING] = "closing"
1409 };
1410
1411 DEFINE_STRING_TABLE_LOOKUP(session_state, SessionState);
1412
1413 static const char* const session_type_table[_SESSION_TYPE_MAX] = {
1414 [SESSION_UNSPECIFIED] = "unspecified",
1415 [SESSION_TTY] = "tty",
1416 [SESSION_X11] = "x11",
1417 [SESSION_WAYLAND] = "wayland",
1418 [SESSION_MIR] = "mir",
1419 [SESSION_WEB] = "web",
1420 };
1421
1422 DEFINE_STRING_TABLE_LOOKUP(session_type, SessionType);
1423
1424 static const char* const session_class_table[_SESSION_CLASS_MAX] = {
1425 [SESSION_USER] = "user",
1426 [SESSION_GREETER] = "greeter",
1427 [SESSION_LOCK_SCREEN] = "lock-screen",
1428 [SESSION_BACKGROUND] = "background"
1429 };
1430
1431 DEFINE_STRING_TABLE_LOOKUP(session_class, SessionClass);
1432
1433 static const char* const kill_who_table[_KILL_WHO_MAX] = {
1434 [KILL_LEADER] = "leader",
1435 [KILL_ALL] = "all"
1436 };
1437
1438 DEFINE_STRING_TABLE_LOOKUP(kill_who, KillWho);
1439
1440 static const char* const tty_validity_table[_TTY_VALIDITY_MAX] = {
1441 [TTY_FROM_PAM] = "from-pam",
1442 [TTY_FROM_UTMP] = "from-utmp",
1443 [TTY_UTMP_INCONSISTENT] = "utmp-inconsistent",
1444 };
1445
1446 DEFINE_STRING_TABLE_LOOKUP(tty_validity, TTYValidity);