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