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