]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/locale/keymap-util.c
journal: drop unnecessary +1 in newa() expression
[thirdparty/systemd.git] / src / locale / keymap-util.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
4897d1dc
ZJS
2
3#include <errno.h>
ca78ad1d
ZJS
4#include <sys/stat.h>
5#include <sys/types.h>
4897d1dc
ZJS
6#include <unistd.h>
7
269e4d2d 8#include "bus-polkit.h"
8f20232f 9#include "copy.h"
686d13b9 10#include "env-file-label.h"
f05e1d0d 11#include "env-file.h"
4897d1dc
ZJS
12#include "env-util.h"
13#include "fd-util.h"
14#include "fileio-label.h"
15#include "fileio.h"
8f20232f 16#include "fs-util.h"
f05e1d0d 17#include "kbd-util.h"
4897d1dc
ZJS
18#include "keymap-util.h"
19#include "locale-util.h"
20#include "macro.h"
21#include "mkdir.h"
d8b4d14d 22#include "nulstr-util.h"
8f20232f 23#include "process-util.h"
4897d1dc
ZJS
24#include "string-util.h"
25#include "strv.h"
e4de7287 26#include "tmpfile-util.h"
4897d1dc
ZJS
27
28static bool startswith_comma(const char *s, const char *prefix) {
5ad327dd
ZJS
29 s = startswith(s, prefix);
30 if (!s)
31 return false;
4897d1dc 32
4c701096 33 return IN_SET(*s, ',', '\0');
4897d1dc
ZJS
34}
35
cabffaf8
ZJS
36static const char* systemd_kbd_model_map(void) {
37 const char* s;
38
39 s = getenv("SYSTEMD_KBD_MODEL_MAP");
40 if (s)
41 return s;
42
43 return SYSTEMD_KBD_MODEL_MAP;
44}
45
46static const char* systemd_language_fallback_map(void) {
47 const char* s;
48
49 s = getenv("SYSTEMD_LANGUAGE_FALLBACK_MAP");
50 if (s)
51 return s;
52
53 return SYSTEMD_LANGUAGE_FALLBACK_MAP;
54}
55
4897d1dc
ZJS
56static void context_free_x11(Context *c) {
57 c->x11_layout = mfree(c->x11_layout);
58 c->x11_options = mfree(c->x11_options);
59 c->x11_model = mfree(c->x11_model);
60 c->x11_variant = mfree(c->x11_variant);
61}
62
63static void context_free_vconsole(Context *c) {
64 c->vc_keymap = mfree(c->vc_keymap);
65 c->vc_keymap_toggle = mfree(c->vc_keymap_toggle);
66}
67
68static void context_free_locale(Context *c) {
ab4ab13c 69 for (LocaleVariable p = 0; p < _VARIABLE_LC_MAX; p++)
4897d1dc
ZJS
70 c->locale[p] = mfree(c->locale[p]);
71}
72
6804d7a8 73void context_clear(Context *c) {
4897d1dc
ZJS
74 context_free_locale(c);
75 context_free_x11(c);
76 context_free_vconsole(c);
65d34266
YW
77
78 sd_bus_message_unref(c->locale_cache);
79 sd_bus_message_unref(c->x11_cache);
80 sd_bus_message_unref(c->vc_cache);
af7865c1
YW
81
82 bus_verify_polkit_async_registry_free(c->polkit_registry);
4897d1dc
ZJS
83};
84
df4fd2c7 85void locale_simplify(char *locale[_VARIABLE_LC_MAX]) {
ab4ab13c 86 for (LocaleVariable p = VARIABLE_LANG+1; p < _VARIABLE_LC_MAX; p++)
df4fd2c7
YW
87 if (isempty(locale[p]) || streq_ptr(locale[VARIABLE_LANG], locale[p]))
88 locale[p] = mfree(locale[p]);
4897d1dc
ZJS
89}
90
df4fd2c7
YW
91int locale_read_data(Context *c, sd_bus_message *m) {
92 struct stat st;
4897d1dc
ZJS
93 int r;
94
df4fd2c7 95 /* Do not try to re-read the file within single bus operation. */
65d34266
YW
96 if (m) {
97 if (m == c->locale_cache)
98 return 0;
4897d1dc 99
65d34266
YW
100 sd_bus_message_unref(c->locale_cache);
101 c->locale_cache = sd_bus_message_ref(m);
102 }
df4fd2c7
YW
103
104 r = stat("/etc/locale.conf", &st);
105 if (r < 0 && errno != ENOENT)
106 return -errno;
107
108 if (r >= 0) {
109 usec_t t;
110
111 /* If mtime is not changed, then we do not need to re-read the file. */
112 t = timespec_load(&st.st_mtim);
113 if (c->locale_mtime != USEC_INFINITY && t == c->locale_mtime)
114 return 0;
4897d1dc 115
df4fd2c7
YW
116 c->locale_mtime = t;
117 context_free_locale(c);
118
aa8fbc74 119 r = parse_env_file(NULL, "/etc/locale.conf",
df4fd2c7
YW
120 "LANG", &c->locale[VARIABLE_LANG],
121 "LANGUAGE", &c->locale[VARIABLE_LANGUAGE],
122 "LC_CTYPE", &c->locale[VARIABLE_LC_CTYPE],
123 "LC_NUMERIC", &c->locale[VARIABLE_LC_NUMERIC],
124 "LC_TIME", &c->locale[VARIABLE_LC_TIME],
125 "LC_COLLATE", &c->locale[VARIABLE_LC_COLLATE],
126 "LC_MONETARY", &c->locale[VARIABLE_LC_MONETARY],
127 "LC_MESSAGES", &c->locale[VARIABLE_LC_MESSAGES],
128 "LC_PAPER", &c->locale[VARIABLE_LC_PAPER],
129 "LC_NAME", &c->locale[VARIABLE_LC_NAME],
130 "LC_ADDRESS", &c->locale[VARIABLE_LC_ADDRESS],
131 "LC_TELEPHONE", &c->locale[VARIABLE_LC_TELEPHONE],
132 "LC_MEASUREMENT", &c->locale[VARIABLE_LC_MEASUREMENT],
13df9c39 133 "LC_IDENTIFICATION", &c->locale[VARIABLE_LC_IDENTIFICATION]);
df4fd2c7
YW
134 if (r < 0)
135 return r;
136 } else {
df4fd2c7
YW
137 c->locale_mtime = USEC_INFINITY;
138 context_free_locale(c);
139
4897d1dc 140 /* Fill in what we got passed from systemd. */
ab4ab13c 141 for (LocaleVariable p = 0; p < _VARIABLE_LC_MAX; p++) {
4897d1dc
ZJS
142 const char *name;
143
144 name = locale_variable_to_string(p);
145 assert(name);
146
147 r = free_and_strdup(&c->locale[p], empty_to_null(getenv(name)));
148 if (r < 0)
149 return r;
150 }
4897d1dc
ZJS
151 }
152
df4fd2c7
YW
153 locale_simplify(c->locale);
154 return 0;
4897d1dc
ZJS
155}
156
df4fd2c7
YW
157int vconsole_read_data(Context *c, sd_bus_message *m) {
158 struct stat st;
159 usec_t t;
4897d1dc
ZJS
160 int r;
161
df4fd2c7 162 /* Do not try to re-read the file within single bus operation. */
65d34266
YW
163 if (m) {
164 if (m == c->vc_cache)
165 return 0;
df4fd2c7 166
65d34266
YW
167 sd_bus_message_unref(c->vc_cache);
168 c->vc_cache = sd_bus_message_ref(m);
169 }
df4fd2c7
YW
170
171 if (stat("/etc/vconsole.conf", &st) < 0) {
172 if (errno != ENOENT)
173 return -errno;
174
175 c->vc_mtime = USEC_INFINITY;
176 context_free_vconsole(c);
177 return 0;
178 }
179
180 /* If mtime is not changed, then we do not need to re-read */
181 t = timespec_load(&st.st_mtim);
182 if (c->vc_mtime != USEC_INFINITY && t == c->vc_mtime)
183 return 0;
184
185 c->vc_mtime = t;
4897d1dc
ZJS
186 context_free_vconsole(c);
187
aa8fbc74 188 r = parse_env_file(NULL, "/etc/vconsole.conf",
4897d1dc 189 "KEYMAP", &c->vc_keymap,
13df9c39 190 "KEYMAP_TOGGLE", &c->vc_keymap_toggle);
df4fd2c7 191 if (r < 0)
4897d1dc
ZJS
192 return r;
193
194 return 0;
195}
196
df4fd2c7
YW
197int x11_read_data(Context *c, sd_bus_message *m) {
198 _cleanup_fclose_ FILE *f = NULL;
4897d1dc 199 bool in_section = false;
df4fd2c7
YW
200 struct stat st;
201 usec_t t;
4897d1dc
ZJS
202 int r;
203
df4fd2c7 204 /* Do not try to re-read the file within single bus operation. */
65d34266
YW
205 if (m) {
206 if (m == c->x11_cache)
207 return 0;
df4fd2c7 208
65d34266
YW
209 sd_bus_message_unref(c->x11_cache);
210 c->x11_cache = sd_bus_message_ref(m);
211 }
df4fd2c7
YW
212
213 if (stat("/etc/X11/xorg.conf.d/00-keyboard.conf", &st) < 0) {
214 if (errno != ENOENT)
215 return -errno;
216
217 c->x11_mtime = USEC_INFINITY;
218 context_free_x11(c);
219 return 0;
220 }
221
222 /* If mtime is not changed, then we do not need to re-read */
223 t = timespec_load(&st.st_mtim);
224 if (c->x11_mtime != USEC_INFINITY && t == c->x11_mtime)
225 return 0;
226
227 c->x11_mtime = t;
4897d1dc
ZJS
228 context_free_x11(c);
229
230 f = fopen("/etc/X11/xorg.conf.d/00-keyboard.conf", "re");
231 if (!f)
df4fd2c7 232 return -errno;
4897d1dc 233
1d47b569
LP
234 for (;;) {
235 _cleanup_free_ char *line = NULL;
4897d1dc
ZJS
236 char *l;
237
1d47b569
LP
238 r = read_line(f, LONG_LINE_MAX, &line);
239 if (r < 0)
240 return r;
241 if (r == 0)
242 break;
4897d1dc 243
1d47b569 244 l = strstrip(line);
4c701096 245 if (IN_SET(l[0], 0, '#'))
4897d1dc
ZJS
246 continue;
247
248 if (in_section && first_word(l, "Option")) {
249 _cleanup_strv_free_ char **a = NULL;
250
90e30d76 251 r = strv_split_full(&a, l, WHITESPACE, EXTRACT_UNQUOTE);
4897d1dc
ZJS
252 if (r < 0)
253 return r;
254
255 if (strv_length(a) == 3) {
256 char **p = NULL;
257
258 if (streq(a[1], "XkbLayout"))
259 p = &c->x11_layout;
260 else if (streq(a[1], "XkbModel"))
261 p = &c->x11_model;
262 else if (streq(a[1], "XkbVariant"))
263 p = &c->x11_variant;
264 else if (streq(a[1], "XkbOptions"))
265 p = &c->x11_options;
266
38cd55b0 267 if (p)
f9ecfd3b 268 free_and_replace(*p, a[2]);
4897d1dc
ZJS
269 }
270
271 } else if (!in_section && first_word(l, "Section")) {
272 _cleanup_strv_free_ char **a = NULL;
273
90e30d76 274 r = strv_split_full(&a, l, WHITESPACE, EXTRACT_UNQUOTE);
4897d1dc
ZJS
275 if (r < 0)
276 return -ENOMEM;
277
278 if (strv_length(a) == 2 && streq(a[1], "InputClass"))
279 in_section = true;
280
281 } else if (in_section && first_word(l, "EndSection"))
282 in_section = false;
283 }
284
285 return 0;
286}
287
4897d1dc 288int locale_write_data(Context *c, char ***settings) {
4897d1dc 289 _cleanup_strv_free_ char **l = NULL;
df4fd2c7 290 struct stat st;
ab4ab13c 291 int r;
4897d1dc
ZJS
292
293 /* Set values will be returned as strv in *settings on success. */
294
f08231fe
ZJS
295 for (LocaleVariable p = 0; p < _VARIABLE_LC_MAX; p++)
296 if (!isempty(c->locale[p])) {
297 r = strv_env_assign(&l, locale_variable_to_string(p), c->locale[p]);
298 if (r < 0)
299 return r;
300 }
4897d1dc
ZJS
301
302 if (strv_isempty(l)) {
303 if (unlink("/etc/locale.conf") < 0)
304 return errno == ENOENT ? 0 : -errno;
305
df4fd2c7 306 c->locale_mtime = USEC_INFINITY;
4897d1dc
ZJS
307 return 0;
308 }
309
310 r = write_env_file_label("/etc/locale.conf", l);
311 if (r < 0)
312 return r;
313
ae2a15bc 314 *settings = TAKE_PTR(l);
df4fd2c7
YW
315
316 if (stat("/etc/locale.conf", &st) >= 0)
317 c->locale_mtime = timespec_load(&st.st_mtim);
318
4897d1dc
ZJS
319 return 0;
320}
321
322int vconsole_write_data(Context *c) {
4897d1dc 323 _cleanup_strv_free_ char **l = NULL;
df4fd2c7
YW
324 struct stat st;
325 int r;
4897d1dc 326
aa8fbc74 327 r = load_env_file(NULL, "/etc/vconsole.conf", &l);
4897d1dc
ZJS
328 if (r < 0 && r != -ENOENT)
329 return r;
330
f08231fe
ZJS
331 r = strv_env_assign(&l, "KEYMAP", empty_to_null(c->vc_keymap));
332 if (r < 0)
333 return r;
4897d1dc 334
f08231fe
ZJS
335 r = strv_env_assign(&l, "KEYMAP_TOGGLE", empty_to_null(c->vc_keymap_toggle));
336 if (r < 0)
337 return r;
4897d1dc
ZJS
338
339 if (strv_isempty(l)) {
340 if (unlink("/etc/vconsole.conf") < 0)
341 return errno == ENOENT ? 0 : -errno;
342
df4fd2c7 343 c->vc_mtime = USEC_INFINITY;
4897d1dc
ZJS
344 return 0;
345 }
346
df4fd2c7
YW
347 r = write_env_file_label("/etc/vconsole.conf", l);
348 if (r < 0)
349 return r;
350
351 if (stat("/etc/vconsole.conf", &st) >= 0)
352 c->vc_mtime = timespec_load(&st.st_mtim);
353
354 return 0;
4897d1dc
ZJS
355}
356
357int x11_write_data(Context *c) {
358 _cleanup_fclose_ FILE *f = NULL;
359 _cleanup_free_ char *temp_path = NULL;
df4fd2c7 360 struct stat st;
4897d1dc
ZJS
361 int r;
362
363 if (isempty(c->x11_layout) &&
364 isempty(c->x11_model) &&
365 isempty(c->x11_variant) &&
366 isempty(c->x11_options)) {
367
368 if (unlink("/etc/X11/xorg.conf.d/00-keyboard.conf") < 0)
369 return errno == ENOENT ? 0 : -errno;
370
df4fd2c7 371 c->vc_mtime = USEC_INFINITY;
4897d1dc
ZJS
372 return 0;
373 }
374
6e5dcce4 375 (void) mkdir_p_label("/etc/X11/xorg.conf.d", 0755);
4897d1dc
ZJS
376 r = fopen_temporary("/etc/X11/xorg.conf.d/00-keyboard.conf", &f, &temp_path);
377 if (r < 0)
378 return r;
379
0d536673 380 (void) fchmod(fileno(f), 0644);
4897d1dc 381
0d536673
LP
382 fputs("# Written by systemd-localed(8), read by systemd-localed and Xorg. It's\n"
383 "# probably wise not to edit this file manually. Use localectl(1) to\n"
384 "# instruct systemd-localed to update it.\n"
385 "Section \"InputClass\"\n"
386 " Identifier \"system-keyboard\"\n"
387 " MatchIsKeyboard \"on\"\n", f);
4897d1dc
ZJS
388
389 if (!isempty(c->x11_layout))
390 fprintf(f, " Option \"XkbLayout\" \"%s\"\n", c->x11_layout);
391
392 if (!isempty(c->x11_model))
393 fprintf(f, " Option \"XkbModel\" \"%s\"\n", c->x11_model);
394
395 if (!isempty(c->x11_variant))
396 fprintf(f, " Option \"XkbVariant\" \"%s\"\n", c->x11_variant);
397
398 if (!isempty(c->x11_options))
399 fprintf(f, " Option \"XkbOptions\" \"%s\"\n", c->x11_options);
400
0d536673 401 fputs("EndSection\n", f);
4897d1dc 402
0675e94a 403 r = fflush_sync_and_check(f);
4897d1dc
ZJS
404 if (r < 0)
405 goto fail;
406
407 if (rename(temp_path, "/etc/X11/xorg.conf.d/00-keyboard.conf") < 0) {
408 r = -errno;
409 goto fail;
410 }
411
df4fd2c7
YW
412 if (stat("/etc/X11/xorg.conf.d/00-keyboard.conf", &st) >= 0)
413 c->x11_mtime = timespec_load(&st.st_mtim);
414
4897d1dc
ZJS
415 return 0;
416
417fail:
4897d1dc
ZJS
418 if (temp_path)
419 (void) unlink(temp_path);
420
421 return r;
422}
423
424static int read_next_mapping(const char* filename,
425 unsigned min_fields, unsigned max_fields,
426 FILE *f, unsigned *n, char ***a) {
427 assert(f);
428 assert(n);
429 assert(a);
430
431 for (;;) {
1d47b569
LP
432 _cleanup_free_ char *line = NULL;
433 size_t length;
4897d1dc
ZJS
434 char *l, **b;
435 int r;
4897d1dc 436
1d47b569
LP
437 r = read_line(f, LONG_LINE_MAX, &line);
438 if (r < 0)
439 return r;
440 if (r == 0)
441 break;
4897d1dc
ZJS
442
443 (*n)++;
444
445 l = strstrip(line);
4c701096 446 if (IN_SET(l[0], 0, '#'))
4897d1dc
ZJS
447 continue;
448
90e30d76 449 r = strv_split_full(&b, l, WHITESPACE, EXTRACT_UNQUOTE);
4897d1dc
ZJS
450 if (r < 0)
451 return r;
452
453 length = strv_length(b);
454 if (length < min_fields || length > max_fields) {
455 log_error("Invalid line %s:%u, ignoring.", filename, *n);
456 strv_free(b);
457 continue;
458
459 }
460
461 *a = b;
462 return 1;
463 }
1d47b569
LP
464
465 return 0;
4897d1dc
ZJS
466}
467
468int vconsole_convert_to_x11(Context *c) {
cabffaf8 469 const char *map;
6f3287b3 470 int modified = -1;
4897d1dc 471
cabffaf8
ZJS
472 map = systemd_kbd_model_map();
473
4897d1dc 474 if (isempty(c->vc_keymap)) {
4897d1dc
ZJS
475 modified =
476 !isempty(c->x11_layout) ||
477 !isempty(c->x11_model) ||
478 !isempty(c->x11_variant) ||
479 !isempty(c->x11_options);
480
481 context_free_x11(c);
482 } else {
483 _cleanup_fclose_ FILE *f = NULL;
484 unsigned n = 0;
485
cabffaf8 486 f = fopen(map, "re");
4897d1dc
ZJS
487 if (!f)
488 return -errno;
489
490 for (;;) {
491 _cleanup_strv_free_ char **a = NULL;
492 int r;
493
cabffaf8 494 r = read_next_mapping(map, 5, UINT_MAX, f, &n, &a);
4897d1dc
ZJS
495 if (r < 0)
496 return r;
497 if (r == 0)
498 break;
499
500 if (!streq(c->vc_keymap, a[0]))
501 continue;
502
dc90e0fa
LP
503 if (!streq_ptr(c->x11_layout, empty_or_dash_to_null(a[1])) ||
504 !streq_ptr(c->x11_model, empty_or_dash_to_null(a[2])) ||
505 !streq_ptr(c->x11_variant, empty_or_dash_to_null(a[3])) ||
506 !streq_ptr(c->x11_options, empty_or_dash_to_null(a[4]))) {
4897d1dc 507
dc90e0fa
LP
508 if (free_and_strdup(&c->x11_layout, empty_or_dash_to_null(a[1])) < 0 ||
509 free_and_strdup(&c->x11_model, empty_or_dash_to_null(a[2])) < 0 ||
510 free_and_strdup(&c->x11_variant, empty_or_dash_to_null(a[3])) < 0 ||
511 free_and_strdup(&c->x11_options, empty_or_dash_to_null(a[4])) < 0)
4897d1dc
ZJS
512 return -ENOMEM;
513
514 modified = true;
515 }
516
517 break;
518 }
519 }
520
6f3287b3 521 if (modified > 0)
4897d1dc
ZJS
522 log_info("Changing X11 keyboard layout to '%s' model '%s' variant '%s' options '%s'",
523 strempty(c->x11_layout),
524 strempty(c->x11_model),
525 strempty(c->x11_variant),
526 strempty(c->x11_options));
6f3287b3
ZJS
527 else if (modified < 0)
528 log_notice("X11 keyboard layout was not modified: no conversion found for \"%s\".",
529 c->vc_keymap);
4897d1dc 530 else
6f3287b3 531 log_debug("X11 keyboard layout did not need to be modified.");
4897d1dc 532
6f3287b3 533 return modified > 0;
4897d1dc
ZJS
534}
535
536int find_converted_keymap(const char *x11_layout, const char *x11_variant, char **new_keymap) {
537 const char *dir;
c2b2df60 538 _cleanup_free_ char *n = NULL;
4897d1dc
ZJS
539
540 if (x11_variant)
605405c6 541 n = strjoin(x11_layout, "-", x11_variant);
4897d1dc
ZJS
542 else
543 n = strdup(x11_layout);
544 if (!n)
545 return -ENOMEM;
546
547 NULSTR_FOREACH(dir, KBD_KEYMAP_DIRS) {
548 _cleanup_free_ char *p = NULL, *pz = NULL;
549 bool uncompressed;
550
605405c6
ZJS
551 p = strjoin(dir, "xkb/", n, ".map");
552 pz = strjoin(dir, "xkb/", n, ".map.gz");
4897d1dc
ZJS
553 if (!p || !pz)
554 return -ENOMEM;
555
556 uncompressed = access(p, F_OK) == 0;
557 if (uncompressed || access(pz, F_OK) == 0) {
558 log_debug("Found converted keymap %s at %s",
559 n, uncompressed ? p : pz);
560
ae2a15bc 561 *new_keymap = TAKE_PTR(n);
4897d1dc
ZJS
562 return 1;
563 }
564 }
565
566 return 0;
567}
568
6a6e9c03 569int find_legacy_keymap(Context *c, char **ret) {
cabffaf8
ZJS
570 const char *map;
571 _cleanup_fclose_ FILE *f = NULL;
6a6e9c03 572 _cleanup_free_ char *new_keymap = NULL;
4897d1dc
ZJS
573 unsigned n = 0;
574 unsigned best_matching = 0;
575 int r;
576
5ad327dd
ZJS
577 assert(!isempty(c->x11_layout));
578
cabffaf8
ZJS
579 map = systemd_kbd_model_map();
580
581 f = fopen(map, "re");
4897d1dc
ZJS
582 if (!f)
583 return -errno;
584
585 for (;;) {
586 _cleanup_strv_free_ char **a = NULL;
587 unsigned matching = 0;
588
cabffaf8 589 r = read_next_mapping(map, 5, UINT_MAX, f, &n, &a);
4897d1dc
ZJS
590 if (r < 0)
591 return r;
592 if (r == 0)
593 break;
594
595 /* Determine how well matching this entry is */
5ad327dd 596 if (streq(c->x11_layout, a[1]))
4897d1dc
ZJS
597 /* If we got an exact match, this is best */
598 matching = 10;
599 else {
600 /* We have multiple X layouts, look for an
601 * entry that matches our key with everything
602 * but the first layout stripped off. */
603 if (startswith_comma(c->x11_layout, a[1]))
604 matching = 5;
605 else {
6d946490 606 _cleanup_free_ char *x = NULL;
4897d1dc
ZJS
607
608 /* If that didn't work, strip off the
609 * other layouts from the entry, too */
6d946490 610 x = strndup(a[1], strcspn(a[1], ","));
4897d1dc
ZJS
611 if (startswith_comma(c->x11_layout, x))
612 matching = 1;
613 }
614 }
615
616 if (matching > 0) {
617 if (isempty(c->x11_model) || streq_ptr(c->x11_model, a[2])) {
618 matching++;
619
620 if (streq_ptr(c->x11_variant, a[3])) {
621 matching++;
622
623 if (streq_ptr(c->x11_options, a[4]))
624 matching++;
625 }
626 }
627 }
628
629 /* The best matching entry so far, then let's save that */
630 if (matching >= MAX(best_matching, 1u)) {
631 log_debug("Found legacy keymap %s with score %u",
632 a[0], matching);
633
634 if (matching > best_matching) {
635 best_matching = matching;
636
6a6e9c03 637 r = free_and_strdup(&new_keymap, a[0]);
4897d1dc
ZJS
638 if (r < 0)
639 return r;
640 }
641 }
642 }
643
644 if (best_matching < 10 && c->x11_layout) {
645 /* The best match is only the first part of the X11
646 * keymap. Check if we have a converted map which
647 * matches just the first layout.
648 */
649 char *l, *v = NULL, *converted;
650
651 l = strndupa(c->x11_layout, strcspn(c->x11_layout, ","));
652 if (c->x11_variant)
653 v = strndupa(c->x11_variant, strcspn(c->x11_variant, ","));
654 r = find_converted_keymap(l, v, &converted);
655 if (r < 0)
656 return r;
6a6e9c03
ZJS
657 if (r > 0)
658 free_and_replace(new_keymap, converted);
4897d1dc
ZJS
659 }
660
6a6e9c03
ZJS
661 *ret = TAKE_PTR(new_keymap);
662 return (bool) *ret;
4897d1dc
ZJS
663}
664
665int find_language_fallback(const char *lang, char **language) {
cabffaf8 666 const char *map;
4897d1dc
ZJS
667 _cleanup_fclose_ FILE *f = NULL;
668 unsigned n = 0;
669
aa63b56f 670 assert(lang);
4897d1dc
ZJS
671 assert(language);
672
cabffaf8
ZJS
673 map = systemd_language_fallback_map();
674
675 f = fopen(map, "re");
4897d1dc
ZJS
676 if (!f)
677 return -errno;
678
679 for (;;) {
680 _cleanup_strv_free_ char **a = NULL;
681 int r;
682
cabffaf8 683 r = read_next_mapping(map, 2, 2, f, &n, &a);
4897d1dc
ZJS
684 if (r <= 0)
685 return r;
686
687 if (streq(lang, a[0])) {
688 assert(strv_length(a) == 2);
1cc6c93a 689 *language = TAKE_PTR(a[1]);
4897d1dc
ZJS
690 return 1;
691 }
692 }
693
04499a70 694 assert_not_reached();
4897d1dc
ZJS
695}
696
697int x11_convert_to_vconsole(Context *c) {
698 bool modified = false;
699
700 if (isempty(c->x11_layout)) {
4897d1dc
ZJS
701 modified =
702 !isempty(c->vc_keymap) ||
703 !isempty(c->vc_keymap_toggle);
704
aa63b56f 705 context_free_vconsole(c);
4897d1dc 706 } else {
6a837b03 707 _cleanup_free_ char *new_keymap = NULL;
4897d1dc
ZJS
708 int r;
709
710 r = find_converted_keymap(c->x11_layout, c->x11_variant, &new_keymap);
711 if (r < 0)
712 return r;
713 else if (r == 0) {
714 r = find_legacy_keymap(c, &new_keymap);
715 if (r < 0)
716 return r;
717 }
5ad327dd
ZJS
718 if (r == 0)
719 /* We search for layout-variant match first, but then we also look
720 * for anything which matches just the layout. So it's accurate to say
721 * that we couldn't find anything which matches the layout. */
722 log_notice("No conversion to virtual console map found for \"%s\".",
723 c->x11_layout);
4897d1dc
ZJS
724
725 if (!streq_ptr(c->vc_keymap, new_keymap)) {
6a837b03 726 free_and_replace(c->vc_keymap, new_keymap);
4897d1dc
ZJS
727 c->vc_keymap_toggle = mfree(c->vc_keymap_toggle);
728 modified = true;
6a837b03 729 }
4897d1dc
ZJS
730 }
731
732 if (modified)
733 log_info("Changing virtual console keymap to '%s' toggle '%s'",
734 strempty(c->vc_keymap), strempty(c->vc_keymap_toggle));
735 else
736 log_debug("Virtual console keymap was not modified.");
737
738 return modified;
739}
8f20232f
MK
740
741bool locale_gen_check_available(void) {
742#if HAVE_LOCALEGEN
743 if (access(LOCALEGEN_PATH, X_OK) < 0) {
744 if (errno != ENOENT)
745 log_warning_errno(errno, "Unable to determine whether " LOCALEGEN_PATH " exists and is executable, assuming it is not: %m");
746 return false;
747 }
748 if (access("/etc/locale.gen", F_OK) < 0) {
749 if (errno != ENOENT)
750 log_warning_errno(errno, "Unable to determine whether /etc/locale.gen exists, assuming it does not: %m");
751 return false;
752 }
753 return true;
754#else
755 return false;
756#endif
757}
758
759#if HAVE_LOCALEGEN
760static bool locale_encoding_is_utf8_or_unspecified(const char *locale) {
761 const char *c = strchr(locale, '.');
762 return !c || strcaseeq(c, ".UTF-8") || strcasestr(locale, ".UTF-8@");
763}
764
765static int locale_gen_locale_supported(const char *locale_entry) {
766 /* Returns an error valus <= 0 if the locale-gen entry is invalid or unsupported,
767 * 1 in case the locale entry is valid, and -EOPNOTSUPP specifically in case
768 * the distributor has not provided us with a SUPPORTED file to check
769 * locale for validity. */
770
771 _cleanup_fclose_ FILE *f = NULL;
772 int r;
773
774 assert(locale_entry);
775
776 /* Locale templates without country code are never supported */
777 if (!strstr(locale_entry, "_"))
778 return -EINVAL;
779
780 f = fopen("/usr/share/i18n/SUPPORTED", "re");
781 if (!f) {
782 if (errno == ENOENT)
783 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
784 "Unable to check validity of locale entry %s: /usr/share/i18n/SUPPORTED does not exist",
785 locale_entry);
786 return -errno;
787 }
788
789 for (;;) {
790 _cleanup_free_ char *line = NULL;
791
792 r = read_line(f, LONG_LINE_MAX, &line);
793 if (r < 0)
794 return log_debug_errno(r, "Failed to read /usr/share/i18n/SUPPORTED: %m");
795 if (r == 0)
796 return 0;
797
798 line = strstrip(line);
799 if (strcaseeq_ptr(line, locale_entry))
800 return 1;
801 }
802}
803#endif
804
805int locale_gen_enable_locale(const char *locale) {
806#if HAVE_LOCALEGEN
807 _cleanup_fclose_ FILE *fr = NULL, *fw = NULL;
808 _cleanup_(unlink_and_freep) char *temp_path = NULL;
809 _cleanup_free_ char *locale_entry = NULL;
810 bool locale_enabled = false, first_line = false;
811 bool write_new = false;
812 int r;
813
814 if (isempty(locale))
815 return 0;
816
817 if (locale_encoding_is_utf8_or_unspecified(locale)) {
818 locale_entry = strjoin(locale, " UTF-8");
819 if (!locale_entry)
820 return -ENOMEM;
821 } else
822 return -ENOEXEC; /* We do not process non-UTF-8 locale */
823
824 r = locale_gen_locale_supported(locale_entry);
825 if (r == 0)
826 return -EINVAL;
827 if (r < 0 && r != -EOPNOTSUPP)
828 return r;
829
830 fr = fopen("/etc/locale.gen", "re");
831 if (!fr) {
832 if (errno != ENOENT)
833 return -errno;
834 write_new = true;
835 }
836
837 r = fopen_temporary("/etc/locale.gen", &fw, &temp_path);
838 if (r < 0)
839 return r;
840
841 if (write_new)
842 (void) fchmod(fileno(fw), 0644);
843 else {
844 /* apply mode & xattrs of the original file to new file */
845 r = copy_access(fileno(fr), fileno(fw));
846 if (r < 0)
847 return r;
23e026de 848 r = copy_xattr(fileno(fr), fileno(fw), COPY_ALL_XATTRS);
8f20232f
MK
849 if (r < 0)
850 return r;
851 }
852
853 if (!write_new) {
854 /* The config file ends with a line break, which we do not want to include before potentially appending a new locale
855 * instead of uncommenting an existing line. By prepending linebreaks, we can avoid buffering this file but can still write
856 * a nice config file without empty lines */
857 first_line = true;
858 for (;;) {
859 _cleanup_free_ char *line = NULL;
860 char *line_locale;
861
862 r = read_line(fr, LONG_LINE_MAX, &line);
863 if (r < 0)
864 return r;
865 if (r == 0)
866 break;
867
868 if (locale_enabled) {
869 /* Just complete writing the file if the new locale was already enabled */
870 if (!first_line)
871 fputc('\n', fw);
872 fputs(line, fw);
873 first_line = false;
874 continue;
875 }
876
877 line = strstrip(line);
878 if (isempty(line)) {
879 fputc('\n', fw);
880 first_line = false;
881 continue;
882 }
883
884 line_locale = line;
885 if (line_locale[0] == '#')
886 line_locale = strstrip(line_locale + 1);
887 else if (strcaseeq_ptr(line_locale, locale_entry))
888 return 0; /* the file already had our locale activated, so skip updating it */
889
890 if (strcaseeq_ptr(line_locale, locale_entry)) {
891 /* Uncomment existing line for new locale */
892 if (!first_line)
893 fputc('\n', fw);
894 fputs(locale_entry, fw);
895 locale_enabled = true;
896 first_line = false;
897 continue;
898 }
899
900 /* The line was not for the locale we want to enable, just copy it */
901 if (!first_line)
902 fputc('\n', fw);
903 fputs(line, fw);
904 first_line = false;
905 }
906 }
907
908 /* Add locale to enable to the end of the file if it was not found as commented line */
909 if (!locale_enabled) {
910 if (!write_new)
911 fputc('\n', fw);
912 fputs(locale_entry, fw);
913 }
914 fputc('\n', fw);
915
916 r = fflush_sync_and_check(fw);
917 if (r < 0)
918 return r;
919
920 if (rename(temp_path, "/etc/locale.gen") < 0)
921 return -errno;
922 temp_path = mfree(temp_path);
923
924 return 0;
925#else
926 return -EOPNOTSUPP;
927#endif
928}
929
930int locale_gen_run(void) {
931#if HAVE_LOCALEGEN
932 pid_t pid;
933 int r;
934
935 r = safe_fork("(sd-localegen)", FORK_RESET_SIGNALS|FORK_RLIMIT_NOFILE_SAFE|FORK_CLOSE_ALL_FDS|FORK_LOG|FORK_WAIT, &pid);
936 if (r < 0)
937 return r;
938 if (r == 0) {
939 execl(LOCALEGEN_PATH, LOCALEGEN_PATH, NULL);
940 _exit(EXIT_FAILURE);
941 }
942
943 return 0;
944#else
945 return -EOPNOTSUPP;
946#endif
947}