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