1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2011 Lennart Poettering
11 #include <stdio_ext.h>
13 #include "alloc-util.h"
14 #include "bus-common-errors.h"
15 #include "bus-error.h"
17 #include "cgroup-util.h"
18 #include "clean-ipc.h"
22 #include "format-util.h"
26 #include "logind-user.h"
28 #include "parse-util.h"
29 #include "path-util.h"
32 #include "stdio-util.h"
33 #include "string-table.h"
34 #include "unit-name.h"
35 #include "user-util.h"
38 int user_new(User **out, Manager *m, uid_t uid, gid_t gid, const char *name) {
39 _cleanup_(user_freep) User *u = NULL;
40 char lu[DECIMAL_STR_MAX(uid_t) + 1];
54 xsprintf(lu, UID_FMT, uid);
56 u->name = strdup(name);
60 if (asprintf(&u->state_file, "/run/systemd/users/"UID_FMT, uid) < 0)
63 if (asprintf(&u->runtime_path, "/run/user/"UID_FMT, uid) < 0)
66 r = slice_build_subslice(SPECIAL_USER_SLICE, lu, &u->slice);
70 r = unit_name_build("user", lu, ".service", &u->service);
74 r = hashmap_put(m->users, UID_TO_PTR(uid), u);
78 r = hashmap_put(m->user_units, u->slice, u);
82 r = hashmap_put(m->user_units, u->service, u);
91 User *user_free(User *u) {
96 LIST_REMOVE(gc_queue, u->manager->user_gc_queue, u);
99 session_free(u->sessions);
102 hashmap_remove_value(u->manager->user_units, u->service, u);
105 hashmap_remove_value(u->manager->user_units, u->slice, u);
107 hashmap_remove_value(u->manager->users, UID_TO_PTR(u->uid), u);
109 #if 0 /// elogind neither supports slice nor service jobs.
110 u->slice_job = mfree(u->slice_job);
111 u->service_job = mfree(u->service_job);
114 u->service = mfree(u->service);
115 u->slice = mfree(u->slice);
116 u->runtime_path = mfree(u->runtime_path);
117 u->state_file = mfree(u->state_file);
118 u->name = mfree(u->name);
123 static int user_save_internal(User *u) {
124 _cleanup_free_ char *temp_path = NULL;
125 _cleanup_fclose_ FILE *f = NULL;
129 assert(u->state_file);
131 r = mkdir_safe_label("/run/systemd/users", 0755, 0, 0, MKDIR_WARN_MODE);
135 r = fopen_temporary(u->state_file, &f, &temp_path);
139 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
140 (void) fchmod(fileno(f), 0644);
143 "# This is private data. Do not parse.\n"
147 user_state_to_string(user_get_state(u)));
149 /* LEGACY: no-one reads RUNTIME= anymore, drop it at some point */
151 fprintf(f, "RUNTIME=%s\n", u->runtime_path);
153 #if 0 /// elogind neither supports service nor slice jobs
155 fprintf(f, "SERVICE_JOB=%s\n", u->service_job);
158 fprintf(f, "SLICE_JOB=%s\n", u->slice_job);
162 fprintf(f, "DISPLAY=%s\n", u->display->id);
164 if (dual_timestamp_is_set(&u->timestamp))
166 "REALTIME="USEC_FMT"\n"
167 "MONOTONIC="USEC_FMT"\n",
168 u->timestamp.realtime,
169 u->timestamp.monotonic);
175 fputs("SESSIONS=", f);
177 LIST_FOREACH(sessions_by_user, i, u->sessions) {
186 fputs("\nSEATS=", f);
188 LIST_FOREACH(sessions_by_user, i, u->sessions) {
197 fputs(i->seat->id, f);
200 fputs("\nACTIVE_SESSIONS=", f);
202 LIST_FOREACH(sessions_by_user, i, u->sessions) {
203 if (!session_is_active(i))
214 fputs("\nONLINE_SESSIONS=", f);
216 LIST_FOREACH(sessions_by_user, i, u->sessions) {
217 if (session_get_state(i) == SESSION_CLOSING)
228 fputs("\nACTIVE_SEATS=", f);
230 LIST_FOREACH(sessions_by_user, i, u->sessions) {
231 if (!session_is_active(i) || !i->seat)
239 fputs(i->seat->id, f);
242 fputs("\nONLINE_SEATS=", f);
244 LIST_FOREACH(sessions_by_user, i, u->sessions) {
245 if (session_get_state(i) == SESSION_CLOSING || !i->seat)
253 fputs(i->seat->id, f);
258 r = fflush_and_check(f);
262 if (rename(temp_path, u->state_file) < 0) {
270 (void) unlink(u->state_file);
273 (void) unlink(temp_path);
275 return log_error_errno(r, "Failed to save user data %s: %m", u->state_file);
278 int user_save(User *u) {
284 return user_save_internal (u);
287 int user_load(User *u) {
288 _cleanup_free_ char *display = NULL, *realtime = NULL, *monotonic = NULL;
294 r = parse_env_file(NULL, u->state_file, NEWLINE,
295 #if 0 /// elogind neither supports service nor slice jobs
296 "SERVICE_JOB", &u->service_job,
297 "SLICE_JOB", &u->slice_job,
300 "REALTIME", &realtime,
301 "MONOTONIC", &monotonic,
307 return log_error_errno(r, "Failed to read %s: %m", u->state_file);
311 s = hashmap_get(u->manager->sessions, display);
313 if (s && s->display && display_is_local(s->display))
317 timestamp_deserialize(realtime, &u->timestamp.realtime);
319 timestamp_deserialize(monotonic, &u->timestamp.monotonic);
325 #if 0 /// elogind can not ask systemd via dbus to start user services
329 hashmap_put(u->manager->user_units, u->slice, u);
331 static int user_start_service(User *u) {
332 #if 0 /// elogind can not ask systemd via dbus to start user services
333 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
339 u->service_job = mfree(u->service_job);
341 r = manager_start_unit(
347 /* we don't fail due to this, let's try to continue */
348 log_error_errno(r, "Failed to start user service, ignoring: %s", bus_error_message(&error, r));
350 u->service_job = job;
354 hashmap_put(u->manager->user_units, u->service, u);
360 int user_start(User *u) {
365 if (u->started && !u->stopping)
369 * If u->stopping is set, the user is marked for removal and the slice
370 * and service stop-jobs are queued. We have to clear that flag before
371 * queing the start-jobs again. If they succeed, the user object can be
372 * re-used just fine (pid1 takes care of job-ordering and proper
373 * restart), but if they fail, we want to force another user_stop() so
374 * possibly pending units are stopped.
375 * Note that we don't clear u->started, as we have no clue what state
376 * the user is in on failure here. Hence, we pretend the user is
377 * running so it will be properly taken down by GC. However, we clearly
378 * return an error from user_start() in that case, so no further
379 * reference to the user is taken.
384 log_debug("Starting services for new user %s.", u->name);
386 /* Save the user data so far, because pam_systemd will read the
387 * XDG_RUNTIME_DIR out of it while starting up systemd --user.
388 * We need to do user_save_internal() because we have not
389 * "officially" started yet. */
390 user_save_internal(u);
392 /* Spawn user systemd */
393 r = user_start_service(u);
398 if (!dual_timestamp_is_set(&u->timestamp))
399 dual_timestamp_get(&u->timestamp);
400 user_send_signal(u, true);
404 /* Save new user data */
410 #if 0 /// UNNEEDED by elogind
411 static int user_stop_slice(User *u) {
412 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
418 r = manager_stop_unit(u->manager, u->slice, &error, &job);
420 log_error("Failed to stop user slice: %s", bus_error_message(&error, r));
430 static int user_stop_service(User *u) {
431 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
437 r = manager_stop_unit(u->manager, u->service, &error, &job);
439 log_error("Failed to stop user service: %s", bus_error_message(&error, r));
443 free_and_replace(u->service_job, job);
448 int user_stop(User *u, bool force) {
453 /* Stop jobs have already been queued */
459 LIST_FOREACH(sessions_by_user, s, u->sessions) {
460 k = session_stop(s, force);
466 #if 0 /// elogind does not support service or slice jobs
467 k = user_stop_service(u);
472 k = user_stop_slice(u);
481 #if 1 /// elogind must queue this user again
482 user_add_to_gc_queue(u);
487 int user_finalize(User *u) {
494 log_debug("User %s logged out.", u->name);
496 LIST_FOREACH(sessions_by_user, s, u->sessions) {
497 k = session_finalize(s);
502 /* Clean SysV + POSIX IPC objects, but only if this is not a system user. Background: in many setups cronjobs
503 * are run in full PAM and thus logind sessions, even if the code run doesn't belong to actual users but to
504 * system components. Since enable RemoveIPC= globally for all users, we need to be a bit careful with such
505 * cases, as we shouldn't accidentally remove a system service's IPC objects while it is running, just because
506 * a cronjob running as the same user just finished. Hence: exclude system users generally from IPC clean-up,
507 * and do it only for normal users. */
508 if (u->manager->remove_ipc && !uid_is_system(u->uid)) {
509 k = clean_ipc_by_uid(u->uid);
514 unlink(u->state_file);
515 user_add_to_gc_queue(u);
518 user_send_signal(u, false);
525 int user_get_idle_hint(User *u, dual_timestamp *t) {
527 bool idle_hint = true;
528 dual_timestamp ts = DUAL_TIMESTAMP_NULL;
532 LIST_FOREACH(sessions_by_user, s, u->sessions) {
536 ih = session_get_idle_hint(s, &k);
542 if (k.monotonic < ts.monotonic)
548 } else if (idle_hint) {
550 if (k.monotonic > ts.monotonic)
561 int user_check_linger_file(User *u) {
562 _cleanup_free_ char *cc = NULL;
565 cc = cescape(u->name);
569 p = strjoina("/var/lib/elogind/linger/", cc);
571 return access(p, F_OK) >= 0;
574 bool user_may_gc(User *u, bool drop_not_started) {
577 if (drop_not_started && !u->started)
583 if (user_check_linger_file(u) > 0)
586 #if 0 /// elogind neither supports service nor slice jobs
587 if (u->slice_job && manager_job_is_active(u->manager, u->slice_job))
590 if (u->service_job && manager_job_is_active(u->manager, u->service_job))
597 void user_add_to_gc_queue(User *u) {
603 LIST_PREPEND(gc_queue, u->manager->user_gc_queue, u);
604 u->in_gc_queue = true;
607 UserState user_get_state(User *u) {
615 #if 0 /// elogind neither supports service nor slice jobs.
616 if (!u->started || u->slice_job || u->service_job)
623 bool all_closing = true;
625 LIST_FOREACH(sessions_by_user, i, u->sessions) {
628 state = session_get_state(i);
629 if (state == SESSION_ACTIVE)
631 if (state != SESSION_CLOSING)
635 return all_closing ? USER_CLOSING : USER_ONLINE;
638 if (user_check_linger_file(u) > 0)
639 return USER_LINGERING;
644 int user_kill(User *u, int signo) {
645 #if 0 /// Without systemd unit support, elogind has to rely on its session system
648 return manager_kill_unit(u->manager, u->slice, KILL_ALL, signo, NULL);
655 LIST_FOREACH(sessions_by_user, s, u->sessions) {
656 int r = session_kill(s, KILL_ALL, signo);
657 if (res == 0 && r < 0)
665 static bool elect_display_filter(Session *s) {
666 /* Return true if the session is a candidate for the user’s ‘primary
667 * session’ or ‘display’. */
670 return (s->class == SESSION_USER && !s->stopping);
673 static int elect_display_compare(Session *s1, Session *s2) {
674 /* Indexed by SessionType. Lower numbers mean more preferred. */
675 const int type_ranks[_SESSION_TYPE_MAX] = {
676 [SESSION_UNSPECIFIED] = 0,
679 [SESSION_WAYLAND] = -3,
684 /* Calculate the partial order relationship between s1 and s2,
685 * returning < 0 if s1 is preferred as the user’s ‘primary session’,
686 * 0 if s1 and s2 are equally preferred or incomparable, or > 0 if s2
689 * s1 or s2 may be NULL. */
693 if ((s1 == NULL) != (s2 == NULL))
694 return (s1 == NULL) - (s2 == NULL);
696 if (s1->stopping != s2->stopping)
697 return s1->stopping - s2->stopping;
699 if ((s1->class != SESSION_USER) != (s2->class != SESSION_USER))
700 return (s1->class != SESSION_USER) - (s2->class != SESSION_USER);
702 if ((s1->type == _SESSION_TYPE_INVALID) != (s2->type == _SESSION_TYPE_INVALID))
703 return (s1->type == _SESSION_TYPE_INVALID) - (s2->type == _SESSION_TYPE_INVALID);
705 if (s1->type != s2->type)
706 return type_ranks[s1->type] - type_ranks[s2->type];
711 void user_elect_display(User *u) {
716 /* This elects a primary session for each user, which we call
717 * the "display". We try to keep the assignment stable, but we
718 * "upgrade" to better choices. */
719 log_debug("Electing new display for user %s", u->name);
721 LIST_FOREACH(sessions_by_user, s, u->sessions) {
722 if (!elect_display_filter(s)) {
723 log_debug("Ignoring session %s", s->id);
727 if (elect_display_compare(s, u->display) < 0) {
728 log_debug("Choosing session %s in preference to %s", s->id, u->display ? u->display->id : "-");
734 static const char* const user_state_table[_USER_STATE_MAX] = {
735 [USER_OFFLINE] = "offline",
736 [USER_OPENING] = "opening",
737 [USER_LINGERING] = "lingering",
738 [USER_ONLINE] = "online",
739 [USER_ACTIVE] = "active",
740 [USER_CLOSING] = "closing"
743 DEFINE_STRING_TABLE_LOOKUP(user_state, UserState);
745 int config_parse_tmpfs_size(
747 const char *filename,
750 unsigned section_line,
765 /* First, try to parse as percentage */
766 r = parse_percent(rvalue);
767 if (r > 0 && r < 100)
768 *sz = physical_memory_scale(r, 100U);
772 /* If the passed argument was not a percentage, or out of range, parse as byte size */
774 r = parse_size(rvalue, 1024, &k);
775 if (r < 0 || k <= 0 || (uint64_t) (size_t) k != k) {
776 log_syntax(unit, LOG_ERR, filename, line, r, "Failed to parse size value, ignoring: %s", rvalue);
780 *sz = PAGE_ALIGN((size_t) k);
786 int config_parse_compat_user_tasks_max(
788 const char *filename,
791 unsigned section_line,
803 log_syntax(unit, LOG_NOTICE, filename, line, 0,
804 "Support for option %s= has been removed.",
806 log_info("Hint: try creating /etc/elogind/system/user-.slice/50-limits.conf with:\n"