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