]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/login/logind-user.c
logind: rework how we manage the slice and user-runtime-dir@.service unit for each...
[thirdparty/systemd.git] / src / login / logind-user.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <errno.h>
4 #include <string.h>
5 #include <unistd.h>
6 #include <stdio_ext.h>
7
8 #include "alloc-util.h"
9 #include "bus-common-errors.h"
10 #include "bus-error.h"
11 #include "bus-util.h"
12 #include "cgroup-util.h"
13 #include "clean-ipc.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.h"
21 #include "logind-user.h"
22 #include "mkdir.h"
23 #include "parse-util.h"
24 #include "path-util.h"
25 #include "rm-rf.h"
26 #include "special.h"
27 #include "stdio-util.h"
28 #include "string-table.h"
29 #include "unit-name.h"
30 #include "user-util.h"
31 #include "util.h"
32
33 int user_new(User **ret, Manager *m, uid_t uid, gid_t gid, const char *name) {
34 _cleanup_(user_freep) User *u = NULL;
35 char lu[DECIMAL_STR_MAX(uid_t) + 1];
36 int r;
37
38 assert(ret);
39 assert(m);
40 assert(name);
41
42 u = new(User, 1);
43 if (!u)
44 return -ENOMEM;
45
46 *u = (User) {
47 .manager = m,
48 .uid = uid,
49 .gid = gid,
50 };
51
52 u->name = strdup(name);
53 if (!u->name)
54 return -ENOMEM;
55
56 if (asprintf(&u->state_file, "/run/systemd/users/"UID_FMT, uid) < 0)
57 return -ENOMEM;
58
59 if (asprintf(&u->runtime_path, "/run/user/"UID_FMT, uid) < 0)
60 return -ENOMEM;
61
62 xsprintf(lu, UID_FMT, uid);
63 r = slice_build_subslice(SPECIAL_USER_SLICE, lu, &u->slice);
64 if (r < 0)
65 return r;
66
67 r = unit_name_build("user", lu, ".service", &u->service);
68 if (r < 0)
69 return r;
70
71 r = unit_name_build("user-runtime-dir", lu, ".service", &u->runtime_dir_service);
72 if (r < 0)
73 return r;
74
75 r = hashmap_put(m->users, UID_TO_PTR(uid), u);
76 if (r < 0)
77 return r;
78
79 r = hashmap_put(m->user_units, u->slice, u);
80 if (r < 0)
81 return r;
82
83 r = hashmap_put(m->user_units, u->service, u);
84 if (r < 0)
85 return r;
86
87 r = hashmap_put(m->user_units, u->runtime_dir_service, u);
88 if (r < 0)
89 return r;
90
91 *ret = TAKE_PTR(u);
92 return 0;
93 }
94
95 User *user_free(User *u) {
96 if (!u)
97 return NULL;
98
99 if (u->in_gc_queue)
100 LIST_REMOVE(gc_queue, u->manager->user_gc_queue, u);
101
102 while (u->sessions)
103 session_free(u->sessions);
104
105 if (u->service)
106 hashmap_remove_value(u->manager->user_units, u->service, u);
107
108 if (u->runtime_dir_service)
109 hashmap_remove_value(u->manager->user_units, u->runtime_dir_service, u);
110
111 if (u->slice)
112 hashmap_remove_value(u->manager->user_units, u->slice, u);
113
114 hashmap_remove_value(u->manager->users, UID_TO_PTR(u->uid), u);
115
116 u->service_job = mfree(u->service_job);
117
118 u->service = mfree(u->service);
119 u->runtime_dir_service = mfree(u->runtime_dir_service);
120 u->slice = mfree(u->slice);
121 u->runtime_path = mfree(u->runtime_path);
122 u->state_file = mfree(u->state_file);
123 u->name = mfree(u->name);
124
125 return mfree(u);
126 }
127
128 static int user_save_internal(User *u) {
129 _cleanup_free_ char *temp_path = NULL;
130 _cleanup_fclose_ FILE *f = NULL;
131 int r;
132
133 assert(u);
134 assert(u->state_file);
135
136 r = mkdir_safe_label("/run/systemd/users", 0755, 0, 0, MKDIR_WARN_MODE);
137 if (r < 0)
138 goto fail;
139
140 r = fopen_temporary(u->state_file, &f, &temp_path);
141 if (r < 0)
142 goto fail;
143
144 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
145 (void) fchmod(fileno(f), 0644);
146
147 fprintf(f,
148 "# This is private data. Do not parse.\n"
149 "NAME=%s\n"
150 "STATE=%s\n" /* friendly user-facing state */
151 "STOPPING=%s\n", /* low-level state */
152 u->name,
153 user_state_to_string(user_get_state(u)),
154 yes_no(u->stopping));
155
156 /* LEGACY: no-one reads RUNTIME= anymore, drop it at some point */
157 if (u->runtime_path)
158 fprintf(f, "RUNTIME=%s\n", u->runtime_path);
159
160 if (u->service_job)
161 fprintf(f, "SERVICE_JOB=%s\n", u->service_job);
162
163 if (u->display)
164 fprintf(f, "DISPLAY=%s\n", u->display->id);
165
166 if (dual_timestamp_is_set(&u->timestamp))
167 fprintf(f,
168 "REALTIME="USEC_FMT"\n"
169 "MONOTONIC="USEC_FMT"\n",
170 u->timestamp.realtime,
171 u->timestamp.monotonic);
172
173 if (u->sessions) {
174 Session *i;
175 bool first;
176
177 fputs("SESSIONS=", f);
178 first = true;
179 LIST_FOREACH(sessions_by_user, i, u->sessions) {
180 if (first)
181 first = false;
182 else
183 fputc(' ', f);
184
185 fputs(i->id, f);
186 }
187
188 fputs("\nSEATS=", f);
189 first = true;
190 LIST_FOREACH(sessions_by_user, i, u->sessions) {
191 if (!i->seat)
192 continue;
193
194 if (first)
195 first = false;
196 else
197 fputc(' ', f);
198
199 fputs(i->seat->id, f);
200 }
201
202 fputs("\nACTIVE_SESSIONS=", f);
203 first = true;
204 LIST_FOREACH(sessions_by_user, i, u->sessions) {
205 if (!session_is_active(i))
206 continue;
207
208 if (first)
209 first = false;
210 else
211 fputc(' ', f);
212
213 fputs(i->id, f);
214 }
215
216 fputs("\nONLINE_SESSIONS=", f);
217 first = true;
218 LIST_FOREACH(sessions_by_user, i, u->sessions) {
219 if (session_get_state(i) == SESSION_CLOSING)
220 continue;
221
222 if (first)
223 first = false;
224 else
225 fputc(' ', f);
226
227 fputs(i->id, f);
228 }
229
230 fputs("\nACTIVE_SEATS=", f);
231 first = true;
232 LIST_FOREACH(sessions_by_user, i, u->sessions) {
233 if (!session_is_active(i) || !i->seat)
234 continue;
235
236 if (first)
237 first = false;
238 else
239 fputc(' ', f);
240
241 fputs(i->seat->id, f);
242 }
243
244 fputs("\nONLINE_SEATS=", f);
245 first = true;
246 LIST_FOREACH(sessions_by_user, i, u->sessions) {
247 if (session_get_state(i) == SESSION_CLOSING || !i->seat)
248 continue;
249
250 if (first)
251 first = false;
252 else
253 fputc(' ', f);
254
255 fputs(i->seat->id, f);
256 }
257 fputc('\n', f);
258 }
259
260 r = fflush_and_check(f);
261 if (r < 0)
262 goto fail;
263
264 if (rename(temp_path, u->state_file) < 0) {
265 r = -errno;
266 goto fail;
267 }
268
269 return 0;
270
271 fail:
272 (void) unlink(u->state_file);
273
274 if (temp_path)
275 (void) unlink(temp_path);
276
277 return log_error_errno(r, "Failed to save user data %s: %m", u->state_file);
278 }
279
280 int user_save(User *u) {
281 assert(u);
282
283 if (!u->started)
284 return 0;
285
286 return user_save_internal(u);
287 }
288
289 int user_load(User *u) {
290 _cleanup_free_ char *realtime = NULL, *monotonic = NULL, *stopping = NULL;
291 int r;
292
293 assert(u);
294
295 r = parse_env_file(NULL, u->state_file, NEWLINE,
296 "SERVICE_JOB", &u->service_job,
297 "STOPPING", &stopping,
298 "REALTIME", &realtime,
299 "MONOTONIC", &monotonic,
300 NULL);
301 if (r == -ENOENT)
302 return 0;
303 if (r < 0)
304 return log_error_errno(r, "Failed to read %s: %m", u->state_file);
305
306 if (stopping) {
307 r = parse_boolean(stopping);
308 if (r < 0)
309 log_debug_errno(r, "Failed to parse 'STOPPING' boolean: %s", stopping);
310 else
311 u->stopping = r;
312 }
313
314 if (realtime)
315 timestamp_deserialize(realtime, &u->timestamp.realtime);
316 if (monotonic)
317 timestamp_deserialize(monotonic, &u->timestamp.monotonic);
318
319 return 0;
320 }
321
322 static void user_start_service(User *u) {
323 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
324 int r;
325
326 assert(u);
327
328 /* Start the service containing the "systemd --user" instance (user@.service). Note that we don't explicitly
329 * start the per-user slice or the systemd-runtime-dir@.service instance, as those are pulled in both by
330 * user@.service and the session scopes as dependencies. */
331
332 u->service_job = mfree(u->service_job);
333
334 r = manager_start_unit(u->manager, u->service, &error, &u->service_job);
335 if (r < 0)
336 log_warning_errno(r, "Failed to start user service '%s', ignoring: %s", u->service, bus_error_message(&error, r));
337 }
338
339 int user_start(User *u) {
340 assert(u);
341
342 if (u->started && !u->stopping)
343 return 0;
344
345 /* If u->stopping is set, the user is marked for removal and service stop-jobs are queued. We have to clear
346 * that flag before queing the start-jobs again. If they succeed, the user object can be re-used just fine
347 * (pid1 takes care of job-ordering and proper restart), but if they fail, we want to force another user_stop()
348 * so possibly pending units are stopped. */
349 u->stopping = false;
350
351 if (!u->started)
352 log_debug("Starting services for new user %s.", u->name);
353
354 /* Save the user data so far, because pam_systemd will read the XDG_RUNTIME_DIR out of it while starting up
355 * systemd --user. We need to do user_save_internal() because we have not "officially" started yet. */
356 user_save_internal(u);
357
358 /* Start user@UID.service */
359 user_start_service(u);
360
361 if (!u->started) {
362 if (!dual_timestamp_is_set(&u->timestamp))
363 dual_timestamp_get(&u->timestamp);
364 user_send_signal(u, true);
365 u->started = true;
366 }
367
368 /* Save new user data */
369 user_save(u);
370
371 return 0;
372 }
373
374 static void user_stop_service(User *u) {
375 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
376 int r;
377
378 assert(u);
379 assert(u->service);
380
381 /* The reverse of user_start_service(). Note that we only stop user@UID.service here, and let StopWhenUnneeded=
382 * deal with the slice and the user-runtime-dir@.service instance. */
383
384 u->service_job = mfree(u->service_job);
385
386 r = manager_stop_unit(u->manager, u->service, &error, &u->service_job);
387 if (r < 0)
388 log_warning_errno(r, "Failed to stop user service '%s', ignoring: %s", u->service, bus_error_message(&error, r));
389 }
390
391 int user_stop(User *u, bool force) {
392 Session *s;
393 int r = 0;
394 assert(u);
395
396 /* This is called whenever we begin with tearing down a user record. It's called in two cases: explicit API
397 * request to do so via the bus (in which case 'force' is true) and automatically due to GC, if there's no
398 * session left pinning it (in which case 'force' is false). Note that this just initiates tearing down of the
399 * user, the User object will remain in memory until user_finalize() is called, see below. */
400
401 if (!u->started)
402 return 0;
403
404 if (u->stopping) { /* Stop jobs have already been queued */
405 user_save(u);
406 return 0;
407 }
408
409 LIST_FOREACH(sessions_by_user, s, u->sessions) {
410 int k;
411
412 k = session_stop(s, force);
413 if (k < 0)
414 r = k;
415 }
416
417 user_stop_service(u);
418
419 u->stopping = true;
420
421 user_save(u);
422
423 return r;
424 }
425
426 int user_finalize(User *u) {
427 Session *s;
428 int r = 0, k;
429
430 assert(u);
431
432 /* Called when the user is really ready to be freed, i.e. when all unit stop jobs and suchlike for it are
433 * done. This is called as a result of an earlier user_done() when all jobs are completed. */
434
435 if (u->started)
436 log_debug("User %s logged out.", u->name);
437
438 LIST_FOREACH(sessions_by_user, s, u->sessions) {
439 k = session_finalize(s);
440 if (k < 0)
441 r = k;
442 }
443
444 /* Clean SysV + POSIX IPC objects, but only if this is not a system user. Background: in many setups cronjobs
445 * are run in full PAM and thus logind sessions, even if the code run doesn't belong to actual users but to
446 * system components. Since enable RemoveIPC= globally for all users, we need to be a bit careful with such
447 * cases, as we shouldn't accidentally remove a system service's IPC objects while it is running, just because
448 * a cronjob running as the same user just finished. Hence: exclude system users generally from IPC clean-up,
449 * and do it only for normal users. */
450 if (u->manager->remove_ipc && !uid_is_system(u->uid)) {
451 k = clean_ipc_by_uid(u->uid);
452 if (k < 0)
453 r = k;
454 }
455
456 (void) unlink(u->state_file);
457 user_add_to_gc_queue(u);
458
459 if (u->started) {
460 user_send_signal(u, false);
461 u->started = false;
462 }
463
464 return r;
465 }
466
467 int user_get_idle_hint(User *u, dual_timestamp *t) {
468 Session *s;
469 bool idle_hint = true;
470 dual_timestamp ts = DUAL_TIMESTAMP_NULL;
471
472 assert(u);
473
474 LIST_FOREACH(sessions_by_user, s, u->sessions) {
475 dual_timestamp k;
476 int ih;
477
478 ih = session_get_idle_hint(s, &k);
479 if (ih < 0)
480 return ih;
481
482 if (!ih) {
483 if (!idle_hint) {
484 if (k.monotonic < ts.monotonic)
485 ts = k;
486 } else {
487 idle_hint = false;
488 ts = k;
489 }
490 } else if (idle_hint) {
491
492 if (k.monotonic > ts.monotonic)
493 ts = k;
494 }
495 }
496
497 if (t)
498 *t = ts;
499
500 return idle_hint;
501 }
502
503 int user_check_linger_file(User *u) {
504 _cleanup_free_ char *cc = NULL;
505 char *p = NULL;
506
507 cc = cescape(u->name);
508 if (!cc)
509 return -ENOMEM;
510
511 p = strjoina("/var/lib/systemd/linger/", cc);
512
513 return access(p, F_OK) >= 0;
514 }
515
516 bool user_may_gc(User *u, bool drop_not_started) {
517 int r;
518
519 assert(u);
520
521 if (drop_not_started && !u->started)
522 return true;
523
524 if (u->sessions)
525 return false;
526
527 if (user_check_linger_file(u) > 0)
528 return false;
529
530 /* Check if our job is still pending */
531 if (u->service_job) {
532 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
533
534 r = manager_job_is_active(u->manager, u->service_job, &error);
535 if (r < 0)
536 log_debug_errno(r, "Failed to determine whether job '%s' is pending, ignoring: %s", u->service_job, bus_error_message(&error, r));
537 if (r != 0)
538 return false;
539 }
540
541 /* Note that we don't care if the three units we manage for each user object are up or not, as we are managing
542 * their state rather than tracking it. */
543
544 return true;
545 }
546
547 void user_add_to_gc_queue(User *u) {
548 assert(u);
549
550 if (u->in_gc_queue)
551 return;
552
553 LIST_PREPEND(gc_queue, u->manager->user_gc_queue, u);
554 u->in_gc_queue = true;
555 }
556
557 UserState user_get_state(User *u) {
558 Session *i;
559
560 assert(u);
561
562 if (u->stopping)
563 return USER_CLOSING;
564
565 if (!u->started || u->service_job)
566 return USER_OPENING;
567
568 if (u->sessions) {
569 bool all_closing = true;
570
571 LIST_FOREACH(sessions_by_user, i, u->sessions) {
572 SessionState state;
573
574 state = session_get_state(i);
575 if (state == SESSION_ACTIVE)
576 return USER_ACTIVE;
577 if (state != SESSION_CLOSING)
578 all_closing = false;
579 }
580
581 return all_closing ? USER_CLOSING : USER_ONLINE;
582 }
583
584 if (user_check_linger_file(u) > 0)
585 return USER_LINGERING;
586
587 return USER_CLOSING;
588 }
589
590 int user_kill(User *u, int signo) {
591 assert(u);
592
593 return manager_kill_unit(u->manager, u->slice, KILL_ALL, signo, NULL);
594 }
595
596 static bool elect_display_filter(Session *s) {
597 /* Return true if the session is a candidate for the user’s ‘primary session’ or ‘display’. */
598 assert(s);
599
600 return s->class == SESSION_USER && s->started && !s->stopping;
601 }
602
603 static int elect_display_compare(Session *s1, Session *s2) {
604 /* Indexed by SessionType. Lower numbers mean more preferred. */
605 const int type_ranks[_SESSION_TYPE_MAX] = {
606 [SESSION_UNSPECIFIED] = 0,
607 [SESSION_TTY] = -2,
608 [SESSION_X11] = -3,
609 [SESSION_WAYLAND] = -3,
610 [SESSION_MIR] = -3,
611 [SESSION_WEB] = -1,
612 };
613
614 /* Calculate the partial order relationship between s1 and s2,
615 * returning < 0 if s1 is preferred as the user’s ‘primary session’,
616 * 0 if s1 and s2 are equally preferred or incomparable, or > 0 if s2
617 * is preferred.
618 *
619 * s1 or s2 may be NULL. */
620 if (!s1 && !s2)
621 return 0;
622
623 if ((s1 == NULL) != (s2 == NULL))
624 return (s1 == NULL) - (s2 == NULL);
625
626 if (s1->stopping != s2->stopping)
627 return s1->stopping - s2->stopping;
628
629 if ((s1->class != SESSION_USER) != (s2->class != SESSION_USER))
630 return (s1->class != SESSION_USER) - (s2->class != SESSION_USER);
631
632 if ((s1->type == _SESSION_TYPE_INVALID) != (s2->type == _SESSION_TYPE_INVALID))
633 return (s1->type == _SESSION_TYPE_INVALID) - (s2->type == _SESSION_TYPE_INVALID);
634
635 if (s1->type != s2->type)
636 return type_ranks[s1->type] - type_ranks[s2->type];
637
638 return 0;
639 }
640
641 void user_elect_display(User *u) {
642 Session *s;
643
644 assert(u);
645
646 /* This elects a primary session for each user, which we call the "display". We try to keep the assignment
647 * stable, but we "upgrade" to better choices. */
648 log_debug("Electing new display for user %s", u->name);
649
650 LIST_FOREACH(sessions_by_user, s, u->sessions) {
651 if (!elect_display_filter(s)) {
652 log_debug("Ignoring session %s", s->id);
653 continue;
654 }
655
656 if (elect_display_compare(s, u->display) < 0) {
657 log_debug("Choosing session %s in preference to %s", s->id, u->display ? u->display->id : "-");
658 u->display = s;
659 }
660 }
661 }
662
663 static const char* const user_state_table[_USER_STATE_MAX] = {
664 [USER_OFFLINE] = "offline",
665 [USER_OPENING] = "opening",
666 [USER_LINGERING] = "lingering",
667 [USER_ONLINE] = "online",
668 [USER_ACTIVE] = "active",
669 [USER_CLOSING] = "closing"
670 };
671
672 DEFINE_STRING_TABLE_LOOKUP(user_state, UserState);
673
674 int config_parse_tmpfs_size(
675 const char* unit,
676 const char *filename,
677 unsigned line,
678 const char *section,
679 unsigned section_line,
680 const char *lvalue,
681 int ltype,
682 const char *rvalue,
683 void *data,
684 void *userdata) {
685
686 uint64_t *sz = data;
687 int r;
688
689 assert(filename);
690 assert(lvalue);
691 assert(rvalue);
692 assert(data);
693
694 /* First, try to parse as percentage */
695 r = parse_permille(rvalue);
696 if (r > 0 && r < 1000)
697 *sz = physical_memory_scale(r, 1000U);
698 else {
699 uint64_t k;
700
701 /* If the passed argument was not a percentage, or out of range, parse as byte size */
702
703 r = parse_size(rvalue, 1024, &k);
704 if (r >= 0 && (k <= 0 || (uint64_t) (size_t) k != k))
705 r = -ERANGE;
706 if (r < 0) {
707 log_syntax(unit, LOG_ERR, filename, line, r, "Failed to parse size value '%s', ignoring: %m", rvalue);
708 return 0;
709 }
710
711 *sz = PAGE_ALIGN((size_t) k);
712 }
713
714 return 0;
715 }
716
717 int config_parse_compat_user_tasks_max(
718 const char *unit,
719 const char *filename,
720 unsigned line,
721 const char *section,
722 unsigned section_line,
723 const char *lvalue,
724 int ltype,
725 const char *rvalue,
726 void *data,
727 void *userdata) {
728
729 assert(filename);
730 assert(lvalue);
731 assert(rvalue);
732 assert(data);
733
734 log_syntax(unit, LOG_NOTICE, filename, line, 0,
735 "Support for option %s= has been removed.",
736 lvalue);
737 log_info("Hint: try creating /etc/systemd/system/user-.slice.d/50-limits.conf with:\n"
738 " [Slice]\n"
739 " TasksMax=%s",
740 rvalue);
741 return 0;
742 }