]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/locale/keymap-util.c
Merge pull request #18863 from keszybz/cmdline-escaping
[thirdparty/systemd.git] / src / locale / keymap-util.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <errno.h>
4 #include <sys/stat.h>
5 #include <sys/types.h>
6 #include <unistd.h>
7
8 #include "bus-polkit.h"
9 #include "copy.h"
10 #include "env-file-label.h"
11 #include "env-file.h"
12 #include "env-util.h"
13 #include "fd-util.h"
14 #include "fileio-label.h"
15 #include "fileio.h"
16 #include "fs-util.h"
17 #include "kbd-util.h"
18 #include "keymap-util.h"
19 #include "locale-util.h"
20 #include "macro.h"
21 #include "mkdir.h"
22 #include "nulstr-util.h"
23 #include "process-util.h"
24 #include "string-util.h"
25 #include "strv.h"
26 #include "tmpfile-util.h"
27
28 static bool startswith_comma(const char *s, const char *prefix) {
29 s = startswith(s, prefix);
30 if (!s)
31 return false;
32
33 return IN_SET(*s, ',', '\0');
34 }
35
36 static 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
46 static 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
56 static 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
63 static 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
68 static void context_free_locale(Context *c) {
69 for (LocaleVariable p = 0; p < _VARIABLE_LC_MAX; p++)
70 c->locale[p] = mfree(c->locale[p]);
71 }
72
73 void context_clear(Context *c) {
74 context_free_locale(c);
75 context_free_x11(c);
76 context_free_vconsole(c);
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);
81
82 bus_verify_polkit_async_registry_free(c->polkit_registry);
83 };
84
85 void locale_simplify(char *locale[_VARIABLE_LC_MAX]) {
86 for (LocaleVariable p = VARIABLE_LANG+1; p < _VARIABLE_LC_MAX; p++)
87 if (isempty(locale[p]) || streq_ptr(locale[VARIABLE_LANG], locale[p]))
88 locale[p] = mfree(locale[p]);
89 }
90
91 int locale_read_data(Context *c, sd_bus_message *m) {
92 struct stat st;
93 int r;
94
95 /* Do not try to re-read the file within single bus operation. */
96 if (m) {
97 if (m == c->locale_cache)
98 return 0;
99
100 sd_bus_message_unref(c->locale_cache);
101 c->locale_cache = sd_bus_message_ref(m);
102 }
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;
115
116 c->locale_mtime = t;
117 context_free_locale(c);
118
119 r = parse_env_file(NULL, "/etc/locale.conf",
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],
133 "LC_IDENTIFICATION", &c->locale[VARIABLE_LC_IDENTIFICATION]);
134 if (r < 0)
135 return r;
136 } else {
137 c->locale_mtime = USEC_INFINITY;
138 context_free_locale(c);
139
140 /* Fill in what we got passed from systemd. */
141 for (LocaleVariable p = 0; p < _VARIABLE_LC_MAX; p++) {
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 }
151 }
152
153 locale_simplify(c->locale);
154 return 0;
155 }
156
157 int vconsole_read_data(Context *c, sd_bus_message *m) {
158 struct stat st;
159 usec_t t;
160 int r;
161
162 /* Do not try to re-read the file within single bus operation. */
163 if (m) {
164 if (m == c->vc_cache)
165 return 0;
166
167 sd_bus_message_unref(c->vc_cache);
168 c->vc_cache = sd_bus_message_ref(m);
169 }
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;
186 context_free_vconsole(c);
187
188 r = parse_env_file(NULL, "/etc/vconsole.conf",
189 "KEYMAP", &c->vc_keymap,
190 "KEYMAP_TOGGLE", &c->vc_keymap_toggle);
191 if (r < 0)
192 return r;
193
194 return 0;
195 }
196
197 int x11_read_data(Context *c, sd_bus_message *m) {
198 _cleanup_fclose_ FILE *f = NULL;
199 bool in_section = false;
200 struct stat st;
201 usec_t t;
202 int r;
203
204 /* Do not try to re-read the file within single bus operation. */
205 if (m) {
206 if (m == c->x11_cache)
207 return 0;
208
209 sd_bus_message_unref(c->x11_cache);
210 c->x11_cache = sd_bus_message_ref(m);
211 }
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;
228 context_free_x11(c);
229
230 f = fopen("/etc/X11/xorg.conf.d/00-keyboard.conf", "re");
231 if (!f)
232 return -errno;
233
234 for (;;) {
235 _cleanup_free_ char *line = NULL;
236 char *l;
237
238 r = read_line(f, LONG_LINE_MAX, &line);
239 if (r < 0)
240 return r;
241 if (r == 0)
242 break;
243
244 l = strstrip(line);
245 if (IN_SET(l[0], 0, '#'))
246 continue;
247
248 if (in_section && first_word(l, "Option")) {
249 _cleanup_strv_free_ char **a = NULL;
250
251 r = strv_split_full(&a, l, WHITESPACE, EXTRACT_UNQUOTE);
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
267 if (p)
268 free_and_replace(*p, a[2]);
269 }
270
271 } else if (!in_section && first_word(l, "Section")) {
272 _cleanup_strv_free_ char **a = NULL;
273
274 r = strv_split_full(&a, l, WHITESPACE, EXTRACT_UNQUOTE);
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
288 int locale_write_data(Context *c, char ***settings) {
289 _cleanup_strv_free_ char **l = NULL;
290 struct stat st;
291 int r;
292
293 /* Set values will be returned as strv in *settings on success. */
294
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 }
301
302 if (strv_isempty(l)) {
303 if (unlink("/etc/locale.conf") < 0)
304 return errno == ENOENT ? 0 : -errno;
305
306 c->locale_mtime = USEC_INFINITY;
307 return 0;
308 }
309
310 r = write_env_file_label("/etc/locale.conf", l);
311 if (r < 0)
312 return r;
313
314 *settings = TAKE_PTR(l);
315
316 if (stat("/etc/locale.conf", &st) >= 0)
317 c->locale_mtime = timespec_load(&st.st_mtim);
318
319 return 0;
320 }
321
322 int vconsole_write_data(Context *c) {
323 _cleanup_strv_free_ char **l = NULL;
324 struct stat st;
325 int r;
326
327 r = load_env_file(NULL, "/etc/vconsole.conf", &l);
328 if (r < 0 && r != -ENOENT)
329 return r;
330
331 r = strv_env_assign(&l, "KEYMAP", empty_to_null(c->vc_keymap));
332 if (r < 0)
333 return r;
334
335 r = strv_env_assign(&l, "KEYMAP_TOGGLE", empty_to_null(c->vc_keymap_toggle));
336 if (r < 0)
337 return r;
338
339 if (strv_isempty(l)) {
340 if (unlink("/etc/vconsole.conf") < 0)
341 return errno == ENOENT ? 0 : -errno;
342
343 c->vc_mtime = USEC_INFINITY;
344 return 0;
345 }
346
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;
355 }
356
357 int x11_write_data(Context *c) {
358 _cleanup_fclose_ FILE *f = NULL;
359 _cleanup_free_ char *temp_path = NULL;
360 struct stat st;
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
371 c->vc_mtime = USEC_INFINITY;
372 return 0;
373 }
374
375 (void) mkdir_p_label("/etc/X11/xorg.conf.d", 0755);
376 r = fopen_temporary("/etc/X11/xorg.conf.d/00-keyboard.conf", &f, &temp_path);
377 if (r < 0)
378 return r;
379
380 (void) fchmod(fileno(f), 0644);
381
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);
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
401 fputs("EndSection\n", f);
402
403 r = fflush_sync_and_check(f);
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
412 if (stat("/etc/X11/xorg.conf.d/00-keyboard.conf", &st) >= 0)
413 c->x11_mtime = timespec_load(&st.st_mtim);
414
415 return 0;
416
417 fail:
418 if (temp_path)
419 (void) unlink(temp_path);
420
421 return r;
422 }
423
424 static 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 (;;) {
432 _cleanup_free_ char *line = NULL;
433 size_t length;
434 char *l, **b;
435 int r;
436
437 r = read_line(f, LONG_LINE_MAX, &line);
438 if (r < 0)
439 return r;
440 if (r == 0)
441 break;
442
443 (*n)++;
444
445 l = strstrip(line);
446 if (IN_SET(l[0], 0, '#'))
447 continue;
448
449 r = strv_split_full(&b, l, WHITESPACE, EXTRACT_UNQUOTE);
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 }
464
465 return 0;
466 }
467
468 int vconsole_convert_to_x11(Context *c) {
469 const char *map;
470 int modified = -1;
471
472 map = systemd_kbd_model_map();
473
474 if (isempty(c->vc_keymap)) {
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
486 f = fopen(map, "re");
487 if (!f)
488 return -errno;
489
490 for (;;) {
491 _cleanup_strv_free_ char **a = NULL;
492 int r;
493
494 r = read_next_mapping(map, 5, UINT_MAX, f, &n, &a);
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
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]))) {
507
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)
512 return -ENOMEM;
513
514 modified = true;
515 }
516
517 break;
518 }
519 }
520
521 if (modified > 0)
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));
527 else if (modified < 0)
528 log_notice("X11 keyboard layout was not modified: no conversion found for \"%s\".",
529 c->vc_keymap);
530 else
531 log_debug("X11 keyboard layout did not need to be modified.");
532
533 return modified > 0;
534 }
535
536 int find_converted_keymap(const char *x11_layout, const char *x11_variant, char **new_keymap) {
537 const char *dir;
538 _cleanup_free_ char *n = NULL;
539
540 if (x11_variant)
541 n = strjoin(x11_layout, "-", x11_variant);
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
551 p = strjoin(dir, "xkb/", n, ".map");
552 pz = strjoin(dir, "xkb/", n, ".map.gz");
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
561 *new_keymap = TAKE_PTR(n);
562 return 1;
563 }
564 }
565
566 return 0;
567 }
568
569 int find_legacy_keymap(Context *c, char **ret) {
570 const char *map;
571 _cleanup_fclose_ FILE *f = NULL;
572 _cleanup_free_ char *new_keymap = NULL;
573 unsigned n = 0;
574 unsigned best_matching = 0;
575 int r;
576
577 assert(!isempty(c->x11_layout));
578
579 map = systemd_kbd_model_map();
580
581 f = fopen(map, "re");
582 if (!f)
583 return -errno;
584
585 for (;;) {
586 _cleanup_strv_free_ char **a = NULL;
587 unsigned matching = 0;
588
589 r = read_next_mapping(map, 5, UINT_MAX, f, &n, &a);
590 if (r < 0)
591 return r;
592 if (r == 0)
593 break;
594
595 /* Determine how well matching this entry is */
596 if (streq(c->x11_layout, a[1]))
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 {
606 _cleanup_free_ char *x = NULL;
607
608 /* If that didn't work, strip off the
609 * other layouts from the entry, too */
610 x = strndup(a[1], strcspn(a[1], ","));
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
637 r = free_and_strdup(&new_keymap, a[0]);
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;
657 if (r > 0)
658 free_and_replace(new_keymap, converted);
659 }
660
661 *ret = TAKE_PTR(new_keymap);
662 return (bool) *ret;
663 }
664
665 int find_language_fallback(const char *lang, char **language) {
666 const char *map;
667 _cleanup_fclose_ FILE *f = NULL;
668 unsigned n = 0;
669
670 assert(lang);
671 assert(language);
672
673 map = systemd_language_fallback_map();
674
675 f = fopen(map, "re");
676 if (!f)
677 return -errno;
678
679 for (;;) {
680 _cleanup_strv_free_ char **a = NULL;
681 int r;
682
683 r = read_next_mapping(map, 2, 2, f, &n, &a);
684 if (r <= 0)
685 return r;
686
687 if (streq(lang, a[0])) {
688 assert(strv_length(a) == 2);
689 *language = TAKE_PTR(a[1]);
690 return 1;
691 }
692 }
693
694 assert_not_reached("should not be here");
695 }
696
697 int x11_convert_to_vconsole(Context *c) {
698 bool modified = false;
699
700 if (isempty(c->x11_layout)) {
701 modified =
702 !isempty(c->vc_keymap) ||
703 !isempty(c->vc_keymap_toggle);
704
705 context_free_vconsole(c);
706 } else {
707 _cleanup_free_ char *new_keymap = NULL;
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 }
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);
724
725 if (!streq_ptr(c->vc_keymap, new_keymap)) {
726 free_and_replace(c->vc_keymap, new_keymap);
727 c->vc_keymap_toggle = mfree(c->vc_keymap_toggle);
728 modified = true;
729 }
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 }
740
741 bool 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
760 static 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
765 static 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
805 int 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;
848 r = copy_xattr(fileno(fr), fileno(fw));
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
930 int 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 }