1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
12 #include "sd-messages.h"
14 #include "alloc-util.h"
15 #include "audit-util.h"
16 #include "bus-error.h"
18 #include "devnum-util.h"
23 #include "format-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"
37 #include "terminal-util.h"
38 #include "tmpfile-util.h"
39 #include "uid-alloc-range.h"
40 #include "user-util.h"
43 #define RELEASE_USEC (20*USEC_PER_SEC)
45 static void session_remove_fifo(Session
*s
);
46 static void session_restore_vt(Session
*s
);
48 int session_new(Session
**ret
, Manager
*m
, const char *id
) {
49 _cleanup_(session_freep
) Session
*s
= NULL
;
56 if (!session_id_valid(id
))
67 .audit_id
= AUDIT_SESSION_INVALID
,
68 .tty_validity
= _TTY_VALIDITY_INVALID
,
71 s
->state_file
= path_join("/run/systemd/sessions", id
);
75 s
->id
= basename(s
->state_file
);
77 s
->devices
= hashmap_new(&devt_hash_ops
);
81 r
= hashmap_put(m
->sessions
, s
->id
, s
);
89 Session
* session_free(Session
*s
) {
96 LIST_REMOVE(gc_queue
, s
->manager
->session_gc_queue
, s
);
98 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
100 session_drop_controller(s
);
102 while ((sd
= hashmap_first(s
->devices
)))
103 session_device_free(sd
);
105 hashmap_free(s
->devices
);
108 LIST_REMOVE(sessions_by_user
, s
->user
->sessions
, s
);
110 if (s
->user
->display
== s
)
111 s
->user
->display
= NULL
;
113 user_update_last_session_timer(s
->user
);
117 if (s
->seat
->active
== s
)
118 s
->seat
->active
= NULL
;
119 if (s
->seat
->pending_switch
== s
)
120 s
->seat
->pending_switch
= NULL
;
122 seat_evict_position(s
->seat
, s
);
123 LIST_REMOVE(sessions_by_seat
, s
->seat
->sessions
, s
);
127 hashmap_remove(s
->manager
->session_units
, s
->scope
);
131 if (pid_is_valid(s
->leader
))
132 (void) hashmap_remove_value(s
->manager
->sessions_by_leader
, PID_TO_PTR(s
->leader
), s
);
136 sd_bus_message_unref(s
->create_message
);
140 free(s
->remote_host
);
141 free(s
->remote_user
);
145 hashmap_remove(s
->manager
->sessions
, s
->id
);
147 sd_event_source_unref(s
->fifo_event_source
);
148 safe_close(s
->fifo_fd
);
150 /* Note that we remove neither the state file nor the fifo path here, since we want both to survive
155 sd_event_source_unref(s
->stop_on_idle_event_source
);
160 void session_set_user(Session
*s
, User
*u
) {
165 LIST_PREPEND(sessions_by_user
, u
->sessions
, s
);
167 user_update_last_session_timer(u
);
170 int session_set_leader(Session
*s
, pid_t pid
) {
175 if (!pid_is_valid(pid
))
178 if (s
->leader
== pid
)
181 r
= hashmap_put(s
->manager
->sessions_by_leader
, PID_TO_PTR(pid
), s
);
185 if (pid_is_valid(s
->leader
))
186 (void) hashmap_remove_value(s
->manager
->sessions_by_leader
, PID_TO_PTR(s
->leader
), s
);
189 (void) audit_session_from_pid(pid
, &s
->audit_id
);
194 static void session_save_devices(Session
*s
, FILE *f
) {
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
));
205 int session_save(Session
*s
) {
206 _cleanup_free_
char *temp_path
= NULL
;
207 _cleanup_fclose_
FILE *f
= NULL
;
218 r
= mkdir_safe_label("/run/systemd/sessions", 0755, 0, 0, MKDIR_WARN_MODE
);
222 r
= fopen_temporary(s
->state_file
, &f
, &temp_path
);
226 (void) fchmod(fileno(f
), 0644);
229 "# This is private data. Do not parse.\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
)),
244 fprintf(f
, "TYPE=%s\n", session_type_to_string(s
->type
));
246 if (s
->original_type
>= 0)
247 fprintf(f
, "ORIGINAL_TYPE=%s\n", session_type_to_string(s
->original_type
));
250 fprintf(f
, "CLASS=%s\n", session_class_to_string(s
->class));
253 fprintf(f
, "SCOPE=%s\n", s
->scope
);
255 fprintf(f
, "SCOPE_JOB=%s\n", s
->scope_job
);
258 fprintf(f
, "FIFO=%s\n", s
->fifo_path
);
261 fprintf(f
, "SEAT=%s\n", s
->seat
->id
);
264 fprintf(f
, "TTY=%s\n", s
->tty
);
266 if (s
->tty_validity
>= 0)
267 fprintf(f
, "TTY_VALIDITY=%s\n", tty_validity_to_string(s
->tty_validity
));
270 fprintf(f
, "DISPLAY=%s\n", s
->display
);
272 if (s
->remote_host
) {
273 _cleanup_free_
char *escaped
= NULL
;
275 escaped
= cescape(s
->remote_host
);
281 fprintf(f
, "REMOTE_HOST=%s\n", escaped
);
284 if (s
->remote_user
) {
285 _cleanup_free_
char *escaped
= NULL
;
287 escaped
= cescape(s
->remote_user
);
293 fprintf(f
, "REMOTE_USER=%s\n", escaped
);
297 _cleanup_free_
char *escaped
= NULL
;
299 escaped
= cescape(s
->service
);
305 fprintf(f
, "SERVICE=%s\n", escaped
);
309 _cleanup_free_
char *escaped
= NULL
;
311 escaped
= cescape(s
->desktop
);
317 fprintf(f
, "DESKTOP=%s\n", escaped
);
320 if (s
->seat
&& seat_has_vts(s
->seat
))
321 fprintf(f
, "VTNR=%u\n", s
->vtnr
);
324 fprintf(f
, "POSITION=%u\n", s
->position
);
326 if (pid_is_valid(s
->leader
))
327 fprintf(f
, "LEADER="PID_FMT
"\n", s
->leader
);
329 if (audit_session_is_valid(s
->audit_id
))
330 fprintf(f
, "AUDIT=%"PRIu32
"\n", s
->audit_id
);
332 if (dual_timestamp_is_set(&s
->timestamp
))
334 "REALTIME="USEC_FMT
"\n"
335 "MONOTONIC="USEC_FMT
"\n",
336 s
->timestamp
.realtime
,
337 s
->timestamp
.monotonic
);
340 fprintf(f
, "CONTROLLER=%s\n", s
->controller
);
341 session_save_devices(s
, f
);
344 r
= fflush_and_check(f
);
348 if (rename(temp_path
, s
->state_file
) < 0) {
356 (void) unlink(s
->state_file
);
359 (void) unlink(temp_path
);
361 return log_error_errno(r
, "Failed to save session data %s: %m", s
->state_file
);
364 static int session_load_devices(Session
*s
, const char *devices
) {
369 for (const char *p
= devices
;;) {
370 _cleanup_free_
char *word
= NULL
;
375 k
= extract_first_word(&p
, &word
, NULL
, 0);
383 k
= parse_devnum(word
, &dev
);
389 /* The file descriptors for loaded devices will be reattached later. */
390 k
= session_device_new(s
, dev
, false, &sd
);
396 log_error_errno(r
, "Loading session devices for session %s failed: %m", s
->id
);
401 int session_load(Session
*s
) {
402 _cleanup_free_
char *remote
= NULL
,
404 *tty_validity
= NULL
,
410 *original_type
= NULL
,
424 r
= parse_env_file(NULL
, s
->state_file
,
427 "SCOPE_JOB", &s
->scope_job
,
428 "FIFO", &s
->fifo_path
,
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
,
439 "POSITION", &position
,
442 "ORIGINAL_TYPE", &original_type
,
445 "REALTIME", &realtime
,
446 "MONOTONIC", &monotonic
,
447 "CONTROLLER", &controller
,
450 "IS_DISPLAY", &is_display
);
452 return log_error_errno(r
, "Failed to read %s: %m", s
->state_file
);
459 return log_error_errno(SYNTHETIC_ERRNO(ENOENT
),
460 "UID not specified for session %s",
463 r
= parse_uid(uid
, &u
);
465 log_error("Failed to parse UID value %s for session %s.", uid
, s
->id
);
469 user
= hashmap_get(s
->manager
->users
, UID_TO_PTR(u
));
471 return log_error_errno(SYNTHETIC_ERRNO(ENOENT
),
472 "User of session %s not known.",
475 session_set_user(s
, user
);
479 k
= parse_boolean(remote
);
485 safe_atou(vtnr
, &s
->vtnr
);
487 if (seat
&& !s
->seat
) {
490 o
= hashmap_get(s
->manager
->seats
, seat
);
492 r
= seat_attach_session(o
, s
);
494 log_error("Cannot attach session %s to seat %s", s
->id
, seat
);
497 if (!s
->seat
|| !seat_has_vts(s
->seat
))
500 if (position
&& s
->seat
) {
503 safe_atou(position
, &npos
);
504 seat_claim_position(s
->seat
, s
, npos
);
510 v
= tty_validity_from_string(tty_validity
);
512 log_debug("Failed to parse TTY validity: %s", tty_validity
);
520 r
= parse_pid(leader
, &pid
);
522 log_debug_errno(r
, "Failed to parse leader PID of session: %s", leader
);
524 r
= session_set_leader(s
, pid
);
526 log_warning_errno(r
, "Failed to set session leader PID, ignoring: %m");
533 t
= session_type_from_string(type
);
541 ot
= session_type_from_string(original_type
);
543 s
->original_type
= ot
;
545 /* Pre-v246 compat: initialize original_type if not set in the state file */
546 s
->original_type
= s
->type
;
551 c
= session_class_from_string(class);
556 if (streq_ptr(state
, "closing"))
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. */
569 fd
= session_create_fifo(s
);
574 (void) deserialize_usec(realtime
, &s
->timestamp
.realtime
);
576 (void) deserialize_usec(monotonic
, &s
->timestamp
.monotonic
);
579 k
= parse_boolean(active
);
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. */
589 k
= parse_boolean(is_display
);
591 log_warning_errno(k
, "Failed to parse IS_DISPLAY session property: %m");
593 s
->user
->display
= s
;
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
);
601 session_restore_vt(s
);
607 int session_activate(Session
*s
) {
608 unsigned num_pending
;
616 if (s
->seat
->active
== s
)
619 /* on seats with VTs, we let VTs manage session-switching */
620 if (seat_has_vts(s
->seat
)) {
624 return chvt(s
->vtnr
);
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. */
634 s
->seat
->pending_switch
= s
;
636 /* if no devices are running, immediately perform the session switch */
637 num_pending
= session_device_try_pause_all(s
);
639 seat_complete_switch(s
->seat
);
644 static int session_start_scope(Session
*s
, sd_bus_message
*properties
, sd_bus_error
*error
) {
651 _cleanup_strv_free_
char **after
= NULL
;
652 _cleanup_free_
char *scope
= NULL
;
653 const char *description
;
655 s
->scope_job
= mfree(s
->scope_job
);
657 scope
= strjoin("session-", s
->id
, ".scope");
661 description
= strjoina("Session ", s
->id
, " of User ", s
->user
->user_record
->user_name
);
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
,
676 r
= manager_start_scope(
682 /* These two have StopWhenUnneeded= set, hence add a dep towards them */
683 STRV_MAKE(s
->user
->runtime_dir_service
,
686 user_record_home_directory(s
->user
->user_record
),
691 return log_error_errno(r
, "Failed to start session scope %s: %s",
692 scope
, bus_error_message(error
, r
));
694 s
->scope
= TAKE_PTR(scope
);
697 (void) hashmap_put(s
->manager
->session_units
, s
->scope
, s
);
702 static int session_dispatch_stop_on_idle(sd_event_source
*source
, uint64_t t
, void *userdata
) {
703 Session
*s
= userdata
;
712 idle
= session_get_idle_hint(s
, &ts
);
714 log_debug("Session \"%s\" of user \"%s\" is idle, stopping.", s
->id
, s
->user
->user_record
->user_name
);
716 return session_stop(s
, /* force */ true);
719 r
= sd_event_source_set_time(source
, usec_add(ts
.monotonic
, s
->manager
->stop_idle_session_usec
));
721 return log_error_errno(r
, "Failed to configure stop on idle session event source: %m");
723 r
= sd_event_source_set_enabled(source
, SD_EVENT_ONESHOT
);
725 return log_error_errno(r
, "Failed to enable stop on idle session event source: %m");
730 static int session_setup_stop_on_idle_timer(Session
*s
) {
735 if (s
->manager
->stop_idle_session_usec
== USEC_INFINITY
)
738 r
= sd_event_add_time_relative(
740 &s
->stop_on_idle_event_source
,
742 s
->manager
->stop_idle_session_usec
,
744 session_dispatch_stop_on_idle
, s
);
746 return log_error_errno(r
, "Failed to add stop on idle session event source: %m");
751 int session_start(Session
*s
, sd_bus_message
*properties
, sd_bus_error
*error
) {
765 r
= user_start(s
->user
);
769 r
= session_start_scope(s
, properties
, error
);
773 r
= session_setup_stop_on_idle_timer(s
);
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
));
784 if (!dual_timestamp_is_set(&s
->timestamp
))
785 dual_timestamp_get(&s
->timestamp
);
788 seat_read_active_vt(s
->seat
);
792 user_elect_display(s
->user
);
801 session_send_signal(s
, true);
802 user_send_changed(s
->user
, "Display", NULL
);
804 if (s
->seat
&& s
->seat
->active
== s
)
805 seat_send_changed(s
->seat
, "ActiveSession", NULL
);
810 static int session_stop_scope(Session
*s
, bool force
) {
811 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
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
);
824 log_warning_errno(r
, "Failed to abandon session scope, ignoring: %s", bus_error_message(&error
, r
));
825 sd_bus_error_free(&error
);
828 s
->scope_job
= mfree(s
->scope_job
);
830 /* Optionally, let's kill everything that's left now. */
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
)))) {
836 r
= manager_stop_unit(s
->manager
, s
->scope
, force
? "replace" : "fail", &error
, &s
->scope_job
);
839 return log_error_errno(r
, "Failed to stop session scope: %s", bus_error_message(&error
, r
));
841 log_warning_errno(r
, "Failed to stop session scope, ignoring: %s", bus_error_message(&error
, r
));
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
));
858 int session_stop(Session
*s
, bool force
) {
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). */
875 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
878 seat_evict_position(s
->seat
, s
);
880 /* We are going down, don't care about FIFOs anymore */
881 session_remove_fifo(s
);
884 r
= session_stop_scope(s
, force
);
888 user_elect_display(s
->user
);
896 int session_finalize(Session
*s
) {
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
));
912 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
915 seat_evict_position(s
->seat
, s
);
917 /* Kill session devices */
918 while ((sd
= hashmap_first(s
->devices
)))
919 session_device_free(sd
);
921 (void) unlink(s
->state_file
);
922 session_add_to_gc_queue(s
);
923 user_add_to_gc_queue(s
->user
);
926 session_send_signal(s
, false);
931 if (s
->seat
->active
== s
)
932 seat_set_active(s
->seat
, NULL
);
938 user_send_changed(s
->user
, "Display", NULL
);
943 static int release_timeout_callback(sd_event_source
*es
, uint64_t usec
, void *userdata
) {
944 Session
*s
= userdata
;
949 session_stop(s
, /* force = */ false);
953 int session_release(Session
*s
) {
956 if (!s
->started
|| s
->stopping
)
959 if (s
->timer_event_source
)
962 return sd_event_add_time_relative(
964 &s
->timer_event_source
,
967 release_timeout_callback
, s
);
970 bool session_is_active(Session
*s
) {
976 return s
->seat
->active
== s
;
979 static int get_tty_atime(const char *tty
, usec_t
*atime
) {
980 _cleanup_free_
char *p
= NULL
;
986 if (!path_is_absolute(tty
)) {
987 p
= path_join("/dev", tty
);
992 } else if (!path_startswith(tty
, "/dev/"))
995 if (lstat(tty
, &st
) < 0)
998 *atime
= timespec_load(&st
.st_atim
);
1002 static int get_process_ctty_atime(pid_t pid
, usec_t
*atime
) {
1003 _cleanup_free_
char *p
= NULL
;
1009 r
= get_ctty(pid
, NULL
, &p
);
1013 return get_tty_atime(p
, atime
);
1016 int session_get_idle_hint(Session
*s
, dual_timestamp
*t
) {
1017 usec_t atime
= 0, dtime
= 0;
1022 /* Graphical sessions have an explicit idle hint */
1023 if (SESSION_TYPE_IS_GRAPHICAL(s
->type
)) {
1025 *t
= s
->idle_hint_timestamp
;
1027 return s
->idle_hint
;
1030 /* For sessions with an explicitly configured tty, let's check its atime */
1032 r
= get_tty_atime(s
->tty
, &atime
);
1037 /* For sessions with a leader but no explicitly configured tty, let's check the controlling tty of
1039 if (pid_is_valid(s
->leader
)) {
1040 r
= get_process_ctty_atime(s
->leader
, &atime
);
1046 *t
= DUAL_TIMESTAMP_NULL
;
1052 dual_timestamp_from_realtime(t
, atime
);
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
;
1063 return usec_add(atime
, dtime
) <= now(CLOCK_REALTIME
);
1066 int session_set_idle_hint(Session
*s
, bool b
) {
1069 if (!SESSION_TYPE_IS_GRAPHICAL(s
->type
))
1072 if (s
->idle_hint
== b
)
1076 dual_timestamp_get(&s
->idle_hint_timestamp
);
1078 session_send_changed(s
, "IdleHint", "IdleSinceHint", "IdleSinceHintMonotonic", NULL
);
1081 seat_send_changed(s
->seat
, "IdleHint", "IdleSinceHint", "IdleSinceHintMonotonic", NULL
);
1083 user_send_changed(s
->user
, "IdleHint", "IdleSinceHint", "IdleSinceHintMonotonic", NULL
);
1084 manager_send_changed(s
->manager
, "IdleHint", "IdleSinceHint", "IdleSinceHintMonotonic", NULL
);
1089 int session_get_locked_hint(Session
*s
) {
1092 return s
->locked_hint
;
1095 void session_set_locked_hint(Session
*s
, bool b
) {
1098 if (s
->locked_hint
== b
)
1103 session_send_changed(s
, "LockedHint", NULL
);
1106 void session_set_type(Session
*s
, SessionType t
) {
1115 session_send_changed(s
, "Type", NULL
);
1118 int session_set_display(Session
*s
, const char *display
) {
1124 r
= free_and_strdup(&s
->display
, display
);
1125 if (r
<= 0) /* 0 means the strings were equal */
1130 session_send_changed(s
, "Display", NULL
);
1135 static int session_dispatch_fifo(sd_event_source
*es
, int fd
, uint32_t revents
, void *userdata
) {
1136 Session
*s
= userdata
;
1139 assert(s
->fifo_fd
== fd
);
1141 /* EOF on the FIFO means the session died abnormally. */
1143 session_remove_fifo(s
);
1144 session_stop(s
, /* force = */ false);
1149 int session_create_fifo(Session
*s
) {
1155 if (!s
->fifo_path
) {
1156 r
= mkdir_safe_label("/run/systemd/sessions", 0755, 0, 0, MKDIR_WARN_MODE
);
1160 s
->fifo_path
= strjoin("/run/systemd/sessions/", s
->id
, ".ref");
1164 if (mkfifo(s
->fifo_path
, 0600) < 0 && errno
!= EEXIST
)
1168 /* Open reading side */
1169 if (s
->fifo_fd
< 0) {
1170 s
->fifo_fd
= open(s
->fifo_path
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
);
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
);
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);
1187 /* Open writing side */
1188 return RET_NERRNO(open(s
->fifo_path
, O_WRONLY
|O_CLOEXEC
|O_NONBLOCK
));
1191 static void session_remove_fifo(Session
*s
) {
1194 s
->fifo_event_source
= sd_event_source_unref(s
->fifo_event_source
);
1195 s
->fifo_fd
= safe_close(s
->fifo_fd
);
1198 (void) unlink(s
->fifo_path
);
1199 s
->fifo_path
= mfree(s
->fifo_path
);
1203 bool session_may_gc(Session
*s
, bool drop_not_started
) {
1208 if (drop_not_started
&& !s
->started
)
1214 if (s
->fifo_fd
>= 0) {
1215 if (pipe_eof(s
->fifo_fd
) <= 0)
1220 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1222 r
= manager_job_is_active(s
->manager
, s
->scope_job
, &error
);
1224 log_debug_errno(r
, "Failed to determine whether job '%s' is pending, ignoring: %s", s
->scope_job
, bus_error_message(&error
, r
));
1230 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1232 r
= manager_unit_is_active(s
->manager
, s
->scope
, &error
);
1234 log_debug_errno(r
, "Failed to determine whether unit '%s' is active, ignoring: %s", s
->scope
, bus_error_message(&error
, r
));
1242 void session_add_to_gc_queue(Session
*s
) {
1248 LIST_PREPEND(gc_queue
, s
->manager
->session_gc_queue
, s
);
1249 s
->in_gc_queue
= true;
1252 SessionState
session_get_state(Session
*s
) {
1255 /* always check closing first */
1256 if (s
->stopping
|| s
->timer_event_source
)
1257 return SESSION_CLOSING
;
1259 if (s
->scope_job
|| s
->fifo_fd
< 0)
1260 return SESSION_OPENING
;
1262 if (session_is_active(s
))
1263 return SESSION_ACTIVE
;
1265 return SESSION_ONLINE
;
1268 int session_kill(Session
*s
, KillWho who
, int signo
) {
1274 return manager_kill_unit(s
->manager
, s
->scope
, who
, signo
, NULL
);
1277 static int session_open_vt(Session
*s
) {
1278 char path
[sizeof("/dev/tty") + DECIMAL_STR_MAX(s
->vtnr
)];
1286 sprintf(path
, "/dev/tty%u", s
->vtnr
);
1287 s
->vtfd
= open_terminal(path
, O_RDWR
| O_CLOEXEC
| O_NONBLOCK
| O_NOCTTY
);
1289 return log_error_errno(s
->vtfd
, "cannot open VT %s of session %s: %m", path
, s
->id
);
1294 static int session_prepare_vt(Session
*s
) {
1296 struct vt_mode mode
= {};
1301 vt
= session_open_vt(s
);
1305 r
= fchown(vt
, s
->user
->user_record
->uid
, -1);
1307 r
= log_error_errno(errno
,
1308 "Cannot change owner of /dev/tty%u: %m",
1313 r
= ioctl(vt
, KDSKBMODE
, K_OFF
);
1315 r
= log_error_errno(errno
,
1316 "Cannot set K_OFF on /dev/tty%u: %m",
1321 r
= ioctl(vt
, KDSETMODE
, KD_GRAPHICS
);
1323 r
= log_error_errno(errno
,
1324 "Cannot set KD_GRAPHICS on /dev/tty%u: %m",
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
);
1337 r
= log_error_errno(errno
,
1338 "Cannot set VT_PROCESS on /dev/tty%u: %m",
1346 session_restore_vt(s
);
1350 static void session_restore_vt(Session
*s
) {
1353 r
= vt_restore(s
->vtfd
);
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. */
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
);
1365 vt
= session_open_vt(s
);
1373 log_warning_errno(r
, "Failed to restore VT, ignoring: %m");
1375 s
->vtfd
= safe_close(s
->vtfd
);
1378 void session_leave_vt(Session
*s
) {
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. */
1397 session_device_pause_all(s
);
1398 r
= vt_release(s
->vtfd
, false);
1400 log_debug_errno(r
, "Cannot release VT of session %s: %m", s
->id
);
1403 bool session_is_controller(Session
*s
, const char *sender
) {
1404 return streq_ptr(ASSERT_PTR(s
)->controller
, sender
);
1407 static void session_release_controller(Session
*s
, bool notify
) {
1408 _unused_ _cleanup_free_
char *name
= NULL
;
1414 name
= s
->controller
;
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. */
1419 s
->controller
= NULL
;
1421 while ((sd
= hashmap_first(s
->devices
)))
1422 session_device_free(sd
);
1424 s
->controller
= NULL
;
1425 s
->track
= sd_bus_track_unref(s
->track
);
1428 static int on_bus_track(sd_bus_track
*track
, void *userdata
) {
1429 Session
*s
= userdata
;
1434 session_drop_controller(s
);
1439 int session_set_controller(Session
*s
, const char *sender
, bool force
, bool prepare
) {
1440 _cleanup_free_
char *name
= NULL
;
1446 if (session_is_controller(s
, sender
))
1448 if (s
->controller
&& !force
)
1451 name
= strdup(sender
);
1455 s
->track
= sd_bus_track_unref(s
->track
);
1456 r
= sd_bus_track_new(s
->manager
->bus
, &s
->track
, on_bus_track
, s
);
1460 r
= sd_bus_track_add_name(s
->track
, name
);
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
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. */
1474 r
= session_prepare_vt(s
);
1476 s
->track
= sd_bus_track_unref(s
->track
);
1481 session_release_controller(s
, true);
1482 s
->controller
= TAKE_PTR(name
);
1488 void session_drop_controller(Session
*s
) {
1494 s
->track
= sd_bus_track_unref(s
->track
);
1495 session_set_type(s
, s
->original_type
);
1496 session_release_controller(s
, false);
1498 session_restore_vt(s
);
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",
1508 DEFINE_STRING_TABLE_LOOKUP(session_state
, SessionState
);
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",
1519 DEFINE_STRING_TABLE_LOOKUP(session_type
, SessionType
);
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",
1528 DEFINE_STRING_TABLE_LOOKUP(session_class
, SessionClass
);
1530 static const char* const kill_who_table
[_KILL_WHO_MAX
] = {
1531 [KILL_LEADER
] = "leader",
1535 DEFINE_STRING_TABLE_LOOKUP(kill_who
, KillWho
);
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",
1543 DEFINE_STRING_TABLE_LOOKUP(tty_validity
, TTYValidity
);