]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/login/logind-user.c
logind: fix serialization/deserialization of user's "display session"
[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 *realtime = NULL, *monotonic = 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 "REALTIME", &realtime,
289 "MONOTONIC", &monotonic,
290 NULL);
291 if (r == -ENOENT)
292 return 0;
293 if (r < 0)
294 return log_error_errno(r, "Failed to read %s: %m", u->state_file);
295
296 if (realtime)
297 timestamp_deserialize(realtime, &u->timestamp.realtime);
298 if (monotonic)
299 timestamp_deserialize(monotonic, &u->timestamp.monotonic);
300
301 return r;
302 }
303
304 static int user_start_service(User *u) {
305 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
306 char *job;
307 int r;
308
309 assert(u);
310
311 u->service_job = mfree(u->service_job);
312
313 r = manager_start_unit(
314 u->manager,
315 u->service,
316 &error,
317 &job);
318 if (r < 0)
319 /* we don't fail due to this, let's try to continue */
320 log_error_errno(r, "Failed to start user service, ignoring: %s", bus_error_message(&error, r));
321 else
322 u->service_job = job;
323
324 return 0;
325 }
326
327 int user_start(User *u) {
328 int r;
329
330 assert(u);
331
332 if (u->started && !u->stopping)
333 return 0;
334
335 /*
336 * If u->stopping is set, the user is marked for removal and the slice
337 * and service stop-jobs are queued. We have to clear that flag before
338 * queing the start-jobs again. If they succeed, the user object can be
339 * re-used just fine (pid1 takes care of job-ordering and proper
340 * restart), but if they fail, we want to force another user_stop() so
341 * possibly pending units are stopped.
342 * Note that we don't clear u->started, as we have no clue what state
343 * the user is in on failure here. Hence, we pretend the user is
344 * running so it will be properly taken down by GC. However, we clearly
345 * return an error from user_start() in that case, so no further
346 * reference to the user is taken.
347 */
348 u->stopping = false;
349
350 if (!u->started)
351 log_debug("Starting services for new user %s.", u->name);
352
353 /* Save the user data so far, because pam_systemd will read the
354 * XDG_RUNTIME_DIR out of it while starting up systemd --user.
355 * We need to do user_save_internal() because we have not
356 * "officially" started yet. */
357 user_save_internal(u);
358
359 /* Spawn user systemd */
360 r = user_start_service(u);
361 if (r < 0)
362 return r;
363
364 if (!u->started) {
365 if (!dual_timestamp_is_set(&u->timestamp))
366 dual_timestamp_get(&u->timestamp);
367 user_send_signal(u, true);
368 u->started = true;
369 }
370
371 /* Save new user data */
372 user_save(u);
373
374 return 0;
375 }
376
377 static int user_stop_slice(User *u) {
378 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
379 char *job;
380 int r;
381
382 assert(u);
383
384 r = manager_stop_unit(u->manager, u->slice, &error, &job);
385 if (r < 0)
386 return log_error_errno(r, "Failed to stop user slice: %s", bus_error_message(&error, r));
387
388 return free_and_replace(u->slice_job, job);
389 }
390
391 static int user_stop_service(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->service, &error, &job);
399 if (r < 0)
400 return log_error_errno(r, "Failed to stop user service: %s", bus_error_message(&error, r));
401
402 return free_and_replace(u->service_job, job);
403 }
404
405 int user_stop(User *u, bool force) {
406 Session *s;
407 int r = 0, k;
408 assert(u);
409
410 /* Stop jobs have already been queued */
411 if (u->stopping) {
412 user_save(u);
413 return r;
414 }
415
416 LIST_FOREACH(sessions_by_user, s, u->sessions) {
417 k = session_stop(s, force);
418 if (k < 0)
419 r = k;
420 }
421
422 /* Kill systemd */
423 k = user_stop_service(u);
424 if (k < 0)
425 r = k;
426
427 /* Kill cgroup */
428 k = user_stop_slice(u);
429 if (k < 0)
430 r = k;
431
432 u->stopping = true;
433
434 user_save(u);
435
436 return r;
437 }
438
439 int user_finalize(User *u) {
440 Session *s;
441 int r = 0, k;
442
443 assert(u);
444
445 if (u->started)
446 log_debug("User %s logged out.", u->name);
447
448 LIST_FOREACH(sessions_by_user, s, u->sessions) {
449 k = session_finalize(s);
450 if (k < 0)
451 r = k;
452 }
453
454 /* Clean SysV + POSIX IPC objects, but only if this is not a system user. Background: in many setups cronjobs
455 * are run in full PAM and thus logind sessions, even if the code run doesn't belong to actual users but to
456 * system components. Since enable RemoveIPC= globally for all users, we need to be a bit careful with such
457 * cases, as we shouldn't accidentally remove a system service's IPC objects while it is running, just because
458 * a cronjob running as the same user just finished. Hence: exclude system users generally from IPC clean-up,
459 * and do it only for normal users. */
460 if (u->manager->remove_ipc && !uid_is_system(u->uid)) {
461 k = clean_ipc_by_uid(u->uid);
462 if (k < 0)
463 r = k;
464 }
465
466 unlink(u->state_file);
467 user_add_to_gc_queue(u);
468
469 if (u->started) {
470 user_send_signal(u, false);
471 u->started = false;
472 }
473
474 return r;
475 }
476
477 int user_get_idle_hint(User *u, dual_timestamp *t) {
478 Session *s;
479 bool idle_hint = true;
480 dual_timestamp ts = DUAL_TIMESTAMP_NULL;
481
482 assert(u);
483
484 LIST_FOREACH(sessions_by_user, s, u->sessions) {
485 dual_timestamp k;
486 int ih;
487
488 ih = session_get_idle_hint(s, &k);
489 if (ih < 0)
490 return ih;
491
492 if (!ih) {
493 if (!idle_hint) {
494 if (k.monotonic < ts.monotonic)
495 ts = k;
496 } else {
497 idle_hint = false;
498 ts = k;
499 }
500 } else if (idle_hint) {
501
502 if (k.monotonic > ts.monotonic)
503 ts = k;
504 }
505 }
506
507 if (t)
508 *t = ts;
509
510 return idle_hint;
511 }
512
513 int user_check_linger_file(User *u) {
514 _cleanup_free_ char *cc = NULL;
515 char *p = NULL;
516
517 cc = cescape(u->name);
518 if (!cc)
519 return -ENOMEM;
520
521 p = strjoina("/var/lib/systemd/linger/", cc);
522
523 return access(p, F_OK) >= 0;
524 }
525
526 bool user_may_gc(User *u, bool drop_not_started) {
527 assert(u);
528
529 if (drop_not_started && !u->started)
530 return true;
531
532 if (u->sessions)
533 return false;
534
535 if (user_check_linger_file(u) > 0)
536 return false;
537
538 if (u->slice_job && manager_job_is_active(u->manager, u->slice_job))
539 return false;
540
541 if (u->service_job && manager_job_is_active(u->manager, u->service_job))
542 return false;
543
544 return true;
545 }
546
547 void user_add_to_gc_queue(User *u) {
548 assert(u);
549
550 if (u->in_gc_queue)
551 return;
552
553 LIST_PREPEND(gc_queue, u->manager->user_gc_queue, u);
554 u->in_gc_queue = true;
555 }
556
557 UserState user_get_state(User *u) {
558 Session *i;
559
560 assert(u);
561
562 if (u->stopping)
563 return USER_CLOSING;
564
565 if (!u->started || u->slice_job || u->service_job)
566 return USER_OPENING;
567
568 if (u->sessions) {
569 bool all_closing = true;
570
571 LIST_FOREACH(sessions_by_user, i, u->sessions) {
572 SessionState state;
573
574 state = session_get_state(i);
575 if (state == SESSION_ACTIVE)
576 return USER_ACTIVE;
577 if (state != SESSION_CLOSING)
578 all_closing = false;
579 }
580
581 return all_closing ? USER_CLOSING : USER_ONLINE;
582 }
583
584 if (user_check_linger_file(u) > 0)
585 return USER_LINGERING;
586
587 return USER_CLOSING;
588 }
589
590 int user_kill(User *u, int signo) {
591 assert(u);
592
593 return manager_kill_unit(u->manager, u->slice, KILL_ALL, signo, NULL);
594 }
595
596 static bool elect_display_filter(Session *s) {
597 /* Return true if the session is a candidate for the user’s ‘primary
598 * session’ or ‘display’. */
599 assert(s);
600
601 return (s->class == SESSION_USER && !s->stopping);
602 }
603
604 static int elect_display_compare(Session *s1, Session *s2) {
605 /* Indexed by SessionType. Lower numbers mean more preferred. */
606 const int type_ranks[_SESSION_TYPE_MAX] = {
607 [SESSION_UNSPECIFIED] = 0,
608 [SESSION_TTY] = -2,
609 [SESSION_X11] = -3,
610 [SESSION_WAYLAND] = -3,
611 [SESSION_MIR] = -3,
612 [SESSION_WEB] = -1,
613 };
614
615 /* Calculate the partial order relationship between s1 and s2,
616 * returning < 0 if s1 is preferred as the user’s ‘primary session’,
617 * 0 if s1 and s2 are equally preferred or incomparable, or > 0 if s2
618 * is preferred.
619 *
620 * s1 or s2 may be NULL. */
621 if (!s1 && !s2)
622 return 0;
623
624 if ((s1 == NULL) != (s2 == NULL))
625 return (s1 == NULL) - (s2 == NULL);
626
627 if (s1->stopping != s2->stopping)
628 return s1->stopping - s2->stopping;
629
630 if ((s1->class != SESSION_USER) != (s2->class != SESSION_USER))
631 return (s1->class != SESSION_USER) - (s2->class != SESSION_USER);
632
633 if ((s1->type == _SESSION_TYPE_INVALID) != (s2->type == _SESSION_TYPE_INVALID))
634 return (s1->type == _SESSION_TYPE_INVALID) - (s2->type == _SESSION_TYPE_INVALID);
635
636 if (s1->type != s2->type)
637 return type_ranks[s1->type] - type_ranks[s2->type];
638
639 return 0;
640 }
641
642 void user_elect_display(User *u) {
643 Session *s;
644
645 assert(u);
646
647 /* This elects a primary session for each user, which we call
648 * the "display". We try to keep the assignment stable, but we
649 * "upgrade" to better choices. */
650 log_debug("Electing new display for user %s", u->name);
651
652 LIST_FOREACH(sessions_by_user, s, u->sessions) {
653 if (!elect_display_filter(s)) {
654 log_debug("Ignoring session %s", s->id);
655 continue;
656 }
657
658 if (elect_display_compare(s, u->display) < 0) {
659 log_debug("Choosing session %s in preference to %s", s->id, u->display ? u->display->id : "-");
660 u->display = s;
661 }
662 }
663 }
664
665 static const char* const user_state_table[_USER_STATE_MAX] = {
666 [USER_OFFLINE] = "offline",
667 [USER_OPENING] = "opening",
668 [USER_LINGERING] = "lingering",
669 [USER_ONLINE] = "online",
670 [USER_ACTIVE] = "active",
671 [USER_CLOSING] = "closing"
672 };
673
674 DEFINE_STRING_TABLE_LOOKUP(user_state, UserState);
675
676 int config_parse_tmpfs_size(
677 const char* unit,
678 const char *filename,
679 unsigned line,
680 const char *section,
681 unsigned section_line,
682 const char *lvalue,
683 int ltype,
684 const char *rvalue,
685 void *data,
686 void *userdata) {
687
688 uint64_t *sz = data;
689 int r;
690
691 assert(filename);
692 assert(lvalue);
693 assert(rvalue);
694 assert(data);
695
696 /* First, try to parse as percentage */
697 r = parse_permille(rvalue);
698 if (r > 0 && r < 1000)
699 *sz = physical_memory_scale(r, 1000U);
700 else {
701 uint64_t k;
702
703 /* If the passed argument was not a percentage, or out of range, parse as byte size */
704
705 r = parse_size(rvalue, 1024, &k);
706 if (r >= 0 && (k <= 0 || (uint64_t) (size_t) k != k))
707 r = -ERANGE;
708 if (r < 0) {
709 log_syntax(unit, LOG_ERR, filename, line, r, "Failed to parse size value '%s', ignoring: %m", rvalue);
710 return 0;
711 }
712
713 *sz = PAGE_ALIGN((size_t) k);
714 }
715
716 return 0;
717 }
718
719 int config_parse_compat_user_tasks_max(
720 const char *unit,
721 const char *filename,
722 unsigned line,
723 const char *section,
724 unsigned section_line,
725 const char *lvalue,
726 int ltype,
727 const char *rvalue,
728 void *data,
729 void *userdata) {
730
731 assert(filename);
732 assert(lvalue);
733 assert(rvalue);
734 assert(data);
735
736 log_syntax(unit, LOG_NOTICE, filename, line, 0,
737 "Support for option %s= has been removed.",
738 lvalue);
739 log_info("Hint: try creating /etc/systemd/system/user-.slice.d/50-limits.conf with:\n"
740 " [Slice]\n"
741 " TasksMax=%s",
742 rvalue);
743 return 0;
744 }