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