1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
8 #include "bus-polkit.h"
10 #include "env-file-label.h"
14 #include "fileio-label.h"
18 #include "localed-util.h"
20 #include "mkdir-label.h"
21 #include "nulstr-util.h"
22 #include "process-util.h"
23 #include "string-util.h"
25 #include "tmpfile-util.h"
27 static bool startswith_comma(const char *s
, const char *prefix
) {
28 s
= startswith(s
, prefix
);
32 return IN_SET(*s
, ',', '\0');
35 static const char* systemd_kbd_model_map(void) {
38 s
= getenv("SYSTEMD_KBD_MODEL_MAP");
42 return SYSTEMD_KBD_MODEL_MAP
;
45 static const char* systemd_language_fallback_map(void) {
48 s
= getenv("SYSTEMD_LANGUAGE_FALLBACK_MAP");
52 return SYSTEMD_LANGUAGE_FALLBACK_MAP
;
55 static 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
);
62 static void context_free_vconsole(Context
*c
) {
63 c
->vc_keymap
= mfree(c
->vc_keymap
);
64 c
->vc_keymap_toggle
= mfree(c
->vc_keymap_toggle
);
67 void context_clear(Context
*c
) {
68 locale_context_clear(&c
->locale_context
);
70 context_free_vconsole(c
);
72 sd_bus_message_unref(c
->locale_cache
);
73 sd_bus_message_unref(c
->x11_cache
);
74 sd_bus_message_unref(c
->vc_cache
);
76 bus_verify_polkit_async_registry_free(c
->polkit_registry
);
79 int locale_read_data(Context
*c
, sd_bus_message
*m
) {
82 /* Do not try to re-read the file within single bus operation. */
84 if (m
== c
->locale_cache
)
87 sd_bus_message_unref(c
->locale_cache
);
88 c
->locale_cache
= sd_bus_message_ref(m
);
91 return locale_context_load(&c
->locale_context
, LOCALE_LOAD_LOCALE_CONF
| LOCALE_LOAD_ENVIRONMENT
| LOCALE_LOAD_SIMPLIFY
);
94 int vconsole_read_data(Context
*c
, sd_bus_message
*m
) {
98 /* Do not try to re-read the file within single bus operation. */
100 if (m
== c
->vc_cache
)
103 sd_bus_message_unref(c
->vc_cache
);
104 c
->vc_cache
= sd_bus_message_ref(m
);
107 if (stat("/etc/vconsole.conf", &st
) < 0) {
111 c
->vc_mtime
= USEC_INFINITY
;
112 context_free_vconsole(c
);
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
)
122 context_free_vconsole(c
);
124 return parse_env_file(NULL
, "/etc/vconsole.conf",
125 "KEYMAP", &c
->vc_keymap
,
126 "KEYMAP_TOGGLE", &c
->vc_keymap_toggle
);
129 int x11_read_data(Context
*c
, sd_bus_message
*m
) {
130 _cleanup_fclose_
FILE *f
= NULL
;
131 bool in_section
= false;
136 /* Do not try to re-read the file within single bus operation. */
138 if (m
== c
->x11_cache
)
141 sd_bus_message_unref(c
->x11_cache
);
142 c
->x11_cache
= sd_bus_message_ref(m
);
145 if (stat("/etc/X11/xorg.conf.d/00-keyboard.conf", &st
) < 0) {
149 c
->x11_mtime
= USEC_INFINITY
;
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
)
162 f
= fopen("/etc/X11/xorg.conf.d/00-keyboard.conf", "re");
167 _cleanup_free_
char *line
= NULL
;
170 r
= read_line(f
, LONG_LINE_MAX
, &line
);
177 if (IN_SET(l
[0], 0, '#'))
180 if (in_section
&& first_word(l
, "Option")) {
181 _cleanup_strv_free_
char **a
= NULL
;
183 r
= strv_split_full(&a
, l
, WHITESPACE
, EXTRACT_UNQUOTE
);
187 if (strv_length(a
) == 3) {
190 if (streq(a
[1], "XkbLayout"))
192 else if (streq(a
[1], "XkbModel"))
194 else if (streq(a
[1], "XkbVariant"))
196 else if (streq(a
[1], "XkbOptions"))
200 free_and_replace(*p
, a
[2]);
203 } else if (!in_section
&& first_word(l
, "Section")) {
204 _cleanup_strv_free_
char **a
= NULL
;
206 r
= strv_split_full(&a
, l
, WHITESPACE
, EXTRACT_UNQUOTE
);
210 if (strv_length(a
) == 2 && streq(a
[1], "InputClass"))
213 } else if (in_section
&& first_word(l
, "EndSection"))
220 int vconsole_write_data(Context
*c
) {
221 _cleanup_strv_free_
char **l
= NULL
;
225 r
= load_env_file(NULL
, "/etc/vconsole.conf", &l
);
226 if (r
< 0 && r
!= -ENOENT
)
229 r
= strv_env_assign(&l
, "KEYMAP", empty_to_null(c
->vc_keymap
));
233 r
= strv_env_assign(&l
, "KEYMAP_TOGGLE", empty_to_null(c
->vc_keymap_toggle
));
237 if (strv_isempty(l
)) {
238 if (unlink("/etc/vconsole.conf") < 0)
239 return errno
== ENOENT
? 0 : -errno
;
241 c
->vc_mtime
= USEC_INFINITY
;
245 r
= write_env_file_label("/etc/vconsole.conf", l
);
249 if (stat("/etc/vconsole.conf", &st
) >= 0)
250 c
->vc_mtime
= timespec_load(&st
.st_mtim
);
255 int x11_write_data(Context
*c
) {
256 _cleanup_fclose_
FILE *f
= NULL
;
257 _cleanup_free_
char *temp_path
= NULL
;
261 if (isempty(c
->x11_layout
) &&
262 isempty(c
->x11_model
) &&
263 isempty(c
->x11_variant
) &&
264 isempty(c
->x11_options
)) {
266 if (unlink("/etc/X11/xorg.conf.d/00-keyboard.conf") < 0)
267 return errno
== ENOENT
? 0 : -errno
;
269 c
->vc_mtime
= USEC_INFINITY
;
273 (void) mkdir_p_label("/etc/X11/xorg.conf.d", 0755);
274 r
= fopen_temporary("/etc/X11/xorg.conf.d/00-keyboard.conf", &f
, &temp_path
);
278 (void) fchmod(fileno(f
), 0644);
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
);
287 if (!isempty(c
->x11_layout
))
288 fprintf(f
, " Option \"XkbLayout\" \"%s\"\n", c
->x11_layout
);
290 if (!isempty(c
->x11_model
))
291 fprintf(f
, " Option \"XkbModel\" \"%s\"\n", c
->x11_model
);
293 if (!isempty(c
->x11_variant
))
294 fprintf(f
, " Option \"XkbVariant\" \"%s\"\n", c
->x11_variant
);
296 if (!isempty(c
->x11_options
))
297 fprintf(f
, " Option \"XkbOptions\" \"%s\"\n", c
->x11_options
);
299 fputs("EndSection\n", f
);
301 r
= fflush_sync_and_check(f
);
305 if (rename(temp_path
, "/etc/X11/xorg.conf.d/00-keyboard.conf") < 0) {
310 if (stat("/etc/X11/xorg.conf.d/00-keyboard.conf", &st
) >= 0)
311 c
->x11_mtime
= timespec_load(&st
.st_mtim
);
317 (void) unlink(temp_path
);
322 static int read_next_mapping(const char* filename
,
323 unsigned min_fields
, unsigned max_fields
,
324 FILE *f
, unsigned *n
, char ***a
) {
330 _cleanup_free_
char *line
= NULL
;
335 r
= read_line(f
, LONG_LINE_MAX
, &line
);
344 if (IN_SET(l
[0], 0, '#'))
347 r
= strv_split_full(&b
, l
, WHITESPACE
, EXTRACT_UNQUOTE
);
351 length
= strv_length(b
);
352 if (length
< min_fields
|| length
> max_fields
) {
353 log_error("Invalid line %s:%u, ignoring.", filename
, *n
);
366 int vconsole_convert_to_x11(Context
*c
) {
370 map
= systemd_kbd_model_map();
372 if (isempty(c
->vc_keymap
)) {
374 !isempty(c
->x11_layout
) ||
375 !isempty(c
->x11_model
) ||
376 !isempty(c
->x11_variant
) ||
377 !isempty(c
->x11_options
);
381 _cleanup_fclose_
FILE *f
= NULL
;
384 f
= fopen(map
, "re");
389 _cleanup_strv_free_
char **a
= NULL
;
392 r
= read_next_mapping(map
, 5, UINT_MAX
, f
, &n
, &a
);
398 if (!streq(c
->vc_keymap
, a
[0]))
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]))) {
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)
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
));
425 else if (modified
< 0)
426 log_notice("X11 keyboard layout was not modified: no conversion found for \"%s\".",
429 log_debug("X11 keyboard layout did not need to be modified.");
434 int find_converted_keymap(const char *x11_layout
, const char *x11_variant
, char **new_keymap
) {
436 _cleanup_free_
char *n
= NULL
;
439 n
= strjoin(x11_layout
, "-", x11_variant
);
441 n
= strdup(x11_layout
);
445 NULSTR_FOREACH(dir
, KBD_KEYMAP_DIRS
) {
446 _cleanup_free_
char *p
= NULL
, *pz
= NULL
;
449 p
= strjoin(dir
, "xkb/", n
, ".map");
450 pz
= strjoin(dir
, "xkb/", n
, ".map.gz");
454 uncompressed
= access(p
, F_OK
) == 0;
455 if (uncompressed
|| access(pz
, F_OK
) == 0) {
456 log_debug("Found converted keymap %s at %s",
457 n
, uncompressed
? p
: pz
);
459 *new_keymap
= TAKE_PTR(n
);
467 int find_legacy_keymap(Context
*c
, char **ret
) {
469 _cleanup_fclose_
FILE *f
= NULL
;
470 _cleanup_free_
char *new_keymap
= NULL
;
472 unsigned best_matching
= 0;
475 assert(!isempty(c
->x11_layout
));
477 map
= systemd_kbd_model_map();
479 f
= fopen(map
, "re");
484 _cleanup_strv_free_
char **a
= NULL
;
485 unsigned matching
= 0;
487 r
= read_next_mapping(map
, 5, UINT_MAX
, f
, &n
, &a
);
493 /* Determine how well matching this entry is */
494 if (streq(c
->x11_layout
, a
[1]))
495 /* If we got an exact match, this is best */
498 /* We have multiple X layouts, look for an
499 * entry that matches our key with everything
500 * but the first layout stripped off. */
501 if (startswith_comma(c
->x11_layout
, a
[1]))
504 _cleanup_free_
char *x
= NULL
;
506 /* If that didn't work, strip off the
507 * other layouts from the entry, too */
508 x
= strndup(a
[1], strcspn(a
[1], ","));
509 if (startswith_comma(c
->x11_layout
, x
))
515 if (isempty(c
->x11_model
) || streq_ptr(c
->x11_model
, a
[2])) {
518 if (streq_ptr(c
->x11_variant
, a
[3])) {
521 if (streq_ptr(c
->x11_options
, a
[4]))
527 /* The best matching entry so far, then let's save that */
528 if (matching
>= MAX(best_matching
, 1u)) {
529 log_debug("Found legacy keymap %s with score %u",
532 if (matching
> best_matching
) {
533 best_matching
= matching
;
535 r
= free_and_strdup(&new_keymap
, a
[0]);
542 if (best_matching
< 10 && c
->x11_layout
) {
543 /* The best match is only the first part of the X11
544 * keymap. Check if we have a converted map which
545 * matches just the first layout.
547 char *l
, *v
= NULL
, *converted
;
549 l
= strndupa_safe(c
->x11_layout
, strcspn(c
->x11_layout
, ","));
551 v
= strndupa_safe(c
->x11_variant
,
552 strcspn(c
->x11_variant
, ","));
553 r
= find_converted_keymap(l
, v
, &converted
);
557 free_and_replace(new_keymap
, converted
);
560 *ret
= TAKE_PTR(new_keymap
);
564 int find_language_fallback(const char *lang
, char **language
) {
566 _cleanup_fclose_
FILE *f
= NULL
;
572 map
= systemd_language_fallback_map();
574 f
= fopen(map
, "re");
579 _cleanup_strv_free_
char **a
= NULL
;
582 r
= read_next_mapping(map
, 2, 2, f
, &n
, &a
);
586 if (streq(lang
, a
[0])) {
587 assert(strv_length(a
) == 2);
588 *language
= TAKE_PTR(a
[1]);
593 assert_not_reached();
596 int x11_convert_to_vconsole(Context
*c
) {
597 bool modified
= false;
599 if (isempty(c
->x11_layout
)) {
601 !isempty(c
->vc_keymap
) ||
602 !isempty(c
->vc_keymap_toggle
);
604 context_free_vconsole(c
);
606 _cleanup_free_
char *new_keymap
= NULL
;
609 r
= find_converted_keymap(c
->x11_layout
, c
->x11_variant
, &new_keymap
);
613 r
= find_legacy_keymap(c
, &new_keymap
);
618 /* We search for layout-variant match first, but then we also look
619 * for anything which matches just the layout. So it's accurate to say
620 * that we couldn't find anything which matches the layout. */
621 log_notice("No conversion to virtual console map found for \"%s\".",
624 if (!streq_ptr(c
->vc_keymap
, new_keymap
)) {
625 free_and_replace(c
->vc_keymap
, new_keymap
);
626 c
->vc_keymap_toggle
= mfree(c
->vc_keymap_toggle
);
632 log_info("Changing virtual console keymap to '%s' toggle '%s'",
633 strempty(c
->vc_keymap
), strempty(c
->vc_keymap_toggle
));
635 log_debug("Virtual console keymap was not modified.");
640 bool locale_gen_check_available(void) {
642 if (access(LOCALEGEN_PATH
, X_OK
) < 0) {
644 log_warning_errno(errno
, "Unable to determine whether " LOCALEGEN_PATH
" exists and is executable, assuming it is not: %m");
647 if (access("/etc/locale.gen", F_OK
) < 0) {
649 log_warning_errno(errno
, "Unable to determine whether /etc/locale.gen exists, assuming it does not: %m");
659 static bool locale_encoding_is_utf8_or_unspecified(const char *locale
) {
660 const char *c
= strchr(locale
, '.');
661 return !c
|| strcaseeq(c
, ".UTF-8") || strcasestr(locale
, ".UTF-8@");
664 static int locale_gen_locale_supported(const char *locale_entry
) {
665 /* Returns an error valus <= 0 if the locale-gen entry is invalid or unsupported,
666 * 1 in case the locale entry is valid, and -EOPNOTSUPP specifically in case
667 * the distributor has not provided us with a SUPPORTED file to check
668 * locale for validity. */
670 _cleanup_fclose_
FILE *f
= NULL
;
673 assert(locale_entry
);
675 /* Locale templates without country code are never supported */
676 if (!strstr(locale_entry
, "_"))
679 f
= fopen("/usr/share/i18n/SUPPORTED", "re");
682 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
683 "Unable to check validity of locale entry %s: /usr/share/i18n/SUPPORTED does not exist",
689 _cleanup_free_
char *line
= NULL
;
691 r
= read_line(f
, LONG_LINE_MAX
, &line
);
693 return log_debug_errno(r
, "Failed to read /usr/share/i18n/SUPPORTED: %m");
697 line
= strstrip(line
);
698 if (strcaseeq_ptr(line
, locale_entry
))
704 int locale_gen_enable_locale(const char *locale
) {
706 _cleanup_fclose_
FILE *fr
= NULL
, *fw
= NULL
;
707 _cleanup_(unlink_and_freep
) char *temp_path
= NULL
;
708 _cleanup_free_
char *locale_entry
= NULL
;
709 bool locale_enabled
= false, first_line
= false;
710 bool write_new
= false;
716 if (locale_encoding_is_utf8_or_unspecified(locale
)) {
717 locale_entry
= strjoin(locale
, " UTF-8");
721 return -ENOEXEC
; /* We do not process non-UTF-8 locale */
723 r
= locale_gen_locale_supported(locale_entry
);
726 if (r
< 0 && r
!= -EOPNOTSUPP
)
729 fr
= fopen("/etc/locale.gen", "re");
736 r
= fopen_temporary("/etc/locale.gen", &fw
, &temp_path
);
741 (void) fchmod(fileno(fw
), 0644);
743 /* apply mode & xattrs of the original file to new file */
744 r
= copy_access(fileno(fr
), fileno(fw
));
747 r
= copy_xattr(fileno(fr
), fileno(fw
), COPY_ALL_XATTRS
);
749 log_debug_errno(r
, "Failed to copy all xattrs from old to new /etc/locale.gen file, ignoring: %m");
753 /* The config file ends with a line break, which we do not want to include before potentially appending a new locale
754 * instead of uncommenting an existing line. By prepending linebreaks, we can avoid buffering this file but can still write
755 * a nice config file without empty lines */
758 _cleanup_free_
char *line
= NULL
;
761 r
= read_line(fr
, LONG_LINE_MAX
, &line
);
767 if (locale_enabled
) {
768 /* Just complete writing the file if the new locale was already enabled */
776 line
= strstrip(line
);
784 if (line_locale
[0] == '#')
785 line_locale
= strstrip(line_locale
+ 1);
786 else if (strcaseeq_ptr(line_locale
, locale_entry
))
787 return 0; /* the file already had our locale activated, so skip updating it */
789 if (strcaseeq_ptr(line_locale
, locale_entry
)) {
790 /* Uncomment existing line for new locale */
793 fputs(locale_entry
, fw
);
794 locale_enabled
= true;
799 /* The line was not for the locale we want to enable, just copy it */
807 /* Add locale to enable to the end of the file if it was not found as commented line */
808 if (!locale_enabled
) {
811 fputs(locale_entry
, fw
);
815 r
= fflush_sync_and_check(fw
);
819 if (rename(temp_path
, "/etc/locale.gen") < 0)
821 temp_path
= mfree(temp_path
);
829 int locale_gen_run(void) {
834 r
= safe_fork("(sd-localegen)", FORK_RESET_SIGNALS
|FORK_RLIMIT_NOFILE_SAFE
|FORK_CLOSE_ALL_FDS
|FORK_LOG
|FORK_WAIT
, &pid
);
838 execl(LOCALEGEN_PATH
, LOCALEGEN_PATH
, NULL
);