1 /* SPDX-License-Identifier: LGPL-2.1+ */
7 #include "alloc-util.h"
8 #include "bus-common-errors.h"
11 #include "cgroup-util.h"
12 #include "clean-ipc.h"
17 #include "format-util.h"
21 #include "limits-util.h"
22 #include "logind-dbus.h"
23 #include "logind-user.h"
24 #include "logind-user-dbus.h"
26 #include "parse-util.h"
27 #include "path-util.h"
29 #include "serialize.h"
31 #include "stdio-util.h"
32 #include "string-table.h"
34 #include "tmpfile-util.h"
35 #include "unit-name.h"
36 #include "user-util.h"
39 int user_new(User
**ret
,
46 _cleanup_(user_freep
) User
*u
= NULL
;
47 char lu
[DECIMAL_STR_MAX(uid_t
) + 1];
62 .last_session_timestamp
= USEC_INFINITY
,
65 u
->name
= strdup(name
);
69 u
->home
= strdup(home
);
73 path_simplify(u
->home
, true);
75 if (asprintf(&u
->state_file
, "/run/systemd/users/"UID_FMT
, uid
) < 0)
78 if (asprintf(&u
->runtime_path
, "/run/user/"UID_FMT
, uid
) < 0)
81 xsprintf(lu
, UID_FMT
, uid
);
82 r
= slice_build_subslice(SPECIAL_USER_SLICE
, lu
, &u
->slice
);
86 r
= unit_name_build("user", lu
, ".service", &u
->service
);
90 r
= unit_name_build("user-runtime-dir", lu
, ".service", &u
->runtime_dir_service
);
94 r
= hashmap_put(m
->users
, UID_TO_PTR(uid
), u
);
98 r
= hashmap_put(m
->user_units
, u
->slice
, u
);
102 r
= hashmap_put(m
->user_units
, u
->service
, u
);
106 r
= hashmap_put(m
->user_units
, u
->runtime_dir_service
, u
);
114 User
*user_free(User
*u
) {
119 LIST_REMOVE(gc_queue
, u
->manager
->user_gc_queue
, u
);
122 session_free(u
->sessions
);
125 hashmap_remove_value(u
->manager
->user_units
, u
->service
, u
);
127 if (u
->runtime_dir_service
)
128 hashmap_remove_value(u
->manager
->user_units
, u
->runtime_dir_service
, u
);
131 hashmap_remove_value(u
->manager
->user_units
, u
->slice
, u
);
133 hashmap_remove_value(u
->manager
->users
, UID_TO_PTR(u
->uid
), u
);
135 (void) sd_event_source_unref(u
->timer_event_source
);
137 u
->service_job
= mfree(u
->service_job
);
139 u
->service
= mfree(u
->service
);
140 u
->runtime_dir_service
= mfree(u
->runtime_dir_service
);
141 u
->slice
= mfree(u
->slice
);
142 u
->runtime_path
= mfree(u
->runtime_path
);
143 u
->state_file
= mfree(u
->state_file
);
144 u
->name
= mfree(u
->name
);
145 u
->home
= mfree(u
->home
);
150 static int user_save_internal(User
*u
) {
151 _cleanup_free_
char *temp_path
= NULL
;
152 _cleanup_fclose_
FILE *f
= NULL
;
156 assert(u
->state_file
);
158 r
= mkdir_safe_label("/run/systemd/users", 0755, 0, 0, MKDIR_WARN_MODE
);
162 r
= fopen_temporary(u
->state_file
, &f
, &temp_path
);
166 (void) fchmod(fileno(f
), 0644);
169 "# This is private data. Do not parse.\n"
171 "STATE=%s\n" /* friendly user-facing state */
172 "STOPPING=%s\n", /* low-level state */
174 user_state_to_string(user_get_state(u
)),
175 yes_no(u
->stopping
));
177 /* LEGACY: no-one reads RUNTIME= anymore, drop it at some point */
179 fprintf(f
, "RUNTIME=%s\n", u
->runtime_path
);
182 fprintf(f
, "SERVICE_JOB=%s\n", u
->service_job
);
185 fprintf(f
, "DISPLAY=%s\n", u
->display
->id
);
187 if (dual_timestamp_is_set(&u
->timestamp
))
189 "REALTIME="USEC_FMT
"\n"
190 "MONOTONIC="USEC_FMT
"\n",
191 u
->timestamp
.realtime
,
192 u
->timestamp
.monotonic
);
194 if (u
->last_session_timestamp
!= USEC_INFINITY
)
195 fprintf(f
, "LAST_SESSION_TIMESTAMP=" USEC_FMT
"\n",
196 u
->last_session_timestamp
);
202 fputs("SESSIONS=", f
);
204 LIST_FOREACH(sessions_by_user
, i
, u
->sessions
) {
213 fputs("\nSEATS=", f
);
215 LIST_FOREACH(sessions_by_user
, i
, u
->sessions
) {
224 fputs(i
->seat
->id
, f
);
227 fputs("\nACTIVE_SESSIONS=", f
);
229 LIST_FOREACH(sessions_by_user
, i
, u
->sessions
) {
230 if (!session_is_active(i
))
241 fputs("\nONLINE_SESSIONS=", f
);
243 LIST_FOREACH(sessions_by_user
, i
, u
->sessions
) {
244 if (session_get_state(i
) == SESSION_CLOSING
)
255 fputs("\nACTIVE_SEATS=", f
);
257 LIST_FOREACH(sessions_by_user
, i
, u
->sessions
) {
258 if (!session_is_active(i
) || !i
->seat
)
266 fputs(i
->seat
->id
, f
);
269 fputs("\nONLINE_SEATS=", f
);
271 LIST_FOREACH(sessions_by_user
, i
, u
->sessions
) {
272 if (session_get_state(i
) == SESSION_CLOSING
|| !i
->seat
)
280 fputs(i
->seat
->id
, f
);
285 r
= fflush_and_check(f
);
289 if (rename(temp_path
, u
->state_file
) < 0) {
297 (void) unlink(u
->state_file
);
300 (void) unlink(temp_path
);
302 return log_error_errno(r
, "Failed to save user data %s: %m", u
->state_file
);
305 int user_save(User
*u
) {
311 return user_save_internal(u
);
314 int user_load(User
*u
) {
315 _cleanup_free_
char *realtime
= NULL
, *monotonic
= NULL
, *stopping
= NULL
, *last_session_timestamp
= NULL
;
320 r
= parse_env_file(NULL
, u
->state_file
,
321 "SERVICE_JOB", &u
->service_job
,
322 "STOPPING", &stopping
,
323 "REALTIME", &realtime
,
324 "MONOTONIC", &monotonic
,
325 "LAST_SESSION_TIMESTAMP", &last_session_timestamp
);
329 return log_error_errno(r
, "Failed to read %s: %m", u
->state_file
);
332 r
= parse_boolean(stopping
);
334 log_debug_errno(r
, "Failed to parse 'STOPPING' boolean: %s", stopping
);
340 (void) deserialize_usec(realtime
, &u
->timestamp
.realtime
);
342 (void) deserialize_usec(monotonic
, &u
->timestamp
.monotonic
);
343 if (last_session_timestamp
)
344 (void) deserialize_usec(last_session_timestamp
, &u
->last_session_timestamp
);
349 static void user_start_service(User
*u
) {
350 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
355 /* Start the service containing the "systemd --user" instance (user@.service). Note that we don't explicitly
356 * start the per-user slice or the systemd-runtime-dir@.service instance, as those are pulled in both by
357 * user@.service and the session scopes as dependencies. */
359 u
->service_job
= mfree(u
->service_job
);
361 r
= manager_start_unit(u
->manager
, u
->service
, &error
, &u
->service_job
);
363 log_full_errno(sd_bus_error_has_name(&error
, BUS_ERROR_UNIT_MASKED
) ? LOG_DEBUG
: LOG_WARNING
, r
,
364 "Failed to start user service '%s', ignoring: %s", u
->service
, bus_error_message(&error
, r
));
367 int user_start(User
*u
) {
370 if (u
->started
&& !u
->stopping
)
373 /* If u->stopping is set, the user is marked for removal and service stop-jobs are queued. We have to clear
374 * that flag before queueing the start-jobs again. If they succeed, the user object can be re-used just fine
375 * (pid1 takes care of job-ordering and proper restart), but if they fail, we want to force another user_stop()
376 * so possibly pending units are stopped. */
380 log_debug("Starting services for new user %s.", u
->name
);
382 /* Save the user data so far, because pam_systemd will read the XDG_RUNTIME_DIR out of it while starting up
383 * systemd --user. We need to do user_save_internal() because we have not "officially" started yet. */
384 user_save_internal(u
);
386 /* Start user@UID.service */
387 user_start_service(u
);
390 if (!dual_timestamp_is_set(&u
->timestamp
))
391 dual_timestamp_get(&u
->timestamp
);
392 user_send_signal(u
, true);
396 /* Save new user data */
402 static void user_stop_service(User
*u
) {
403 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
409 /* The reverse of user_start_service(). Note that we only stop user@UID.service here, and let StopWhenUnneeded=
410 * deal with the slice and the user-runtime-dir@.service instance. */
412 u
->service_job
= mfree(u
->service_job
);
414 r
= manager_stop_unit(u
->manager
, u
->service
, &error
, &u
->service_job
);
416 log_warning_errno(r
, "Failed to stop user service '%s', ignoring: %s", u
->service
, bus_error_message(&error
, r
));
419 int user_stop(User
*u
, bool force
) {
424 /* This is called whenever we begin with tearing down a user record. It's called in two cases: explicit API
425 * request to do so via the bus (in which case 'force' is true) and automatically due to GC, if there's no
426 * session left pinning it (in which case 'force' is false). Note that this just initiates tearing down of the
427 * user, the User object will remain in memory until user_finalize() is called, see below. */
432 if (u
->stopping
) { /* Stop jobs have already been queued */
437 LIST_FOREACH(sessions_by_user
, s
, u
->sessions
) {
440 k
= session_stop(s
, force
);
445 user_stop_service(u
);
454 int user_finalize(User
*u
) {
460 /* Called when the user is really ready to be freed, i.e. when all unit stop jobs and suchlike for it are
461 * done. This is called as a result of an earlier user_done() when all jobs are completed. */
464 log_debug("User %s logged out.", u
->name
);
466 LIST_FOREACH(sessions_by_user
, s
, u
->sessions
) {
467 k
= session_finalize(s
);
472 /* Clean SysV + POSIX IPC objects, but only if this is not a system user. Background: in many setups cronjobs
473 * are run in full PAM and thus logind sessions, even if the code run doesn't belong to actual users but to
474 * system components. Since enable RemoveIPC= globally for all users, we need to be a bit careful with such
475 * cases, as we shouldn't accidentally remove a system service's IPC objects while it is running, just because
476 * a cronjob running as the same user just finished. Hence: exclude system users generally from IPC clean-up,
477 * and do it only for normal users. */
478 if (u
->manager
->remove_ipc
&& !uid_is_system(u
->uid
)) {
479 k
= clean_ipc_by_uid(u
->uid
);
484 (void) unlink(u
->state_file
);
485 user_add_to_gc_queue(u
);
488 user_send_signal(u
, false);
495 int user_get_idle_hint(User
*u
, dual_timestamp
*t
) {
497 bool idle_hint
= true;
498 dual_timestamp ts
= DUAL_TIMESTAMP_NULL
;
502 LIST_FOREACH(sessions_by_user
, s
, u
->sessions
) {
506 ih
= session_get_idle_hint(s
, &k
);
512 if (k
.monotonic
< ts
.monotonic
)
518 } else if (idle_hint
) {
520 if (k
.monotonic
> ts
.monotonic
)
531 int user_check_linger_file(User
*u
) {
532 _cleanup_free_
char *cc
= NULL
;
535 cc
= cescape(u
->name
);
539 p
= strjoina("/var/lib/systemd/linger/", cc
);
540 if (access(p
, F_OK
) < 0) {
550 static bool user_unit_active(User
*u
) {
555 assert(u
->runtime_dir_service
);
558 FOREACH_STRING(i
, u
->service
, u
->runtime_dir_service
, u
->slice
) {
559 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
561 r
= manager_unit_is_active(u
->manager
, i
, &error
);
563 log_debug_errno(r
, "Failed to determine whether unit '%s' is active, ignoring: %s", u
->service
, bus_error_message(&error
, r
));
571 bool user_may_gc(User
*u
, bool drop_not_started
) {
576 if (drop_not_started
&& !u
->started
)
582 if (u
->last_session_timestamp
!= USEC_INFINITY
) {
583 /* All sessions have been closed. Let's see if we shall leave the user record around for a bit */
585 if (u
->manager
->user_stop_delay
== USEC_INFINITY
)
586 return false; /* Leave it around forever! */
587 if (u
->manager
->user_stop_delay
> 0 &&
588 now(CLOCK_MONOTONIC
) < usec_add(u
->last_session_timestamp
, u
->manager
->user_stop_delay
))
589 return false; /* Leave it around for a bit longer. */
592 /* Is this a user that shall stay around forever ("linger")? Before we say "no" to GC'ing for lingering users, let's check
593 * if any of the three units that we maintain for this user is still around. If none of them is,
594 * there's no need to keep this user around even if lingering is enabled. */
595 if (user_check_linger_file(u
) > 0 && user_unit_active(u
))
598 /* Check if our job is still pending */
599 if (u
->service_job
) {
600 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
602 r
= manager_job_is_active(u
->manager
, u
->service_job
, &error
);
604 log_debug_errno(r
, "Failed to determine whether job '%s' is pending, ignoring: %s", u
->service_job
, bus_error_message(&error
, r
));
609 /* Note that we don't care if the three units we manage for each user object are up or not, as we are managing
610 * their state rather than tracking it. */
615 void user_add_to_gc_queue(User
*u
) {
621 LIST_PREPEND(gc_queue
, u
->manager
->user_gc_queue
, u
);
622 u
->in_gc_queue
= true;
625 UserState
user_get_state(User
*u
) {
633 if (!u
->started
|| u
->service_job
)
637 bool all_closing
= true;
639 LIST_FOREACH(sessions_by_user
, i
, u
->sessions
) {
642 state
= session_get_state(i
);
643 if (state
== SESSION_ACTIVE
)
645 if (state
!= SESSION_CLOSING
)
649 return all_closing
? USER_CLOSING
: USER_ONLINE
;
652 if (user_check_linger_file(u
) > 0 && user_unit_active(u
))
653 return USER_LINGERING
;
658 int user_kill(User
*u
, int signo
) {
661 return manager_kill_unit(u
->manager
, u
->slice
, KILL_ALL
, signo
, NULL
);
664 static bool elect_display_filter(Session
*s
) {
665 /* Return true if the session is a candidate for the user’s ‘primary session’ or ‘display’. */
668 return IN_SET(s
->class, SESSION_USER
, SESSION_GREETER
) && s
->started
&& !s
->stopping
;
671 static int elect_display_compare(Session
*s1
, Session
*s2
) {
672 /* Indexed by SessionType. Lower numbers mean more preferred. */
673 static const int type_ranks
[_SESSION_TYPE_MAX
] = {
674 [SESSION_UNSPECIFIED
] = 0,
677 [SESSION_WAYLAND
] = -3,
682 /* Calculate the partial order relationship between s1 and s2,
683 * returning < 0 if s1 is preferred as the user’s ‘primary session’,
684 * 0 if s1 and s2 are equally preferred or incomparable, or > 0 if s2
687 * s1 or s2 may be NULL. */
691 if ((s1
== NULL
) != (s2
== NULL
))
692 return (s1
== NULL
) - (s2
== NULL
);
694 if (s1
->stopping
!= s2
->stopping
)
695 return s1
->stopping
- s2
->stopping
;
697 if ((s1
->class != SESSION_USER
) != (s2
->class != SESSION_USER
))
698 return (s1
->class != SESSION_USER
) - (s2
->class != SESSION_USER
);
700 if ((s1
->type
== _SESSION_TYPE_INVALID
) != (s2
->type
== _SESSION_TYPE_INVALID
))
701 return (s1
->type
== _SESSION_TYPE_INVALID
) - (s2
->type
== _SESSION_TYPE_INVALID
);
703 if (s1
->type
!= s2
->type
)
704 return type_ranks
[s1
->type
] - type_ranks
[s2
->type
];
709 void user_elect_display(User
*u
) {
714 /* This elects a primary session for each user, which we call the "display". We try to keep the assignment
715 * stable, but we "upgrade" to better choices. */
716 log_debug("Electing new display for user %s", u
->name
);
718 LIST_FOREACH(sessions_by_user
, s
, u
->sessions
) {
719 if (!elect_display_filter(s
)) {
720 log_debug("Ignoring session %s", s
->id
);
724 if (elect_display_compare(s
, u
->display
) < 0) {
725 log_debug("Choosing session %s in preference to %s", s
->id
, u
->display
? u
->display
->id
: "-");
731 static int user_stop_timeout_callback(sd_event_source
*es
, uint64_t usec
, void *userdata
) {
735 user_add_to_gc_queue(u
);
740 void user_update_last_session_timer(User
*u
) {
746 /* There are sessions, turn off the timer */
747 u
->last_session_timestamp
= USEC_INFINITY
;
748 u
->timer_event_source
= sd_event_source_unref(u
->timer_event_source
);
752 if (u
->last_session_timestamp
!= USEC_INFINITY
)
753 return; /* Timer already started */
755 u
->last_session_timestamp
= now(CLOCK_MONOTONIC
);
757 assert(!u
->timer_event_source
);
759 if (IN_SET(u
->manager
->user_stop_delay
, 0, USEC_INFINITY
))
762 if (sd_event_get_state(u
->manager
->event
) == SD_EVENT_FINISHED
) {
763 log_debug("Not allocating user stop timeout, since we are already exiting.");
767 r
= sd_event_add_time(u
->manager
->event
,
768 &u
->timer_event_source
,
770 usec_add(u
->last_session_timestamp
, u
->manager
->user_stop_delay
), 0,
771 user_stop_timeout_callback
, u
);
773 log_warning_errno(r
, "Failed to enqueue user stop event source, ignoring: %m");
776 char s
[FORMAT_TIMESPAN_MAX
];
778 log_debug("Last session of user '%s' logged out, terminating user context in %s.",
780 format_timespan(s
, sizeof(s
), u
->manager
->user_stop_delay
, USEC_PER_MSEC
));
784 static const char* const user_state_table
[_USER_STATE_MAX
] = {
785 [USER_OFFLINE
] = "offline",
786 [USER_OPENING
] = "opening",
787 [USER_LINGERING
] = "lingering",
788 [USER_ONLINE
] = "online",
789 [USER_ACTIVE
] = "active",
790 [USER_CLOSING
] = "closing"
793 DEFINE_STRING_TABLE_LOOKUP(user_state
, UserState
);
795 int config_parse_tmpfs_size(
797 const char *filename
,
800 unsigned section_line
,
815 /* First, try to parse as percentage */
816 r
= parse_permille(rvalue
);
817 if (r
> 0 && r
< 1000)
818 *sz
= physical_memory_scale(r
, 1000U);
822 /* If the passed argument was not a percentage, or out of range, parse as byte size */
824 r
= parse_size(rvalue
, 1024, &k
);
825 if (r
>= 0 && (k
<= 0 || (uint64_t) (size_t) k
!= k
))
828 log_syntax(unit
, LOG_ERR
, filename
, line
, r
, "Failed to parse size value '%s', ignoring: %m", rvalue
);
832 *sz
= PAGE_ALIGN((size_t) k
);
838 int config_parse_compat_user_tasks_max(
840 const char *filename
,
843 unsigned section_line
,
855 log_syntax(unit
, LOG_NOTICE
, filename
, line
, 0,
856 "Support for option %s= has been removed.",
858 log_info("Hint: try creating /etc/systemd/system/user-.slice.d/50-limits.conf with:\n"