chiark / gitweb /
edfbf874304de64912844c5399a6d0fb981cfe8d
[elogind.git] / src / login / logind-seat.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3   Copyright 2011 Lennart Poettering
4 ***/
5
6 #include <errno.h>
7 #include <fcntl.h>
8 #include <stdio_ext.h>
9 #include <string.h>
10 #include <unistd.h>
11
12 #include "sd-messages.h"
13
14 #include "alloc-util.h"
15 #include "fd-util.h"
16 #include "fileio.h"
17 #include "format-util.h"
18 #include "logind-acl.h"
19 #include "logind-seat.h"
20 #include "mkdir.h"
21 #include "parse-util.h"
22 #include "stdio-util.h"
23 #include "string-util.h"
24 #include "terminal-util.h"
25 #include "util.h"
26
27 Seat *seat_new(Manager *m, const char *id) {
28         Seat *s;
29
30         assert(m);
31         assert(id);
32
33         s = new0(Seat, 1);
34         if (!s)
35                 return NULL;
36
37         s->state_file = strappend("/run/systemd/seats/", id);
38         if (!s->state_file)
39                 return mfree(s);
40
41         s->id = basename(s->state_file);
42         s->manager = m;
43
44         if (hashmap_put(m->seats, s->id, s) < 0) {
45                 free(s->state_file);
46                 return mfree(s);
47         }
48
49         return s;
50 }
51
52 void seat_free(Seat *s) {
53         assert(s);
54
55         if (s->in_gc_queue)
56                 LIST_REMOVE(gc_queue, s->manager->seat_gc_queue, s);
57
58         while (s->sessions)
59                 session_free(s->sessions);
60
61         assert(!s->active);
62
63         while (s->devices)
64                 device_free(s->devices);
65
66         hashmap_remove(s->manager->seats, s->id);
67
68         free(s->positions);
69         free(s->state_file);
70         free(s);
71 }
72
73 int seat_save(Seat *s) {
74         _cleanup_free_ char *temp_path = NULL;
75         _cleanup_fclose_ FILE *f = NULL;
76         int r;
77
78         assert(s);
79
80         if (!s->started)
81                 return 0;
82
83         r = mkdir_safe_label("/run/systemd/seats", 0755, 0, 0, MKDIR_WARN_MODE);
84         if (r < 0)
85                 goto fail;
86
87         r = fopen_temporary(s->state_file, &f, &temp_path);
88         if (r < 0)
89                 goto fail;
90
91         (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
92         (void) fchmod(fileno(f), 0644);
93
94         fprintf(f,
95                 "# This is private data. Do not parse.\n"
96                 "IS_SEAT0=%i\n"
97                 "CAN_MULTI_SESSION=%i\n"
98                 "CAN_TTY=%i\n"
99                 "CAN_GRAPHICAL=%i\n",
100                 seat_is_seat0(s),
101                 seat_can_multi_session(s),
102                 seat_can_tty(s),
103                 seat_can_graphical(s));
104
105         if (s->active) {
106                 assert(s->active->user);
107
108                 fprintf(f,
109                         "ACTIVE=%s\n"
110                         "ACTIVE_UID="UID_FMT"\n",
111                         s->active->id,
112                         s->active->user->uid);
113         }
114
115         if (s->sessions) {
116                 Session *i;
117
118                 fputs("SESSIONS=", f);
119                 LIST_FOREACH(sessions_by_seat, i, s->sessions) {
120                         fprintf(f,
121                                 "%s%c",
122                                 i->id,
123                                 i->sessions_by_seat_next ? ' ' : '\n');
124                 }
125
126                 fputs("UIDS=", f);
127                 LIST_FOREACH(sessions_by_seat, i, s->sessions)
128                         fprintf(f,
129                                 UID_FMT"%c",
130                                 i->user->uid,
131                                 i->sessions_by_seat_next ? ' ' : '\n');
132         }
133
134         r = fflush_and_check(f);
135         if (r < 0)
136                 goto fail;
137
138         if (rename(temp_path, s->state_file) < 0) {
139                 r = -errno;
140                 goto fail;
141         }
142
143         return 0;
144
145 fail:
146         (void) unlink(s->state_file);
147
148         if (temp_path)
149                 (void) unlink(temp_path);
150
151         return log_error_errno(r, "Failed to save seat data %s: %m", s->state_file);
152 }
153
154 int seat_load(Seat *s) {
155         assert(s);
156
157         /* There isn't actually anything to read here ... */
158
159         return 0;
160 }
161
162 #if 0 /// UNNEEDED by elogind
163 static int vt_allocate(unsigned int vtnr) {
164         char p[sizeof("/dev/tty") + DECIMAL_STR_MAX(unsigned int)];
165         _cleanup_close_ int fd = -1;
166
167         assert(vtnr >= 1);
168
169         xsprintf(p, "/dev/tty%u", vtnr);
170         fd = open_terminal(p, O_RDWR|O_NOCTTY|O_CLOEXEC);
171         if (fd < 0)
172                 return -errno;
173
174         return 0;
175 }
176
177 int seat_preallocate_vts(Seat *s) {
178         int r = 0;
179         unsigned i;
180
181         assert(s);
182         assert(s->manager);
183
184         log_debug("Preallocating VTs...");
185
186         if (s->manager->n_autovts <= 0)
187                 return 0;
188
189         if (!seat_has_vts(s))
190                 return 0;
191
192         for (i = 1; i <= s->manager->n_autovts; i++) {
193                 int q;
194
195                 q = vt_allocate(i);
196                 if (q < 0) {
197                         log_error_errno(q, "Failed to preallocate VT %u: %m", i);
198                         r = q;
199                 }
200         }
201
202         return r;
203 }
204 #endif // 0
205
206 int seat_apply_acls(Seat *s, Session *old_active) {
207         int r;
208
209         assert(s);
210
211         r = devnode_acl_all(s->manager->udev,
212                             s->id,
213                             false,
214                             !!old_active, old_active ? old_active->user->uid : 0,
215                             !!s->active, s->active ? s->active->user->uid : 0);
216
217         if (r < 0)
218                 log_error_errno(r, "Failed to apply ACLs: %m");
219
220         return r;
221 }
222
223 int seat_set_active(Seat *s, Session *session) {
224         Session *old_active;
225
226         assert(s);
227         assert(!session || session->seat == s);
228
229         if (session == s->active)
230                 return 0;
231
232         old_active = s->active;
233         s->active = session;
234
235         if (old_active) {
236                 session_device_pause_all(old_active);
237                 session_send_changed(old_active, "Active", NULL);
238         }
239
240         seat_apply_acls(s, old_active);
241
242         if (session && session->started) {
243                 session_send_changed(session, "Active", NULL);
244                 session_device_resume_all(session);
245         }
246
247         if (!session || session->started)
248                 seat_send_changed(s, "ActiveSession", NULL);
249
250         seat_save(s);
251
252         if (session) {
253                 session_save(session);
254                 user_save(session->user);
255         }
256
257         if (old_active) {
258                 session_save(old_active);
259                 if (!session || session->user != old_active->user)
260                         user_save(old_active->user);
261         }
262
263         return 0;
264 }
265
266 int seat_switch_to(Seat *s, unsigned int num) {
267         /* Public session positions skip 0 (there is only F1-F12). Maybe it
268          * will get reassigned in the future, so return error for now. */
269         if (num == 0)
270                 return -EINVAL;
271
272         if (num >= s->position_count || !s->positions[num]) {
273                 /* allow switching to unused VTs to trigger auto-activate */
274                 if (seat_has_vts(s) && num < 64)
275                         return chvt(num);
276
277                 return -EINVAL;
278         }
279
280         return session_activate(s->positions[num]);
281 }
282
283 int seat_switch_to_next(Seat *s) {
284         unsigned int start, i;
285
286         if (s->position_count == 0)
287                 return -EINVAL;
288
289         start = 1;
290         if (s->active && s->active->position > 0)
291                 start = s->active->position;
292
293         for (i = start + 1; i < s->position_count; ++i)
294                 if (s->positions[i])
295                         return session_activate(s->positions[i]);
296
297         for (i = 1; i < start; ++i)
298                 if (s->positions[i])
299                         return session_activate(s->positions[i]);
300
301         return -EINVAL;
302 }
303
304 int seat_switch_to_previous(Seat *s) {
305         unsigned int start, i;
306
307         if (s->position_count == 0)
308                 return -EINVAL;
309
310         start = 1;
311         if (s->active && s->active->position > 0)
312                 start = s->active->position;
313
314         for (i = start - 1; i > 0; --i)
315                 if (s->positions[i])
316                         return session_activate(s->positions[i]);
317
318         for (i = s->position_count - 1; i > start; --i)
319                 if (s->positions[i])
320                         return session_activate(s->positions[i]);
321
322         return -EINVAL;
323 }
324
325 int seat_active_vt_changed(Seat *s, unsigned int vtnr) {
326         Session *i, *new_active = NULL;
327         int r;
328
329         assert(s);
330         assert(vtnr >= 1);
331
332         if (!seat_has_vts(s))
333                 return -EINVAL;
334
335         log_debug("VT changed to %u", vtnr);
336
337         /* we might have earlier closing sessions on the same VT, so try to
338          * find a running one first */
339         LIST_FOREACH(sessions_by_seat, i, s->sessions)
340                 if (i->vtnr == vtnr && !i->stopping) {
341                         new_active = i;
342                         break;
343                 }
344
345         if (!new_active) {
346                 /* no running one? then we can't decide which one is the
347                  * active one, let the first one win */
348                 LIST_FOREACH(sessions_by_seat, i, s->sessions)
349                         if (i->vtnr == vtnr) {
350                                 new_active = i;
351                                 break;
352                         }
353         }
354
355         r = seat_set_active(s, new_active);
356 #if 0 /// elogind does not spawn autovt
357         manager_spawn_autovt(s->manager, vtnr);
358 #endif // 0
359
360         return r;
361 }
362
363 int seat_read_active_vt(Seat *s) {
364         char t[64];
365         ssize_t k;
366         unsigned int vtnr;
367         int r;
368
369         assert(s);
370
371         if (!seat_has_vts(s))
372                 return 0;
373
374         if (lseek(s->manager->console_active_fd, SEEK_SET, 0) < 0)
375                 return log_error_errno(errno, "lseek on console_active_fd failed: %m");
376
377         k = read(s->manager->console_active_fd, t, sizeof(t)-1);
378         if (k <= 0) {
379                 log_error("Failed to read current console: %s", k < 0 ? strerror(-errno) : "EOF");
380                 return k < 0 ? -errno : -EIO;
381         }
382
383         t[k] = 0;
384         truncate_nl(t);
385
386         if (!startswith(t, "tty")) {
387                 log_error("Hm, /sys/class/tty/tty0/active is badly formatted.");
388                 return -EIO;
389         }
390
391         r = safe_atou(t+3, &vtnr);
392         if (r < 0)
393                 return log_error_errno(r, "Failed to parse VT number \"%s\": %m", t+3);
394
395         if (!vtnr) {
396                 log_error("VT number invalid: %s", t+3);
397                 return -EIO;
398         }
399
400         return seat_active_vt_changed(s, vtnr);
401 }
402
403 int seat_start(Seat *s) {
404         assert(s);
405
406         if (s->started)
407                 return 0;
408
409         log_struct(LOG_INFO,
410                    "MESSAGE_ID=" SD_MESSAGE_SEAT_START_STR,
411                    "SEAT_ID=%s", s->id,
412                    LOG_MESSAGE("New seat %s.", s->id));
413
414         /* Initialize VT magic stuff */
415 #if 0 /// elogind does not support autospawning vts
416         seat_preallocate_vts(s);
417 #endif // 0
418
419         /* Read current VT */
420         seat_read_active_vt(s);
421
422         s->started = true;
423
424         /* Save seat data */
425         seat_save(s);
426
427         seat_send_signal(s, true);
428
429         return 0;
430 }
431
432 int seat_stop(Seat *s, bool force) {
433         int r = 0;
434
435         assert(s);
436
437         if (s->started)
438                 log_struct(LOG_INFO,
439                            "MESSAGE_ID=" SD_MESSAGE_SEAT_STOP_STR,
440                            "SEAT_ID=%s", s->id,
441                            LOG_MESSAGE("Removed seat %s.", s->id));
442
443         seat_stop_sessions(s, force);
444
445         unlink(s->state_file);
446         seat_add_to_gc_queue(s);
447
448         if (s->started)
449                 seat_send_signal(s, false);
450
451         s->started = false;
452
453         return r;
454 }
455
456 int seat_stop_sessions(Seat *s, bool force) {
457         Session *session;
458         int r = 0, k;
459
460         assert(s);
461
462         LIST_FOREACH(sessions_by_seat, session, s->sessions) {
463                 k = session_stop(session, force);
464                 if (k < 0)
465                         r = k;
466         }
467
468         return r;
469 }
470
471 void seat_evict_position(Seat *s, Session *session) {
472         Session *iter;
473         unsigned int pos = session->position;
474
475         session->position = 0;
476
477         if (pos == 0)
478                 return;
479
480         if (pos < s->position_count && s->positions[pos] == session) {
481                 s->positions[pos] = NULL;
482
483                 /* There might be another session claiming the same
484                  * position (eg., during gdm->session transition), so let's look
485                  * for it and set it on the free slot. */
486                 LIST_FOREACH(sessions_by_seat, iter, s->sessions) {
487                         if (iter->position == pos && session_get_state(iter) != SESSION_CLOSING) {
488                                 s->positions[pos] = iter;
489                                 break;
490                         }
491                 }
492         }
493 }
494
495 void seat_claim_position(Seat *s, Session *session, unsigned int pos) {
496         /* with VTs, the position is always the same as the VTnr */
497         if (seat_has_vts(s))
498                 pos = session->vtnr;
499
500         if (!GREEDY_REALLOC0(s->positions, s->position_count, pos + 1))
501                 return;
502
503         seat_evict_position(s, session);
504
505         session->position = pos;
506         if (pos > 0)
507                 s->positions[pos] = session;
508 }
509
510 static void seat_assign_position(Seat *s, Session *session) {
511         unsigned int pos;
512
513         if (session->position > 0)
514                 return;
515
516         for (pos = 1; pos < s->position_count; ++pos)
517                 if (!s->positions[pos])
518                         break;
519
520         seat_claim_position(s, session, pos);
521 }
522
523 int seat_attach_session(Seat *s, Session *session) {
524         assert(s);
525         assert(session);
526         assert(!session->seat);
527
528         if (!seat_has_vts(s) != !session->vtnr)
529                 return -EINVAL;
530
531         session->seat = s;
532         LIST_PREPEND(sessions_by_seat, s->sessions, session);
533         seat_assign_position(s, session);
534
535         /* On seats with VTs, the VT logic defines which session is active. On
536          * seats without VTs, we automatically activate new sessions. */
537         if (!seat_has_vts(s))
538                 seat_set_active(s, session);
539
540         return 0;
541 }
542
543 void seat_complete_switch(Seat *s) {
544         Session *session;
545
546         assert(s);
547
548         /* if no session-switch is pending or if it got canceled, do nothing */
549         if (!s->pending_switch)
550                 return;
551
552         session = TAKE_PTR(s->pending_switch);
553
554         seat_set_active(s, session);
555 }
556
557 bool seat_has_vts(Seat *s) {
558         assert(s);
559
560         return seat_is_seat0(s) && s->manager->console_active_fd >= 0;
561 }
562
563 bool seat_is_seat0(Seat *s) {
564         assert(s);
565
566         return s->manager->seat0 == s;
567 }
568
569 bool seat_can_multi_session(Seat *s) {
570         assert(s);
571
572         return seat_has_vts(s);
573 }
574
575 bool seat_can_tty(Seat *s) {
576         assert(s);
577
578         return seat_has_vts(s);
579 }
580
581 bool seat_has_master_device(Seat *s) {
582         assert(s);
583
584         /* device list is ordered by "master" flag */
585         return !!s->devices && s->devices->master;
586 }
587
588 bool seat_can_graphical(Seat *s) {
589         assert(s);
590
591         return seat_has_master_device(s);
592 }
593
594 int seat_get_idle_hint(Seat *s, dual_timestamp *t) {
595         Session *session;
596         bool idle_hint = true;
597         dual_timestamp ts = DUAL_TIMESTAMP_NULL;
598
599         assert(s);
600
601         LIST_FOREACH(sessions_by_seat, session, s->sessions) {
602                 dual_timestamp k;
603                 int ih;
604
605                 ih = session_get_idle_hint(session, &k);
606                 if (ih < 0)
607                         return ih;
608
609                 if (!ih) {
610                         if (!idle_hint) {
611                                 if (k.monotonic > ts.monotonic)
612                                         ts = k;
613                         } else {
614                                 idle_hint = false;
615                                 ts = k;
616                         }
617                 } else if (idle_hint) {
618
619                         if (k.monotonic > ts.monotonic)
620                                 ts = k;
621                 }
622         }
623
624         if (t)
625                 *t = ts;
626
627         return idle_hint;
628 }
629
630 bool seat_may_gc(Seat *s, bool drop_not_started) {
631         assert(s);
632
633         if (drop_not_started && !s->started)
634                 return true;
635
636         if (seat_is_seat0(s))
637                 return false;
638
639         return !seat_has_master_device(s);
640 }
641
642 void seat_add_to_gc_queue(Seat *s) {
643         assert(s);
644
645         if (s->in_gc_queue)
646                 return;
647
648         LIST_PREPEND(gc_queue, s->manager->seat_gc_queue, s);
649         s->in_gc_queue = true;
650 }
651
652 static bool seat_name_valid_char(char c) {
653         return
654                 (c >= 'a' && c <= 'z') ||
655                 (c >= 'A' && c <= 'Z') ||
656                 (c >= '0' && c <= '9') ||
657                 IN_SET(c, '-', '_');
658 }
659
660 bool seat_name_is_valid(const char *name) {
661         const char *p;
662
663         assert(name);
664
665         if (!startswith(name, "seat"))
666                 return false;
667
668         if (!name[4])
669                 return false;
670
671         for (p = name; *p; p++)
672                 if (!seat_name_valid_char(*p))
673                         return false;
674
675         if (strlen(name) > 255)
676                 return false;
677
678         return true;
679 }