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