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