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"
42 #define RELEASE_USEC (20*USEC_PER_SEC)
44 static void session_remove_fifo(Session
*s
);
45 static void session_restore_vt(Session
*s
);
47 int session_new(Session
**ret
, Manager
*m
, const char *id
) {
48 _cleanup_(session_freep
) Session
*s
= NULL
;
55 if (!session_id_valid(id
))
66 .audit_id
= AUDIT_SESSION_INVALID
,
67 .tty_validity
= _TTY_VALIDITY_INVALID
,
70 s
->state_file
= path_join("/run/systemd/sessions", id
);
74 s
->id
= basename(s
->state_file
);
76 s
->devices
= hashmap_new(&devt_hash_ops
);
80 r
= hashmap_put(m
->sessions
, s
->id
, s
);
88 Session
* session_free(Session
*s
) {
95 LIST_REMOVE(gc_queue
, s
->manager
->session_gc_queue
, s
);
97 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
99 session_drop_controller(s
);
101 while ((sd
= hashmap_first(s
->devices
)))
102 session_device_free(sd
);
104 hashmap_free(s
->devices
);
107 LIST_REMOVE(sessions_by_user
, s
->user
->sessions
, s
);
109 if (s
->user
->display
== s
)
110 s
->user
->display
= NULL
;
112 user_update_last_session_timer(s
->user
);
116 if (s
->seat
->active
== s
)
117 s
->seat
->active
= NULL
;
118 if (s
->seat
->pending_switch
== s
)
119 s
->seat
->pending_switch
= NULL
;
121 seat_evict_position(s
->seat
, s
);
122 LIST_REMOVE(sessions_by_seat
, s
->seat
->sessions
, s
);
126 hashmap_remove(s
->manager
->session_units
, s
->scope
);
130 if (pid_is_valid(s
->leader
))
131 (void) hashmap_remove_value(s
->manager
->sessions_by_leader
, PID_TO_PTR(s
->leader
), s
);
135 sd_bus_message_unref(s
->create_message
);
139 free(s
->remote_host
);
140 free(s
->remote_user
);
144 hashmap_remove(s
->manager
->sessions
, s
->id
);
146 sd_event_source_unref(s
->fifo_event_source
);
147 safe_close(s
->fifo_fd
);
149 /* Note that we remove neither the state file nor the fifo path here, since we want both to survive
154 sd_event_source_unref(s
->stop_on_idle_event_source
);
159 void session_set_user(Session
*s
, User
*u
) {
164 LIST_PREPEND(sessions_by_user
, u
->sessions
, s
);
166 user_update_last_session_timer(u
);
169 int session_set_leader(Session
*s
, pid_t pid
) {
174 if (!pid_is_valid(pid
))
177 if (s
->leader
== pid
)
180 r
= hashmap_put(s
->manager
->sessions_by_leader
, PID_TO_PTR(pid
), s
);
184 if (pid_is_valid(s
->leader
))
185 (void) hashmap_remove_value(s
->manager
->sessions_by_leader
, PID_TO_PTR(s
->leader
), s
);
188 (void) audit_session_from_pid(pid
, &s
->audit_id
);
193 static void session_save_devices(Session
*s
, FILE *f
) {
196 if (!hashmap_isempty(s
->devices
)) {
197 fprintf(f
, "DEVICES=");
198 HASHMAP_FOREACH(sd
, s
->devices
)
199 fprintf(f
, "%u:%u ", major(sd
->dev
), minor(sd
->dev
));
204 int session_save(Session
*s
) {
205 _cleanup_free_
char *temp_path
= NULL
;
206 _cleanup_fclose_
FILE *f
= NULL
;
217 r
= mkdir_safe_label("/run/systemd/sessions", 0755, 0, 0, MKDIR_WARN_MODE
);
221 r
= fopen_temporary(s
->state_file
, &f
, &temp_path
);
225 (void) fchmod(fileno(f
), 0644);
228 "# This is private data. Do not parse.\n"
235 s
->user
->user_record
->uid
,
236 s
->user
->user_record
->user_name
,
237 session_is_active(s
),
238 s
->user
->display
== s
,
239 session_state_to_string(session_get_state(s
)),
243 fprintf(f
, "TYPE=%s\n", session_type_to_string(s
->type
));
245 if (s
->original_type
>= 0)
246 fprintf(f
, "ORIGINAL_TYPE=%s\n", session_type_to_string(s
->original_type
));
249 fprintf(f
, "CLASS=%s\n", session_class_to_string(s
->class));
252 fprintf(f
, "SCOPE=%s\n", s
->scope
);
254 fprintf(f
, "SCOPE_JOB=%s\n", s
->scope_job
);
257 fprintf(f
, "FIFO=%s\n", s
->fifo_path
);
260 fprintf(f
, "SEAT=%s\n", s
->seat
->id
);
263 fprintf(f
, "TTY=%s\n", s
->tty
);
265 if (s
->tty_validity
>= 0)
266 fprintf(f
, "TTY_VALIDITY=%s\n", tty_validity_to_string(s
->tty_validity
));
269 fprintf(f
, "DISPLAY=%s\n", s
->display
);
271 if (s
->remote_host
) {
272 _cleanup_free_
char *escaped
= NULL
;
274 escaped
= cescape(s
->remote_host
);
280 fprintf(f
, "REMOTE_HOST=%s\n", escaped
);
283 if (s
->remote_user
) {
284 _cleanup_free_
char *escaped
= NULL
;
286 escaped
= cescape(s
->remote_user
);
292 fprintf(f
, "REMOTE_USER=%s\n", escaped
);
296 _cleanup_free_
char *escaped
= NULL
;
298 escaped
= cescape(s
->service
);
304 fprintf(f
, "SERVICE=%s\n", escaped
);
308 _cleanup_free_
char *escaped
= NULL
;
310 escaped
= cescape(s
->desktop
);
316 fprintf(f
, "DESKTOP=%s\n", escaped
);
319 if (s
->seat
&& seat_has_vts(s
->seat
))
320 fprintf(f
, "VTNR=%u\n", s
->vtnr
);
323 fprintf(f
, "POSITION=%u\n", s
->position
);
325 if (pid_is_valid(s
->leader
))
326 fprintf(f
, "LEADER="PID_FMT
"\n", s
->leader
);
328 if (audit_session_is_valid(s
->audit_id
))
329 fprintf(f
, "AUDIT=%"PRIu32
"\n", s
->audit_id
);
331 if (dual_timestamp_is_set(&s
->timestamp
))
333 "REALTIME="USEC_FMT
"\n"
334 "MONOTONIC="USEC_FMT
"\n",
335 s
->timestamp
.realtime
,
336 s
->timestamp
.monotonic
);
339 fprintf(f
, "CONTROLLER=%s\n", s
->controller
);
340 session_save_devices(s
, f
);
343 r
= fflush_and_check(f
);
347 if (rename(temp_path
, s
->state_file
) < 0) {
355 (void) unlink(s
->state_file
);
358 (void) unlink(temp_path
);
360 return log_error_errno(r
, "Failed to save session data %s: %m", s
->state_file
);
363 static int session_load_devices(Session
*s
, const char *devices
) {
368 for (const char *p
= devices
;;) {
369 _cleanup_free_
char *word
= NULL
;
374 k
= extract_first_word(&p
, &word
, NULL
, 0);
382 k
= parse_devnum(word
, &dev
);
388 /* The file descriptors for loaded devices will be reattached later. */
389 k
= session_device_new(s
, dev
, false, &sd
);
395 log_error_errno(r
, "Loading session devices for session %s failed: %m", s
->id
);
400 int session_load(Session
*s
) {
401 _cleanup_free_
char *remote
= NULL
,
403 *tty_validity
= NULL
,
409 *original_type
= NULL
,
423 r
= parse_env_file(NULL
, s
->state_file
,
426 "SCOPE_JOB", &s
->scope_job
,
427 "FIFO", &s
->fifo_path
,
430 "TTY_VALIDITY", &tty_validity
,
431 "DISPLAY", &s
->display
,
432 "REMOTE_HOST", &s
->remote_host
,
433 "REMOTE_USER", &s
->remote_user
,
434 "SERVICE", &s
->service
,
435 "DESKTOP", &s
->desktop
,
438 "POSITION", &position
,
441 "ORIGINAL_TYPE", &original_type
,
444 "REALTIME", &realtime
,
445 "MONOTONIC", &monotonic
,
446 "CONTROLLER", &controller
,
449 "IS_DISPLAY", &is_display
);
451 return log_error_errno(r
, "Failed to read %s: %m", s
->state_file
);
458 return log_error_errno(SYNTHETIC_ERRNO(ENOENT
),
459 "UID not specified for session %s",
462 r
= parse_uid(uid
, &u
);
464 log_error("Failed to parse UID value %s for session %s.", uid
, s
->id
);
468 user
= hashmap_get(s
->manager
->users
, UID_TO_PTR(u
));
470 return log_error_errno(SYNTHETIC_ERRNO(ENOENT
),
471 "User of session %s not known.",
474 session_set_user(s
, user
);
478 k
= parse_boolean(remote
);
484 safe_atou(vtnr
, &s
->vtnr
);
486 if (seat
&& !s
->seat
) {
489 o
= hashmap_get(s
->manager
->seats
, seat
);
491 r
= seat_attach_session(o
, s
);
493 log_error("Cannot attach session %s to seat %s", s
->id
, seat
);
496 if (!s
->seat
|| !seat_has_vts(s
->seat
))
499 if (position
&& s
->seat
) {
502 safe_atou(position
, &npos
);
503 seat_claim_position(s
->seat
, s
, npos
);
509 v
= tty_validity_from_string(tty_validity
);
511 log_debug("Failed to parse TTY validity: %s", tty_validity
);
519 r
= parse_pid(leader
, &pid
);
521 log_debug_errno(r
, "Failed to parse leader PID of session: %s", leader
);
523 r
= session_set_leader(s
, pid
);
525 log_warning_errno(r
, "Failed to set session leader PID, ignoring: %m");
532 t
= session_type_from_string(type
);
540 ot
= session_type_from_string(original_type
);
542 s
->original_type
= ot
;
544 /* Pre-v246 compat: initialize original_type if not set in the state file */
545 s
->original_type
= s
->type
;
550 c
= session_class_from_string(class);
555 if (streq_ptr(state
, "closing"))
561 /* If we open an unopened pipe for reading we will not
562 get an EOF. to trigger an EOF we hence open it for
563 writing, but close it right away which then will
564 trigger the EOF. This will happen immediately if no
565 other process has the FIFO open for writing, i. e.
566 when the session died before logind (re)started. */
568 fd
= session_create_fifo(s
);
573 (void) deserialize_usec(realtime
, &s
->timestamp
.realtime
);
575 (void) deserialize_usec(monotonic
, &s
->timestamp
.monotonic
);
578 k
= parse_boolean(active
);
584 /* Note that when enumerating users are loaded before sessions, hence the display session to use is
585 * something we have to store along with the session and not the user, as in that case we couldn't
586 * apply it at the time we load the user. */
588 k
= parse_boolean(is_display
);
590 log_warning_errno(k
, "Failed to parse IS_DISPLAY session property: %m");
592 s
->user
->display
= s
;
596 if (bus_name_has_owner(s
->manager
->bus
, controller
, NULL
) > 0) {
597 session_set_controller(s
, controller
, false, false);
598 session_load_devices(s
, devices
);
600 session_restore_vt(s
);
606 int session_activate(Session
*s
) {
607 unsigned num_pending
;
615 if (s
->seat
->active
== s
)
618 /* on seats with VTs, we let VTs manage session-switching */
619 if (seat_has_vts(s
->seat
)) {
623 return chvt(s
->vtnr
);
626 /* On seats without VTs, we implement session-switching in logind. We
627 * try to pause all session-devices and wait until the session
628 * controller acknowledged them. Once all devices are asleep, we simply
629 * switch the active session and be done.
630 * We save the session we want to switch to in seat->pending_switch and
631 * seat_complete_switch() will perform the final switch. */
633 s
->seat
->pending_switch
= s
;
635 /* if no devices are running, immediately perform the session switch */
636 num_pending
= session_device_try_pause_all(s
);
638 seat_complete_switch(s
->seat
);
643 static int session_start_scope(Session
*s
, sd_bus_message
*properties
, sd_bus_error
*error
) {
650 _cleanup_strv_free_
char **after
= NULL
;
651 _cleanup_free_
char *scope
= NULL
;
652 const char *description
;
654 s
->scope_job
= mfree(s
->scope_job
);
656 scope
= strjoin("session-", s
->id
, ".scope");
660 description
= strjoina("Session ", s
->id
, " of User ", s
->user
->user_record
->user_name
);
662 /* We usually want to order session scopes after systemd-user-sessions.service since the
663 * latter unit is used as login session barrier for unprivileged users. However the barrier
664 * doesn't apply for root as sysadmin should always be able to log in (and without waiting
665 * for any timeout to expire) in case something goes wrong during the boot process. Since
666 * ordering after systemd-user-sessions.service and the user instance is optional we make use
667 * of STRV_IGNORE with strv_new() to skip these order constraints when needed. */
668 after
= strv_new("systemd-logind.service",
669 s
->user
->runtime_dir_service
,
670 !uid_is_system(s
->user
->user_record
->uid
) ? "systemd-user-sessions.service" : STRV_IGNORE
,
675 r
= manager_start_scope(
681 /* These two have StopWhenUnneeded= set, hence add a dep towards them */
682 STRV_MAKE(s
->user
->runtime_dir_service
,
685 user_record_home_directory(s
->user
->user_record
),
690 return log_error_errno(r
, "Failed to start session scope %s: %s",
691 scope
, bus_error_message(error
, r
));
693 s
->scope
= TAKE_PTR(scope
);
696 (void) hashmap_put(s
->manager
->session_units
, s
->scope
, s
);
701 static int session_dispatch_stop_on_idle(sd_event_source
*source
, uint64_t t
, void *userdata
) {
702 Session
*s
= userdata
;
711 idle
= session_get_idle_hint(s
, &ts
);
713 log_debug("Session \"%s\" of user \"%s\" is idle, stopping.", s
->id
, s
->user
->user_record
->user_name
);
715 return session_stop(s
, /* force */ true);
718 r
= sd_event_source_set_time(
720 usec_add(dual_timestamp_is_set(&ts
) ? ts
.monotonic
: now(CLOCK_MONOTONIC
),
721 s
->manager
->stop_idle_session_usec
));
723 return log_error_errno(r
, "Failed to configure stop on idle session event source: %m");
725 r
= sd_event_source_set_enabled(source
, SD_EVENT_ONESHOT
);
727 return log_error_errno(r
, "Failed to enable stop on idle session event source: %m");
732 static int session_setup_stop_on_idle_timer(Session
*s
) {
737 if (s
->manager
->stop_idle_session_usec
== USEC_INFINITY
)
740 r
= sd_event_add_time_relative(
742 &s
->stop_on_idle_event_source
,
744 s
->manager
->stop_idle_session_usec
,
746 session_dispatch_stop_on_idle
, s
);
748 return log_error_errno(r
, "Failed to add stop on idle session event source: %m");
753 int session_start(Session
*s
, sd_bus_message
*properties
, sd_bus_error
*error
) {
767 r
= user_start(s
->user
);
771 r
= session_start_scope(s
, properties
, error
);
775 r
= session_setup_stop_on_idle_timer(s
);
779 log_struct(s
->class == SESSION_BACKGROUND
? LOG_DEBUG
: LOG_INFO
,
780 "MESSAGE_ID=" SD_MESSAGE_SESSION_START_STR
,
781 "SESSION_ID=%s", s
->id
,
782 "USER_ID=%s", s
->user
->user_record
->user_name
,
783 "LEADER="PID_FMT
, s
->leader
,
784 LOG_MESSAGE("New session %s of user %s.", s
->id
, s
->user
->user_record
->user_name
));
786 if (!dual_timestamp_is_set(&s
->timestamp
))
787 dual_timestamp_get(&s
->timestamp
);
790 seat_read_active_vt(s
->seat
);
794 user_elect_display(s
->user
);
803 session_send_signal(s
, true);
804 user_send_changed(s
->user
, "Display", NULL
);
806 if (s
->seat
&& s
->seat
->active
== s
)
807 seat_send_changed(s
->seat
, "ActiveSession", NULL
);
812 static int session_stop_scope(Session
*s
, bool force
) {
813 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
821 /* Let's always abandon the scope first. This tells systemd that we are not interested anymore, and everything
822 * that is left in the scope is "left-over". Informing systemd about this has the benefit that it will log
823 * when killing any processes left after this point. */
824 r
= manager_abandon_scope(s
->manager
, s
->scope
, &error
);
826 log_warning_errno(r
, "Failed to abandon session scope, ignoring: %s", bus_error_message(&error
, r
));
827 sd_bus_error_free(&error
);
830 s
->scope_job
= mfree(s
->scope_job
);
832 /* Optionally, let's kill everything that's left now. */
834 (s
->user
->user_record
->kill_processes
!= 0 &&
835 (s
->user
->user_record
->kill_processes
> 0 ||
836 manager_shall_kill(s
->manager
, s
->user
->user_record
->user_name
)))) {
838 r
= manager_stop_unit(s
->manager
, s
->scope
, force
? "replace" : "fail", &error
, &s
->scope_job
);
841 return log_error_errno(r
, "Failed to stop session scope: %s", bus_error_message(&error
, r
));
843 log_warning_errno(r
, "Failed to stop session scope, ignoring: %s", bus_error_message(&error
, r
));
847 /* With no killing, this session is allowed to persist in "closing" state indefinitely.
848 * Therefore session stop and session removal may be two distinct events.
849 * Session stop is quite significant on its own, let's log it. */
850 log_struct(s
->class == SESSION_BACKGROUND
? LOG_DEBUG
: LOG_INFO
,
851 "SESSION_ID=%s", s
->id
,
852 "USER_ID=%s", s
->user
->user_record
->user_name
,
853 "LEADER="PID_FMT
, s
->leader
,
854 LOG_MESSAGE("Session %s logged out. Waiting for processes to exit.", s
->id
));
860 int session_stop(Session
*s
, bool force
) {
865 /* This is called whenever we begin with tearing down a session record. It's called in four cases: explicit API
866 * request via the bus (either directly for the session object or for the seat or user object this session
867 * belongs to; 'force' is true), or due to automatic GC (i.e. scope vanished; 'force' is false), or because the
868 * session FIFO saw an EOF ('force' is false), or because the release timer hit ('force' is false). */
877 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
880 seat_evict_position(s
->seat
, s
);
882 /* We are going down, don't care about FIFOs anymore */
883 session_remove_fifo(s
);
886 r
= session_stop_scope(s
, force
);
890 user_elect_display(s
->user
);
898 int session_finalize(Session
*s
) {
907 log_struct(s
->class == SESSION_BACKGROUND
? LOG_DEBUG
: LOG_INFO
,
908 "MESSAGE_ID=" SD_MESSAGE_SESSION_STOP_STR
,
909 "SESSION_ID=%s", s
->id
,
910 "USER_ID=%s", s
->user
->user_record
->user_name
,
911 "LEADER="PID_FMT
, s
->leader
,
912 LOG_MESSAGE("Removed session %s.", s
->id
));
914 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
917 seat_evict_position(s
->seat
, s
);
919 /* Kill session devices */
920 while ((sd
= hashmap_first(s
->devices
)))
921 session_device_free(sd
);
923 (void) unlink(s
->state_file
);
924 session_add_to_gc_queue(s
);
925 user_add_to_gc_queue(s
->user
);
928 session_send_signal(s
, false);
933 if (s
->seat
->active
== s
)
934 seat_set_active(s
->seat
, NULL
);
940 user_send_changed(s
->user
, "Display", NULL
);
945 static int release_timeout_callback(sd_event_source
*es
, uint64_t usec
, void *userdata
) {
946 Session
*s
= ASSERT_PTR(userdata
);
950 session_stop(s
, /* force = */ false);
954 int session_release(Session
*s
) {
957 if (!s
->started
|| s
->stopping
)
960 if (s
->timer_event_source
)
963 return sd_event_add_time_relative(
965 &s
->timer_event_source
,
968 release_timeout_callback
, s
);
971 bool session_is_active(Session
*s
) {
977 return s
->seat
->active
== s
;
980 static int get_tty_atime(const char *tty
, usec_t
*atime
) {
981 _cleanup_free_
char *p
= NULL
;
987 if (!path_is_absolute(tty
)) {
988 p
= path_join("/dev", tty
);
993 } else if (!path_startswith(tty
, "/dev/"))
996 if (lstat(tty
, &st
) < 0)
999 *atime
= timespec_load(&st
.st_atim
);
1003 static int get_process_ctty_atime(pid_t pid
, usec_t
*atime
) {
1004 _cleanup_free_
char *p
= NULL
;
1010 r
= get_ctty(pid
, NULL
, &p
);
1014 return get_tty_atime(p
, atime
);
1017 int session_get_idle_hint(Session
*s
, dual_timestamp
*t
) {
1018 usec_t atime
= 0, dtime
= 0;
1023 /* Graphical sessions have an explicit idle hint */
1024 if (SESSION_TYPE_IS_GRAPHICAL(s
->type
)) {
1026 *t
= s
->idle_hint_timestamp
;
1028 return s
->idle_hint
;
1031 /* For sessions with an explicitly configured tty, let's check its atime */
1033 r
= get_tty_atime(s
->tty
, &atime
);
1038 /* For sessions with a leader but no explicitly configured tty, let's check the controlling tty of
1040 if (pid_is_valid(s
->leader
)) {
1041 r
= get_process_ctty_atime(s
->leader
, &atime
);
1047 *t
= DUAL_TIMESTAMP_NULL
;
1053 dual_timestamp_from_realtime(t
, atime
);
1055 if (s
->manager
->idle_action_usec
> 0 && s
->manager
->stop_idle_session_usec
!= USEC_INFINITY
)
1056 dtime
= MIN(s
->manager
->idle_action_usec
, s
->manager
->stop_idle_session_usec
);
1057 else if (s
->manager
->idle_action_usec
> 0)
1058 dtime
= s
->manager
->idle_action_usec
;
1059 else if (s
->manager
->stop_idle_session_usec
!= USEC_INFINITY
)
1060 dtime
= s
->manager
->stop_idle_session_usec
;
1064 return usec_add(atime
, dtime
) <= now(CLOCK_REALTIME
);
1067 int session_set_idle_hint(Session
*s
, bool b
) {
1070 if (!SESSION_TYPE_IS_GRAPHICAL(s
->type
))
1073 if (s
->idle_hint
== b
)
1077 dual_timestamp_get(&s
->idle_hint_timestamp
);
1079 session_send_changed(s
, "IdleHint", "IdleSinceHint", "IdleSinceHintMonotonic", NULL
);
1082 seat_send_changed(s
->seat
, "IdleHint", "IdleSinceHint", "IdleSinceHintMonotonic", NULL
);
1084 user_send_changed(s
->user
, "IdleHint", "IdleSinceHint", "IdleSinceHintMonotonic", NULL
);
1085 manager_send_changed(s
->manager
, "IdleHint", "IdleSinceHint", "IdleSinceHintMonotonic", NULL
);
1090 int session_get_locked_hint(Session
*s
) {
1093 return s
->locked_hint
;
1096 void session_set_locked_hint(Session
*s
, bool b
) {
1099 if (s
->locked_hint
== b
)
1104 session_send_changed(s
, "LockedHint", NULL
);
1107 void session_set_type(Session
*s
, SessionType t
) {
1116 session_send_changed(s
, "Type", NULL
);
1119 int session_set_display(Session
*s
, const char *display
) {
1125 r
= free_and_strdup(&s
->display
, display
);
1126 if (r
<= 0) /* 0 means the strings were equal */
1131 session_send_changed(s
, "Display", NULL
);
1136 static int session_dispatch_fifo(sd_event_source
*es
, int fd
, uint32_t revents
, void *userdata
) {
1137 Session
*s
= ASSERT_PTR(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
= ASSERT_PTR(userdata
);
1433 session_drop_controller(s
);
1438 int session_set_controller(Session
*s
, const char *sender
, bool force
, bool prepare
) {
1439 _cleanup_free_
char *name
= NULL
;
1445 if (session_is_controller(s
, sender
))
1447 if (s
->controller
&& !force
)
1450 name
= strdup(sender
);
1454 s
->track
= sd_bus_track_unref(s
->track
);
1455 r
= sd_bus_track_new(s
->manager
->bus
, &s
->track
, on_bus_track
, s
);
1459 r
= sd_bus_track_add_name(s
->track
, name
);
1463 /* When setting a session controller, we forcibly mute the VT and set
1464 * it into graphics-mode. Applications can override that by changing
1465 * VT state after calling TakeControl(). However, this serves as a good
1466 * default and well-behaving controllers can now ignore VTs entirely.
1467 * Note that we reset the VT on ReleaseControl() and if the controller
1469 * If logind crashes/restarts, we restore the controller during restart
1470 * (without preparing the VT since the controller has probably overridden
1471 * VT state by now) or reset the VT in case it crashed/exited, too. */
1473 r
= session_prepare_vt(s
);
1475 s
->track
= sd_bus_track_unref(s
->track
);
1480 session_release_controller(s
, true);
1481 s
->controller
= TAKE_PTR(name
);
1487 void session_drop_controller(Session
*s
) {
1493 s
->track
= sd_bus_track_unref(s
->track
);
1494 session_set_type(s
, s
->original_type
);
1495 session_release_controller(s
, false);
1497 session_restore_vt(s
);
1500 static const char* const session_state_table
[_SESSION_STATE_MAX
] = {
1501 [SESSION_OPENING
] = "opening",
1502 [SESSION_ONLINE
] = "online",
1503 [SESSION_ACTIVE
] = "active",
1504 [SESSION_CLOSING
] = "closing",
1507 DEFINE_STRING_TABLE_LOOKUP(session_state
, SessionState
);
1509 static const char* const session_type_table
[_SESSION_TYPE_MAX
] = {
1510 [SESSION_UNSPECIFIED
] = "unspecified",
1511 [SESSION_TTY
] = "tty",
1512 [SESSION_X11
] = "x11",
1513 [SESSION_WAYLAND
] = "wayland",
1514 [SESSION_MIR
] = "mir",
1515 [SESSION_WEB
] = "web",
1518 DEFINE_STRING_TABLE_LOOKUP(session_type
, SessionType
);
1520 static const char* const session_class_table
[_SESSION_CLASS_MAX
] = {
1521 [SESSION_USER
] = "user",
1522 [SESSION_GREETER
] = "greeter",
1523 [SESSION_LOCK_SCREEN
] = "lock-screen",
1524 [SESSION_BACKGROUND
] = "background",
1527 DEFINE_STRING_TABLE_LOOKUP(session_class
, SessionClass
);
1529 static const char* const kill_who_table
[_KILL_WHO_MAX
] = {
1530 [KILL_LEADER
] = "leader",
1534 DEFINE_STRING_TABLE_LOOKUP(kill_who
, KillWho
);
1536 static const char* const tty_validity_table
[_TTY_VALIDITY_MAX
] = {
1537 [TTY_FROM_PAM
] = "from-pam",
1538 [TTY_FROM_UTMP
] = "from-utmp",
1539 [TTY_UTMP_INCONSISTENT
] = "utmp-inconsistent",
1542 DEFINE_STRING_TABLE_LOOKUP(tty_validity
, TTYValidity
);