Debian Codegraph @

src/shared/vconsole-util.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <stdlib.h>
4 #include <unistd.h>
5
6 #include "alloc-util.h"
7 #include "efivars.h"
8 #include "env-util.h"
9 #include "extract-word.h"
10 #include "fd-util.h"
11 #include "fileio.h"
12 #include "kbd-util.h"
13 #include "log.h"
14 #include "string-util.h"
15 #include "strv.h"
16 #include "vconsole-util.h"
17
18 static bool startswith_comma(const char *s, const char *prefix) {
19 assert(s);
20 assert(prefix);
21
22 s = startswith(s, prefix);
23 if (!s)
24 return false;
25
26 return IN_SET(*s, ',', '\0');
27 }
28
29 static const char* systemd_kbd_model_map(void) {
30 const char* s;
31
32 s = getenv("SYSTEMD_KBD_MODEL_MAP");
33 if (s)
34 return s;
35
36 return SYSTEMD_KBD_MODEL_MAP;
37 }
38
39 static const char* systemd_language_fallback_map(void) {
40 const char* s;
41
42 s = getenv("SYSTEMD_LANGUAGE_FALLBACK_MAP");
43 if (s)
44 return s;
45
46 return SYSTEMD_LANGUAGE_FALLBACK_MAP;
47 }
48
49 void x11_context_clear(X11Context *xc) {
50 assert(xc);
51
52 xc->layout = mfree(xc->layout);
53 xc->options = mfree(xc->options);
54 xc->model = mfree(xc->model);
55 xc->variant = mfree(xc->variant);
56 }
57
58 void x11_context_replace(X11Context *dest, X11Context *src) {
59 assert(dest);
60 assert(src);
61
62 x11_context_clear(dest);
63 *dest = TAKE_STRUCT(*src);
64 }
65
66 bool x11_context_isempty(const X11Context *xc) {
67 assert(xc);
68
69 return
70 isempty(xc->layout) &&
71 isempty(xc->model) &&
72 isempty(xc->variant) &&
73 isempty(xc->options);
74 }
75
76 void x11_context_empty_to_null(X11Context *xc) {
77 assert(xc);
78
79 /* Do not call x11_context_clear() for the passed object. */
80
81 xc->layout = empty_to_null(xc->layout);
82 xc->model = empty_to_null(xc->model);
83 xc->variant = empty_to_null(xc->variant);
84 xc->options = empty_to_null(xc->options);
85 }
86
87 bool x11_context_is_safe(const X11Context *xc) {
88 assert(xc);
89
90 return
91 (!xc->layout || string_is_safe(xc->layout, /* flags= */ 0)) &&
92 (!xc->model || string_is_safe(xc->model, /* flags= */ 0)) &&
93 (!xc->variant || string_is_safe(xc->variant, /* flags= */ 0)) &&
94 (!xc->options || string_is_safe(xc->options, /* flags= */ 0));
95 }
96
97 bool x11_context_equal(const X11Context *a, const X11Context *b) {
98 assert(a);
99 assert(b);
100
101 return
102 streq_ptr(a->layout, b->layout) &&
103 streq_ptr(a->model, b->model) &&
104 streq_ptr(a->variant, b->variant) &&
105 streq_ptr(a->options, b->options);
106 }
107
108 int x11_context_copy(X11Context *dest, const X11Context *src) {
109 bool modified;
110 int r;
111
112 assert(dest);
113
114 if (dest == src)
115 return 0;
116
117 if (!src) {
118 modified = !x11_context_isempty(dest);
119 x11_context_clear(dest);
120 return modified;
121 }
122
123 r = free_and_strdup(&dest->layout, src->layout);
124 if (r < 0)
125 return r;
126 modified = r > 0;
127
128 r = free_and_strdup(&dest->model, src->model);
129 if (r < 0)
130 return r;
131 modified = modified || r > 0;
132
133 r = free_and_strdup(&dest->variant, src->variant);
134 if (r < 0)
135 return r;
136 modified = modified || r > 0;
137
138 r = free_and_strdup(&dest->options, src->options);
139 if (r < 0)
140 return r;
141 modified = modified || r > 0;
142
143 return modified;
144 }
145
146 void vc_context_clear(VCContext *vc) {
147 assert(vc);
148
149 vc->keymap = mfree(vc->keymap);
150 vc->toggle = mfree(vc->toggle);
151 }
152
153 void vc_context_replace(VCContext *dest, VCContext *src) {
154 assert(dest);
155 assert(src);
156
157 vc_context_clear(dest);
158 *dest = TAKE_STRUCT(*src);
159 }
160
161 bool vc_context_isempty(const VCContext *vc) {
162 assert(vc);
163
164 return
165 isempty(vc->keymap) &&
166 isempty(vc->toggle);
167 }
168
169 void vc_context_empty_to_null(VCContext *vc) {
170 assert(vc);
171
172 /* Do not call vc_context_clear() for the passed object. */
173
174 vc->keymap = empty_to_null(vc->keymap);
175 vc->toggle = empty_to_null(vc->toggle);
176 }
177
178 bool vc_context_equal(const VCContext *a, const VCContext *b) {
179 assert(a);
180 assert(b);
181
182 return
183 streq_ptr(a->keymap, b->keymap) &&
184 streq_ptr(a->toggle, b->toggle);
185 }
186
187 int vc_context_copy(VCContext *dest, const VCContext *src) {
188 bool modified;
189 int r;
190
191 assert(dest);
192
193 if (dest == src)
194 return 0;
195
196 if (!src) {
197 modified = !vc_context_isempty(dest);
198 vc_context_clear(dest);
199 return modified;
200 }
201
202 r = free_and_strdup(&dest->keymap, src->keymap);
203 if (r < 0)
204 return r;
205 modified = r > 0;
206
207 r = free_and_strdup(&dest->toggle, src->toggle);
208 if (r < 0)
209 return r;
210 modified = modified || r > 0;
211
212 return modified;
213 }
214
215 static int read_next_mapping(
216 const char *filename,
217 unsigned min_fields,
218 unsigned max_fields,
219 FILE *f,
220 unsigned *n,
221 char ***ret) {
222
223 assert(f);
224 assert(n);
225 assert(ret);
226
227 for (;;) {
228 _cleanup_strv_free_ char **b = NULL;
229 _cleanup_free_ char *line = NULL;
230 size_t length;
231 int r;
232
233 r = read_stripped_line(f, LONG_LINE_MAX, &line);
234 if (r < 0)
235 return r;
236 if (r == 0)
237 break;
238
239 (*n)++;
240
241 if (IN_SET(line[0], 0, '#'))
242 continue;
243
244 r = strv_split_full(&b, line, WHITESPACE, EXTRACT_UNQUOTE);
245 if (r < 0)
246 return r;
247
248 length = strv_length(b);
249 if (length < min_fields || length > max_fields) {
250 log_debug("Invalid line %s:%u, ignoring.", strna(filename), *n);
251 continue;
252
253 }
254
255 *ret = TAKE_PTR(b);
256 return 1;
257 }
258
259 *ret = NULL;
260 return 0;
261 }
262
263 int vconsole_convert_to_x11(const VCContext *vc, X11VerifyCallback verify, X11Context *ret) {
264 _cleanup_fclose_ FILE *f = NULL;
265 const char *map;
266 X11Context xc;
267 int r;
268
269 assert(vc);
270 assert(ret);
271
272 if (isempty(vc->keymap)) {
273 *ret = (X11Context) {};
274 return 0;
275 }
276
277 map = systemd_kbd_model_map();
278 f = fopen(map, "re");
279 if (!f)
280 return -errno;
281
282 for (unsigned n = 0;;) {
283 _cleanup_strv_free_ char **a = NULL;
284
285 r = read_next_mapping(map, 5, UINT_MAX, f, &n, &a);
286 if (r < 0)
287 return r;
288 if (r == 0)
289 break;
290
291 if (!streq(vc->keymap, a[0]))
292 continue;
293
294 xc = (X11Context) {
295 .layout = empty_or_dash_to_null(a[1]),
296 .model = empty_or_dash_to_null(a[2]),
297 .variant = empty_or_dash_to_null(a[3]),
298 .options = empty_or_dash_to_null(a[4]),
299 };
300
301 if (verify && verify(&xc) < 0)
302 continue;
303
304 return x11_context_copy(ret, &xc);
305 }
306
307 /* No custom mapping has been found, see if the keymap is a converted one. In such case deducing the
308 * corresponding x11 layout is easy. */
309 _cleanup_free_ char *xlayout = NULL, *converted = NULL;
310 char *xvariant;
311
312 xlayout = strdup(vc->keymap);
313 if (!xlayout)
314 return -ENOMEM;
315 xvariant = strchr(xlayout, '-');
316 if (xvariant) {
317 xvariant[0] = '\0';
318 xvariant++;
319 }
320
321 /* Note: by default we use keyboard model "microsoftpro" which should be equivalent to "pc105" but
322 * with the internet/media key mapping added. */
323 xc = (X11Context) {
324 .layout = xlayout,
325 .model = (char*) "microsoftpro",
326 .variant = xvariant,
327 .options = (char*) "terminate:ctrl_alt_bksp",
328 };
329
330 /* This sanity check seems redundant with the verification of the X11 layout done on the next
331 * step. However xkbcommon is an optional dependency hence the verification might be a NOP. */
332 r = find_converted_keymap(&xc, &converted);
333 if (r == 0 && xc.variant) {
334 /* If we still haven't find a match, try with no variant, it's still better than nothing. */
335 xc.variant = NULL;
336 r = find_converted_keymap(&xc, &converted);
337 }
338 if (r < 0)
339 return r;
340
341 if (r == 0 || (verify && verify(&xc) < 0)) {
342 *ret = (X11Context) {};
343 return 0;
344 }
345
346 return x11_context_copy(ret, &xc);
347 }
348
349 int find_converted_keymap(const X11Context *xc, char **ret) {
350 _cleanup_free_ char *n = NULL, *p = NULL, *pz = NULL;
351 _cleanup_strv_free_ char **keymap_dirs = NULL;
352 int r;
353
354 assert(xc);
355 assert(!isempty(xc->layout));
356 assert(ret);
357
358 if (xc->variant)
359 n = strjoin(xc->layout, "-", xc->variant);
360 else
361 n = strdup(xc->layout);
362 if (!n)
363 return -ENOMEM;
364
365 p = strjoin("xkb/", n, ".map");
366 pz = strjoin("xkb/", n, ".map.gz");
367 if (!p || !pz)
368 return -ENOMEM;
369
370 r = keymap_directories(&keymap_dirs);
371 if (r < 0)
372 return r;
373
374 STRV_FOREACH(dir, keymap_dirs) {
375 _cleanup_close_ int dir_fd = -EBADF;
376 bool uncompressed;
377
378 dir_fd = open(*dir, O_CLOEXEC | O_DIRECTORY | O_PATH);
379 if (dir_fd < 0) {
380 if (errno != ENOENT)
381 log_debug_errno(errno, "Failed to open %s, ignoring: %m", *dir);
382 continue;
383 }
384
385 uncompressed = faccessat(dir_fd, p, F_OK, 0) >= 0;
386 if (uncompressed || faccessat(dir_fd, pz, F_OK, 0) >= 0) {
387 log_debug("Found converted keymap %s at %s/%s", n, *dir, uncompressed ? p : pz);
388 *ret = TAKE_PTR(n);
389 return 1;
390 }
391 }
392
393 *ret = NULL;
394 return 0;
395 }
396
397 int find_legacy_keymap(const X11Context *xc, char **ret) {
398 const char *map;
399 _cleanup_fclose_ FILE *f = NULL;
400 _cleanup_free_ char *new_keymap = NULL;
401 unsigned best_matching = 0;
402 int r;
403
404 assert(xc);
405 assert(!isempty(xc->layout));
406
407 map = systemd_kbd_model_map();
408 f = fopen(map, "re");
409 if (!f)
410 return -errno;
411
412 for (unsigned n = 0;;) {
413 _cleanup_strv_free_ char **a = NULL;
414 unsigned matching = 0;
415
416 r = read_next_mapping(map, 5, UINT_MAX, f, &n, &a);
417 if (r < 0)
418 return r;
419 if (r == 0)
420 break;
421
422 /* Determine how well matching this entry is */
423 if (streq(xc->layout, a[1]))
424 /* If we got an exact match, this is the best */
425 matching = 10;
426 else {
427 /* see if we get an exact match with the order reversed */
428 _cleanup_strv_free_ char **b = NULL;
429 _cleanup_free_ char *c = NULL;
430 r = strv_split_full(&b, a[1], ",", 0);
431 if (r < 0)
432 return r;
433 strv_reverse(b);
434 c = strv_join(b, ",");
435 if (!c)
436 return log_oom();
437 if (streq(xc->layout, c))
438 matching = 9;
439 else {
440 /* We have multiple X layouts, look for an
441 * entry that matches our key with everything
442 * but the first layout stripped off. */
443 if (startswith_comma(xc->layout, a[1]))
444 matching = 5;
445 else {
446 _cleanup_free_ char *x = NULL;
447
448 /* If that didn't work, strip off the
449 * other layouts from the entry, too */
450 x = strdupcspn(a[1], ",");
451 if (!x)
452 return -ENOMEM;
453 if (startswith_comma(xc->layout, x))
454 matching = 1;
455 }
456 }
457 }
458
459 if (matching > 0) {
460 if (isempty(xc->model) || streq_ptr(xc->model, a[2])) {
461 matching++;
462
463 if (streq_ptr(xc->variant, a[3]) || ((isempty(xc->variant) || streq_skip_trailing_chars(xc->variant, "", ",")) && streq(a[3], "-"))) {
464 matching++;
465
466 if (streq_ptr(xc->options, a[4]))
467 matching++;
468 }
469 }
470 }
471
472 /* The best matching entry so far, then let's save that */
473 if (matching >= MAX(best_matching, 1u)) {
474 log_debug("Found legacy keymap %s with score %u", a[0], matching);
475
476 if (matching > best_matching) {
477 best_matching = matching;
478
479 r = free_and_strdup(&new_keymap, a[0]);
480 if (r < 0)
481 return r;
482 }
483 }
484 }
485
486 if (best_matching < 9 && !isempty(xc->layout)) {
487 _cleanup_free_ char *l = NULL, *v = NULL, *converted = NULL;
488
489 /* The best match is only the first part of the X11
490 * keymap. Check if we have a converted map which
491 * matches just the first layout.
492 */
493
494 l = strdupcspn(xc->layout, ",");
495 if (!l)
496 return -ENOMEM;
497
498 if (!isempty(xc->variant)) {
499 v = strdupcspn(xc->variant, ",");
500 if (!v)
501 return -ENOMEM;
502 }
503
504 r = find_converted_keymap(
505 &(X11Context) {
506 .layout = l,
507 .variant = v,
508 },
509 &converted);
510 if (r < 0)
511 return r;
512 if (r > 0)
513 free_and_replace(new_keymap, converted);
514 }
515
516 *ret = TAKE_PTR(new_keymap);
517 return !!*ret;
518 }
519
520 int x11_convert_to_vconsole(const X11Context *xc, VCContext *ret) {
521 _cleanup_free_ char *keymap = NULL;
522 int r;
523
524 assert(xc);
525 assert(ret);
526
527 if (isempty(xc->layout)) {
528 *ret = (VCContext) {};
529 return 0;
530 }
531
532 r = find_converted_keymap(xc, &keymap);
533 if (r == 0) {
534 r = find_legacy_keymap(xc, &keymap);
535 if (r == 0 && xc->variant)
536 /* If we still haven't find a match, try with no variant, it's still better than
537 * nothing. */
538 r = find_converted_keymap(
539 &(X11Context) {
540 .layout = xc->layout,
541 },
542 &keymap);
543 }
544 if (r < 0)
545 return r;
546
547 *ret = (VCContext) {
548 .keymap = TAKE_PTR(keymap),
549 };
550 return 0;
551 }
552
553 int find_language_fallback(const char *lang, char **ret) {
554 const char *map;
555 _cleanup_fclose_ FILE *f = NULL;
556 unsigned n = 0;
557 int r;
558
559 assert(lang);
560 assert(ret);
561
562 map = systemd_language_fallback_map();
563 f = fopen(map, "re");
564 if (!f)
565 return -errno;
566
567 for (;;) {
568 _cleanup_strv_free_ char **a = NULL;
569
570 r = read_next_mapping(map, 2, 2, f, &n, &a);
571 if (r <= 0)
572 return r;
573
574 if (streq(lang, a[0])) {
575 assert(strv_length(a) == 2);
576 *ret = TAKE_PTR(a[1]);
577 return 1;
578 }
579 }
580 }
581
582 int find_vconsole_keymap_for_bcp47(const char *tag, char **ret) {
583 _cleanup_fclose_ FILE *f = NULL;
584 _cleanup_free_ char *fallback = NULL;
585 const char *map;
586 int r;
587
588 /* Look up a vconsole keymap by RFC 4646 / BCP 47 language tag (e.g. "de-DE") using the optional
589 * sixth column of /usr/share/systemd/kbd-model-map. That column lists comma-separated tags the
590 * row matches. An exact (case-insensitive) tag match returns immediately; if no exact match
591 * exists, the first row whose tag matches the input's primary subtag wins. Returns 1 on match,
592 * 0 otherwise. */
593
594 assert(tag);
595 assert(ret);
596
597 if (isempty(tag)) {
598 *ret = NULL;
599 return 0;
600 }
601
602 size_t primary_len = strcspn(tag, "-");
603 if (primary_len == 0) {
604 *ret = NULL;
605 return 0;
606 }
607
608 map = systemd_kbd_model_map();
609 f = fopen(map, "re");
610 if (!f)
611 return -errno;
612
613 for (unsigned n = 0;;) {
614 _cleanup_strv_free_ char **a = NULL, **tags = NULL;
615
616 r = read_next_mapping(map, 5, UINT_MAX, f, &n, &a);
617 if (r < 0)
618 return r;
619 if (r == 0)
620 break;
621
622 /* The BCP 47 tag list is the optional 6th column. "-" / empty means "no tags". */
623 if (strv_length(a) < 6 || isempty(a[5]) || streq(a[5], "-"))
624 continue;
625
626 r = strv_split_full(&tags, a[5], ",", /* flags= */ 0);
627 if (r < 0)
628 return r;
629
630 STRV_FOREACH(t, tags) {
631 if (strcaseeq(*t, tag)) {
632 log_debug("Found vconsole keymap '%s' for BCP 47 tag '%s' (exact match).",
633 a[0], tag);
634
635 r = strdup_to(ret, a[0]);
636 if (r < 0)
637 return r;
638
639 return 1;
640 }
641 if (!fallback && strlen(*t) == primary_len && !strchr(*t, '-') && strncaseeq(*t, tag, primary_len)) {
642 fallback = strdup(a[0]);
643 if (!fallback)
644 return -ENOMEM;
645 }
646 }
647 }
648
649 if (!fallback) {
650 *ret = NULL;
651 return 0;
652 }
653
654 log_debug("Found vconsole keymap '%s' for BCP 47 tag '%s' (primary subtag match).", fallback, tag);
655 *ret = TAKE_PTR(fallback);
656 return 1;
657 }
658
659 int vconsole_keymap_from_efi(char **ret) {
660 int r;
661
662 assert(ret);
663
664 if (!is_efi_boot()) {
665 *ret = NULL;
666 return 0;
667 }
668
669 _cleanup_free_ char *tag = NULL;
670 r = efi_get_variable_string(EFI_LOADER_VARIABLE_STR("LoaderKeyboardLayout"), &tag);
671 if (r == -ENOENT) {
672 *ret = NULL;
673 return 0;
674 }
675 if (r < 0)
676 return log_debug_errno(r, "Failed to read LoaderKeyboardLayout EFI variable: %m");
677
678 r = find_vconsole_keymap_for_bcp47(tag, ret);
679 if (r < 0)
680 return log_debug_errno(r, "Failed to look up vconsole keymap for firmware tag '%s': %m", tag);
681
682 return r;
683 }
684
685 int vconsole_serialize(const VCContext *vc, const X11Context *xc, char ***env) {
686 int r;
687
688 /* This function modifies the passed strv in place. */
689
690 assert(vc);
691 assert(xc);
692 assert(env);
693
694 r = strv_env_assign(env, "KEYMAP", empty_to_null(vc->keymap));
695 if (r < 0)
696 return r;
697
698 r = strv_env_assign(env, "KEYMAP_TOGGLE", empty_to_null(vc->toggle));
699 if (r < 0)
700 return r;
701
702 r = strv_env_assign(env, "XKBLAYOUT", empty_to_null(xc->layout));
703 if (r < 0)
704 return r;
705
706 r = strv_env_assign(env, "XKBMODEL", empty_to_null(xc->model));
707 if (r < 0)
708 return r;
709
710 r = strv_env_assign(env, "XKBVARIANT", empty_to_null(xc->variant));
711 if (r < 0)
712 return r;
713
714 r = strv_env_assign(env, "XKBOPTIONS", empty_to_null(xc->options));
715 if (r < 0)
716 return r;
717
718 return 0;
719 }