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