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