1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 /***
3   Copyright © 2016 Michal Soltys <soltys@ziu.info>
4 ***/
5 
6 #include <errno.h>
7 #include <fcntl.h>
8 #include <limits.h>
9 #include <linux/kd.h>
10 #include <linux/tiocl.h>
11 #include <linux/vt.h>
12 #include <stdbool.h>
13 #include <stdlib.h>
14 #include <sys/ioctl.h>
15 #include <sysexits.h>
16 #include <termios.h>
17 #include <sys/stat.h>
18 #include <sys/types.h>
19 #include <unistd.h>
20 
21 #include "alloc-util.h"
22 #include "env-file.h"
23 #include "errno-util.h"
24 #include "fd-util.h"
25 #include "fileio.h"
26 #include "io-util.h"
27 #include "locale-util.h"
28 #include "log.h"
29 #include "proc-cmdline.h"
30 #include "process-util.h"
31 #include "signal-util.h"
32 #include "stdio-util.h"
33 #include "string-util.h"
34 #include "strv.h"
35 #include "terminal-util.h"
36 #include "util.h"
37 #include "virt.h"
38 
verify_vc_device(int fd)39 static int verify_vc_device(int fd) {
40         unsigned char data[] = {
41                 TIOCL_GETFGCONSOLE,
42         };
43 
44         return RET_NERRNO(ioctl(fd, TIOCLINUX, data));
45 }
46 
verify_vc_allocation(unsigned idx)47 static int verify_vc_allocation(unsigned idx) {
48         char vcname[sizeof("/dev/vcs") + DECIMAL_STR_MAX(unsigned) - 2];
49 
50         xsprintf(vcname, "/dev/vcs%u", idx);
51 
52         return RET_NERRNO(access(vcname, F_OK));
53 }
54 
verify_vc_allocation_byfd(int fd)55 static int verify_vc_allocation_byfd(int fd) {
56         struct vt_stat vcs = {};
57 
58         if (ioctl(fd, VT_GETSTATE, &vcs) < 0)
59                 return -errno;
60 
61         return verify_vc_allocation(vcs.v_active);
62 }
63 
verify_vc_kbmode(int fd)64 static int verify_vc_kbmode(int fd) {
65         int curr_mode;
66 
67         /*
68          * Make sure we only adjust consoles in K_XLATE or K_UNICODE mode.
69          * Otherwise we would (likely) interfere with X11's processing of the
70          * key events.
71          *
72          * http://lists.freedesktop.org/archives/systemd-devel/2013-February/008573.html
73          */
74 
75         if (ioctl(fd, KDGKBMODE, &curr_mode) < 0)
76                 return -errno;
77 
78         return IN_SET(curr_mode, K_XLATE, K_UNICODE) ? 0 : -EBUSY;
79 }
80 
toggle_utf8_vc(const char * name,int fd,bool utf8)81 static int toggle_utf8_vc(const char *name, int fd, bool utf8) {
82         int r;
83         struct termios tc = {};
84 
85         assert(name);
86         assert(fd >= 0);
87 
88         r = ioctl(fd, KDSKBMODE, utf8 ? K_UNICODE : K_XLATE);
89         if (r < 0)
90                 return log_warning_errno(errno, "Failed to %s UTF-8 kbdmode on %s: %m", enable_disable(utf8), name);
91 
92         r = loop_write(fd, utf8 ? "\033%G" : "\033%@", 3, false);
93         if (r < 0)
94                 return log_warning_errno(r, "Failed to %s UTF-8 term processing on %s: %m", enable_disable(utf8), name);
95 
96         r = tcgetattr(fd, &tc);
97         if (r >= 0) {
98                 SET_FLAG(tc.c_iflag, IUTF8, utf8);
99                 r = tcsetattr(fd, TCSANOW, &tc);
100         }
101         if (r < 0)
102                 return log_warning_errno(errno, "Failed to %s iutf8 flag on %s: %m", enable_disable(utf8), name);
103 
104         log_debug("UTF-8 kbdmode %sd on %s", enable_disable(utf8), name);
105         return 0;
106 }
107 
toggle_utf8_sysfs(bool utf8)108 static int toggle_utf8_sysfs(bool utf8) {
109         int r;
110 
111         r = write_string_file("/sys/module/vt/parameters/default_utf8", one_zero(utf8), WRITE_STRING_FILE_DISABLE_BUFFER);
112         if (r < 0)
113                 return log_warning_errno(r, "Failed to %s sysfs UTF-8 flag: %m", enable_disable(utf8));
114 
115         log_debug("Sysfs UTF-8 flag %sd", enable_disable(utf8));
116         return 0;
117 }
118 
keyboard_load_and_wait(const char * vc,const char * map,const char * map_toggle,bool utf8)119 static int keyboard_load_and_wait(const char *vc, const char *map, const char *map_toggle, bool utf8) {
120         const char *args[8];
121         unsigned i = 0;
122         pid_t pid;
123         int r;
124 
125         /* An empty map means kernel map */
126         if (isempty(map))
127                 return 0;
128 
129         args[i++] = KBD_LOADKEYS;
130         args[i++] = "-q";
131         args[i++] = "-C";
132         args[i++] = vc;
133         if (utf8)
134                 args[i++] = "-u";
135         args[i++] = map;
136         if (map_toggle)
137                 args[i++] = map_toggle;
138         args[i++] = NULL;
139 
140         if (DEBUG_LOGGING) {
141                 _cleanup_free_ char *cmd = NULL;
142 
143                 cmd = strv_join((char**) args, " ");
144                 log_debug("Executing \"%s\"...", strnull(cmd));
145         }
146 
147         r = safe_fork("(loadkeys)", FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_RLIMIT_NOFILE_SAFE|FORK_LOG, &pid);
148         if (r < 0)
149                 return r;
150         if (r == 0) {
151                 execv(args[0], (char **) args);
152                 _exit(EXIT_FAILURE);
153         }
154 
155         return wait_for_terminate_and_check(KBD_LOADKEYS, pid, WAIT_LOG);
156 }
157 
font_load_and_wait(const char * vc,const char * font,const char * map,const char * unimap)158 static int font_load_and_wait(const char *vc, const char *font, const char *map, const char *unimap) {
159         const char *args[9];
160         unsigned i = 0;
161         pid_t pid;
162         int r;
163 
164         /* Any part can be set independently */
165         if (isempty(font) && isempty(map) && isempty(unimap))
166                 return 0;
167 
168         args[i++] = KBD_SETFONT;
169         args[i++] = "-C";
170         args[i++] = vc;
171         if (!isempty(map)) {
172                 args[i++] = "-m";
173                 args[i++] = map;
174         }
175         if (!isempty(unimap)) {
176                 args[i++] = "-u";
177                 args[i++] = unimap;
178         }
179         if (!isempty(font))
180                 args[i++] = font;
181         args[i++] = NULL;
182 
183         if (DEBUG_LOGGING) {
184                 _cleanup_free_ char *cmd = NULL;
185 
186                 cmd = strv_join((char**) args, " ");
187                 log_debug("Executing \"%s\"...", strnull(cmd));
188         }
189 
190         r = safe_fork("(setfont)", FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_RLIMIT_NOFILE_SAFE|FORK_LOG, &pid);
191         if (r < 0)
192                 return r;
193         if (r == 0) {
194                 execv(args[0], (char **) args);
195                 _exit(EXIT_FAILURE);
196         }
197 
198         return wait_for_terminate_and_check(KBD_SETFONT, pid, WAIT_LOG);
199 }
200 
201 /*
202  * A newly allocated VT uses the font from the source VT. Here
203  * we update all possibly already allocated VTs with the configured
204  * font. It also allows to restart systemd-vconsole-setup.service,
205  * to apply a new font to all VTs.
206  *
207  * We also setup per-console utf8 related stuff: kbdmode, term
208  * processing, stty iutf8.
209  */
setup_remaining_vcs(int src_fd,unsigned src_idx,bool utf8)210 static void setup_remaining_vcs(int src_fd, unsigned src_idx, bool utf8) {
211         struct console_font_op cfo = {
212                 .op = KD_FONT_OP_GET,
213                 .width = UINT_MAX, .height = UINT_MAX,
214                 .charcount = UINT_MAX,
215         };
216         struct unimapinit adv = {};
217         struct unimapdesc unimapd;
218         _cleanup_free_ struct unipair* unipairs = NULL;
219         _cleanup_free_ void *fontbuf = NULL;
220         unsigned i;
221         int log_level;
222         int r;
223 
224         unipairs = new(struct unipair, USHRT_MAX);
225         if (!unipairs) {
226                 log_oom();
227                 return;
228         }
229 
230         log_level = LOG_WARNING;
231 
232         /* get metadata of the current font (width, height, count) */
233         r = ioctl(src_fd, KDFONTOP, &cfo);
234         if (r < 0) {
235                 /* We might be called to operate on the dummy console (to setup keymap
236                  * mainly) when fbcon deferred takeover is used for example. In such case,
237                  * setting font is not supported and is expected to fail. */
238                 if (errno == ENOSYS)
239                         log_level = LOG_DEBUG;
240 
241                 log_full_errno(log_level, errno,
242                                "KD_FONT_OP_GET failed while trying to get the font metadata: %m");
243         } else {
244                 /* verify parameter sanity first */
245                 if (cfo.width > 32 || cfo.height > 32 || cfo.charcount > 512)
246                         log_warning("Invalid font metadata - width: %u (max 32), height: %u (max 32), count: %u (max 512)",
247                                     cfo.width, cfo.height, cfo.charcount);
248                 else {
249                         /*
250                          * Console fonts supported by the kernel are limited in size to 32 x 32 and maximum 512
251                          * characters. Thus with 1 bit per pixel it requires up to 65536 bytes. The height always
252                          * requires 32 per glyph, regardless of the actual height - see the comment above #define
253                          * max_font_size 65536 in drivers/tty/vt/vt.c for more details.
254                          */
255                         fontbuf = malloc_multiply((cfo.width + 7) / 8 * 32, cfo.charcount);
256                         if (!fontbuf) {
257                                 log_oom();
258                                 return;
259                         }
260                         /* get fonts from the source console */
261                         cfo.data = fontbuf;
262                         r = ioctl(src_fd, KDFONTOP, &cfo);
263                         if (r < 0)
264                                 log_warning_errno(errno, "KD_FONT_OP_GET failed while trying to read the font data: %m");
265                         else {
266                                 unimapd.entries  = unipairs;
267                                 unimapd.entry_ct = USHRT_MAX;
268                                 r = ioctl(src_fd, GIO_UNIMAP, &unimapd);
269                                 if (r < 0)
270                                         log_warning_errno(errno, "GIO_UNIMAP failed while trying to read unicode mappings: %m");
271                                 else
272                                         cfo.op = KD_FONT_OP_SET;
273                         }
274                 }
275         }
276 
277         if (cfo.op != KD_FONT_OP_SET)
278                 log_full(log_level, "Fonts will not be copied to remaining consoles");
279 
280         for (i = 1; i <= 63; i++) {
281                 char ttyname[sizeof("/dev/tty63")];
282                 _cleanup_close_ int fd_d = -1;
283 
284                 if (i == src_idx || verify_vc_allocation(i) < 0)
285                         continue;
286 
287                 /* try to open terminal */
288                 xsprintf(ttyname, "/dev/tty%u", i);
289                 fd_d = open_terminal(ttyname, O_RDWR|O_CLOEXEC|O_NOCTTY);
290                 if (fd_d < 0) {
291                         log_warning_errno(fd_d, "Unable to open tty%u, fonts will not be copied: %m", i);
292                         continue;
293                 }
294 
295                 if (verify_vc_kbmode(fd_d) < 0)
296                         continue;
297 
298                 (void) toggle_utf8_vc(ttyname, fd_d, utf8);
299 
300                 if (cfo.op != KD_FONT_OP_SET)
301                         continue;
302 
303                 r = ioctl(fd_d, KDFONTOP, &cfo);
304                 if (r < 0) {
305                         int last_errno, mode;
306 
307                         /* The fonts couldn't have been copied. It might be due to the
308                          * terminal being in graphical mode. In this case the kernel
309                          * returns -EINVAL which is too generic for distinguishing this
310                          * specific case. So we need to retrieve the terminal mode and if
311                          * the graphical mode is in used, let's assume that something else
312                          * is using the terminal and the failure was expected as we
313                          * shouldn't have tried to copy the fonts. */
314 
315                         last_errno = errno;
316                         if (ioctl(fd_d, KDGETMODE, &mode) >= 0 && mode != KD_TEXT)
317                                 log_debug("KD_FONT_OP_SET skipped: tty%u is not in text mode", i);
318                         else
319                                 log_warning_errno(last_errno, "KD_FONT_OP_SET failed, fonts will not be copied to tty%u: %m", i);
320 
321                         continue;
322                 }
323 
324                 /*
325                  * copy unicode translation table unimapd is a ushort count and a pointer
326                  * to an array of struct unipair { ushort, ushort }
327                  */
328                 r = ioctl(fd_d, PIO_UNIMAPCLR, &adv);
329                 if (r < 0) {
330                         log_warning_errno(errno, "PIO_UNIMAPCLR failed, unimaps might be incorrect for tty%u: %m", i);
331                         continue;
332                 }
333 
334                 r = ioctl(fd_d, PIO_UNIMAP, &unimapd);
335                 if (r < 0) {
336                         log_warning_errno(errno, "PIO_UNIMAP failed, unimaps might be incorrect for tty%u: %m", i);
337                         continue;
338                 }
339 
340                 log_debug("Font and unimap successfully copied to %s", ttyname);
341         }
342 }
343 
find_source_vc(char ** ret_path,unsigned * ret_idx)344 static int find_source_vc(char **ret_path, unsigned *ret_idx) {
345         _cleanup_free_ char *path = NULL;
346         int r, err = 0;
347         unsigned i;
348 
349         path = new(char, sizeof("/dev/tty63"));
350         if (!path)
351                 return log_oom();
352 
353         for (i = 1; i <= 63; i++) {
354                 _cleanup_close_ int fd = -1;
355 
356                 r = verify_vc_allocation(i);
357                 if (r < 0) {
358                         if (!err)
359                                 err = -r;
360                         continue;
361                 }
362 
363                 sprintf(path, "/dev/tty%u", i);
364                 fd = open_terminal(path, O_RDWR|O_CLOEXEC|O_NOCTTY);
365                 if (fd < 0) {
366                         if (!err)
367                                 err = -fd;
368                         continue;
369                 }
370                 r = verify_vc_kbmode(fd);
371                 if (r < 0) {
372                         if (!err)
373                                 err = -r;
374                         continue;
375                 }
376 
377                 /* all checks passed, return this one as a source console */
378                 *ret_idx = i;
379                 *ret_path = TAKE_PTR(path);
380                 return TAKE_FD(fd);
381         }
382 
383         return log_error_errno(err, "No usable source console found: %m");
384 }
385 
verify_source_vc(char ** ret_path,const char * src_vc)386 static int verify_source_vc(char **ret_path, const char *src_vc) {
387         _cleanup_close_ int fd = -1;
388         char *path;
389         int r;
390 
391         fd = open_terminal(src_vc, O_RDWR|O_CLOEXEC|O_NOCTTY);
392         if (fd < 0)
393                 return log_error_errno(fd, "Failed to open %s: %m", src_vc);
394 
395         r = verify_vc_device(fd);
396         if (r < 0)
397                 return log_error_errno(r, "Device %s is not a virtual console: %m", src_vc);
398 
399         r = verify_vc_allocation_byfd(fd);
400         if (r < 0)
401                 return log_error_errno(r, "Virtual console %s is not allocated: %m", src_vc);
402 
403         r = verify_vc_kbmode(fd);
404         if (r < 0)
405                 return log_error_errno(r, "Virtual console %s is not in K_XLATE or K_UNICODE: %m", src_vc);
406 
407         path = strdup(src_vc);
408         if (!path)
409                 return log_oom();
410 
411         *ret_path = path;
412         return TAKE_FD(fd);
413 }
414 
main(int argc,char ** argv)415 int main(int argc, char **argv) {
416         _cleanup_free_ char
417                 *vc = NULL,
418                 *vc_keymap = NULL, *vc_keymap_toggle = NULL,
419                 *vc_font = NULL, *vc_font_map = NULL, *vc_font_unimap = NULL;
420         _cleanup_close_ int fd = -1;
421         bool utf8, keyboard_ok;
422         unsigned idx = 0;
423         int r;
424 
425         log_setup();
426 
427         umask(0022);
428 
429         if (argv[1])
430                 fd = verify_source_vc(&vc, argv[1]);
431         else
432                 fd = find_source_vc(&vc, &idx);
433         if (fd < 0)
434                 return EXIT_FAILURE;
435 
436         utf8 = is_locale_utf8();
437 
438         r = parse_env_file(NULL, "/etc/vconsole.conf",
439                            "KEYMAP", &vc_keymap,
440                            "KEYMAP_TOGGLE", &vc_keymap_toggle,
441                            "FONT", &vc_font,
442                            "FONT_MAP", &vc_font_map,
443                            "FONT_UNIMAP", &vc_font_unimap);
444         if (r < 0 && r != -ENOENT)
445                 log_warning_errno(r, "Failed to read /etc/vconsole.conf: %m");
446 
447         /* Let the kernel command line override /etc/vconsole.conf */
448         r = proc_cmdline_get_key_many(
449                         PROC_CMDLINE_STRIP_RD_PREFIX,
450                         "vconsole.keymap", &vc_keymap,
451                         "vconsole.keymap_toggle", &vc_keymap_toggle,
452                         "vconsole.font", &vc_font,
453                         "vconsole.font_map", &vc_font_map,
454                         "vconsole.font_unimap", &vc_font_unimap,
455                         /* compatibility with obsolete multiple-dot scheme */
456                         "vconsole.keymap.toggle", &vc_keymap_toggle,
457                         "vconsole.font.map", &vc_font_map,
458                         "vconsole.font.unimap", &vc_font_unimap);
459         if (r < 0 && r != -ENOENT)
460                 log_warning_errno(r, "Failed to read /proc/cmdline: %m");
461 
462         (void) toggle_utf8_sysfs(utf8);
463         (void) toggle_utf8_vc(vc, fd, utf8);
464 
465         r = font_load_and_wait(vc, vc_font, vc_font_map, vc_font_unimap);
466         keyboard_ok = keyboard_load_and_wait(vc, vc_keymap, vc_keymap_toggle, utf8) == 0;
467 
468         if (idx > 0) {
469                 if (r == 0)
470                         setup_remaining_vcs(fd, idx, utf8);
471                 else if (r == EX_OSERR)
472                         /* setfont returns EX_OSERR when ioctl(KDFONTOP/PIO_FONTX/PIO_FONTX) fails.
473                          * This might mean various things, but in particular lack of a graphical
474                          * console. Let's be generous and not treat this as an error. */
475                         log_notice("Setting fonts failed with a \"system error\", ignoring.");
476                 else
477                         log_warning("Setting source virtual console failed, ignoring remaining ones");
478         }
479 
480         return IN_SET(r, 0, EX_OSERR) && keyboard_ok ? EXIT_SUCCESS : EXIT_FAILURE;
481 }
482