Debian Codegraph @

src/login/logind-user.c

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