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