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