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