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