chiark / gitweb /
tree-wide: remove Lennart's copyright lines
[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
320 #if 0 /// elogind can not ask systemd via dbus to start user services
321 #else
322         assert(u);
323
324         hashmap_put(u->manager->user_units, u->slice, u);
325 #endif // 0
326 static int user_start_service(User *u) {
327 #if 0 /// elogind can not ask systemd via dbus to start user services
328         _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
329         char *job;
330         int r;
331
332         assert(u);
333
334         u->service_job = mfree(u->service_job);
335
336         r = manager_start_unit(
337                         u->manager,
338                         u->service,
339                         &error,
340                         &job);
341         if (r < 0)
342                 /* we don't fail due to this, let's try to continue */
343                 log_error_errno(r, "Failed to start user service, ignoring: %s", bus_error_message(&error, r));
344         else
345                 u->service_job = job;
346 #else
347         assert(u);
348
349         hashmap_put(u->manager->user_units, u->service, u);
350 #endif // 0
351
352         return 0;
353 }
354
355 int user_start(User *u) {
356         int r;
357
358         assert(u);
359
360         if (u->started && !u->stopping)
361                 return 0;
362
363         /*
364          * If u->stopping is set, the user is marked for removal and the slice
365          * and service stop-jobs are queued. We have to clear that flag before
366          * queing the start-jobs again. If they succeed, the user object can be
367          * re-used just fine (pid1 takes care of job-ordering and proper
368          * restart), but if they fail, we want to force another user_stop() so
369          * possibly pending units are stopped.
370          * Note that we don't clear u->started, as we have no clue what state
371          * the user is in on failure here. Hence, we pretend the user is
372          * running so it will be properly taken down by GC. However, we clearly
373          * return an error from user_start() in that case, so no further
374          * reference to the user is taken.
375          */
376         u->stopping = false;
377
378         if (!u->started)
379                 log_debug("Starting services for new user %s.", u->name);
380
381         /* Save the user data so far, because pam_systemd will read the
382          * XDG_RUNTIME_DIR out of it while starting up systemd --user.
383          * We need to do user_save_internal() because we have not
384          * "officially" started yet. */
385         user_save_internal(u);
386
387         /* Spawn user systemd */
388         r = user_start_service(u);
389         if (r < 0)
390                 return r;
391
392         if (!u->started) {
393                 if (!dual_timestamp_is_set(&u->timestamp))
394                         dual_timestamp_get(&u->timestamp);
395                 user_send_signal(u, true);
396                 u->started = true;
397         }
398
399         /* Save new user data */
400         user_save(u);
401
402         return 0;
403 }
404
405 #if 0 /// UNNEEDED by elogind
406 static int user_stop_slice(User *u) {
407         _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
408         char *job;
409         int r;
410
411         assert(u);
412
413         r = manager_stop_unit(u->manager, u->slice, &error, &job);
414         if (r < 0) {
415                 log_error("Failed to stop user slice: %s", bus_error_message(&error, r));
416                 return r;
417         }
418
419         free(u->slice_job);
420         u->slice_job = job;
421
422         return r;
423 }
424
425 static int user_stop_service(User *u) {
426         _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
427         char *job;
428         int r;
429
430         assert(u);
431
432         r = manager_stop_unit(u->manager, u->service, &error, &job);
433         if (r < 0) {
434                 log_error("Failed to stop user service: %s", bus_error_message(&error, r));
435                 return r;
436         }
437
438         free_and_replace(u->service_job, job);
439         return r;
440 }
441 #endif // 0
442
443 int user_stop(User *u, bool force) {
444         Session *s;
445         int r = 0, k;
446         assert(u);
447
448         /* Stop jobs have already been queued */
449         if (u->stopping) {
450                 user_save(u);
451                 return r;
452         }
453
454         LIST_FOREACH(sessions_by_user, s, u->sessions) {
455                 k = session_stop(s, force);
456                 if (k < 0)
457                         r = k;
458         }
459
460         /* Kill systemd */
461 #if 0 /// elogind does not support service or slice jobs
462         k = user_stop_service(u);
463         if (k < 0)
464                 r = k;
465
466         /* Kill cgroup */
467         k = user_stop_slice(u);
468         if (k < 0)
469                 r = k;
470 #endif // 0
471
472         u->stopping = true;
473
474         user_save(u);
475
476 #if 1 /// elogind must queue this user again
477         user_add_to_gc_queue(u);
478 #endif // 1
479         return r;
480 }
481
482 int user_finalize(User *u) {
483         Session *s;
484         int r = 0, k;
485
486         assert(u);
487
488         if (u->started)
489                 log_debug("User %s logged out.", u->name);
490
491         LIST_FOREACH(sessions_by_user, s, u->sessions) {
492                 k = session_finalize(s);
493                 if (k < 0)
494                         r = k;
495         }
496
497         /* Clean SysV + POSIX IPC objects, but only if this is not a system user. Background: in many setups cronjobs
498          * are run in full PAM and thus logind sessions, even if the code run doesn't belong to actual users but to
499          * system components. Since enable RemoveIPC= globally for all users, we need to be a bit careful with such
500          * cases, as we shouldn't accidentally remove a system service's IPC objects while it is running, just because
501          * a cronjob running as the same user just finished. Hence: exclude system users generally from IPC clean-up,
502          * and do it only for normal users. */
503         if (u->manager->remove_ipc && !uid_is_system(u->uid)) {
504                 k = clean_ipc_by_uid(u->uid);
505                 if (k < 0)
506                         r = k;
507         }
508
509         unlink(u->state_file);
510         user_add_to_gc_queue(u);
511
512         if (u->started) {
513                 user_send_signal(u, false);
514                 u->started = false;
515         }
516
517         return r;
518 }
519
520 int user_get_idle_hint(User *u, dual_timestamp *t) {
521         Session *s;
522         bool idle_hint = true;
523         dual_timestamp ts = DUAL_TIMESTAMP_NULL;
524
525         assert(u);
526
527         LIST_FOREACH(sessions_by_user, s, u->sessions) {
528                 dual_timestamp k;
529                 int ih;
530
531                 ih = session_get_idle_hint(s, &k);
532                 if (ih < 0)
533                         return ih;
534
535                 if (!ih) {
536                         if (!idle_hint) {
537                                 if (k.monotonic < ts.monotonic)
538                                         ts = k;
539                         } else {
540                                 idle_hint = false;
541                                 ts = k;
542                         }
543                 } else if (idle_hint) {
544
545                         if (k.monotonic > ts.monotonic)
546                                 ts = k;
547                 }
548         }
549
550         if (t)
551                 *t = ts;
552
553         return idle_hint;
554 }
555
556 int user_check_linger_file(User *u) {
557         _cleanup_free_ char *cc = NULL;
558         char *p = NULL;
559
560         cc = cescape(u->name);
561         if (!cc)
562                 return -ENOMEM;
563
564         p = strjoina("/var/lib/elogind/linger/", cc);
565
566         return access(p, F_OK) >= 0;
567 }
568
569 bool user_may_gc(User *u, bool drop_not_started) {
570         assert(u);
571
572         if (drop_not_started && !u->started)
573                 return true;
574
575         if (u->sessions)
576                 return false;
577
578         if (user_check_linger_file(u) > 0)
579                 return false;
580
581 #if 0 /// elogind neither supports service nor slice jobs
582         if (u->slice_job && manager_job_is_active(u->manager, u->slice_job))
583                 return false;
584
585         if (u->service_job && manager_job_is_active(u->manager, u->service_job))
586                 return false;
587 #endif // 0
588
589         return true;
590 }
591
592 void user_add_to_gc_queue(User *u) {
593         assert(u);
594
595         if (u->in_gc_queue)
596                 return;
597
598         LIST_PREPEND(gc_queue, u->manager->user_gc_queue, u);
599         u->in_gc_queue = true;
600 }
601
602 UserState user_get_state(User *u) {
603         Session *i;
604
605         assert(u);
606
607         if (u->stopping)
608                 return USER_CLOSING;
609
610 #if 0 /// elogind neither supports service nor slice jobs.
611         if (!u->started || u->slice_job || u->service_job)
612 #else
613         if (!u->started)
614 #endif // 0
615                 return USER_OPENING;
616
617         if (u->sessions) {
618                 bool all_closing = true;
619
620                 LIST_FOREACH(sessions_by_user, i, u->sessions) {
621                         SessionState state;
622
623                         state = session_get_state(i);
624                         if (state == SESSION_ACTIVE)
625                                 return USER_ACTIVE;
626                         if (state != SESSION_CLOSING)
627                                 all_closing = false;
628                 }
629
630                 return all_closing ? USER_CLOSING : USER_ONLINE;
631         }
632
633         if (user_check_linger_file(u) > 0)
634                 return USER_LINGERING;
635
636         return USER_CLOSING;
637 }
638
639 int user_kill(User *u, int signo) {
640 #if 0 /// Without systemd unit support, elogind has to rely on its session system
641         assert(u);
642
643         return manager_kill_unit(u->manager, u->slice, KILL_ALL, signo, NULL);
644 #else
645         Session *s;
646         int res = 0;
647
648         assert(u);
649
650         LIST_FOREACH(sessions_by_user, s, u->sessions) {
651                 int r = session_kill(s, KILL_ALL, signo);
652                 if (res == 0 && r < 0)
653                         res = r;
654         }
655
656         return res;
657 #endif // 0
658 }
659
660 static bool elect_display_filter(Session *s) {
661         /* Return true if the session is a candidate for the user’s ‘primary
662          * session’ or ‘display’. */
663         assert(s);
664
665         return (s->class == SESSION_USER && !s->stopping);
666 }
667
668 static int elect_display_compare(Session *s1, Session *s2) {
669         /* Indexed by SessionType. Lower numbers mean more preferred. */
670         const int type_ranks[_SESSION_TYPE_MAX] = {
671                 [SESSION_UNSPECIFIED] = 0,
672                 [SESSION_TTY] = -2,
673                 [SESSION_X11] = -3,
674                 [SESSION_WAYLAND] = -3,
675                 [SESSION_MIR] = -3,
676                 [SESSION_WEB] = -1,
677         };
678
679         /* Calculate the partial order relationship between s1 and s2,
680          * returning < 0 if s1 is preferred as the user’s ‘primary session’,
681          * 0 if s1 and s2 are equally preferred or incomparable, or > 0 if s2
682          * is preferred.
683          *
684          * s1 or s2 may be NULL. */
685         if (!s1 && !s2)
686                 return 0;
687
688         if ((s1 == NULL) != (s2 == NULL))
689                 return (s1 == NULL) - (s2 == NULL);
690
691         if (s1->stopping != s2->stopping)
692                 return s1->stopping - s2->stopping;
693
694         if ((s1->class != SESSION_USER) != (s2->class != SESSION_USER))
695                 return (s1->class != SESSION_USER) - (s2->class != SESSION_USER);
696
697         if ((s1->type == _SESSION_TYPE_INVALID) != (s2->type == _SESSION_TYPE_INVALID))
698                 return (s1->type == _SESSION_TYPE_INVALID) - (s2->type == _SESSION_TYPE_INVALID);
699
700         if (s1->type != s2->type)
701                 return type_ranks[s1->type] - type_ranks[s2->type];
702
703         return 0;
704 }
705
706 void user_elect_display(User *u) {
707         Session *s;
708
709         assert(u);
710
711         /* This elects a primary session for each user, which we call
712          * the "display". We try to keep the assignment stable, but we
713          * "upgrade" to better choices. */
714         log_debug("Electing new display for user %s", u->name);
715
716         LIST_FOREACH(sessions_by_user, s, u->sessions) {
717                 if (!elect_display_filter(s)) {
718                         log_debug("Ignoring session %s", s->id);
719                         continue;
720                 }
721
722                 if (elect_display_compare(s, u->display) < 0) {
723                         log_debug("Choosing session %s in preference to %s", s->id, u->display ? u->display->id : "-");
724                         u->display = s;
725                 }
726         }
727 }
728
729 static const char* const user_state_table[_USER_STATE_MAX] = {
730         [USER_OFFLINE] = "offline",
731         [USER_OPENING] = "opening",
732         [USER_LINGERING] = "lingering",
733         [USER_ONLINE] = "online",
734         [USER_ACTIVE] = "active",
735         [USER_CLOSING] = "closing"
736 };
737
738 DEFINE_STRING_TABLE_LOOKUP(user_state, UserState);
739
740 int config_parse_tmpfs_size(
741                 const char* unit,
742                 const char *filename,
743                 unsigned line,
744                 const char *section,
745                 unsigned section_line,
746                 const char *lvalue,
747                 int ltype,
748                 const char *rvalue,
749                 void *data,
750                 void *userdata) {
751
752         uint64_t *sz = data;
753         int r;
754
755         assert(filename);
756         assert(lvalue);
757         assert(rvalue);
758         assert(data);
759
760         /* First, try to parse as percentage */
761         r = parse_percent(rvalue);
762         if (r > 0 && r < 100)
763                 *sz = physical_memory_scale(r, 100U);
764         else {
765                 uint64_t k;
766
767                 /* If the passed argument was not a percentage, or out of range, parse as byte size */
768
769                 r = parse_size(rvalue, 1024, &k);
770                 if (r < 0 || k <= 0 || (uint64_t) (size_t) k != k) {
771                         log_syntax(unit, LOG_ERR, filename, line, r, "Failed to parse size value, ignoring: %s", rvalue);
772                         return 0;
773                 }
774
775                 *sz = PAGE_ALIGN((size_t) k);
776         }
777
778         return 0;
779 }
780
781 int config_parse_compat_user_tasks_max(
782                 const char *unit,
783                 const char *filename,
784                 unsigned line,
785                 const char *section,
786                 unsigned section_line,
787                 const char *lvalue,
788                 int ltype,
789                 const char *rvalue,
790                 void *data,
791                 void *userdata) {
792
793         assert(filename);
794         assert(lvalue);
795         assert(rvalue);
796         assert(data);
797
798         log_syntax(unit, LOG_NOTICE, filename, line, 0,
799                    "Support for option %s= has been removed.",
800                    lvalue);
801         log_info("Hint: try creating /etc/elogind/system/user-.slice/50-limits.conf with:\n"
802                  "        [Slice]\n"
803                  "        TasksMax=%s",
804                  rvalue);
805         return 0;
806 }