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