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