1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2011 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
28 #include <sys/ioctl.h>
32 #include "sd-messages.h"
36 #include "path-util.h"
40 #include "bus-error.h"
41 #include "logind-session.h"
43 #define RELEASE_USEC (20*USEC_PER_SEC)
45 static void session_remove_fifo(Session *s);
47 static unsigned long devt_hash_func(const void *p, const uint8_t hash_key[HASH_KEY_SIZE]) {
48 uint64_t u = *(const dev_t*)p;
50 return uint64_hash_func(&u, hash_key);
53 static int devt_compare_func(const void *_a, const void *_b) {
56 a = *(const dev_t*) _a;
57 b = *(const dev_t*) _b;
59 return a < b ? -1 : (a > b ? 1 : 0);
62 Session* session_new(Manager *m, const char *id) {
67 assert(session_id_valid(id));
73 s->state_file = strappend("/run/systemd/sessions/", id);
79 s->devices = hashmap_new(devt_hash_func, devt_compare_func);
86 s->id = basename(s->state_file);
88 if (hashmap_put(m->sessions, s->id, s) < 0) {
89 hashmap_free(s->devices);
102 void session_free(Session *s) {
108 LIST_REMOVE(gc_queue, s->manager->session_gc_queue, s);
110 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
112 session_remove_fifo(s);
114 session_drop_controller(s);
116 while ((sd = hashmap_first(s->devices)))
117 session_device_free(sd);
119 hashmap_free(s->devices);
122 LIST_REMOVE(sessions_by_user, s->user->sessions, s);
124 if (s->user->display == s)
125 s->user->display = NULL;
129 if (s->seat->active == s)
130 s->seat->active = NULL;
131 if (s->seat->pending_switch == s)
132 s->seat->pending_switch = NULL;
134 seat_evict_position(s->seat, s);
135 LIST_REMOVE(sessions_by_seat, s->seat->sessions, s);
139 hashmap_remove(s->manager->session_units, s->scope);
145 sd_bus_message_unref(s->create_message);
149 free(s->remote_host);
150 free(s->remote_user);
154 hashmap_remove(s->manager->sessions, s->id);
160 void session_set_user(Session *s, User *u) {
165 LIST_PREPEND(sessions_by_user, u->sessions, s);
168 int session_save(Session *s) {
169 _cleanup_free_ char *temp_path = NULL;
170 _cleanup_fclose_ FILE *f = NULL;
181 r = mkdir_safe_label("/run/systemd/sessions", 0755, 0, 0);
185 r = fopen_temporary(s->state_file, &f, &temp_path);
191 fchmod(fileno(f), 0644);
194 "# This is private data. Do not parse.\n"
202 session_is_active(s),
203 session_state_to_string(session_get_state(s)),
207 fprintf(f, "TYPE=%s\n", session_type_to_string(s->type));
210 fprintf(f, "CLASS=%s\n", session_class_to_string(s->class));
213 fprintf(f, "SCOPE=%s\n", s->scope);
215 fprintf(f, "SCOPE_JOB=%s\n", s->scope_job);
218 fprintf(f, "FIFO=%s\n", s->fifo_path);
221 fprintf(f, "SEAT=%s\n", s->seat->id);
224 fprintf(f, "TTY=%s\n", s->tty);
227 fprintf(f, "DISPLAY=%s\n", s->display);
229 if (s->remote_host) {
230 _cleanup_free_ char *escaped;
232 escaped = cescape(s->remote_host);
238 fprintf(f, "REMOTE_HOST=%s\n", escaped);
241 if (s->remote_user) {
242 _cleanup_free_ char *escaped;
244 escaped = cescape(s->remote_user);
250 fprintf(f, "REMOTE_USER=%s\n", escaped);
254 _cleanup_free_ char *escaped;
256 escaped = cescape(s->service);
262 fprintf(f, "SERVICE=%s\n", escaped);
266 _cleanup_free_ char *escaped;
269 escaped = cescape(s->desktop);
275 fprintf(f, "DESKTOP=%s\n", escaped);
278 if (s->seat && seat_has_vts(s->seat))
279 fprintf(f, "VTNR=%u\n", s->vtnr);
282 fprintf(f, "POS=%u\n", s->pos);
285 fprintf(f, "LEADER="PID_FMT"\n", s->leader);
288 fprintf(f, "AUDIT=%"PRIu32"\n", s->audit_id);
290 if (dual_timestamp_is_set(&s->timestamp))
292 "REALTIME="USEC_FMT"\n"
293 "MONOTONIC="USEC_FMT"\n",
294 s->timestamp.realtime,
295 s->timestamp.monotonic);
298 fprintf(f, "CONTROLLER=%s\n", s->controller);
302 if (ferror(f) || rename(temp_path, s->state_file) < 0) {
304 unlink(s->state_file);
310 log_error("Failed to save session data %s: %s", s->state_file, strerror(-r));
315 int session_load(Session *s) {
316 _cleanup_free_ char *remote = NULL,
332 r = parse_env_file(s->state_file, NEWLINE,
335 "SCOPE_JOB", &s->scope_job,
336 "FIFO", &s->fifo_path,
339 "DISPLAY", &s->display,
340 "REMOTE_HOST", &s->remote_host,
341 "REMOTE_USER", &s->remote_user,
342 "SERVICE", &s->service,
343 "DESKTOP", &s->desktop,
350 "REALTIME", &realtime,
351 "MONOTONIC", &monotonic,
352 "CONTROLLER", &controller,
356 log_error("Failed to read %s: %s", s->state_file, strerror(-r));
365 log_error("UID not specified for session %s", s->id);
369 r = parse_uid(uid, &u);
371 log_error("Failed to parse UID value %s for session %s.", uid, s->id);
375 user = hashmap_get(s->manager->users, ULONG_TO_PTR((unsigned long) u));
377 log_error("User of session %s not known.", s->id);
381 session_set_user(s, user);
385 k = parse_boolean(remote);
391 safe_atou(vtnr, &s->vtnr);
393 if (seat && !s->seat) {
396 o = hashmap_get(s->manager->seats, seat);
398 r = seat_attach_session(o, s);
400 log_error("Cannot attach session %s to seat %s", s->id, seat);
403 if (!s->seat || !seat_has_vts(s->seat))
406 if (pos && s->seat) {
409 safe_atou(pos, &npos);
410 seat_claim_position(s->seat, s, npos);
414 k = parse_pid(leader, &s->leader);
416 audit_session_from_pid(s->leader, &s->audit_id);
422 t = session_type_from_string(type);
430 c = session_class_from_string(class);
438 /* If we open an unopened pipe for reading we will not
439 get an EOF. to trigger an EOF we hence open it for
440 reading, but close it right-away which then will
443 fd = session_create_fifo(s);
448 unsigned long long l;
449 if (sscanf(realtime, "%llu", &l) > 0)
450 s->timestamp.realtime = l;
454 unsigned long long l;
455 if (sscanf(monotonic, "%llu", &l) > 0)
456 s->timestamp.monotonic = l;
460 if (bus_name_has_owner(s->manager->bus, controller, NULL) > 0)
461 session_set_controller(s, controller, false);
463 session_restore_vt(s);
469 int session_activate(Session *s) {
470 unsigned int num_pending;
478 if (s->seat->active == s)
481 /* on seats with VTs, we let VTs manage session-switching */
482 if (seat_has_vts(s->seat)) {
486 return chvt(s->vtnr);
489 /* On seats without VTs, we implement session-switching in logind. We
490 * try to pause all session-devices and wait until the session
491 * controller acknowledged them. Once all devices are asleep, we simply
492 * switch the active session and be done.
493 * We save the session we want to switch to in seat->pending_switch and
494 * seat_complete_switch() will perform the final switch. */
496 s->seat->pending_switch = s;
498 /* if no devices are running, immediately perform the session switch */
499 num_pending = session_device_try_pause_all(s);
501 seat_complete_switch(s->seat);
506 static int session_start_scope(Session *s) {
511 assert(s->user->slice);
514 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
515 _cleanup_free_ char *description = NULL;
516 char *scope, *job = NULL;
518 description = strjoin("Session ", s->id, " of user ", s->user->name, NULL);
522 scope = strjoin("session-", s->id, ".scope", NULL);
526 r = manager_start_scope(s->manager, scope, s->leader, s->user->slice, description, "systemd-logind.service", "systemd-user-sessions.service", &error, &job);
528 log_error("Failed to start session scope %s: %s %s",
529 scope, bus_error_message(&error, r), error.name);
541 hashmap_put(s->manager->session_units, s->scope, s);
546 int session_start(Session *s) {
557 r = user_start(s->user);
562 r = session_start_scope(s);
566 log_struct(s->class == SESSION_BACKGROUND ? LOG_DEBUG : LOG_INFO,
567 MESSAGE_ID(SD_MESSAGE_SESSION_START),
568 "SESSION_ID=%s", s->id,
569 "USER_ID=%s", s->user->name,
570 "LEADER="PID_FMT, s->leader,
571 "MESSAGE=New session %s of user %s.", s->id, s->user->name,
574 if (!dual_timestamp_is_set(&s->timestamp))
575 dual_timestamp_get(&s->timestamp);
578 seat_read_active_vt(s->seat);
582 user_elect_display(s->user);
591 session_send_signal(s, true);
592 user_send_changed(s->user, "Sessions", "Display", NULL);
594 if (s->seat->active == s)
595 seat_send_changed(s->seat, "Sessions", "ActiveSession", NULL);
597 seat_send_changed(s->seat, "Sessions", NULL);
603 static int session_stop_scope(Session *s, bool force) {
604 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
613 if (force || manager_shall_kill(s->manager, s->user->name)) {
614 r = manager_stop_unit(s->manager, s->scope, &error, &job);
616 log_error("Failed to stop session scope: %s", bus_error_message(&error, r));
623 r = manager_abandon_scope(s->manager, s->scope, &error);
625 log_error("Failed to abandon session scope: %s", bus_error_message(&error, r));
633 int session_stop(Session *s, bool force) {
641 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
643 /* We are going down, don't care about FIFOs anymore */
644 session_remove_fifo(s);
647 r = session_stop_scope(s, force);
651 user_elect_display(s->user);
659 int session_finalize(Session *s) {
669 log_struct(s->class == SESSION_BACKGROUND ? LOG_DEBUG : LOG_INFO,
670 MESSAGE_ID(SD_MESSAGE_SESSION_STOP),
671 "SESSION_ID=%s", s->id,
672 "USER_ID=%s", s->user->name,
673 "LEADER="PID_FMT, s->leader,
674 "MESSAGE=Removed session %s.", s->id,
677 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
679 /* Kill session devices */
680 while ((sd = hashmap_first(s->devices)))
681 session_device_free(sd);
683 unlink(s->state_file);
684 session_add_to_gc_queue(s);
685 user_add_to_gc_queue(s->user);
688 session_send_signal(s, false);
693 if (s->seat->active == s)
694 seat_set_active(s->seat, NULL);
697 seat_send_changed(s->seat, "Sessions", NULL);
701 user_send_changed(s->user, "Sessions", "Display", NULL);
706 static int release_timeout_callback(sd_event_source *es, uint64_t usec, void *userdata) {
707 Session *s = userdata;
712 session_stop(s, false);
716 void session_release(Session *s) {
719 if (!s->started || s->stopping)
722 if (!s->timer_event_source)
723 sd_event_add_time(s->manager->event,
724 &s->timer_event_source,
726 now(CLOCK_MONOTONIC) + RELEASE_USEC, 0,
727 release_timeout_callback, s);
730 bool session_is_active(Session *s) {
736 return s->seat->active == s;
739 static int get_tty_atime(const char *tty, usec_t *atime) {
740 _cleanup_free_ char *p = NULL;
746 if (!path_is_absolute(tty)) {
747 p = strappend("/dev/", tty);
752 } else if (!path_startswith(tty, "/dev/"))
755 if (lstat(tty, &st) < 0)
758 *atime = timespec_load(&st.st_atim);
762 static int get_process_ctty_atime(pid_t pid, usec_t *atime) {
763 _cleanup_free_ char *p = NULL;
769 r = get_ctty(pid, NULL, &p);
773 return get_tty_atime(p, atime);
776 int session_get_idle_hint(Session *s, dual_timestamp *t) {
782 /* Explicit idle hint is set */
785 *t = s->idle_hint_timestamp;
790 /* Graphical sessions should really implement a real
795 /* For sessions with an explicitly configured tty, let's check
798 r = get_tty_atime(s->tty, &atime);
803 /* For sessions with a leader but no explicitly configured
804 * tty, let's check the controlling tty of the leader */
806 r = get_process_ctty_atime(s->leader, &atime);
813 *t = s->idle_hint_timestamp;
819 dual_timestamp_from_realtime(t, atime);
821 n = now(CLOCK_REALTIME);
823 if (s->manager->idle_action_usec <= 0)
826 return atime + s->manager->idle_action_usec <= n;
829 void session_set_idle_hint(Session *s, bool b) {
832 if (s->idle_hint == b)
836 dual_timestamp_get(&s->idle_hint_timestamp);
838 session_send_changed(s, "IdleHint", "IdleSinceHint", "IdleSinceHintMonotonic", NULL);
841 seat_send_changed(s->seat, "IdleHint", "IdleSinceHint", "IdleSinceHintMonotonic", NULL);
843 user_send_changed(s->user, "IdleHint", "IdleSinceHint", "IdleSinceHintMonotonic", NULL);
844 manager_send_changed(s->manager, "IdleHint", "IdleSinceHint", "IdleSinceHintMonotonic", NULL);
847 static int session_dispatch_fifo(sd_event_source *es, int fd, uint32_t revents, void *userdata) {
848 Session *s = userdata;
851 assert(s->fifo_fd == fd);
853 /* EOF on the FIFO means the session died abnormally. */
855 session_remove_fifo(s);
856 session_stop(s, false);
861 int session_create_fifo(Session *s) {
868 r = mkdir_safe_label("/run/systemd/sessions", 0755, 0, 0);
872 if (asprintf(&s->fifo_path, "/run/systemd/sessions/%s.ref", s->id) < 0)
875 if (mkfifo(s->fifo_path, 0600) < 0 && errno != EEXIST)
879 /* Open reading side */
880 if (s->fifo_fd < 0) {
881 s->fifo_fd = open(s->fifo_path, O_RDONLY|O_CLOEXEC|O_NDELAY);
887 if (!s->fifo_event_source) {
888 r = sd_event_add_io(s->manager->event, &s->fifo_event_source, s->fifo_fd, 0, session_dispatch_fifo, s);
892 r = sd_event_source_set_priority(s->fifo_event_source, SD_EVENT_PRIORITY_IDLE);
897 /* Open writing side */
898 r = open(s->fifo_path, O_WRONLY|O_CLOEXEC|O_NDELAY);
905 static void session_remove_fifo(Session *s) {
908 s->fifo_event_source = sd_event_source_unref(s->fifo_event_source);
909 s->fifo_fd = safe_close(s->fifo_fd);
912 unlink(s->fifo_path);
918 bool session_check_gc(Session *s, bool drop_not_started) {
921 if (drop_not_started && !s->started)
927 if (s->fifo_fd >= 0) {
928 if (pipe_eof(s->fifo_fd) <= 0)
932 if (s->scope_job && manager_job_is_active(s->manager, s->scope_job))
935 if (s->scope && manager_unit_is_active(s->manager, s->scope))
941 void session_add_to_gc_queue(Session *s) {
947 LIST_PREPEND(gc_queue, s->manager->session_gc_queue, s);
948 s->in_gc_queue = true;
951 SessionState session_get_state(Session *s) {
954 /* always check closing first */
955 if (s->stopping || s->timer_event_source)
956 return SESSION_CLOSING;
958 if (s->scope_job || s->fifo_fd < 0)
959 return SESSION_OPENING;
961 if (session_is_active(s))
962 return SESSION_ACTIVE;
964 return SESSION_ONLINE;
967 int session_kill(Session *s, KillWho who, int signo) {
973 return manager_kill_unit(s->manager, s->scope, who, signo, NULL);
976 static int session_open_vt(Session *s) {
977 char path[sizeof("/dev/tty") + DECIMAL_STR_MAX(s->vtnr)];
985 sprintf(path, "/dev/tty%u", s->vtnr);
986 s->vtfd = open(path, O_RDWR | O_CLOEXEC | O_NONBLOCK | O_NOCTTY);
988 log_error("cannot open VT %s of session %s: %m", path, s->id);
995 int session_prepare_vt(Session *s) {
997 struct vt_mode mode = { 0 };
1002 vt = session_open_vt(s);
1006 r = fchown(vt, s->user->uid, -1);
1009 log_error("Cannot change owner of /dev/tty%u: %m", s->vtnr);
1013 r = ioctl(vt, KDSKBMODE, K_OFF);
1016 log_error("Cannot set K_OFF on /dev/tty%u: %m", s->vtnr);
1020 r = ioctl(vt, KDSETMODE, KD_GRAPHICS);
1023 log_error("Cannot set KD_GRAPHICS on /dev/tty%u: %m", s->vtnr);
1027 /* Oh, thanks to the VT layer, VT_AUTO does not work with KD_GRAPHICS.
1028 * So we need a dummy handler here which just acknowledges *all* VT
1029 * switch requests. */
1030 mode.mode = VT_PROCESS;
1031 mode.relsig = SIGRTMIN;
1032 mode.acqsig = SIGRTMIN + 1;
1033 r = ioctl(vt, VT_SETMODE, &mode);
1036 log_error("Cannot set VT_PROCESS on /dev/tty%u: %m", s->vtnr);
1043 session_restore_vt(s);
1047 void session_restore_vt(Session *s) {
1048 _cleanup_free_ char *utf8 = NULL;
1049 int vt, kb = K_XLATE;
1050 struct vt_mode mode = { 0 };
1052 vt = session_open_vt(s);
1056 ioctl(vt, KDSETMODE, KD_TEXT);
1058 if (read_one_line_file("/sys/module/vt/parameters/default_utf8", &utf8) >= 0 && *utf8 == '1')
1061 ioctl(vt, KDSKBMODE, kb);
1063 mode.mode = VT_AUTO;
1064 ioctl(vt, VT_SETMODE, &mode);
1068 s->vtfd = safe_close(s->vtfd);
1071 bool session_is_controller(Session *s, const char *sender) {
1074 return streq_ptr(s->controller, sender);
1077 static void session_swap_controller(Session *s, char *name) {
1080 if (s->controller) {
1081 manager_drop_busname(s->manager, s->controller);
1082 free(s->controller);
1083 s->controller = NULL;
1085 /* Drop all devices as they're now unused. Do that after the
1086 * controller is released to avoid sending out useles
1088 while ((sd = hashmap_first(s->devices)))
1089 session_device_free(sd);
1092 session_restore_vt(s);
1095 s->controller = name;
1099 int session_set_controller(Session *s, const char *sender, bool force) {
1106 if (session_is_controller(s, sender))
1108 if (s->controller && !force)
1115 r = manager_watch_busname(s->manager, sender);
1121 /* When setting a session controller, we forcibly mute the VT and set
1122 * it into graphics-mode. Applications can override that by changing
1123 * VT state after calling TakeControl(). However, this serves as a good
1124 * default and well-behaving controllers can now ignore VTs entirely.
1125 * Note that we reset the VT on ReleaseControl() and if the controller
1127 * If logind crashes/restarts, we restore the controller during restart
1128 * or reset the VT in case it crashed/exited, too. */
1129 r = session_prepare_vt(s);
1133 session_swap_controller(s, t);
1138 void session_drop_controller(Session *s) {
1144 session_swap_controller(s, NULL);
1147 static const char* const session_state_table[_SESSION_STATE_MAX] = {
1148 [SESSION_OPENING] = "opening",
1149 [SESSION_ONLINE] = "online",
1150 [SESSION_ACTIVE] = "active",
1151 [SESSION_CLOSING] = "closing"
1154 DEFINE_STRING_TABLE_LOOKUP(session_state, SessionState);
1156 static const char* const session_type_table[_SESSION_TYPE_MAX] = {
1157 [SESSION_UNSPECIFIED] = "unspecified",
1158 [SESSION_TTY] = "tty",
1159 [SESSION_X11] = "x11",
1160 [SESSION_WAYLAND] = "wayland",
1161 [SESSION_MIR] = "mir",
1164 DEFINE_STRING_TABLE_LOOKUP(session_type, SessionType);
1166 static const char* const session_class_table[_SESSION_CLASS_MAX] = {
1167 [SESSION_USER] = "user",
1168 [SESSION_GREETER] = "greeter",
1169 [SESSION_LOCK_SCREEN] = "lock-screen",
1170 [SESSION_BACKGROUND] = "background"
1173 DEFINE_STRING_TABLE_LOOKUP(session_class, SessionClass);
1175 static const char* const kill_who_table[_KILL_WHO_MAX] = {
1176 [KILL_LEADER] = "leader",
1180 DEFINE_STRING_TABLE_LOOKUP(kill_who, KillWho);