]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/login/logind-user.c
logind: voidify a few calls
[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" /* friendly user-facing state */
140 "STOPPING=%s\n", /* low-level state */
141 u->name,
142 user_state_to_string(user_get_state(u)),
143 yes_no(u->stopping));
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 *realtime = NULL, *monotonic = NULL, *stopping = NULL;
283 int r;
284
285 assert(u);
286
287 r = parse_env_file(NULL, u->state_file, NEWLINE,
288 "SERVICE_JOB", &u->service_job,
289 "STOPPING", &stopping,
290 "REALTIME", &realtime,
291 "MONOTONIC", &monotonic,
292 NULL);
293 if (r == -ENOENT)
294 return 0;
295 if (r < 0)
296 return log_error_errno(r, "Failed to read %s: %m", u->state_file);
297
298 if (stopping) {
299 r = parse_boolean(stopping);
300 if (r < 0)
301 log_debug_errno(r, "Failed to parse 'STOPPING' boolean: %s", stopping);
302 else
303 u->stopping = r;
304 }
305
306 if (realtime)
307 timestamp_deserialize(realtime, &u->timestamp.realtime);
308 if (monotonic)
309 timestamp_deserialize(monotonic, &u->timestamp.monotonic);
310
311 return 0;
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 (void) 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 int r;
538
539 assert(u);
540
541 if (drop_not_started && !u->started)
542 return true;
543
544 if (u->sessions)
545 return false;
546
547 if (user_check_linger_file(u) > 0)
548 return false;
549
550 /* Check if our job is still pending */
551 if (u->service_job) {
552 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
553
554 r = manager_job_is_active(u->manager, u->service_job, &error);
555 if (r < 0)
556 log_debug_errno(r, "Failed to determine whether job '%s' is pending, ignoring: %s", u->service_job, bus_error_message(&error, r));
557 if (r != 0)
558 return false;
559 }
560
561 /* Note that we don't care if the three units we manage for each user object are up or not, as we are managing
562 * their state rather than tracking it. */
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 session’ or ‘display’. */
618 assert(s);
619
620 return s->class == SESSION_USER && s->started && !s->stopping;
621 }
622
623 static int elect_display_compare(Session *s1, Session *s2) {
624 /* Indexed by SessionType. Lower numbers mean more preferred. */
625 const int type_ranks[_SESSION_TYPE_MAX] = {
626 [SESSION_UNSPECIFIED] = 0,
627 [SESSION_TTY] = -2,
628 [SESSION_X11] = -3,
629 [SESSION_WAYLAND] = -3,
630 [SESSION_MIR] = -3,
631 [SESSION_WEB] = -1,
632 };
633
634 /* Calculate the partial order relationship between s1 and s2,
635 * returning < 0 if s1 is preferred as the user’s ‘primary session’,
636 * 0 if s1 and s2 are equally preferred or incomparable, or > 0 if s2
637 * is preferred.
638 *
639 * s1 or s2 may be NULL. */
640 if (!s1 && !s2)
641 return 0;
642
643 if ((s1 == NULL) != (s2 == NULL))
644 return (s1 == NULL) - (s2 == NULL);
645
646 if (s1->stopping != s2->stopping)
647 return s1->stopping - s2->stopping;
648
649 if ((s1->class != SESSION_USER) != (s2->class != SESSION_USER))
650 return (s1->class != SESSION_USER) - (s2->class != SESSION_USER);
651
652 if ((s1->type == _SESSION_TYPE_INVALID) != (s2->type == _SESSION_TYPE_INVALID))
653 return (s1->type == _SESSION_TYPE_INVALID) - (s2->type == _SESSION_TYPE_INVALID);
654
655 if (s1->type != s2->type)
656 return type_ranks[s1->type] - type_ranks[s2->type];
657
658 return 0;
659 }
660
661 void user_elect_display(User *u) {
662 Session *s;
663
664 assert(u);
665
666 /* This elects a primary session for each user, which we call the "display". We try to keep the assignment
667 * stable, but we "upgrade" to better choices. */
668 log_debug("Electing new display for user %s", u->name);
669
670 LIST_FOREACH(sessions_by_user, s, u->sessions) {
671 if (!elect_display_filter(s)) {
672 log_debug("Ignoring session %s", s->id);
673 continue;
674 }
675
676 if (elect_display_compare(s, u->display) < 0) {
677 log_debug("Choosing session %s in preference to %s", s->id, u->display ? u->display->id : "-");
678 u->display = s;
679 }
680 }
681 }
682
683 static const char* const user_state_table[_USER_STATE_MAX] = {
684 [USER_OFFLINE] = "offline",
685 [USER_OPENING] = "opening",
686 [USER_LINGERING] = "lingering",
687 [USER_ONLINE] = "online",
688 [USER_ACTIVE] = "active",
689 [USER_CLOSING] = "closing"
690 };
691
692 DEFINE_STRING_TABLE_LOOKUP(user_state, UserState);
693
694 int config_parse_tmpfs_size(
695 const char* unit,
696 const char *filename,
697 unsigned line,
698 const char *section,
699 unsigned section_line,
700 const char *lvalue,
701 int ltype,
702 const char *rvalue,
703 void *data,
704 void *userdata) {
705
706 uint64_t *sz = data;
707 int r;
708
709 assert(filename);
710 assert(lvalue);
711 assert(rvalue);
712 assert(data);
713
714 /* First, try to parse as percentage */
715 r = parse_permille(rvalue);
716 if (r > 0 && r < 1000)
717 *sz = physical_memory_scale(r, 1000U);
718 else {
719 uint64_t k;
720
721 /* If the passed argument was not a percentage, or out of range, parse as byte size */
722
723 r = parse_size(rvalue, 1024, &k);
724 if (r >= 0 && (k <= 0 || (uint64_t) (size_t) k != k))
725 r = -ERANGE;
726 if (r < 0) {
727 log_syntax(unit, LOG_ERR, filename, line, r, "Failed to parse size value '%s', ignoring: %m", 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.d/50-limits.conf with:\n"
758 " [Slice]\n"
759 " TasksMax=%s",
760 rvalue);
761 return 0;
762 }