1 /* SPDX-License-Identifier: LGPL-2.1+ */
8 #include "alloc-util.h"
9 #include "bus-common-errors.h"
10 #include "bus-error.h"
12 #include "cgroup-util.h"
13 #include "clean-ipc.h"
17 #include "format-util.h"
21 #include "logind-user.h"
23 #include "parse-util.h"
24 #include "path-util.h"
26 #include "serialize.h"
28 #include "stdio-util.h"
29 #include "string-table.h"
31 #include "unit-name.h"
32 #include "user-util.h"
35 int user_new(User
**ret
,
42 _cleanup_(user_freep
) User
*u
= NULL
;
43 char lu
[DECIMAL_STR_MAX(uid_t
) + 1];
58 .last_session_timestamp
= USEC_INFINITY
,
61 u
->name
= strdup(name
);
65 u
->home
= strdup(home
);
69 if (asprintf(&u
->state_file
, "/run/systemd/users/"UID_FMT
, uid
) < 0)
72 if (asprintf(&u
->runtime_path
, "/run/user/"UID_FMT
, uid
) < 0)
75 xsprintf(lu
, UID_FMT
, uid
);
76 r
= slice_build_subslice(SPECIAL_USER_SLICE
, lu
, &u
->slice
);
80 r
= unit_name_build("user", lu
, ".service", &u
->service
);
84 r
= unit_name_build("user-runtime-dir", lu
, ".service", &u
->runtime_dir_service
);
88 r
= hashmap_put(m
->users
, UID_TO_PTR(uid
), u
);
92 r
= hashmap_put(m
->user_units
, u
->slice
, u
);
96 r
= hashmap_put(m
->user_units
, u
->service
, u
);
100 r
= hashmap_put(m
->user_units
, u
->runtime_dir_service
, u
);
108 User
*user_free(User
*u
) {
113 LIST_REMOVE(gc_queue
, u
->manager
->user_gc_queue
, u
);
116 session_free(u
->sessions
);
119 hashmap_remove_value(u
->manager
->user_units
, u
->service
, u
);
121 if (u
->runtime_dir_service
)
122 hashmap_remove_value(u
->manager
->user_units
, u
->runtime_dir_service
, u
);
125 hashmap_remove_value(u
->manager
->user_units
, u
->slice
, u
);
127 hashmap_remove_value(u
->manager
->users
, UID_TO_PTR(u
->uid
), u
);
129 (void) sd_event_source_unref(u
->timer_event_source
);
131 u
->service_job
= mfree(u
->service_job
);
133 u
->service
= mfree(u
->service
);
134 u
->runtime_dir_service
= mfree(u
->runtime_dir_service
);
135 u
->slice
= mfree(u
->slice
);
136 u
->runtime_path
= mfree(u
->runtime_path
);
137 u
->state_file
= mfree(u
->state_file
);
138 u
->name
= mfree(u
->name
);
139 u
->home
= mfree(u
->home
);
144 static int user_save_internal(User
*u
) {
145 _cleanup_free_
char *temp_path
= NULL
;
146 _cleanup_fclose_
FILE *f
= NULL
;
150 assert(u
->state_file
);
152 r
= mkdir_safe_label("/run/systemd/users", 0755, 0, 0, MKDIR_WARN_MODE
);
156 r
= fopen_temporary(u
->state_file
, &f
, &temp_path
);
160 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
161 (void) fchmod(fileno(f
), 0644);
164 "# This is private data. Do not parse.\n"
166 "STATE=%s\n" /* friendly user-facing state */
167 "STOPPING=%s\n", /* low-level state */
169 user_state_to_string(user_get_state(u
)),
170 yes_no(u
->stopping
));
172 /* LEGACY: no-one reads RUNTIME= anymore, drop it at some point */
174 fprintf(f
, "RUNTIME=%s\n", u
->runtime_path
);
177 fprintf(f
, "SERVICE_JOB=%s\n", u
->service_job
);
180 fprintf(f
, "DISPLAY=%s\n", u
->display
->id
);
182 if (dual_timestamp_is_set(&u
->timestamp
))
184 "REALTIME="USEC_FMT
"\n"
185 "MONOTONIC="USEC_FMT
"\n",
186 u
->timestamp
.realtime
,
187 u
->timestamp
.monotonic
);
189 if (u
->last_session_timestamp
!= USEC_INFINITY
)
190 fprintf(f
, "LAST_SESSION_TIMESTAMP=" USEC_FMT
"\n",
191 u
->last_session_timestamp
);
197 fputs("SESSIONS=", f
);
199 LIST_FOREACH(sessions_by_user
, i
, u
->sessions
) {
208 fputs("\nSEATS=", f
);
210 LIST_FOREACH(sessions_by_user
, i
, u
->sessions
) {
219 fputs(i
->seat
->id
, f
);
222 fputs("\nACTIVE_SESSIONS=", f
);
224 LIST_FOREACH(sessions_by_user
, i
, u
->sessions
) {
225 if (!session_is_active(i
))
236 fputs("\nONLINE_SESSIONS=", f
);
238 LIST_FOREACH(sessions_by_user
, i
, u
->sessions
) {
239 if (session_get_state(i
) == SESSION_CLOSING
)
250 fputs("\nACTIVE_SEATS=", f
);
252 LIST_FOREACH(sessions_by_user
, i
, u
->sessions
) {
253 if (!session_is_active(i
) || !i
->seat
)
261 fputs(i
->seat
->id
, f
);
264 fputs("\nONLINE_SEATS=", f
);
266 LIST_FOREACH(sessions_by_user
, i
, u
->sessions
) {
267 if (session_get_state(i
) == SESSION_CLOSING
|| !i
->seat
)
275 fputs(i
->seat
->id
, f
);
280 r
= fflush_and_check(f
);
284 if (rename(temp_path
, u
->state_file
) < 0) {
292 (void) unlink(u
->state_file
);
295 (void) unlink(temp_path
);
297 return log_error_errno(r
, "Failed to save user data %s: %m", u
->state_file
);
300 int user_save(User
*u
) {
306 return user_save_internal(u
);
309 int user_load(User
*u
) {
310 _cleanup_free_
char *realtime
= NULL
, *monotonic
= NULL
, *stopping
= NULL
, *last_session_timestamp
= NULL
;
315 r
= parse_env_file(NULL
, u
->state_file
,
316 "SERVICE_JOB", &u
->service_job
,
317 "STOPPING", &stopping
,
318 "REALTIME", &realtime
,
319 "MONOTONIC", &monotonic
,
320 "LAST_SESSION_TIMESTAMP", &last_session_timestamp
);
324 return log_error_errno(r
, "Failed to read %s: %m", u
->state_file
);
327 r
= parse_boolean(stopping
);
329 log_debug_errno(r
, "Failed to parse 'STOPPING' boolean: %s", stopping
);
335 (void) deserialize_usec(realtime
, &u
->timestamp
.realtime
);
337 (void) deserialize_usec(monotonic
, &u
->timestamp
.monotonic
);
338 if (last_session_timestamp
)
339 (void) deserialize_usec(last_session_timestamp
, &u
->last_session_timestamp
);
344 static void user_start_service(User
*u
) {
345 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
350 /* Start the service containing the "systemd --user" instance (user@.service). Note that we don't explicitly
351 * start the per-user slice or the systemd-runtime-dir@.service instance, as those are pulled in both by
352 * user@.service and the session scopes as dependencies. */
354 u
->service_job
= mfree(u
->service_job
);
356 r
= manager_start_unit(u
->manager
, u
->service
, &error
, &u
->service_job
);
358 log_warning_errno(r
, "Failed to start user service '%s', ignoring: %s", u
->service
, bus_error_message(&error
, r
));
361 int user_start(User
*u
) {
364 if (u
->started
&& !u
->stopping
)
367 /* If u->stopping is set, the user is marked for removal and service stop-jobs are queued. We have to clear
368 * that flag before queing the start-jobs again. If they succeed, the user object can be re-used just fine
369 * (pid1 takes care of job-ordering and proper restart), but if they fail, we want to force another user_stop()
370 * so possibly pending units are stopped. */
374 log_debug("Starting services for new user %s.", u
->name
);
376 /* Save the user data so far, because pam_systemd will read the XDG_RUNTIME_DIR out of it while starting up
377 * systemd --user. We need to do user_save_internal() because we have not "officially" started yet. */
378 user_save_internal(u
);
380 /* Start user@UID.service */
381 user_start_service(u
);
384 if (!dual_timestamp_is_set(&u
->timestamp
))
385 dual_timestamp_get(&u
->timestamp
);
386 user_send_signal(u
, true);
390 /* Save new user data */
396 static void user_stop_service(User
*u
) {
397 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
403 /* The reverse of user_start_service(). Note that we only stop user@UID.service here, and let StopWhenUnneeded=
404 * deal with the slice and the user-runtime-dir@.service instance. */
406 u
->service_job
= mfree(u
->service_job
);
408 r
= manager_stop_unit(u
->manager
, u
->service
, &error
, &u
->service_job
);
410 log_warning_errno(r
, "Failed to stop user service '%s', ignoring: %s", u
->service
, bus_error_message(&error
, r
));
413 int user_stop(User
*u
, bool force
) {
418 /* This is called whenever we begin with tearing down a user record. It's called in two cases: explicit API
419 * request to do so via the bus (in which case 'force' is true) and automatically due to GC, if there's no
420 * session left pinning it (in which case 'force' is false). Note that this just initiates tearing down of the
421 * user, the User object will remain in memory until user_finalize() is called, see below. */
426 if (u
->stopping
) { /* Stop jobs have already been queued */
431 LIST_FOREACH(sessions_by_user
, s
, u
->sessions
) {
434 k
= session_stop(s
, force
);
439 user_stop_service(u
);
448 int user_finalize(User
*u
) {
454 /* Called when the user is really ready to be freed, i.e. when all unit stop jobs and suchlike for it are
455 * done. This is called as a result of an earlier user_done() when all jobs are completed. */
458 log_debug("User %s logged out.", u
->name
);
460 LIST_FOREACH(sessions_by_user
, s
, u
->sessions
) {
461 k
= session_finalize(s
);
466 /* Clean SysV + POSIX IPC objects, but only if this is not a system user. Background: in many setups cronjobs
467 * are run in full PAM and thus logind sessions, even if the code run doesn't belong to actual users but to
468 * system components. Since enable RemoveIPC= globally for all users, we need to be a bit careful with such
469 * cases, as we shouldn't accidentally remove a system service's IPC objects while it is running, just because
470 * a cronjob running as the same user just finished. Hence: exclude system users generally from IPC clean-up,
471 * and do it only for normal users. */
472 if (u
->manager
->remove_ipc
&& !uid_is_system(u
->uid
)) {
473 k
= clean_ipc_by_uid(u
->uid
);
478 (void) unlink(u
->state_file
);
479 user_add_to_gc_queue(u
);
482 user_send_signal(u
, false);
489 int user_get_idle_hint(User
*u
, dual_timestamp
*t
) {
491 bool idle_hint
= true;
492 dual_timestamp ts
= DUAL_TIMESTAMP_NULL
;
496 LIST_FOREACH(sessions_by_user
, s
, u
->sessions
) {
500 ih
= session_get_idle_hint(s
, &k
);
506 if (k
.monotonic
< ts
.monotonic
)
512 } else if (idle_hint
) {
514 if (k
.monotonic
> ts
.monotonic
)
525 int user_check_linger_file(User
*u
) {
526 _cleanup_free_
char *cc
= NULL
;
529 cc
= cescape(u
->name
);
533 p
= strjoina("/var/lib/systemd/linger/", cc
);
534 if (access(p
, F_OK
) < 0) {
544 static bool user_unit_active(User
*u
) {
549 assert(u
->runtime_dir_service
);
552 FOREACH_STRING(i
, u
->service
, u
->runtime_dir_service
, u
->slice
) {
553 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
555 r
= manager_unit_is_active(u
->manager
, i
, &error
);
557 log_debug_errno(r
, "Failed to determine whether unit '%s' is active, ignoring: %s", u
->service
, bus_error_message(&error
, r
));
565 bool user_may_gc(User
*u
, bool drop_not_started
) {
570 if (drop_not_started
&& !u
->started
)
576 if (u
->last_session_timestamp
!= USEC_INFINITY
) {
577 /* All sessions have been closed. Let's see if we shall leave the user record around for a bit */
579 if (u
->manager
->user_stop_delay
== USEC_INFINITY
)
580 return false; /* Leave it around forever! */
581 if (u
->manager
->user_stop_delay
> 0 &&
582 now(CLOCK_MONOTONIC
) < usec_add(u
->last_session_timestamp
, u
->manager
->user_stop_delay
))
583 return false; /* Leave it around for a bit longer. */
586 /* Is this a user that shall stay around forever ("linger")? Before we say "no" to GC'ing for lingering users, let's check
587 * if any of the three units that we maintain for this user is still around. If none of them is,
588 * there's no need to keep this user around even if lingering is enabled. */
589 if (user_check_linger_file(u
) > 0 && user_unit_active(u
))
592 /* Check if our job is still pending */
593 if (u
->service_job
) {
594 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
596 r
= manager_job_is_active(u
->manager
, u
->service_job
, &error
);
598 log_debug_errno(r
, "Failed to determine whether job '%s' is pending, ignoring: %s", u
->service_job
, bus_error_message(&error
, r
));
603 /* Note that we don't care if the three units we manage for each user object are up or not, as we are managing
604 * their state rather than tracking it. */
609 void user_add_to_gc_queue(User
*u
) {
615 LIST_PREPEND(gc_queue
, u
->manager
->user_gc_queue
, u
);
616 u
->in_gc_queue
= true;
619 UserState
user_get_state(User
*u
) {
627 if (!u
->started
|| u
->service_job
)
631 bool all_closing
= true;
633 LIST_FOREACH(sessions_by_user
, i
, u
->sessions
) {
636 state
= session_get_state(i
);
637 if (state
== SESSION_ACTIVE
)
639 if (state
!= SESSION_CLOSING
)
643 return all_closing
? USER_CLOSING
: USER_ONLINE
;
646 if (user_check_linger_file(u
) > 0 && user_unit_active(u
))
647 return USER_LINGERING
;
652 int user_kill(User
*u
, int signo
) {
655 return manager_kill_unit(u
->manager
, u
->slice
, KILL_ALL
, signo
, NULL
);
658 static bool elect_display_filter(Session
*s
) {
659 /* Return true if the session is a candidate for the user’s ‘primary session’ or ‘display’. */
662 return s
->class == SESSION_USER
&& s
->started
&& !s
->stopping
;
665 static int elect_display_compare(Session
*s1
, Session
*s2
) {
666 /* Indexed by SessionType. Lower numbers mean more preferred. */
667 const int type_ranks
[_SESSION_TYPE_MAX
] = {
668 [SESSION_UNSPECIFIED
] = 0,
671 [SESSION_WAYLAND
] = -3,
676 /* Calculate the partial order relationship between s1 and s2,
677 * returning < 0 if s1 is preferred as the user’s ‘primary session’,
678 * 0 if s1 and s2 are equally preferred or incomparable, or > 0 if s2
681 * s1 or s2 may be NULL. */
685 if ((s1
== NULL
) != (s2
== NULL
))
686 return (s1
== NULL
) - (s2
== NULL
);
688 if (s1
->stopping
!= s2
->stopping
)
689 return s1
->stopping
- s2
->stopping
;
691 if ((s1
->class != SESSION_USER
) != (s2
->class != SESSION_USER
))
692 return (s1
->class != SESSION_USER
) - (s2
->class != SESSION_USER
);
694 if ((s1
->type
== _SESSION_TYPE_INVALID
) != (s2
->type
== _SESSION_TYPE_INVALID
))
695 return (s1
->type
== _SESSION_TYPE_INVALID
) - (s2
->type
== _SESSION_TYPE_INVALID
);
697 if (s1
->type
!= s2
->type
)
698 return type_ranks
[s1
->type
] - type_ranks
[s2
->type
];
703 void user_elect_display(User
*u
) {
708 /* This elects a primary session for each user, which we call the "display". We try to keep the assignment
709 * stable, but we "upgrade" to better choices. */
710 log_debug("Electing new display for user %s", u
->name
);
712 LIST_FOREACH(sessions_by_user
, s
, u
->sessions
) {
713 if (!elect_display_filter(s
)) {
714 log_debug("Ignoring session %s", s
->id
);
718 if (elect_display_compare(s
, u
->display
) < 0) {
719 log_debug("Choosing session %s in preference to %s", s
->id
, u
->display
? u
->display
->id
: "-");
725 static int user_stop_timeout_callback(sd_event_source
*es
, uint64_t usec
, void *userdata
) {
729 user_add_to_gc_queue(u
);
734 void user_update_last_session_timer(User
*u
) {
740 /* There are sessions, turn off the timer */
741 u
->last_session_timestamp
= USEC_INFINITY
;
742 u
->timer_event_source
= sd_event_source_unref(u
->timer_event_source
);
746 if (u
->last_session_timestamp
!= USEC_INFINITY
)
747 return; /* Timer already started */
749 u
->last_session_timestamp
= now(CLOCK_MONOTONIC
);
751 assert(!u
->timer_event_source
);
753 if (u
->manager
->user_stop_delay
== 0 || u
->manager
->user_stop_delay
== USEC_INFINITY
)
756 if (sd_event_get_state(u
->manager
->event
) == SD_EVENT_FINISHED
) {
757 log_debug("Not allocating user stop timeout, since we are already exiting.");
761 r
= sd_event_add_time(u
->manager
->event
,
762 &u
->timer_event_source
,
764 usec_add(u
->last_session_timestamp
, u
->manager
->user_stop_delay
), 0,
765 user_stop_timeout_callback
, u
);
767 log_warning_errno(r
, "Failed to enqueue user stop event source, ignoring: %m");
770 char s
[FORMAT_TIMESPAN_MAX
];
772 log_debug("Last session of user '%s' logged out, terminating user context in %s.",
774 format_timespan(s
, sizeof(s
), u
->manager
->user_stop_delay
, USEC_PER_MSEC
));
778 static const char* const user_state_table
[_USER_STATE_MAX
] = {
779 [USER_OFFLINE
] = "offline",
780 [USER_OPENING
] = "opening",
781 [USER_LINGERING
] = "lingering",
782 [USER_ONLINE
] = "online",
783 [USER_ACTIVE
] = "active",
784 [USER_CLOSING
] = "closing"
787 DEFINE_STRING_TABLE_LOOKUP(user_state
, UserState
);
789 int config_parse_tmpfs_size(
791 const char *filename
,
794 unsigned section_line
,
809 /* First, try to parse as percentage */
810 r
= parse_permille(rvalue
);
811 if (r
> 0 && r
< 1000)
812 *sz
= physical_memory_scale(r
, 1000U);
816 /* If the passed argument was not a percentage, or out of range, parse as byte size */
818 r
= parse_size(rvalue
, 1024, &k
);
819 if (r
>= 0 && (k
<= 0 || (uint64_t) (size_t) k
!= k
))
822 log_syntax(unit
, LOG_ERR
, filename
, line
, r
, "Failed to parse size value '%s', ignoring: %m", rvalue
);
826 *sz
= PAGE_ALIGN((size_t) k
);
832 int config_parse_compat_user_tasks_max(
834 const char *filename
,
837 unsigned section_line
,
849 log_syntax(unit
, LOG_NOTICE
, filename
, line
, 0,
850 "Support for option %s= has been removed.",
852 log_info("Hint: try creating /etc/systemd/system/user-.slice.d/50-limits.conf with:\n"