1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
6 #include "alloc-util.h"
7 #include "bus-common-errors.h"
9 #include "bus-locator.h"
11 #include "cgroup-util.h"
12 #include "clean-ipc.h"
17 #include "format-util.h"
20 #include "label-util.h"
21 #include "limits-util.h"
22 #include "logind-dbus.h"
23 #include "logind-user-dbus.h"
24 #include "logind-user.h"
25 #include "mkdir-label.h"
26 #include "parse-util.h"
27 #include "path-util.h"
28 #include "percent-util.h"
30 #include "serialize.h"
32 #include "stdio-util.h"
33 #include "string-table.h"
35 #include "tmpfile-util.h"
36 #include "uid-alloc-range.h"
37 #include "unit-name.h"
38 #include "user-util.h"
40 int user_new(User
**ret
,
44 _cleanup_(user_freep
) User
*u
= NULL
;
45 char lu
[DECIMAL_STR_MAX(uid_t
) + 1];
55 if (!uid_is_valid(ur
->uid
))
64 .user_record
= user_record_ref(ur
),
65 .last_session_timestamp
= USEC_INFINITY
,
68 if (asprintf(&u
->state_file
, "/run/systemd/users/" UID_FMT
, ur
->uid
) < 0)
71 if (asprintf(&u
->runtime_path
, "/run/user/" UID_FMT
, ur
->uid
) < 0)
74 xsprintf(lu
, UID_FMT
, ur
->uid
);
75 r
= slice_build_subslice(SPECIAL_USER_SLICE
, lu
, &u
->slice
);
79 r
= unit_name_build("user", lu
, ".service", &u
->service
);
83 r
= unit_name_build("user-runtime-dir", lu
, ".service", &u
->runtime_dir_service
);
87 r
= hashmap_put(m
->users
, UID_TO_PTR(ur
->uid
), u
);
91 r
= hashmap_put(m
->user_units
, u
->slice
, u
);
95 r
= hashmap_put(m
->user_units
, u
->service
, u
);
99 r
= hashmap_put(m
->user_units
, u
->runtime_dir_service
, u
);
107 User
*user_free(User
*u
) {
112 LIST_REMOVE(gc_queue
, u
->manager
->user_gc_queue
, u
);
115 session_free(u
->sessions
);
118 hashmap_remove_value(u
->manager
->user_units
, u
->service
, u
);
120 if (u
->runtime_dir_service
)
121 hashmap_remove_value(u
->manager
->user_units
, u
->runtime_dir_service
, u
);
124 hashmap_remove_value(u
->manager
->user_units
, u
->slice
, u
);
126 hashmap_remove_value(u
->manager
->users
, UID_TO_PTR(u
->user_record
->uid
), u
);
128 sd_event_source_unref(u
->timer_event_source
);
130 u
->service_job
= mfree(u
->service_job
);
132 u
->service
= mfree(u
->service
);
133 u
->runtime_dir_service
= mfree(u
->runtime_dir_service
);
134 u
->slice
= mfree(u
->slice
);
135 u
->runtime_path
= mfree(u
->runtime_path
);
136 u
->state_file
= mfree(u
->state_file
);
138 user_record_unref(u
->user_record
);
143 static int user_save_internal(User
*u
) {
144 _cleanup_(unlink_and_freep
) char *temp_path
= NULL
;
145 _cleanup_fclose_
FILE *f
= NULL
;
149 assert(u
->state_file
);
151 r
= mkdir_safe_label("/run/systemd/users", 0755, 0, 0, MKDIR_WARN_MODE
);
155 r
= fopen_temporary(u
->state_file
, &f
, &temp_path
);
159 (void) fchmod(fileno(f
), 0644);
162 "# This is private data. Do not parse.\n"
164 "STATE=%s\n" /* friendly user-facing state */
165 "STOPPING=%s\n", /* low-level state */
166 u
->user_record
->user_name
,
167 user_state_to_string(user_get_state(u
)),
168 yes_no(u
->stopping
));
170 /* LEGACY: no-one reads RUNTIME= anymore, drop it at some point */
172 fprintf(f
, "RUNTIME=%s\n", u
->runtime_path
);
175 fprintf(f
, "SERVICE_JOB=%s\n", u
->service_job
);
178 fprintf(f
, "DISPLAY=%s\n", u
->display
->id
);
180 if (dual_timestamp_is_set(&u
->timestamp
))
182 "REALTIME="USEC_FMT
"\n"
183 "MONOTONIC="USEC_FMT
"\n",
184 u
->timestamp
.realtime
,
185 u
->timestamp
.monotonic
);
187 if (u
->last_session_timestamp
!= USEC_INFINITY
)
188 fprintf(f
, "LAST_SESSION_TIMESTAMP=" USEC_FMT
"\n",
189 u
->last_session_timestamp
);
194 fputs("SESSIONS=", f
);
196 LIST_FOREACH(sessions_by_user
, i
, u
->sessions
) {
205 fputs("\nSEATS=", f
);
207 LIST_FOREACH(sessions_by_user
, i
, u
->sessions
) {
216 fputs(i
->seat
->id
, f
);
219 fputs("\nACTIVE_SESSIONS=", f
);
221 LIST_FOREACH(sessions_by_user
, i
, u
->sessions
) {
222 if (!session_is_active(i
))
233 fputs("\nONLINE_SESSIONS=", f
);
235 LIST_FOREACH(sessions_by_user
, i
, u
->sessions
) {
236 if (session_get_state(i
) == SESSION_CLOSING
)
247 fputs("\nACTIVE_SEATS=", f
);
249 LIST_FOREACH(sessions_by_user
, i
, u
->sessions
) {
250 if (!session_is_active(i
) || !i
->seat
)
258 fputs(i
->seat
->id
, f
);
261 fputs("\nONLINE_SEATS=", f
);
263 LIST_FOREACH(sessions_by_user
, i
, u
->sessions
) {
264 if (session_get_state(i
) == SESSION_CLOSING
|| !i
->seat
)
272 fputs(i
->seat
->id
, f
);
277 r
= fflush_and_check(f
);
281 if (rename(temp_path
, u
->state_file
) < 0) {
286 temp_path
= mfree(temp_path
);
290 (void) unlink(u
->state_file
);
292 return log_error_errno(r
, "Failed to save user data %s: %m", u
->state_file
);
295 int user_save(User
*u
) {
301 return user_save_internal(u
);
304 int user_load(User
*u
) {
305 _cleanup_free_
char *realtime
= NULL
, *monotonic
= NULL
, *stopping
= NULL
, *last_session_timestamp
= NULL
;
310 r
= parse_env_file(NULL
, u
->state_file
,
311 "SERVICE_JOB", &u
->service_job
,
312 "STOPPING", &stopping
,
313 "REALTIME", &realtime
,
314 "MONOTONIC", &monotonic
,
315 "LAST_SESSION_TIMESTAMP", &last_session_timestamp
);
319 return log_error_errno(r
, "Failed to read %s: %m", u
->state_file
);
322 r
= parse_boolean(stopping
);
324 log_debug_errno(r
, "Failed to parse 'STOPPING' boolean: %s", stopping
);
330 (void) deserialize_usec(realtime
, &u
->timestamp
.realtime
);
332 (void) deserialize_usec(monotonic
, &u
->timestamp
.monotonic
);
333 if (last_session_timestamp
)
334 (void) deserialize_usec(last_session_timestamp
, &u
->last_session_timestamp
);
339 static void user_start_service(User
*u
) {
340 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
345 /* Start the service containing the "systemd --user" instance (user@.service). Note that we don't explicitly
346 * start the per-user slice or the systemd-runtime-dir@.service instance, as those are pulled in both by
347 * user@.service and the session scopes as dependencies. */
349 u
->service_job
= mfree(u
->service_job
);
351 r
= manager_start_unit(u
->manager
, u
->service
, &error
, &u
->service_job
);
353 log_full_errno(sd_bus_error_has_name(&error
, BUS_ERROR_UNIT_MASKED
) ? LOG_DEBUG
: LOG_WARNING
, r
,
354 "Failed to start user service '%s', ignoring: %s", u
->service
, bus_error_message(&error
, r
));
357 static int update_slice_callback(sd_bus_message
*m
, void *userdata
, sd_bus_error
*ret_error
) {
358 _cleanup_(user_record_unrefp
) UserRecord
*ur
= ASSERT_PTR(userdata
);
359 const sd_bus_error
*e
;
364 e
= sd_bus_message_get_error(m
);
366 r
= sd_bus_error_get_errno(e
);
368 "Failed to update slice of %s, ignoring: %s",
370 bus_error_message(e
, r
));
375 log_debug("Successfully set slice parameters of %s.", ur
->user_name
);
379 static int user_update_slice(User
*u
) {
380 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
385 if (u
->user_record
->tasks_max
== UINT64_MAX
&&
386 u
->user_record
->memory_high
== UINT64_MAX
&&
387 u
->user_record
->memory_max
== UINT64_MAX
&&
388 u
->user_record
->cpu_weight
== UINT64_MAX
&&
389 u
->user_record
->io_weight
== UINT64_MAX
)
392 r
= bus_message_new_method_call(u
->manager
->bus
, &m
, bus_systemd_mgr
, "SetUnitProperties");
394 return bus_log_create_error(r
);
396 r
= sd_bus_message_append(m
, "sb", u
->slice
, true);
398 return bus_log_create_error(r
);
400 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
402 return bus_log_create_error(r
);
408 { "TasksMax", u
->user_record
->tasks_max
},
409 { "MemoryMax", u
->user_record
->memory_max
},
410 { "MemoryHigh", u
->user_record
->memory_high
},
411 { "CPUWeight", u
->user_record
->cpu_weight
},
412 { "IOWeight", u
->user_record
->io_weight
},
415 FOREACH_ARRAY(st
, settings
, ELEMENTSOF(settings
)) {
416 if (st
->value
== UINT64_MAX
)
419 r
= sd_bus_message_append(m
, "(sv)", st
->name
, "t", st
->value
);
421 return bus_log_create_error(r
);
424 r
= sd_bus_message_close_container(m
);
426 return bus_log_create_error(r
);
428 r
= sd_bus_call_async(u
->manager
->bus
, NULL
, m
, update_slice_callback
, u
->user_record
, 0);
430 return log_error_errno(r
, "Failed to change user slice properties: %m");
432 /* Ref the user record pointer, so that the slot keeps it pinned */
433 user_record_ref(u
->user_record
);
438 int user_start(User
*u
) {
441 if (u
->started
&& !u
->stopping
)
444 /* If u->stopping is set, the user is marked for removal and service stop-jobs are queued. We have to clear
445 * that flag before queueing the start-jobs again. If they succeed, the user object can be re-used just fine
446 * (pid1 takes care of job-ordering and proper restart), but if they fail, we want to force another user_stop()
447 * so possibly pending units are stopped. */
451 log_debug("Starting services for new user %s.", u
->user_record
->user_name
);
453 /* Save the user data so far, because pam_systemd will read the XDG_RUNTIME_DIR out of it while starting up
454 * systemd --user. We need to do user_save_internal() because we have not "officially" started yet. */
455 user_save_internal(u
);
457 /* Set slice parameters */
458 (void) user_update_slice(u
);
460 /* Start user@UID.service */
461 user_start_service(u
);
464 if (!dual_timestamp_is_set(&u
->timestamp
))
465 dual_timestamp_now(&u
->timestamp
);
466 user_send_signal(u
, true);
470 /* Save new user data */
476 static void user_stop_service(User
*u
, bool force
) {
477 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
483 /* The reverse of user_start_service(). Note that we only stop user@UID.service here, and let StopWhenUnneeded=
484 * deal with the slice and the user-runtime-dir@.service instance. */
486 u
->service_job
= mfree(u
->service_job
);
488 r
= manager_stop_unit(u
->manager
, u
->service
, force
? "replace" : "fail", &error
, &u
->service_job
);
490 log_warning_errno(r
, "Failed to stop user service '%s', ignoring: %s", u
->service
, bus_error_message(&error
, r
));
493 int user_stop(User
*u
, bool force
) {
498 /* This is called whenever we begin with tearing down a user record. It's called in two cases: explicit API
499 * request to do so via the bus (in which case 'force' is true) and automatically due to GC, if there's no
500 * session left pinning it (in which case 'force' is false). Note that this just initiates tearing down of the
501 * user, the User object will remain in memory until user_finalize() is called, see below. */
506 if (u
->stopping
) { /* Stop jobs have already been queued */
511 LIST_FOREACH(sessions_by_user
, s
, u
->sessions
) {
514 k
= session_stop(s
, force
);
519 user_stop_service(u
, force
);
528 int user_finalize(User
*u
) {
533 /* Called when the user is really ready to be freed, i.e. when all unit stop jobs and suchlike for it are
534 * done. This is called as a result of an earlier user_done() when all jobs are completed. */
537 log_debug("User %s logged out.", u
->user_record
->user_name
);
539 LIST_FOREACH(sessions_by_user
, s
, u
->sessions
) {
540 k
= session_finalize(s
);
545 /* Clean SysV + POSIX IPC objects, but only if this is not a system user. Background: in many setups cronjobs
546 * are run in full PAM and thus logind sessions, even if the code run doesn't belong to actual users but to
547 * system components. Since enable RemoveIPC= globally for all users, we need to be a bit careful with such
548 * cases, as we shouldn't accidentally remove a system service's IPC objects while it is running, just because
549 * a cronjob running as the same user just finished. Hence: exclude system users generally from IPC clean-up,
550 * and do it only for normal users. */
551 if (u
->manager
->remove_ipc
&& !uid_is_system(u
->user_record
->uid
)) {
552 k
= clean_ipc_by_uid(u
->user_record
->uid
);
557 (void) unlink(u
->state_file
);
558 user_add_to_gc_queue(u
);
561 user_send_signal(u
, false);
568 int user_get_idle_hint(User
*u
, dual_timestamp
*t
) {
569 bool idle_hint
= true;
570 dual_timestamp ts
= DUAL_TIMESTAMP_NULL
;
574 LIST_FOREACH(sessions_by_user
, s
, u
->sessions
) {
578 ih
= session_get_idle_hint(s
, &k
);
584 if (k
.monotonic
< ts
.monotonic
)
590 } else if (idle_hint
) {
592 if (k
.monotonic
> ts
.monotonic
)
603 int user_check_linger_file(User
*u
) {
604 _cleanup_free_
char *cc
= NULL
;
607 cc
= cescape(u
->user_record
->user_name
);
611 p
= strjoina("/var/lib/systemd/linger/", cc
);
612 if (access(p
, F_OK
) < 0) {
622 static bool user_unit_active(User
*u
) {
626 assert(u
->runtime_dir_service
);
629 FOREACH_STRING(i
, u
->service
, u
->runtime_dir_service
, u
->slice
) {
630 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
632 r
= manager_unit_is_active(u
->manager
, i
, &error
);
634 log_debug_errno(r
, "Failed to determine whether unit '%s' is active, ignoring: %s", i
, bus_error_message(&error
, r
));
642 static usec_t
user_get_stop_delay(User
*u
) {
645 if (u
->user_record
->stop_delay_usec
!= UINT64_MAX
)
646 return u
->user_record
->stop_delay_usec
;
648 if (user_record_removable(u
->user_record
) > 0)
649 return 0; /* For removable users lower the stop delay to zero */
651 return u
->manager
->user_stop_delay
;
654 bool user_may_gc(User
*u
, bool drop_not_started
) {
659 if (drop_not_started
&& !u
->started
)
665 if (u
->last_session_timestamp
!= USEC_INFINITY
) {
666 usec_t user_stop_delay
;
668 /* All sessions have been closed. Let's see if we shall leave the user record around for a bit */
670 user_stop_delay
= user_get_stop_delay(u
);
672 if (user_stop_delay
== USEC_INFINITY
)
673 return false; /* Leave it around forever! */
674 if (user_stop_delay
> 0 &&
675 now(CLOCK_MONOTONIC
) < usec_add(u
->last_session_timestamp
, user_stop_delay
))
676 return false; /* Leave it around for a bit longer. */
679 /* Is this a user that shall stay around forever ("linger")? Before we say "no" to GC'ing for lingering users, let's check
680 * if any of the three units that we maintain for this user is still around. If none of them is,
681 * there's no need to keep this user around even if lingering is enabled. */
682 if (user_check_linger_file(u
) > 0 && user_unit_active(u
))
685 /* Check if our job is still pending */
686 if (u
->service_job
) {
687 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
689 r
= manager_job_is_active(u
->manager
, u
->service_job
, &error
);
691 log_debug_errno(r
, "Failed to determine whether job '%s' is pending, ignoring: %s", u
->service_job
, bus_error_message(&error
, r
));
696 /* Note that we don't care if the three units we manage for each user object are up or not, as we are managing
697 * their state rather than tracking it. */
702 void user_add_to_gc_queue(User
*u
) {
708 LIST_PREPEND(gc_queue
, u
->manager
->user_gc_queue
, u
);
709 u
->in_gc_queue
= true;
712 UserState
user_get_state(User
*u
) {
718 if (!u
->started
|| u
->service_job
)
722 bool all_closing
= true;
724 LIST_FOREACH(sessions_by_user
, i
, u
->sessions
) {
727 state
= session_get_state(i
);
728 if (state
== SESSION_ACTIVE
)
730 if (state
!= SESSION_CLOSING
)
734 return all_closing
? USER_CLOSING
: USER_ONLINE
;
737 if (user_check_linger_file(u
) > 0 && user_unit_active(u
))
738 return USER_LINGERING
;
743 int user_kill(User
*u
, int signo
) {
746 return manager_kill_unit(u
->manager
, u
->slice
, KILL_ALL
, signo
, NULL
);
749 static bool elect_display_filter(Session
*s
) {
750 /* Return true if the session is a candidate for the user’s ‘primary session’ or ‘display’. */
753 return IN_SET(s
->class, SESSION_USER
, SESSION_GREETER
) && s
->started
&& !s
->stopping
;
756 static int elect_display_compare(Session
*s1
, Session
*s2
) {
757 /* Indexed by SessionType. Lower numbers mean more preferred. */
758 static const int type_ranks
[_SESSION_TYPE_MAX
] = {
759 [SESSION_UNSPECIFIED
] = 0,
762 [SESSION_WAYLAND
] = -3,
767 /* Calculate the partial order relationship between s1 and s2,
768 * returning < 0 if s1 is preferred as the user’s ‘primary session’,
769 * 0 if s1 and s2 are equally preferred or incomparable, or > 0 if s2
772 * s1 or s2 may be NULL. */
776 if ((s1
== NULL
) != (s2
== NULL
))
777 return (s1
== NULL
) - (s2
== NULL
);
779 if (s1
->stopping
!= s2
->stopping
)
780 return s1
->stopping
- s2
->stopping
;
782 if ((s1
->class != SESSION_USER
) != (s2
->class != SESSION_USER
))
783 return (s1
->class != SESSION_USER
) - (s2
->class != SESSION_USER
);
785 if ((s1
->type
== _SESSION_TYPE_INVALID
) != (s2
->type
== _SESSION_TYPE_INVALID
))
786 return (s1
->type
== _SESSION_TYPE_INVALID
) - (s2
->type
== _SESSION_TYPE_INVALID
);
788 if (s1
->type
!= s2
->type
)
789 return type_ranks
[s1
->type
] - type_ranks
[s2
->type
];
794 void user_elect_display(User
*u
) {
797 /* This elects a primary session for each user, which we call the "display". We try to keep the assignment
798 * stable, but we "upgrade" to better choices. */
799 log_debug("Electing new display for user %s", u
->user_record
->user_name
);
801 LIST_FOREACH(sessions_by_user
, s
, u
->sessions
) {
802 if (!elect_display_filter(s
)) {
803 log_debug("Ignoring session %s", s
->id
);
807 if (elect_display_compare(s
, u
->display
) < 0) {
808 log_debug("Choosing session %s in preference to %s", s
->id
, u
->display
? u
->display
->id
: "-");
814 static int user_stop_timeout_callback(sd_event_source
*es
, uint64_t usec
, void *userdata
) {
815 User
*u
= ASSERT_PTR(userdata
);
817 user_add_to_gc_queue(u
);
822 void user_update_last_session_timer(User
*u
) {
823 usec_t user_stop_delay
;
829 /* There are sessions, turn off the timer */
830 u
->last_session_timestamp
= USEC_INFINITY
;
831 u
->timer_event_source
= sd_event_source_unref(u
->timer_event_source
);
835 if (u
->last_session_timestamp
!= USEC_INFINITY
)
836 return; /* Timer already started */
838 u
->last_session_timestamp
= now(CLOCK_MONOTONIC
);
840 assert(!u
->timer_event_source
);
842 user_stop_delay
= user_get_stop_delay(u
);
843 if (!timestamp_is_set(user_stop_delay
))
846 if (sd_event_get_state(u
->manager
->event
) == SD_EVENT_FINISHED
) {
847 log_debug("Not allocating user stop timeout, since we are already exiting.");
851 r
= sd_event_add_time(u
->manager
->event
,
852 &u
->timer_event_source
,
854 usec_add(u
->last_session_timestamp
, user_stop_delay
), 0,
855 user_stop_timeout_callback
, u
);
857 log_warning_errno(r
, "Failed to enqueue user stop event source, ignoring: %m");
860 log_debug("Last session of user '%s' logged out, terminating user context in %s.",
861 u
->user_record
->user_name
,
862 FORMAT_TIMESPAN(user_stop_delay
, USEC_PER_MSEC
));
865 static const char* const user_state_table
[_USER_STATE_MAX
] = {
866 [USER_OFFLINE
] = "offline",
867 [USER_OPENING
] = "opening",
868 [USER_LINGERING
] = "lingering",
869 [USER_ONLINE
] = "online",
870 [USER_ACTIVE
] = "active",
871 [USER_CLOSING
] = "closing"
874 DEFINE_STRING_TABLE_LOOKUP(user_state
, UserState
);
876 int config_parse_tmpfs_size(
878 const char *filename
,
881 unsigned section_line
,
888 uint64_t *sz
= ASSERT_PTR(data
);
895 /* First, try to parse as percentage */
896 r
= parse_permyriad(rvalue
);
898 *sz
= physical_memory_scale(r
, 10000U);
902 /* If the passed argument was not a percentage, or out of range, parse as byte size */
904 r
= parse_size(rvalue
, 1024, &k
);
905 if (r
>= 0 && (k
<= 0 || (uint64_t) (size_t) k
!= k
))
908 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
, "Failed to parse size value '%s', ignoring: %m", rvalue
);
912 *sz
= PAGE_ALIGN((size_t) k
);
918 int config_parse_compat_user_tasks_max(
920 const char *filename
,
923 unsigned section_line
,
934 log_syntax(unit
, LOG_NOTICE
, filename
, line
, 0,
935 "Support for option %s= has been removed.",
937 log_info("Hint: try creating /etc/systemd/system/user-.slice.d/50-limits.conf with:\n"