]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/login/logind-user.c
use FOREACH_ELEMENT
[thirdparty/systemd.git] / src / login / logind-user.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <errno.h>
4 #include <unistd.h>
5
6 #include "alloc-util.h"
7 #include "bus-common-errors.h"
8 #include "bus-error.h"
9 #include "bus-locator.h"
10 #include "bus-util.h"
11 #include "cgroup-util.h"
12 #include "clean-ipc.h"
13 #include "env-file.h"
14 #include "escape.h"
15 #include "fd-util.h"
16 #include "fileio.h"
17 #include "format-util.h"
18 #include "fs-util.h"
19 #include "hashmap.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"
29 #include "rm-rf.h"
30 #include "serialize.h"
31 #include "special.h"
32 #include "stdio-util.h"
33 #include "string-table.h"
34 #include "strv.h"
35 #include "tmpfile-util.h"
36 #include "uid-classification.h"
37 #include "unit-name.h"
38 #include "user-util.h"
39
40 int user_new(Manager *m, UserRecord *ur, User **ret) {
41 _cleanup_(user_freep) User *u = NULL;
42 char lu[DECIMAL_STR_MAX(uid_t) + 1];
43 int r;
44
45 assert(m);
46 assert(ur);
47 assert(ret);
48
49 if (!ur->user_name)
50 return -EINVAL;
51
52 if (!uid_is_valid(ur->uid))
53 return -EINVAL;
54
55 u = new(User, 1);
56 if (!u)
57 return -ENOMEM;
58
59 *u = (User) {
60 .manager = m,
61 .user_record = user_record_ref(ur),
62 .last_session_timestamp = USEC_INFINITY,
63 .gc_mode = USER_GC_BY_ANY,
64 };
65
66 if (asprintf(&u->state_file, "/run/systemd/users/" UID_FMT, ur->uid) < 0)
67 return -ENOMEM;
68
69 if (asprintf(&u->runtime_path, "/run/user/" UID_FMT, ur->uid) < 0)
70 return -ENOMEM;
71
72 xsprintf(lu, UID_FMT, ur->uid);
73 r = slice_build_subslice(SPECIAL_USER_SLICE, lu, &u->slice);
74 if (r < 0)
75 return r;
76
77 r = unit_name_build("user-runtime-dir", lu, ".service", &u->runtime_dir_unit);
78 if (r < 0)
79 return r;
80
81 r = unit_name_build("user", lu, ".service", &u->service_manager_unit);
82 if (r < 0)
83 return r;
84
85 r = hashmap_put(m->users, UID_TO_PTR(ur->uid), u);
86 if (r < 0)
87 return r;
88
89 r = hashmap_put(m->user_units, u->slice, u);
90 if (r < 0)
91 return r;
92
93 r = hashmap_put(m->user_units, u->runtime_dir_unit, u);
94 if (r < 0)
95 return r;
96
97 r = hashmap_put(m->user_units, u->service_manager_unit, u);
98 if (r < 0)
99 return r;
100
101 *ret = TAKE_PTR(u);
102 return 0;
103 }
104
105 User *user_free(User *u) {
106 if (!u)
107 return NULL;
108
109 if (u->in_gc_queue)
110 LIST_REMOVE(gc_queue, u->manager->user_gc_queue, u);
111
112 while (u->sessions)
113 session_free(u->sessions);
114
115 sd_event_source_unref(u->timer_event_source);
116
117 if (u->service_manager_unit) {
118 (void) hashmap_remove_value(u->manager->user_units, u->service_manager_unit, u);
119 free(u->service_manager_job);
120 free(u->service_manager_unit);
121 }
122
123 if (u->runtime_dir_unit) {
124 (void) hashmap_remove_value(u->manager->user_units, u->runtime_dir_unit, u);
125 free(u->runtime_dir_job);
126 free(u->runtime_dir_unit);
127 }
128
129 if (u->slice) {
130 (void) hashmap_remove_value(u->manager->user_units, u->slice, u);
131 free(u->slice);
132 }
133
134 (void) hashmap_remove_value(u->manager->users, UID_TO_PTR(u->user_record->uid), u);
135
136 free(u->runtime_path);
137 free(u->state_file);
138
139 user_record_unref(u->user_record);
140
141 return mfree(u);
142 }
143
144 static int user_save_internal(User *u) {
145 _cleanup_(unlink_and_freep) char *temp_path = NULL;
146 _cleanup_fclose_ FILE *f = NULL;
147 int r;
148
149 assert(u);
150 assert(u->state_file);
151
152 r = mkdir_safe_label("/run/systemd/users", 0755, 0, 0, MKDIR_WARN_MODE);
153 if (r < 0)
154 goto fail;
155
156 r = fopen_temporary(u->state_file, &f, &temp_path);
157 if (r < 0)
158 goto fail;
159
160 (void) fchmod(fileno(f), 0644);
161
162 fprintf(f,
163 "# This is private data. Do not parse.\n"
164 "NAME=%s\n"
165 "STATE=%s\n" /* friendly user-facing state */
166 "STOPPING=%s\n" /* low-level state */
167 "GC_MODE=%s\n",
168 u->user_record->user_name,
169 user_state_to_string(user_get_state(u)),
170 yes_no(u->stopping),
171 user_gc_mode_to_string(u->gc_mode));
172
173 /* LEGACY: no-one reads RUNTIME= anymore, drop it at some point */
174 if (u->runtime_path)
175 fprintf(f, "RUNTIME=%s\n", u->runtime_path);
176
177 if (u->runtime_dir_job)
178 fprintf(f, "RUNTIME_DIR_JOB=%s\n", u->runtime_dir_job);
179
180 if (u->service_manager_job)
181 fprintf(f, "SERVICE_JOB=%s\n", u->service_manager_job);
182
183 if (u->display)
184 fprintf(f, "DISPLAY=%s\n", u->display->id);
185
186 if (dual_timestamp_is_set(&u->timestamp))
187 fprintf(f,
188 "REALTIME="USEC_FMT"\n"
189 "MONOTONIC="USEC_FMT"\n",
190 u->timestamp.realtime,
191 u->timestamp.monotonic);
192
193 if (u->last_session_timestamp != USEC_INFINITY)
194 fprintf(f, "LAST_SESSION_TIMESTAMP=" USEC_FMT "\n",
195 u->last_session_timestamp);
196
197 if (u->sessions) {
198 bool first;
199
200 fputs("SESSIONS=", f);
201 first = true;
202 LIST_FOREACH(sessions_by_user, i, u->sessions) {
203 if (first)
204 first = false;
205 else
206 fputc(' ', f);
207
208 fputs(i->id, f);
209 }
210
211 fputs("\nSEATS=", f);
212 first = true;
213 LIST_FOREACH(sessions_by_user, i, u->sessions) {
214 if (!i->seat)
215 continue;
216
217 if (first)
218 first = false;
219 else
220 fputc(' ', f);
221
222 fputs(i->seat->id, f);
223 }
224
225 fputs("\nACTIVE_SESSIONS=", f);
226 first = true;
227 LIST_FOREACH(sessions_by_user, i, u->sessions) {
228 if (!session_is_active(i))
229 continue;
230
231 if (first)
232 first = false;
233 else
234 fputc(' ', f);
235
236 fputs(i->id, f);
237 }
238
239 fputs("\nONLINE_SESSIONS=", f);
240 first = true;
241 LIST_FOREACH(sessions_by_user, i, u->sessions) {
242 if (session_get_state(i) == SESSION_CLOSING)
243 continue;
244
245 if (first)
246 first = false;
247 else
248 fputc(' ', f);
249
250 fputs(i->id, f);
251 }
252
253 fputs("\nACTIVE_SEATS=", f);
254 first = true;
255 LIST_FOREACH(sessions_by_user, i, u->sessions) {
256 if (!session_is_active(i) || !i->seat)
257 continue;
258
259 if (first)
260 first = false;
261 else
262 fputc(' ', f);
263
264 fputs(i->seat->id, f);
265 }
266
267 fputs("\nONLINE_SEATS=", f);
268 first = true;
269 LIST_FOREACH(sessions_by_user, i, u->sessions) {
270 if (session_get_state(i) == SESSION_CLOSING || !i->seat)
271 continue;
272
273 if (first)
274 first = false;
275 else
276 fputc(' ', f);
277
278 fputs(i->seat->id, f);
279 }
280 fputc('\n', f);
281 }
282
283 r = fflush_and_check(f);
284 if (r < 0)
285 goto fail;
286
287 if (rename(temp_path, u->state_file) < 0) {
288 r = -errno;
289 goto fail;
290 }
291
292 temp_path = mfree(temp_path);
293 return 0;
294
295 fail:
296 (void) unlink(u->state_file);
297
298 return log_error_errno(r, "Failed to save user data %s: %m", u->state_file);
299 }
300
301 int user_save(User *u) {
302 assert(u);
303
304 if (!u->started)
305 return 0;
306
307 return user_save_internal(u);
308 }
309
310 int user_load(User *u) {
311 _cleanup_free_ char *realtime = NULL, *monotonic = NULL, *stopping = NULL, *last_session_timestamp = NULL, *gc_mode = NULL;
312 int r;
313
314 assert(u);
315
316 r = parse_env_file(NULL, u->state_file,
317 "RUNTIME_DIR_JOB", &u->runtime_dir_job,
318 "SERVICE_JOB", &u->service_manager_job,
319 "STOPPING", &stopping,
320 "REALTIME", &realtime,
321 "MONOTONIC", &monotonic,
322 "LAST_SESSION_TIMESTAMP", &last_session_timestamp,
323 "GC_MODE", &gc_mode);
324 if (r == -ENOENT)
325 return 0;
326 if (r < 0)
327 return log_error_errno(r, "Failed to read %s: %m", u->state_file);
328
329 if (stopping) {
330 r = parse_boolean(stopping);
331 if (r < 0)
332 log_debug_errno(r, "Failed to parse 'STOPPING' boolean: %s", stopping);
333 else {
334 u->stopping = r;
335 if (u->stopping && !u->runtime_dir_job)
336 log_debug("User '%s' is stopping, but no job is being tracked.", u->user_record->user_name);
337 }
338 }
339
340 if (realtime)
341 (void) deserialize_usec(realtime, &u->timestamp.realtime);
342 if (monotonic)
343 (void) deserialize_usec(monotonic, &u->timestamp.monotonic);
344 if (last_session_timestamp)
345 (void) deserialize_usec(last_session_timestamp, &u->last_session_timestamp);
346
347 u->gc_mode = user_gc_mode_from_string(gc_mode);
348 if (u->gc_mode < 0)
349 u->gc_mode = USER_GC_BY_PIN;
350
351 return 0;
352 }
353
354 static int user_start_runtime_dir(User *u) {
355 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
356 int r;
357
358 assert(u);
359 assert(!u->stopping);
360 assert(u->manager);
361 assert(u->runtime_dir_unit);
362
363 u->runtime_dir_job = mfree(u->runtime_dir_job);
364
365 r = manager_start_unit(u->manager, u->runtime_dir_unit, &error, &u->runtime_dir_job);
366 if (r < 0)
367 return log_full_errno(sd_bus_error_has_name(&error, BUS_ERROR_UNIT_MASKED) ? LOG_DEBUG : LOG_ERR,
368 r, "Failed to start user service '%s': %s",
369 u->runtime_dir_unit, bus_error_message(&error, r));
370
371 return 0;
372 }
373
374 static bool user_wants_service_manager(User *u) {
375 assert(u);
376
377 LIST_FOREACH(sessions_by_user, s, u->sessions)
378 if (SESSION_CLASS_WANTS_SERVICE_MANAGER(s->class))
379 return true;
380
381 return false;
382 }
383
384 int user_start_service_manager(User *u) {
385 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
386 int r;
387
388 assert(u);
389 assert(!u->stopping);
390 assert(u->manager);
391 assert(u->service_manager_unit);
392
393 if (u->service_manager_started)
394 return 1;
395
396 /* Only start user service manager if there's at least one session which wants it */
397 if (!user_wants_service_manager(u))
398 return 0;
399
400 u->service_manager_job = mfree(u->service_manager_job);
401
402 r = manager_start_unit(u->manager, u->service_manager_unit, &error, &u->service_manager_job);
403 if (r < 0) {
404 if (sd_bus_error_has_name(&error, BUS_ERROR_UNIT_MASKED))
405 return 0;
406
407 return log_error_errno(r, "Failed to start user service '%s': %s",
408 u->service_manager_unit, bus_error_message(&error, r));
409 }
410
411 return (u->service_manager_started = true);
412 }
413
414 static int update_slice_callback(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
415 _cleanup_(user_record_unrefp) UserRecord *ur = ASSERT_PTR(userdata);
416 const sd_bus_error *e;
417 int r;
418
419 assert(m);
420
421 e = sd_bus_message_get_error(m);
422 if (e) {
423 r = sd_bus_error_get_errno(e);
424 log_warning_errno(r,
425 "Failed to update slice of %s, ignoring: %s",
426 ur->user_name,
427 bus_error_message(e, r));
428
429 return 0;
430 }
431
432 log_debug("Successfully set slice parameters of %s.", ur->user_name);
433 return 0;
434 }
435
436 static int user_update_slice(User *u) {
437 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
438 int r;
439
440 assert(u);
441
442 if (u->user_record->tasks_max == UINT64_MAX &&
443 u->user_record->memory_high == UINT64_MAX &&
444 u->user_record->memory_max == UINT64_MAX &&
445 u->user_record->cpu_weight == UINT64_MAX &&
446 u->user_record->io_weight == UINT64_MAX)
447 return 0;
448
449 r = bus_message_new_method_call(u->manager->bus, &m, bus_systemd_mgr, "SetUnitProperties");
450 if (r < 0)
451 return bus_log_create_error(r);
452
453 r = sd_bus_message_append(m, "sb", u->slice, true);
454 if (r < 0)
455 return bus_log_create_error(r);
456
457 r = sd_bus_message_open_container(m, 'a', "(sv)");
458 if (r < 0)
459 return bus_log_create_error(r);
460
461 const struct {
462 const char *name;
463 uint64_t value;
464 } settings[] = {
465 { "TasksMax", u->user_record->tasks_max },
466 { "MemoryMax", u->user_record->memory_max },
467 { "MemoryHigh", u->user_record->memory_high },
468 { "CPUWeight", u->user_record->cpu_weight },
469 { "IOWeight", u->user_record->io_weight },
470 };
471
472 FOREACH_ELEMENT(st, settings) {
473 if (st->value == UINT64_MAX)
474 continue;
475
476 r = sd_bus_message_append(m, "(sv)", st->name, "t", st->value);
477 if (r < 0)
478 return bus_log_create_error(r);
479 }
480
481 r = sd_bus_message_close_container(m);
482 if (r < 0)
483 return bus_log_create_error(r);
484
485 r = sd_bus_call_async(u->manager->bus, NULL, m, update_slice_callback, u->user_record, 0);
486 if (r < 0)
487 return log_error_errno(r, "Failed to change user slice properties: %m");
488
489 /* Ref the user record pointer, so that the slot keeps it pinned */
490 user_record_ref(u->user_record);
491
492 return 0;
493 }
494
495 int user_start(User *u) {
496 int r;
497
498 assert(u);
499
500 if (u->service_manager_started) {
501 /* Everything is up. No action needed. */
502 assert(u->started && !u->stopping);
503 return 0;
504 }
505
506 if (!u->started || u->stopping) {
507 /* If u->stopping is set, the user is marked for removal and service stop-jobs are queued.
508 * We have to clear that flag before queueing the start-jobs again. If they succeed, the
509 * user object can be re-used just fine (pid1 takes care of job-ordering and proper restart),
510 * but if they fail, we want to force another user_stop() so possibly pending units are
511 * stopped. */
512 u->stopping = false;
513
514 if (!u->started)
515 log_debug("Tracking new user %s.", u->user_record->user_name);
516
517 /* Save the user data so far, because pam_systemd will read the XDG_RUNTIME_DIR out of it
518 * while starting up systemd --user. We need to do user_save_internal() because we have not
519 * "officially" started yet. */
520 user_save_internal(u);
521
522 /* Set slice parameters */
523 (void) user_update_slice(u);
524
525 (void) user_start_runtime_dir(u);
526 }
527
528 /* Start user@UID.service if needed. */
529 r = user_start_service_manager(u);
530 if (r < 0)
531 return r;
532
533 if (!u->started) {
534 if (!dual_timestamp_is_set(&u->timestamp))
535 dual_timestamp_now(&u->timestamp);
536
537 user_send_signal(u, true);
538 u->started = true;
539 }
540
541 /* Save new user data */
542 user_save(u);
543
544 return 0;
545 }
546
547 static void user_stop_service(User *u, bool force) {
548 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
549 int r;
550
551 assert(u);
552 assert(u->manager);
553 assert(u->runtime_dir_unit);
554
555 /* Note that we only stop user-runtime-dir@.service here, and let BindsTo= deal with the user@.service
556 * instance. However, we still need to clear service_manager_job here, so that if the stop is
557 * interrupted, the new sessions won't be confused by leftovers. */
558
559 u->service_manager_job = mfree(u->service_manager_job);
560 u->service_manager_started = false;
561
562 u->runtime_dir_job = mfree(u->runtime_dir_job);
563
564 r = manager_stop_unit(u->manager, u->runtime_dir_unit, force ? "replace" : "fail", &error, &u->runtime_dir_job);
565 if (r < 0)
566 log_warning_errno(r, "Failed to stop user service '%s', ignoring: %s",
567 u->runtime_dir_unit, bus_error_message(&error, r));
568 }
569
570 int user_stop(User *u, bool force) {
571 int r = 0;
572
573 assert(u);
574
575 /* This is called whenever we begin with tearing down a user record. It's called in two cases: explicit API
576 * request to do so via the bus (in which case 'force' is true) and automatically due to GC, if there's no
577 * session left pinning it (in which case 'force' is false). Note that this just initiates tearing down of the
578 * user, the User object will remain in memory until user_finalize() is called, see below. */
579
580 if (!u->started)
581 return 0;
582
583 if (u->stopping) { /* Stop jobs have already been queued */
584 user_save(u);
585 return 0;
586 }
587
588 LIST_FOREACH(sessions_by_user, s, u->sessions)
589 RET_GATHER(r, session_stop(s, force));
590
591 user_stop_service(u, force);
592
593 u->stopping = true;
594
595 user_save(u);
596
597 return r;
598 }
599
600 int user_finalize(User *u) {
601 int r = 0;
602
603 assert(u);
604
605 /* Called when the user is really ready to be freed, i.e. when all unit stop jobs and suchlike for it are
606 * done. This is called as a result of an earlier user_done() when all jobs are completed. */
607
608 if (u->started)
609 log_debug("User %s exited.", u->user_record->user_name);
610
611 LIST_FOREACH(sessions_by_user, s, u->sessions)
612 RET_GATHER(r, session_finalize(s));
613
614 /* Clean SysV + POSIX IPC objects, but only if this is not a system user. Background: in many setups cronjobs
615 * are run in full PAM and thus logind sessions, even if the code run doesn't belong to actual users but to
616 * system components. Since enable RemoveIPC= globally for all users, we need to be a bit careful with such
617 * cases, as we shouldn't accidentally remove a system service's IPC objects while it is running, just because
618 * a cronjob running as the same user just finished. Hence: exclude system users generally from IPC clean-up,
619 * and do it only for normal users. */
620 if (u->manager->remove_ipc && !uid_is_system(u->user_record->uid))
621 RET_GATHER(r, clean_ipc_by_uid(u->user_record->uid));
622
623 (void) unlink(u->state_file);
624 user_add_to_gc_queue(u);
625
626 if (u->started) {
627 user_send_signal(u, false);
628 u->started = false;
629 }
630
631 return r;
632 }
633
634 int user_get_idle_hint(User *u, dual_timestamp *t) {
635 bool idle_hint = true;
636 dual_timestamp ts = DUAL_TIMESTAMP_NULL;
637
638 assert(u);
639
640 LIST_FOREACH(sessions_by_user, s, u->sessions) {
641 dual_timestamp k;
642 int ih;
643
644 if (!SESSION_CLASS_CAN_IDLE(s->class))
645 continue;
646
647 ih = session_get_idle_hint(s, &k);
648 if (ih < 0)
649 return ih;
650
651 if (!ih) {
652 if (!idle_hint) {
653 if (k.monotonic < ts.monotonic)
654 ts = k;
655 } else {
656 idle_hint = false;
657 ts = k;
658 }
659 } else if (idle_hint) {
660
661 if (k.monotonic > ts.monotonic)
662 ts = k;
663 }
664 }
665
666 if (t)
667 *t = ts;
668
669 return idle_hint;
670 }
671
672 int user_check_linger_file(User *u) {
673 _cleanup_free_ char *cc = NULL;
674 char *p = NULL;
675
676 cc = cescape(u->user_record->user_name);
677 if (!cc)
678 return -ENOMEM;
679
680 p = strjoina("/var/lib/systemd/linger/", cc);
681 if (access(p, F_OK) < 0) {
682 if (errno != ENOENT)
683 return -errno;
684
685 return false;
686 }
687
688 return true;
689 }
690
691 static bool user_unit_active(User *u) {
692 int r;
693
694 assert(u->slice);
695 assert(u->runtime_dir_unit);
696 assert(u->service_manager_unit);
697
698 FOREACH_STRING(i, u->slice, u->runtime_dir_unit, u->service_manager_unit) {
699 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
700
701 r = manager_unit_is_active(u->manager, i, &error);
702 if (r < 0)
703 log_debug_errno(r, "Failed to determine whether unit '%s' is active, ignoring: %s", i, bus_error_message(&error, r));
704 if (r != 0)
705 return true;
706 }
707
708 return false;
709 }
710
711 static usec_t user_get_stop_delay(User *u) {
712 assert(u);
713
714 if (u->user_record->stop_delay_usec != UINT64_MAX)
715 return u->user_record->stop_delay_usec;
716
717 if (user_record_removable(u->user_record) > 0)
718 return 0; /* For removable users lower the stop delay to zero */
719
720 return u->manager->user_stop_delay;
721 }
722
723 static bool user_pinned_by_sessions(User *u) {
724 assert(u);
725
726 /* Returns true if at least one session exists that shall keep the user tracking alive. That
727 * generally means one session that isn't the service manager still exists. */
728
729 switch (u->gc_mode) {
730
731 case USER_GC_BY_ANY:
732 return u->sessions;
733
734 case USER_GC_BY_PIN:
735 LIST_FOREACH(sessions_by_user, i, u->sessions)
736 if (SESSION_CLASS_PIN_USER(i->class))
737 return true;
738
739 return false;
740
741 default:
742 assert_not_reached();
743 }
744 }
745
746 bool user_may_gc(User *u, bool drop_not_started) {
747 int r;
748
749 assert(u);
750
751 if (drop_not_started && !u->started)
752 return true;
753
754 if (user_pinned_by_sessions(u))
755 return false;
756
757 if (u->last_session_timestamp != USEC_INFINITY) {
758 usec_t user_stop_delay;
759
760 /* All sessions have been closed. Let's see if we shall leave the user record around for a bit */
761
762 user_stop_delay = user_get_stop_delay(u);
763
764 if (user_stop_delay == USEC_INFINITY)
765 return false; /* Leave it around forever! */
766 if (user_stop_delay > 0 &&
767 now(CLOCK_MONOTONIC) < usec_add(u->last_session_timestamp, user_stop_delay))
768 return false; /* Leave it around for a bit longer. */
769 }
770
771 /* Is this a user that shall stay around forever ("linger")? Before we say "no" to GC'ing for lingering users, let's check
772 * if any of the three units that we maintain for this user is still around. If none of them is,
773 * there's no need to keep this user around even if lingering is enabled. */
774 if (user_check_linger_file(u) > 0 && user_unit_active(u))
775 return false;
776
777 /* Check if our job is still pending */
778 const char *j;
779 FOREACH_ARGUMENT(j, u->runtime_dir_job, u->service_manager_job) {
780 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
781
782 if (!j)
783 continue;
784
785 r = manager_job_is_active(u->manager, j, &error);
786 if (r < 0)
787 log_debug_errno(r, "Failed to determine whether job '%s' is pending, ignoring: %s",
788 j, bus_error_message(&error, r));
789 if (r != 0)
790 return false;
791 }
792
793 /* Note that we don't care if the three units we manage for each user object are up or not, as we are
794 * managing their state rather than tracking it. */
795
796 return true;
797 }
798
799 void user_add_to_gc_queue(User *u) {
800 assert(u);
801
802 if (u->in_gc_queue)
803 return;
804
805 LIST_PREPEND(gc_queue, u->manager->user_gc_queue, u);
806 u->in_gc_queue = true;
807 }
808
809 UserState user_get_state(User *u) {
810 assert(u);
811
812 if (u->stopping)
813 return USER_CLOSING;
814
815 if (!u->started || u->runtime_dir_job)
816 return USER_OPENING;
817
818 bool any = false, all_closing = true;
819 LIST_FOREACH(sessions_by_user, i, u->sessions) {
820 SessionState state;
821
822 /* Ignore sessions that don't pin the user, i.e. are not supposed to have an effect on user state */
823 if (!SESSION_CLASS_PIN_USER(i->class))
824 continue;
825
826 state = session_get_state(i);
827 if (state == SESSION_ACTIVE)
828 return USER_ACTIVE;
829 if (state != SESSION_CLOSING)
830 all_closing = false;
831
832 any = true;
833 }
834
835 if (any)
836 return all_closing ? USER_CLOSING : USER_ONLINE;
837
838 if (user_check_linger_file(u) > 0 && user_unit_active(u))
839 return USER_LINGERING;
840
841 return USER_CLOSING;
842 }
843
844 int user_kill(User *u, int signo) {
845 assert(u);
846
847 return manager_kill_unit(u->manager, u->slice, KILL_ALL, signo, NULL);
848 }
849
850 static bool elect_display_filter(Session *s) {
851 /* Return true if the session is a candidate for the user’s ‘primary session’ or ‘display’. */
852 assert(s);
853
854 return SESSION_CLASS_CAN_DISPLAY(s->class) && s->started && !s->stopping;
855 }
856
857 static int elect_display_compare(Session *s1, Session *s2) {
858 /* Indexed by SessionType. Lower numbers mean more preferred. */
859 static const int type_ranks[_SESSION_TYPE_MAX] = {
860 [SESSION_UNSPECIFIED] = 0,
861 [SESSION_TTY] = -2,
862 [SESSION_X11] = -3,
863 [SESSION_WAYLAND] = -3,
864 [SESSION_MIR] = -3,
865 [SESSION_WEB] = -1,
866 };
867
868 /* Calculate the partial order relationship between s1 and s2,
869 * returning < 0 if s1 is preferred as the user’s ‘primary session’,
870 * 0 if s1 and s2 are equally preferred or incomparable, or > 0 if s2
871 * is preferred.
872 *
873 * s1 or s2 may be NULL. */
874 if (!s1 && !s2)
875 return 0;
876
877 if ((s1 == NULL) != (s2 == NULL))
878 return (s1 == NULL) - (s2 == NULL);
879
880 if (s1->stopping != s2->stopping)
881 return s1->stopping - s2->stopping;
882
883 if ((s1->class != SESSION_USER) != (s2->class != SESSION_USER))
884 return (s1->class != SESSION_USER) - (s2->class != SESSION_USER);
885
886 if ((s1->class != SESSION_USER_EARLY) != (s2->class != SESSION_USER_EARLY))
887 return (s1->class != SESSION_USER_EARLY) - (s2->class != SESSION_USER_EARLY);
888
889 if ((s1->type == _SESSION_TYPE_INVALID) != (s2->type == _SESSION_TYPE_INVALID))
890 return (s1->type == _SESSION_TYPE_INVALID) - (s2->type == _SESSION_TYPE_INVALID);
891
892 if (s1->type != s2->type)
893 return type_ranks[s1->type] - type_ranks[s2->type];
894
895 return 0;
896 }
897
898 void user_elect_display(User *u) {
899 assert(u);
900
901 /* This elects a primary session for each user, which we call the "display". We try to keep the assignment
902 * stable, but we "upgrade" to better choices. */
903 log_debug("Electing new display for user %s", u->user_record->user_name);
904
905 LIST_FOREACH(sessions_by_user, s, u->sessions) {
906 if (!elect_display_filter(s)) {
907 log_debug("Ignoring session %s", s->id);
908 continue;
909 }
910
911 if (elect_display_compare(s, u->display) < 0) {
912 log_debug("Choosing session %s in preference to %s", s->id, u->display ? u->display->id : "-");
913 u->display = s;
914 }
915 }
916 }
917
918 static int user_stop_timeout_callback(sd_event_source *es, uint64_t usec, void *userdata) {
919 User *u = ASSERT_PTR(userdata);
920
921 user_add_to_gc_queue(u);
922
923 return 0;
924 }
925
926 void user_update_last_session_timer(User *u) {
927 usec_t user_stop_delay;
928 int r;
929
930 assert(u);
931
932 if (user_pinned_by_sessions(u)) {
933 /* There are sessions, turn off the timer */
934 u->last_session_timestamp = USEC_INFINITY;
935 u->timer_event_source = sd_event_source_unref(u->timer_event_source);
936 return;
937 }
938
939 if (u->last_session_timestamp != USEC_INFINITY)
940 return; /* Timer already started */
941
942 u->last_session_timestamp = now(CLOCK_MONOTONIC);
943
944 assert(!u->timer_event_source);
945
946 user_stop_delay = user_get_stop_delay(u);
947 if (!timestamp_is_set(user_stop_delay))
948 return;
949
950 if (sd_event_get_state(u->manager->event) == SD_EVENT_FINISHED) {
951 log_debug("Not allocating user stop timeout, since we are already exiting.");
952 return;
953 }
954
955 r = sd_event_add_time(u->manager->event,
956 &u->timer_event_source,
957 CLOCK_MONOTONIC,
958 usec_add(u->last_session_timestamp, user_stop_delay), 0,
959 user_stop_timeout_callback, u);
960 if (r < 0)
961 log_warning_errno(r, "Failed to enqueue user stop event source, ignoring: %m");
962
963 if (DEBUG_LOGGING)
964 log_debug("Last session of user '%s' logged out, terminating user context in %s.",
965 u->user_record->user_name,
966 FORMAT_TIMESPAN(user_stop_delay, USEC_PER_MSEC));
967 }
968
969 static const char* const user_state_table[_USER_STATE_MAX] = {
970 [USER_OFFLINE] = "offline",
971 [USER_OPENING] = "opening",
972 [USER_LINGERING] = "lingering",
973 [USER_ONLINE] = "online",
974 [USER_ACTIVE] = "active",
975 [USER_CLOSING] = "closing"
976 };
977
978 DEFINE_STRING_TABLE_LOOKUP(user_state, UserState);
979
980 static const char* const user_gc_mode_table[_USER_GC_MODE_MAX] = {
981 [USER_GC_BY_PIN] = "pin",
982 [USER_GC_BY_ANY] = "any",
983 };
984
985 DEFINE_STRING_TABLE_LOOKUP(user_gc_mode, UserGCMode);
986
987 int config_parse_tmpfs_size(
988 const char* unit,
989 const char *filename,
990 unsigned line,
991 const char *section,
992 unsigned section_line,
993 const char *lvalue,
994 int ltype,
995 const char *rvalue,
996 void *data,
997 void *userdata) {
998
999 uint64_t *sz = ASSERT_PTR(data);
1000 int r;
1001
1002 assert(filename);
1003 assert(lvalue);
1004 assert(rvalue);
1005
1006 /* First, try to parse as percentage */
1007 r = parse_permyriad(rvalue);
1008 if (r > 0)
1009 *sz = physical_memory_scale(r, 10000U);
1010 else {
1011 uint64_t k;
1012
1013 /* If the passed argument was not a percentage, or out of range, parse as byte size */
1014
1015 r = parse_size(rvalue, 1024, &k);
1016 if (r >= 0 && (k <= 0 || (uint64_t) (size_t) k != k))
1017 r = -ERANGE;
1018 if (r < 0) {
1019 log_syntax(unit, LOG_WARNING, filename, line, r, "Failed to parse size value '%s', ignoring: %m", rvalue);
1020 return 0;
1021 }
1022
1023 *sz = PAGE_ALIGN((size_t) k);
1024 }
1025
1026 return 0;
1027 }
1028
1029 int config_parse_compat_user_tasks_max(
1030 const char *unit,
1031 const char *filename,
1032 unsigned line,
1033 const char *section,
1034 unsigned section_line,
1035 const char *lvalue,
1036 int ltype,
1037 const char *rvalue,
1038 void *data,
1039 void *userdata) {
1040
1041 assert(filename);
1042 assert(lvalue);
1043 assert(rvalue);
1044
1045 log_syntax(unit, LOG_NOTICE, filename, line, 0,
1046 "Support for option %s= has been removed.",
1047 lvalue);
1048 log_info("Hint: try creating /etc/systemd/system/user-.slice.d/50-limits.conf with:\n"
1049 " [Slice]\n"
1050 " TasksMax=%s",
1051 rvalue);
1052 return 0;
1053 }