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