1 /* SPDX-License-Identifier: LGPL-2.1+ */
10 #include <sys/ioctl.h>
13 #include "sd-messages.h"
15 #include "alloc-util.h"
16 #include "audit-util.h"
17 #include "bus-error.h"
22 #include "format-util.h"
24 #include "logind-session.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"
32 #include "terminal-util.h"
33 #include "user-util.h"
36 #define RELEASE_USEC (20*USEC_PER_SEC)
38 static void session_remove_fifo(Session
*s
);
39 static void session_restore_vt(Session
*s
);
41 int session_new(Session
**ret
, Manager
*m
, const char *id
) {
42 _cleanup_(session_freep
) Session
*s
= NULL
;
49 if (!session_id_valid(id
))
60 .audit_id
= AUDIT_SESSION_INVALID
,
61 .tty_validity
= _TTY_VALIDITY_INVALID
,
64 s
->state_file
= strappend("/run/systemd/sessions/", id
);
68 s
->id
= basename(s
->state_file
);
70 s
->devices
= hashmap_new(&devt_hash_ops
);
74 r
= hashmap_put(m
->sessions
, s
->id
, s
);
82 Session
* session_free(Session
*s
) {
89 LIST_REMOVE(gc_queue
, s
->manager
->session_gc_queue
, s
);
91 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
93 session_remove_fifo(s
);
95 session_drop_controller(s
);
97 while ((sd
= hashmap_first(s
->devices
)))
98 session_device_free(sd
);
100 hashmap_free(s
->devices
);
103 LIST_REMOVE(sessions_by_user
, s
->user
->sessions
, s
);
105 if (s
->user
->display
== s
)
106 s
->user
->display
= NULL
;
108 user_update_last_session_timer(s
->user
);
112 if (s
->seat
->active
== s
)
113 s
->seat
->active
= NULL
;
114 if (s
->seat
->pending_switch
== s
)
115 s
->seat
->pending_switch
= NULL
;
117 seat_evict_position(s
->seat
, s
);
118 LIST_REMOVE(sessions_by_seat
, s
->seat
->sessions
, s
);
122 hashmap_remove(s
->manager
->session_units
, s
->scope
);
126 if (pid_is_valid(s
->leader
))
127 (void) hashmap_remove_value(s
->manager
->sessions_by_leader
, PID_TO_PTR(s
->leader
), s
);
131 sd_bus_message_unref(s
->create_message
);
135 free(s
->remote_host
);
136 free(s
->remote_user
);
140 hashmap_remove(s
->manager
->sessions
, s
->id
);
147 void session_set_user(Session
*s
, User
*u
) {
152 LIST_PREPEND(sessions_by_user
, u
->sessions
, s
);
154 user_update_last_session_timer(u
);
157 int session_set_leader(Session
*s
, pid_t pid
) {
162 if (!pid_is_valid(pid
))
165 if (s
->leader
== pid
)
168 r
= hashmap_put(s
->manager
->sessions_by_leader
, PID_TO_PTR(pid
), s
);
172 if (pid_is_valid(s
->leader
))
173 (void) hashmap_remove_value(s
->manager
->sessions_by_leader
, PID_TO_PTR(s
->leader
), s
);
176 (void) audit_session_from_pid(pid
, &s
->audit_id
);
181 static void session_save_devices(Session
*s
, FILE *f
) {
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
));
193 int session_save(Session
*s
) {
194 _cleanup_free_
char *temp_path
= NULL
;
195 _cleanup_fclose_
FILE *f
= NULL
;
206 r
= mkdir_safe_label("/run/systemd/sessions", 0755, 0, 0, MKDIR_WARN_MODE
);
210 r
= fopen_temporary(s
->state_file
, &f
, &temp_path
);
214 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
215 (void) fchmod(fileno(f
), 0644);
218 "# This is private data. Do not parse.\n"
227 session_is_active(s
),
228 s
->user
->display
== s
,
229 session_state_to_string(session_get_state(s
)),
233 fprintf(f
, "TYPE=%s\n", session_type_to_string(s
->type
));
236 fprintf(f
, "CLASS=%s\n", session_class_to_string(s
->class));
239 fprintf(f
, "SCOPE=%s\n", s
->scope
);
241 fprintf(f
, "SCOPE_JOB=%s\n", s
->scope_job
);
244 fprintf(f
, "FIFO=%s\n", s
->fifo_path
);
247 fprintf(f
, "SEAT=%s\n", s
->seat
->id
);
250 fprintf(f
, "TTY=%s\n", s
->tty
);
252 if (s
->tty_validity
>= 0)
253 fprintf(f
, "TTY_VALIDITY=%s\n", tty_validity_to_string(s
->tty_validity
));
256 fprintf(f
, "DISPLAY=%s\n", s
->display
);
258 if (s
->remote_host
) {
259 _cleanup_free_
char *escaped
;
261 escaped
= cescape(s
->remote_host
);
267 fprintf(f
, "REMOTE_HOST=%s\n", escaped
);
270 if (s
->remote_user
) {
271 _cleanup_free_
char *escaped
;
273 escaped
= cescape(s
->remote_user
);
279 fprintf(f
, "REMOTE_USER=%s\n", escaped
);
283 _cleanup_free_
char *escaped
;
285 escaped
= cescape(s
->service
);
291 fprintf(f
, "SERVICE=%s\n", escaped
);
295 _cleanup_free_
char *escaped
;
297 escaped
= cescape(s
->desktop
);
303 fprintf(f
, "DESKTOP=%s\n", escaped
);
306 if (s
->seat
&& seat_has_vts(s
->seat
))
307 fprintf(f
, "VTNR=%u\n", s
->vtnr
);
310 fprintf(f
, "POSITION=%u\n", s
->position
);
312 if (pid_is_valid(s
->leader
))
313 fprintf(f
, "LEADER="PID_FMT
"\n", s
->leader
);
315 if (audit_session_is_valid(s
->audit_id
))
316 fprintf(f
, "AUDIT=%"PRIu32
"\n", s
->audit_id
);
318 if (dual_timestamp_is_set(&s
->timestamp
))
320 "REALTIME="USEC_FMT
"\n"
321 "MONOTONIC="USEC_FMT
"\n",
322 s
->timestamp
.realtime
,
323 s
->timestamp
.monotonic
);
326 fprintf(f
, "CONTROLLER=%s\n", s
->controller
);
327 session_save_devices(s
, f
);
330 r
= fflush_and_check(f
);
334 if (rename(temp_path
, s
->state_file
) < 0) {
342 (void) unlink(s
->state_file
);
345 (void) unlink(temp_path
);
347 return log_error_errno(r
, "Failed to save session data %s: %m", s
->state_file
);
350 static int session_load_devices(Session
*s
, const char *devices
) {
356 for (p
= devices
;;) {
357 _cleanup_free_
char *word
= NULL
;
362 k
= extract_first_word(&p
, &word
, NULL
, 0);
370 k
= parse_dev(word
, &dev
);
376 /* The file descriptors for loaded devices will be reattached later. */
377 k
= session_device_new(s
, dev
, false, &sd
);
383 log_error_errno(r
, "Loading session devices for session %s failed: %m", s
->id
);
388 int session_load(Session
*s
) {
389 _cleanup_free_
char *remote
= NULL
,
391 *tty_validity
= NULL
,
410 r
= parse_env_file(NULL
, s
->state_file
,
413 "SCOPE_JOB", &s
->scope_job
,
414 "FIFO", &s
->fifo_path
,
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
,
425 "POSITION", &position
,
430 "REALTIME", &realtime
,
431 "MONOTONIC", &monotonic
,
432 "CONTROLLER", &controller
,
435 "IS_DISPLAY", &is_display
);
438 return log_error_errno(r
, "Failed to read %s: %m", s
->state_file
);
445 log_error("UID not specified for session %s", s
->id
);
449 r
= parse_uid(uid
, &u
);
451 log_error("Failed to parse UID value %s for session %s.", uid
, s
->id
);
455 user
= hashmap_get(s
->manager
->users
, UID_TO_PTR(u
));
457 log_error("User of session %s not known.", s
->id
);
461 session_set_user(s
, user
);
465 k
= parse_boolean(remote
);
471 safe_atou(vtnr
, &s
->vtnr
);
473 if (seat
&& !s
->seat
) {
476 o
= hashmap_get(s
->manager
->seats
, seat
);
478 r
= seat_attach_session(o
, s
);
480 log_error("Cannot attach session %s to seat %s", s
->id
, seat
);
483 if (!s
->seat
|| !seat_has_vts(s
->seat
))
486 if (position
&& s
->seat
) {
489 safe_atou(position
, &npos
);
490 seat_claim_position(s
->seat
, s
, npos
);
496 v
= tty_validity_from_string(tty_validity
);
498 log_debug("Failed to parse TTY validity: %s", tty_validity
);
506 r
= parse_pid(leader
, &pid
);
508 log_debug_errno(r
, "Failed to parse leader PID of session: %s", leader
);
510 r
= session_set_leader(s
, pid
);
512 log_warning_errno(r
, "Failed to set session leader PID, ignoring: %m");
519 t
= session_type_from_string(type
);
527 c
= session_class_from_string(class);
532 if (state
&& streq(state
, "closing"))
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. */
545 fd
= session_create_fifo(s
);
550 (void) deserialize_usec(realtime
, &s
->timestamp
.realtime
);
552 (void) deserialize_usec(monotonic
, &s
->timestamp
.monotonic
);
555 k
= parse_boolean(active
);
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. */
565 k
= parse_boolean(is_display
);
567 log_warning_errno(k
, "Failed to parse IS_DISPLAY session property: %m");
569 s
->user
->display
= s
;
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
);
577 session_restore_vt(s
);
583 int session_activate(Session
*s
) {
584 unsigned num_pending
;
592 if (s
->seat
->active
== s
)
595 /* on seats with VTs, we let VTs manage session-switching */
596 if (seat_has_vts(s
->seat
)) {
600 return chvt(s
->vtnr
);
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. */
610 s
->seat
->pending_switch
= s
;
612 /* if no devices are running, immediately perform the session switch */
613 num_pending
= session_device_try_pause_all(s
);
615 seat_complete_switch(s
->seat
);
620 static int session_start_scope(Session
*s
, sd_bus_message
*properties
, sd_bus_error
*error
) {
627 _cleanup_free_
char *scope
= NULL
;
628 const char *description
;
630 s
->scope_job
= mfree(s
->scope_job
);
632 scope
= strjoin("session-", s
->id
, ".scope");
636 description
= strjoina("Session ", s
->id
, " of user ", s
->user
->name
);
638 r
= manager_start_scope(
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 */
651 return log_error_errno(r
, "Failed to start session scope %s: %s", scope
, bus_error_message(error
, r
));
653 s
->scope
= TAKE_PTR(scope
);
657 (void) hashmap_put(s
->manager
->session_units
, s
->scope
, s
);
662 int session_start(Session
*s
, sd_bus_message
*properties
, sd_bus_error
*error
) {
676 r
= user_start(s
->user
);
680 r
= session_start_scope(s
, properties
, error
);
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
));
691 if (!dual_timestamp_is_set(&s
->timestamp
))
692 dual_timestamp_get(&s
->timestamp
);
695 seat_read_active_vt(s
->seat
);
699 user_elect_display(s
->user
);
708 session_send_signal(s
, true);
709 user_send_changed(s
->user
, "Display", NULL
);
711 if (s
->seat
->active
== s
)
712 seat_send_changed(s
->seat
, "ActiveSession", NULL
);
718 static int session_stop_scope(Session
*s
, bool force
) {
719 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
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
);
732 log_warning_errno(r
, "Failed to abandon session scope, ignoring: %s", bus_error_message(&error
, r
));
733 sd_bus_error_free(&error
);
736 s
->scope_job
= mfree(s
->scope_job
);
738 /* Optionally, let's kill everything that's left now. */
739 if (force
|| manager_shall_kill(s
->manager
, s
->user
->name
)) {
741 r
= manager_stop_unit(s
->manager
, s
->scope
, &error
, &s
->scope_job
);
744 return log_error_errno(r
, "Failed to stop session scope: %s", bus_error_message(&error
, r
));
746 log_warning_errno(r
, "Failed to stop session scope, ignoring: %s", bus_error_message(&error
, r
));
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
));
763 int session_stop(Session
*s
, bool force
) {
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). */
780 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
783 seat_evict_position(s
->seat
, s
);
785 /* We are going down, don't care about FIFOs anymore */
786 session_remove_fifo(s
);
789 r
= session_stop_scope(s
, force
);
793 user_elect_display(s
->user
);
801 int session_finalize(Session
*s
) {
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
));
817 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
820 seat_evict_position(s
->seat
, s
);
822 /* Kill session devices */
823 while ((sd
= hashmap_first(s
->devices
)))
824 session_device_free(sd
);
826 (void) unlink(s
->state_file
);
827 session_add_to_gc_queue(s
);
828 user_add_to_gc_queue(s
->user
);
831 session_send_signal(s
, false);
836 if (s
->seat
->active
== s
)
837 seat_set_active(s
->seat
, NULL
);
843 user_send_changed(s
->user
, "Display", NULL
);
848 static int release_timeout_callback(sd_event_source
*es
, uint64_t usec
, void *userdata
) {
849 Session
*s
= userdata
;
854 session_stop(s
, false);
858 int session_release(Session
*s
) {
861 if (!s
->started
|| s
->stopping
)
864 if (s
->timer_event_source
)
867 return sd_event_add_time(s
->manager
->event
,
868 &s
->timer_event_source
,
870 usec_add(now(CLOCK_MONOTONIC
), RELEASE_USEC
), 0,
871 release_timeout_callback
, s
);
874 bool session_is_active(Session
*s
) {
880 return s
->seat
->active
== s
;
883 static int get_tty_atime(const char *tty
, usec_t
*atime
) {
884 _cleanup_free_
char *p
= NULL
;
890 if (!path_is_absolute(tty
)) {
891 p
= strappend("/dev/", tty
);
896 } else if (!path_startswith(tty
, "/dev/"))
899 if (lstat(tty
, &st
) < 0)
902 *atime
= timespec_load(&st
.st_atim
);
906 static int get_process_ctty_atime(pid_t pid
, usec_t
*atime
) {
907 _cleanup_free_
char *p
= NULL
;
913 r
= get_ctty(pid
, NULL
, &p
);
917 return get_tty_atime(p
, atime
);
920 int session_get_idle_hint(Session
*s
, dual_timestamp
*t
) {
926 /* Explicit idle hint is set */
929 *t
= s
->idle_hint_timestamp
;
934 /* Graphical sessions should really implement a real
936 if (SESSION_TYPE_IS_GRAPHICAL(s
->type
))
939 /* For sessions with an explicitly configured tty, let's check
942 r
= get_tty_atime(s
->tty
, &atime
);
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
);
957 *t
= s
->idle_hint_timestamp
;
963 dual_timestamp_from_realtime(t
, atime
);
965 n
= now(CLOCK_REALTIME
);
967 if (s
->manager
->idle_action_usec
<= 0)
970 return atime
+ s
->manager
->idle_action_usec
<= n
;
973 void session_set_idle_hint(Session
*s
, bool b
) {
976 if (s
->idle_hint
== b
)
980 dual_timestamp_get(&s
->idle_hint_timestamp
);
982 session_send_changed(s
, "IdleHint", "IdleSinceHint", "IdleSinceHintMonotonic", NULL
);
985 seat_send_changed(s
->seat
, "IdleHint", "IdleSinceHint", "IdleSinceHintMonotonic", NULL
);
987 user_send_changed(s
->user
, "IdleHint", "IdleSinceHint", "IdleSinceHintMonotonic", NULL
);
988 manager_send_changed(s
->manager
, "IdleHint", "IdleSinceHint", "IdleSinceHintMonotonic", NULL
);
991 int session_get_locked_hint(Session
*s
) {
994 return s
->locked_hint
;
997 void session_set_locked_hint(Session
*s
, bool b
) {
1000 if (s
->locked_hint
== b
)
1005 session_send_changed(s
, "LockedHint", NULL
);
1008 static int session_dispatch_fifo(sd_event_source
*es
, int fd
, uint32_t revents
, void *userdata
) {
1009 Session
*s
= userdata
;
1012 assert(s
->fifo_fd
== fd
);
1014 /* EOF on the FIFO means the session died abnormally. */
1016 session_remove_fifo(s
);
1017 session_stop(s
, false);
1022 int session_create_fifo(Session
*s
) {
1028 if (!s
->fifo_path
) {
1029 r
= mkdir_safe_label("/run/systemd/sessions", 0755, 0, 0, MKDIR_WARN_MODE
);
1033 s
->fifo_path
= strjoin("/run/systemd/sessions/", s
->id
, ".ref");
1037 if (mkfifo(s
->fifo_path
, 0600) < 0 && errno
!= EEXIST
)
1041 /* Open reading side */
1042 if (s
->fifo_fd
< 0) {
1043 s
->fifo_fd
= open(s
->fifo_path
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
);
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
);
1053 /* Let's make sure we noticed dead sessions before we process new bus requests (which might create new
1055 r
= sd_event_source_set_priority(s
->fifo_event_source
, SD_EVENT_PRIORITY_NORMAL
-10);
1060 /* Open writing side */
1061 r
= open(s
->fifo_path
, O_WRONLY
|O_CLOEXEC
|O_NONBLOCK
);
1068 static void session_remove_fifo(Session
*s
) {
1071 s
->fifo_event_source
= sd_event_source_unref(s
->fifo_event_source
);
1072 s
->fifo_fd
= safe_close(s
->fifo_fd
);
1075 (void) unlink(s
->fifo_path
);
1076 s
->fifo_path
= mfree(s
->fifo_path
);
1080 bool session_may_gc(Session
*s
, bool drop_not_started
) {
1085 if (drop_not_started
&& !s
->started
)
1091 if (s
->fifo_fd
>= 0) {
1092 if (pipe_eof(s
->fifo_fd
) <= 0)
1097 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1099 r
= manager_job_is_active(s
->manager
, s
->scope_job
, &error
);
1101 log_debug_errno(r
, "Failed to determine whether job '%s' is pending, ignoring: %s", s
->scope_job
, bus_error_message(&error
, r
));
1107 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1109 r
= manager_unit_is_active(s
->manager
, s
->scope
, &error
);
1111 log_debug_errno(r
, "Failed to determine whether unit '%s' is active, ignoring: %s", s
->scope
, bus_error_message(&error
, r
));
1119 void session_add_to_gc_queue(Session
*s
) {
1125 LIST_PREPEND(gc_queue
, s
->manager
->session_gc_queue
, s
);
1126 s
->in_gc_queue
= true;
1129 SessionState
session_get_state(Session
*s
) {
1132 /* always check closing first */
1133 if (s
->stopping
|| s
->timer_event_source
)
1134 return SESSION_CLOSING
;
1136 if (s
->scope_job
|| s
->fifo_fd
< 0)
1137 return SESSION_OPENING
;
1139 if (session_is_active(s
))
1140 return SESSION_ACTIVE
;
1142 return SESSION_ONLINE
;
1145 int session_kill(Session
*s
, KillWho who
, int signo
) {
1151 return manager_kill_unit(s
->manager
, s
->scope
, who
, signo
, NULL
);
1154 static int session_open_vt(Session
*s
) {
1155 char path
[sizeof("/dev/tty") + DECIMAL_STR_MAX(s
->vtnr
)];
1163 sprintf(path
, "/dev/tty%u", s
->vtnr
);
1164 s
->vtfd
= open_terminal(path
, O_RDWR
| O_CLOEXEC
| O_NONBLOCK
| O_NOCTTY
);
1166 return log_error_errno(s
->vtfd
, "cannot open VT %s of session %s: %m", path
, s
->id
);
1171 int session_prepare_vt(Session
*s
) {
1173 struct vt_mode mode
= { 0 };
1178 vt
= session_open_vt(s
);
1182 r
= fchown(vt
, s
->user
->uid
, -1);
1184 r
= log_error_errno(errno
,
1185 "Cannot change owner of /dev/tty%u: %m",
1190 r
= ioctl(vt
, KDSKBMODE
, K_OFF
);
1192 r
= log_error_errno(errno
,
1193 "Cannot set K_OFF on /dev/tty%u: %m",
1198 r
= ioctl(vt
, KDSETMODE
, KD_GRAPHICS
);
1200 r
= log_error_errno(errno
,
1201 "Cannot set KD_GRAPHICS on /dev/tty%u: %m",
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
);
1214 r
= log_error_errno(errno
,
1215 "Cannot set VT_PROCESS on /dev/tty%u: %m",
1223 session_restore_vt(s
);
1227 static void session_restore_vt(Session
*s
) {
1237 /* The virtual terminal can potentially be entering in hung-up state at any time
1238 * depending on when the controlling process exits.
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.
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
);
1249 char path
[sizeof("/dev/tty") + DECIMAL_STR_MAX(s
->vtnr
)];
1252 /* We must be a session leader in order to become the controlling process. */
1255 log_error_errno(errno
, "Failed to become session leader: %m");
1256 _exit(EXIT_FAILURE
);
1259 sprintf(path
, "/dev/tty%u", s
->vtnr
);
1260 vt
= acquire_terminal(path
, ACQUIRE_TERMINAL_FORCE
, USEC_INFINITY
);
1262 log_error_errno(vt
, "Cannot acquire VT %s of session %s: %m", path
, s
->id
);
1263 _exit(EXIT_FAILURE
);
1268 log_warning_errno(r
, "Failed to restore VT, ignoring: %m");
1270 /* Give up and release the controlling terminal. */
1272 _exit(EXIT_SUCCESS
);
1275 /* Close the fd in any cases. */
1276 s
->vtfd
= safe_close(s
->vtfd
);
1279 void session_leave_vt(Session
*s
) {
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. */
1298 session_device_pause_all(s
);
1299 r
= vt_release(s
->vtfd
, false);
1301 log_debug_errno(r
, "Cannot release VT of session %s: %m", s
->id
);
1304 bool session_is_controller(Session
*s
, const char *sender
) {
1307 return streq_ptr(s
->controller
, sender
);
1310 static void session_release_controller(Session
*s
, bool notify
) {
1311 _cleanup_free_
char *name
= NULL
;
1317 name
= s
->controller
;
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. */
1323 s
->controller
= NULL
;
1325 while ((sd
= hashmap_first(s
->devices
)))
1326 session_device_free(sd
);
1328 s
->controller
= NULL
;
1329 s
->track
= sd_bus_track_unref(s
->track
);
1332 static int on_bus_track(sd_bus_track
*track
, void *userdata
) {
1333 Session
*s
= userdata
;
1338 session_drop_controller(s
);
1343 int session_set_controller(Session
*s
, const char *sender
, bool force
, bool prepare
) {
1344 _cleanup_free_
char *name
= NULL
;
1350 if (session_is_controller(s
, sender
))
1352 if (s
->controller
&& !force
)
1355 name
= strdup(sender
);
1359 s
->track
= sd_bus_track_unref(s
->track
);
1360 r
= sd_bus_track_new(s
->manager
->bus
, &s
->track
, on_bus_track
, s
);
1364 r
= sd_bus_track_add_name(s
->track
, name
);
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
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. */
1378 r
= session_prepare_vt(s
);
1380 s
->track
= sd_bus_track_unref(s
->track
);
1385 session_release_controller(s
, true);
1386 s
->controller
= TAKE_PTR(name
);
1392 void session_drop_controller(Session
*s
) {
1398 s
->track
= sd_bus_track_unref(s
->track
);
1399 session_release_controller(s
, false);
1401 session_restore_vt(s
);
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"
1411 DEFINE_STRING_TABLE_LOOKUP(session_state
, SessionState
);
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",
1422 DEFINE_STRING_TABLE_LOOKUP(session_type
, SessionType
);
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"
1431 DEFINE_STRING_TABLE_LOOKUP(session_class
, SessionClass
);
1433 static const char* const kill_who_table
[_KILL_WHO_MAX
] = {
1434 [KILL_LEADER
] = "leader",
1438 DEFINE_STRING_TABLE_LOOKUP(kill_who
, KillWho
);
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",
1446 DEFINE_STRING_TABLE_LOOKUP(tty_validity
, TTYValidity
);