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"
18 #include "format-util.h"
22 #include "logind-user.h"
24 #include "parse-util.h"
25 #include "path-util.h"
27 #include "serialize.h"
29 #include "stdio-util.h"
30 #include "string-table.h"
32 #include "tmpfile-util.h"
33 #include "unit-name.h"
34 #include "user-util.h"
37 int user_new(User
**ret
,
44 _cleanup_(user_freep
) User
*u
= NULL
;
45 char lu
[DECIMAL_STR_MAX(uid_t
) + 1];
60 .last_session_timestamp
= USEC_INFINITY
,
63 u
->name
= strdup(name
);
67 u
->home
= strdup(home
);
71 if (asprintf(&u
->state_file
, "/run/systemd/users/"UID_FMT
, uid
) < 0)
74 if (asprintf(&u
->runtime_path
, "/run/user/"UID_FMT
, uid
) < 0)
77 xsprintf(lu
, UID_FMT
, uid
);
78 r
= slice_build_subslice(SPECIAL_USER_SLICE
, lu
, &u
->slice
);
82 r
= unit_name_build("user", lu
, ".service", &u
->service
);
86 r
= unit_name_build("user-runtime-dir", lu
, ".service", &u
->runtime_dir_service
);
90 r
= hashmap_put(m
->users
, UID_TO_PTR(uid
), u
);
94 r
= hashmap_put(m
->user_units
, u
->slice
, u
);
98 r
= hashmap_put(m
->user_units
, u
->service
, u
);
102 r
= hashmap_put(m
->user_units
, u
->runtime_dir_service
, u
);
110 User
*user_free(User
*u
) {
115 LIST_REMOVE(gc_queue
, u
->manager
->user_gc_queue
, u
);
118 session_free(u
->sessions
);
121 hashmap_remove_value(u
->manager
->user_units
, u
->service
, u
);
123 if (u
->runtime_dir_service
)
124 hashmap_remove_value(u
->manager
->user_units
, u
->runtime_dir_service
, u
);
127 hashmap_remove_value(u
->manager
->user_units
, u
->slice
, u
);
129 hashmap_remove_value(u
->manager
->users
, UID_TO_PTR(u
->uid
), u
);
131 (void) sd_event_source_unref(u
->timer_event_source
);
133 u
->service_job
= mfree(u
->service_job
);
135 u
->service
= mfree(u
->service
);
136 u
->runtime_dir_service
= mfree(u
->runtime_dir_service
);
137 u
->slice
= mfree(u
->slice
);
138 u
->runtime_path
= mfree(u
->runtime_path
);
139 u
->state_file
= mfree(u
->state_file
);
140 u
->name
= mfree(u
->name
);
141 u
->home
= mfree(u
->home
);
146 static int user_save_internal(User
*u
) {
147 _cleanup_free_
char *temp_path
= NULL
;
148 _cleanup_fclose_
FILE *f
= NULL
;
152 assert(u
->state_file
);
154 r
= mkdir_safe_label("/run/systemd/users", 0755, 0, 0, MKDIR_WARN_MODE
);
158 r
= fopen_temporary(u
->state_file
, &f
, &temp_path
);
162 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
163 (void) fchmod(fileno(f
), 0644);
166 "# This is private data. Do not parse.\n"
168 "STATE=%s\n" /* friendly user-facing state */
169 "STOPPING=%s\n", /* low-level state */
171 user_state_to_string(user_get_state(u
)),
172 yes_no(u
->stopping
));
174 /* LEGACY: no-one reads RUNTIME= anymore, drop it at some point */
176 fprintf(f
, "RUNTIME=%s\n", u
->runtime_path
);
179 fprintf(f
, "SERVICE_JOB=%s\n", u
->service_job
);
182 fprintf(f
, "DISPLAY=%s\n", u
->display
->id
);
184 if (dual_timestamp_is_set(&u
->timestamp
))
186 "REALTIME="USEC_FMT
"\n"
187 "MONOTONIC="USEC_FMT
"\n",
188 u
->timestamp
.realtime
,
189 u
->timestamp
.monotonic
);
191 if (u
->last_session_timestamp
!= USEC_INFINITY
)
192 fprintf(f
, "LAST_SESSION_TIMESTAMP=" USEC_FMT
"\n",
193 u
->last_session_timestamp
);
199 fputs("SESSIONS=", f
);
201 LIST_FOREACH(sessions_by_user
, i
, u
->sessions
) {
210 fputs("\nSEATS=", f
);
212 LIST_FOREACH(sessions_by_user
, i
, u
->sessions
) {
221 fputs(i
->seat
->id
, f
);
224 fputs("\nACTIVE_SESSIONS=", f
);
226 LIST_FOREACH(sessions_by_user
, i
, u
->sessions
) {
227 if (!session_is_active(i
))
238 fputs("\nONLINE_SESSIONS=", f
);
240 LIST_FOREACH(sessions_by_user
, i
, u
->sessions
) {
241 if (session_get_state(i
) == SESSION_CLOSING
)
252 fputs("\nACTIVE_SEATS=", f
);
254 LIST_FOREACH(sessions_by_user
, i
, u
->sessions
) {
255 if (!session_is_active(i
) || !i
->seat
)
263 fputs(i
->seat
->id
, f
);
266 fputs("\nONLINE_SEATS=", f
);
268 LIST_FOREACH(sessions_by_user
, i
, u
->sessions
) {
269 if (session_get_state(i
) == SESSION_CLOSING
|| !i
->seat
)
277 fputs(i
->seat
->id
, f
);
282 r
= fflush_and_check(f
);
286 if (rename(temp_path
, u
->state_file
) < 0) {
294 (void) unlink(u
->state_file
);
297 (void) unlink(temp_path
);
299 return log_error_errno(r
, "Failed to save user data %s: %m", u
->state_file
);
302 int user_save(User
*u
) {
308 return user_save_internal(u
);
311 int user_load(User
*u
) {
312 _cleanup_free_
char *realtime
= NULL
, *monotonic
= NULL
, *stopping
= NULL
, *last_session_timestamp
= NULL
;
317 r
= parse_env_file(NULL
, u
->state_file
,
318 "SERVICE_JOB", &u
->service_job
,
319 "STOPPING", &stopping
,
320 "REALTIME", &realtime
,
321 "MONOTONIC", &monotonic
,
322 "LAST_SESSION_TIMESTAMP", &last_session_timestamp
);
326 return log_error_errno(r
, "Failed to read %s: %m", u
->state_file
);
329 r
= parse_boolean(stopping
);
331 log_debug_errno(r
, "Failed to parse 'STOPPING' boolean: %s", stopping
);
337 (void) deserialize_usec(realtime
, &u
->timestamp
.realtime
);
339 (void) deserialize_usec(monotonic
, &u
->timestamp
.monotonic
);
340 if (last_session_timestamp
)
341 (void) deserialize_usec(last_session_timestamp
, &u
->last_session_timestamp
);
346 static void user_start_service(User
*u
) {
347 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
352 /* Start the service containing the "systemd --user" instance (user@.service). Note that we don't explicitly
353 * start the per-user slice or the systemd-runtime-dir@.service instance, as those are pulled in both by
354 * user@.service and the session scopes as dependencies. */
356 u
->service_job
= mfree(u
->service_job
);
358 r
= manager_start_unit(u
->manager
, u
->service
, &error
, &u
->service_job
);
360 log_warning_errno(r
, "Failed to start user service '%s', ignoring: %s", u
->service
, bus_error_message(&error
, r
));
363 int user_start(User
*u
) {
366 if (u
->started
&& !u
->stopping
)
369 /* If u->stopping is set, the user is marked for removal and service stop-jobs are queued. We have to clear
370 * that flag before queing the start-jobs again. If they succeed, the user object can be re-used just fine
371 * (pid1 takes care of job-ordering and proper restart), but if they fail, we want to force another user_stop()
372 * so possibly pending units are stopped. */
376 log_debug("Starting services for new user %s.", u
->name
);
378 /* Save the user data so far, because pam_systemd will read the XDG_RUNTIME_DIR out of it while starting up
379 * systemd --user. We need to do user_save_internal() because we have not "officially" started yet. */
380 user_save_internal(u
);
382 /* Start user@UID.service */
383 user_start_service(u
);
386 if (!dual_timestamp_is_set(&u
->timestamp
))
387 dual_timestamp_get(&u
->timestamp
);
388 user_send_signal(u
, true);
392 /* Save new user data */
398 static void user_stop_service(User
*u
) {
399 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
405 /* The reverse of user_start_service(). Note that we only stop user@UID.service here, and let StopWhenUnneeded=
406 * deal with the slice and the user-runtime-dir@.service instance. */
408 u
->service_job
= mfree(u
->service_job
);
410 r
= manager_stop_unit(u
->manager
, u
->service
, &error
, &u
->service_job
);
412 log_warning_errno(r
, "Failed to stop user service '%s', ignoring: %s", u
->service
, bus_error_message(&error
, r
));
415 int user_stop(User
*u
, bool force
) {
420 /* This is called whenever we begin with tearing down a user record. It's called in two cases: explicit API
421 * request to do so via the bus (in which case 'force' is true) and automatically due to GC, if there's no
422 * session left pinning it (in which case 'force' is false). Note that this just initiates tearing down of the
423 * user, the User object will remain in memory until user_finalize() is called, see below. */
428 if (u
->stopping
) { /* Stop jobs have already been queued */
433 LIST_FOREACH(sessions_by_user
, s
, u
->sessions
) {
436 k
= session_stop(s
, force
);
441 user_stop_service(u
);
450 int user_finalize(User
*u
) {
456 /* Called when the user is really ready to be freed, i.e. when all unit stop jobs and suchlike for it are
457 * done. This is called as a result of an earlier user_done() when all jobs are completed. */
460 log_debug("User %s logged out.", u
->name
);
462 LIST_FOREACH(sessions_by_user
, s
, u
->sessions
) {
463 k
= session_finalize(s
);
468 /* Clean SysV + POSIX IPC objects, but only if this is not a system user. Background: in many setups cronjobs
469 * are run in full PAM and thus logind sessions, even if the code run doesn't belong to actual users but to
470 * system components. Since enable RemoveIPC= globally for all users, we need to be a bit careful with such
471 * cases, as we shouldn't accidentally remove a system service's IPC objects while it is running, just because
472 * a cronjob running as the same user just finished. Hence: exclude system users generally from IPC clean-up,
473 * and do it only for normal users. */
474 if (u
->manager
->remove_ipc
&& !uid_is_system(u
->uid
)) {
475 k
= clean_ipc_by_uid(u
->uid
);
480 (void) unlink(u
->state_file
);
481 user_add_to_gc_queue(u
);
484 user_send_signal(u
, false);
491 int user_get_idle_hint(User
*u
, dual_timestamp
*t
) {
493 bool idle_hint
= true;
494 dual_timestamp ts
= DUAL_TIMESTAMP_NULL
;
498 LIST_FOREACH(sessions_by_user
, s
, u
->sessions
) {
502 ih
= session_get_idle_hint(s
, &k
);
508 if (k
.monotonic
< ts
.monotonic
)
514 } else if (idle_hint
) {
516 if (k
.monotonic
> ts
.monotonic
)
527 int user_check_linger_file(User
*u
) {
528 _cleanup_free_
char *cc
= NULL
;
531 cc
= cescape(u
->name
);
535 p
= strjoina("/var/lib/systemd/linger/", cc
);
536 if (access(p
, F_OK
) < 0) {
546 static bool user_unit_active(User
*u
) {
551 assert(u
->runtime_dir_service
);
554 FOREACH_STRING(i
, u
->service
, u
->runtime_dir_service
, u
->slice
) {
555 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
557 r
= manager_unit_is_active(u
->manager
, i
, &error
);
559 log_debug_errno(r
, "Failed to determine whether unit '%s' is active, ignoring: %s", u
->service
, bus_error_message(&error
, r
));
567 bool user_may_gc(User
*u
, bool drop_not_started
) {
572 if (drop_not_started
&& !u
->started
)
578 if (u
->last_session_timestamp
!= USEC_INFINITY
) {
579 /* All sessions have been closed. Let's see if we shall leave the user record around for a bit */
581 if (u
->manager
->user_stop_delay
== USEC_INFINITY
)
582 return false; /* Leave it around forever! */
583 if (u
->manager
->user_stop_delay
> 0 &&
584 now(CLOCK_MONOTONIC
) < usec_add(u
->last_session_timestamp
, u
->manager
->user_stop_delay
))
585 return false; /* Leave it around for a bit longer. */
588 /* Is this a user that shall stay around forever ("linger")? Before we say "no" to GC'ing for lingering users, let's check
589 * if any of the three units that we maintain for this user is still around. If none of them is,
590 * there's no need to keep this user around even if lingering is enabled. */
591 if (user_check_linger_file(u
) > 0 && user_unit_active(u
))
594 /* Check if our job is still pending */
595 if (u
->service_job
) {
596 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
598 r
= manager_job_is_active(u
->manager
, u
->service_job
, &error
);
600 log_debug_errno(r
, "Failed to determine whether job '%s' is pending, ignoring: %s", u
->service_job
, bus_error_message(&error
, r
));
605 /* Note that we don't care if the three units we manage for each user object are up or not, as we are managing
606 * their state rather than tracking it. */
611 void user_add_to_gc_queue(User
*u
) {
617 LIST_PREPEND(gc_queue
, u
->manager
->user_gc_queue
, u
);
618 u
->in_gc_queue
= true;
621 UserState
user_get_state(User
*u
) {
629 if (!u
->started
|| u
->service_job
)
633 bool all_closing
= true;
635 LIST_FOREACH(sessions_by_user
, i
, u
->sessions
) {
638 state
= session_get_state(i
);
639 if (state
== SESSION_ACTIVE
)
641 if (state
!= SESSION_CLOSING
)
645 return all_closing
? USER_CLOSING
: USER_ONLINE
;
648 if (user_check_linger_file(u
) > 0 && user_unit_active(u
))
649 return USER_LINGERING
;
654 int user_kill(User
*u
, int signo
) {
657 return manager_kill_unit(u
->manager
, u
->slice
, KILL_ALL
, signo
, NULL
);
660 static bool elect_display_filter(Session
*s
) {
661 /* Return true if the session is a candidate for the user’s ‘primary session’ or ‘display’. */
664 return s
->class == SESSION_USER
&& s
->started
&& !s
->stopping
;
667 static int elect_display_compare(Session
*s1
, Session
*s2
) {
668 /* Indexed by SessionType. Lower numbers mean more preferred. */
669 const int type_ranks
[_SESSION_TYPE_MAX
] = {
670 [SESSION_UNSPECIFIED
] = 0,
673 [SESSION_WAYLAND
] = -3,
678 /* Calculate the partial order relationship between s1 and s2,
679 * returning < 0 if s1 is preferred as the user’s ‘primary session’,
680 * 0 if s1 and s2 are equally preferred or incomparable, or > 0 if s2
683 * s1 or s2 may be NULL. */
687 if ((s1
== NULL
) != (s2
== NULL
))
688 return (s1
== NULL
) - (s2
== NULL
);
690 if (s1
->stopping
!= s2
->stopping
)
691 return s1
->stopping
- s2
->stopping
;
693 if ((s1
->class != SESSION_USER
) != (s2
->class != SESSION_USER
))
694 return (s1
->class != SESSION_USER
) - (s2
->class != SESSION_USER
);
696 if ((s1
->type
== _SESSION_TYPE_INVALID
) != (s2
->type
== _SESSION_TYPE_INVALID
))
697 return (s1
->type
== _SESSION_TYPE_INVALID
) - (s2
->type
== _SESSION_TYPE_INVALID
);
699 if (s1
->type
!= s2
->type
)
700 return type_ranks
[s1
->type
] - type_ranks
[s2
->type
];
705 void user_elect_display(User
*u
) {
710 /* This elects a primary session for each user, which we call the "display". We try to keep the assignment
711 * stable, but we "upgrade" to better choices. */
712 log_debug("Electing new display for user %s", u
->name
);
714 LIST_FOREACH(sessions_by_user
, s
, u
->sessions
) {
715 if (!elect_display_filter(s
)) {
716 log_debug("Ignoring session %s", s
->id
);
720 if (elect_display_compare(s
, u
->display
) < 0) {
721 log_debug("Choosing session %s in preference to %s", s
->id
, u
->display
? u
->display
->id
: "-");
727 static int user_stop_timeout_callback(sd_event_source
*es
, uint64_t usec
, void *userdata
) {
731 user_add_to_gc_queue(u
);
736 void user_update_last_session_timer(User
*u
) {
742 /* There are sessions, turn off the timer */
743 u
->last_session_timestamp
= USEC_INFINITY
;
744 u
->timer_event_source
= sd_event_source_unref(u
->timer_event_source
);
748 if (u
->last_session_timestamp
!= USEC_INFINITY
)
749 return; /* Timer already started */
751 u
->last_session_timestamp
= now(CLOCK_MONOTONIC
);
753 assert(!u
->timer_event_source
);
755 if (u
->manager
->user_stop_delay
== 0 || u
->manager
->user_stop_delay
== USEC_INFINITY
)
758 if (sd_event_get_state(u
->manager
->event
) == SD_EVENT_FINISHED
) {
759 log_debug("Not allocating user stop timeout, since we are already exiting.");
763 r
= sd_event_add_time(u
->manager
->event
,
764 &u
->timer_event_source
,
766 usec_add(u
->last_session_timestamp
, u
->manager
->user_stop_delay
), 0,
767 user_stop_timeout_callback
, u
);
769 log_warning_errno(r
, "Failed to enqueue user stop event source, ignoring: %m");
772 char s
[FORMAT_TIMESPAN_MAX
];
774 log_debug("Last session of user '%s' logged out, terminating user context in %s.",
776 format_timespan(s
, sizeof(s
), u
->manager
->user_stop_delay
, USEC_PER_MSEC
));
780 static const char* const user_state_table
[_USER_STATE_MAX
] = {
781 [USER_OFFLINE
] = "offline",
782 [USER_OPENING
] = "opening",
783 [USER_LINGERING
] = "lingering",
784 [USER_ONLINE
] = "online",
785 [USER_ACTIVE
] = "active",
786 [USER_CLOSING
] = "closing"
789 DEFINE_STRING_TABLE_LOOKUP(user_state
, UserState
);
791 int config_parse_tmpfs_size(
793 const char *filename
,
796 unsigned section_line
,
811 /* First, try to parse as percentage */
812 r
= parse_permille(rvalue
);
813 if (r
> 0 && r
< 1000)
814 *sz
= physical_memory_scale(r
, 1000U);
818 /* If the passed argument was not a percentage, or out of range, parse as byte size */
820 r
= parse_size(rvalue
, 1024, &k
);
821 if (r
>= 0 && (k
<= 0 || (uint64_t) (size_t) k
!= k
))
824 log_syntax(unit
, LOG_ERR
, filename
, line
, r
, "Failed to parse size value '%s', ignoring: %m", rvalue
);
828 *sz
= PAGE_ALIGN((size_t) k
);
834 int config_parse_compat_user_tasks_max(
836 const char *filename
,
839 unsigned section_line
,
851 log_syntax(unit
, LOG_NOTICE
, filename
, line
, 0,
852 "Support for option %s= has been removed.",
854 log_info("Hint: try creating /etc/systemd/system/user-.slice.d/50-limits.conf with:\n"