xref: /freebsd/usr.sbin/kbdcontrol/kbdcontrol.c (revision 535af610)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 1994-1995 Søren Schmidt
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer,
12  *    in this position and unchanged.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. The name of the author may not be used to endorse or promote products
17  *    derived from this software without specific prior written permission
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30 
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33 
34 #include <ctype.h>
35 #include <err.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <unistd.h>
40 #include <fcntl.h>
41 #include <sys/kbio.h>
42 #include <sys/consio.h>
43 #include <sys/param.h>
44 #include <sys/queue.h>
45 #include <sys/sysctl.h>
46 #include "path.h"
47 #include "lex.h"
48 
49 #define	SPECIAL		0x80000000
50 
51 static const char ctrl_names[32][4] = {
52 	"nul", "soh", "stx", "etx", "eot", "enq", "ack", "bel",
53 	"bs ", "ht ", "nl ", "vt ", "ff ", "cr ", "so ", "si ",
54 	"dle", "dc1", "dc2", "dc3", "dc4", "nak", "syn", "etb",
55 	"can", "em ", "sub", "esc", "fs ", "gs ", "rs ", "us "
56 	};
57 
58 static const char acc_names[15][5] = {
59 	"dgra", "dacu", "dcir", "dtil", "dmac", "dbre", "ddot",
60 	"duml", "dsla", "drin", "dced", "dapo", "ddac", "dogo",
61 	"dcar",
62 	};
63 
64 static const char acc_names_u[15][5] = {
65 	"DGRA", "DACU", "DCIR", "DTIL", "DMAC", "DBRE", "DDOT",
66 	"DUML", "DSLA", "DRIN", "DCED", "DAPO", "DDAC", "DOGO",
67 	"DCAR",
68 	};
69 
70 static const char fkey_table[96][MAXFK] = {
71 /* 01-04 */	"\033[M", "\033[N", "\033[O", "\033[P",
72 /* 05-08 */	"\033[Q", "\033[R", "\033[S", "\033[T",
73 /* 09-12 */	"\033[U", "\033[V", "\033[W", "\033[X",
74 /* 13-16 */	"\033[Y", "\033[Z", "\033[a", "\033[b",
75 /* 17-20 */	"\033[c", "\033[d", "\033[e", "\033[f",
76 /* 21-24 */	"\033[g", "\033[h", "\033[i", "\033[j",
77 /* 25-28 */	"\033[k", "\033[l", "\033[m", "\033[n",
78 /* 29-32 */	"\033[o", "\033[p", "\033[q", "\033[r",
79 /* 33-36 */	"\033[s", "\033[t", "\033[u", "\033[v",
80 /* 37-40 */	"\033[w", "\033[x", "\033[y", "\033[z",
81 /* 41-44 */	"\033[@", "\033[[", "\033[\\","\033[]",
82 /* 45-48 */     "\033[^", "\033[_", "\033[`", "\033[{",
83 /* 49-52 */	"\033[H", "\033[A", "\033[I", "-"     ,
84 /* 53-56 */	"\033[D", "\033[E", "\033[C", "+"     ,
85 /* 57-60 */	"\033[F", "\033[B", "\033[G", "\033[L",
86 /* 61-64 */     "\177",   "\033[J", "\033[~", "\033[}",
87 /* 65-68 */	""      , ""      , ""      , ""      ,
88 /* 69-72 */	""      , ""      , ""      , ""      ,
89 /* 73-76 */	""      , ""      , ""      , ""      ,
90 /* 77-80 */	""      , ""      , ""      , ""      ,
91 /* 81-84 */	""      , ""      , ""      , ""      ,
92 /* 85-88 */	""      , ""      , ""      , ""      ,
93 /* 89-92 */	""      , ""      , ""      , ""      ,
94 /* 93-96 */	""      , ""      , ""      , ""      ,
95 	};
96 
97 static const int ndelays = nitems(kbdelays);
98 static const int nrepeats = nitems(kbrates);
99 static int	hex = 0;
100 static int	paths_configured = 0;
101 static int	token;
102 
103 int		number;
104 char		letter;
105 
106 static void	add_keymap_path(const char *path);
107 static void	dump_accent_definition(char *name, accentmap_t *accentmap);
108 static void	dump_entry(int value);
109 static void	dump_key_definition(char *name, keymap_t *keymap);
110 static int	get_accent_definition_line(accentmap_t *);
111 static int	get_entry(void);
112 static int	get_key_definition_line(keymap_t *);
113 static void	load_keymap(char *opt, int dumponly);
114 static void	load_default_functionkeys(void);
115 static char *	nextarg(int ac, char **av, int *indp, int oc);
116 static char *	mkfullname(const char *s1, const char *s2, const char *s3);
117 static void	print_accent_definition_line(FILE *fp, int accent,
118 		struct acc_t *key);
119 static void	print_entry(FILE *fp, int value);
120 static void	print_key_definition_line(FILE *fp, int scancode,
121 		struct keyent_t *key);
122 static void	print_keymap(void);
123 static void	release_keyboard(void);
124 static void	mux_keyboard(u_int op, char *kbd);
125 static void	set_bell_values(char *opt);
126 static void	set_functionkey(char *keynumstr, char *string);
127 static void	set_keyboard(char *device);
128 static void	set_keyrates(char *opt);
129 static void	show_kbd_info(void);
130 static void	usage(void) __dead2;
131 
132 struct pathent {
133 	STAILQ_ENTRY(pathent) next;
134 	char *path;
135 };
136 static STAILQ_HEAD(, pathent) pathlist = STAILQ_HEAD_INITIALIZER(pathlist);
137 
138 /* Detect presence of vt(4). */
139 static int
140 is_vt4(void)
141 {
142 	char vty_name[4] = "";
143 	size_t len = sizeof(vty_name);
144 
145 	if (sysctlbyname("kern.vty", vty_name, &len, NULL, 0) != 0)
146 		return (0);
147 	return (strcmp(vty_name, "vt") == 0);
148 }
149 
150 static char *
151 nextarg(int ac, char **av, int *indp, int oc)
152 {
153 	if (*indp < ac)
154 		return(av[(*indp)++]);
155 	warnx("option requires two arguments -- %c", oc);
156 	usage();
157 }
158 
159 
160 static char *
161 mkfullname(const char *s1, const char *s2, const char *s3)
162 {
163 	static char	*buf = NULL;
164 	static int	bufl = 0;
165 	int		f;
166 
167 	f = strlen(s1) + strlen(s2) + strlen(s3) + 1;
168 	if (f > bufl) {
169 		if (buf)
170 			buf = (char *)realloc(buf, f);
171 		else
172 			buf = (char *)malloc(f);
173 	}
174 	if (!buf) {
175 		bufl = 0;
176 		return(NULL);
177 	}
178 
179 	bufl = f;
180 	strcpy(buf, s1);
181 	strcat(buf, s2);
182 	strcat(buf, s3);
183 	return(buf);
184 }
185 
186 
187 static int
188 get_entry(void)
189 {
190 	switch ((token = yylex())) {
191 	case TNOP:
192 		return NOP | SPECIAL;
193 	case TLSH:
194 		return LSH | SPECIAL;
195 	case TRSH:
196 		return RSH | SPECIAL;
197 	case TCLK:
198 		return CLK | SPECIAL;
199 	case TNLK:
200 		return NLK | SPECIAL;
201 	case TSLK:
202 		return SLK | SPECIAL;
203 	case TBTAB:
204 		return BTAB | SPECIAL;
205 	case TLALT:
206 		return LALT | SPECIAL;
207 	case TLCTR:
208 		return LCTR | SPECIAL;
209 	case TNEXT:
210 		return NEXT | SPECIAL;
211 	case TPREV:
212 		return PREV | SPECIAL;
213 	case TRCTR:
214 		return RCTR | SPECIAL;
215 	case TRALT:
216 		return RALT | SPECIAL;
217 	case TALK:
218 		return ALK | SPECIAL;
219 	case TASH:
220 		return ASH | SPECIAL;
221 	case TMETA:
222 		return META | SPECIAL;
223 	case TRBT:
224 		return RBT | SPECIAL;
225 	case TDBG:
226 		return DBG | SPECIAL;
227 	case TSUSP:
228 		return SUSP | SPECIAL;
229 	case TSPSC:
230 		return SPSC | SPECIAL;
231 	case TPANIC:
232 		return PNC | SPECIAL;
233 	case TLSHA:
234 		return LSHA | SPECIAL;
235 	case TRSHA:
236 		return RSHA | SPECIAL;
237 	case TLCTRA:
238 		return LCTRA | SPECIAL;
239 	case TRCTRA:
240 		return RCTRA | SPECIAL;
241 	case TLALTA:
242 		return LALTA | SPECIAL;
243 	case TRALTA:
244 		return RALTA | SPECIAL;
245 	case THALT:
246 		return HALT | SPECIAL;
247 	case TPDWN:
248 		return PDWN | SPECIAL;
249 	case TPASTE:
250 		return PASTE | SPECIAL;
251 	case TACC:
252 		if (ACC(number) > L_ACC)
253 			return -1;
254 		return ACC(number) | SPECIAL;
255 	case TFUNC:
256 		if (F(number) > L_FN)
257 			return -1;
258 		return F(number) | SPECIAL;
259 	case TSCRN:
260 		if (S(number) > L_SCR)
261 			return -1;
262 		return S(number) | SPECIAL;
263 	case TLET:
264 		return (unsigned char)letter;
265 	case TNUM:
266 		if (number < 0x000000 || number > 0x10FFFF)
267 			return -1;
268 		return number;
269 	default:
270 		return -1;
271 	}
272 }
273 
274 static int
275 get_definition_line(FILE *file, keymap_t *keymap, accentmap_t *accentmap)
276 {
277 	int c;
278 
279 	yyin = file;
280 
281 	if (token < 0)
282 		token = yylex();
283 	switch (token) {
284 	case TNUM:
285 		c = get_key_definition_line(keymap);
286 		if (c < 0)
287 			errx(1, "invalid key definition");
288 		if (c > keymap->n_keys)
289 			keymap->n_keys = c;
290 		break;
291 	case TACC:
292 		c = get_accent_definition_line(accentmap);
293 		if (c < 0)
294 			errx(1, "invalid accent key definition");
295 		if (c > accentmap->n_accs)
296 			accentmap->n_accs = c;
297 		break;
298 	case 0:
299 		/* EOF */
300 		return -1;
301 	default:
302 		errx(1, "illegal definition line");
303 	}
304 	return c;
305 }
306 
307 static int
308 get_key_definition_line(keymap_t *map)
309 {
310 	int i, def, scancode;
311 
312 	/* check scancode number */
313 	if (number < 0 || number >= NUM_KEYS)
314 		return -1;
315 	scancode = number;
316 
317 	/* get key definitions */
318 	map->key[scancode].spcl = 0;
319 	for (i=0; i<NUM_STATES; i++) {
320 		if ((def = get_entry()) == -1)
321 			return -1;
322 		if (def & SPECIAL)
323 			map->key[scancode].spcl |= (0x80 >> i);
324 		map->key[scancode].map[i] = def & ~SPECIAL;
325 	}
326 	/* get lock state key def */
327 	if ((token = yylex()) != TFLAG)
328 		return -1;
329 	map->key[scancode].flgs = number;
330 	token = yylex();
331 	return (scancode + 1);
332 }
333 
334 static int
335 get_accent_definition_line(accentmap_t *map)
336 {
337 	int accent;
338 	int c1, c2;
339 	int i;
340 
341 	if (ACC(number) < F_ACC || ACC(number) > L_ACC)
342 		/* number out of range */
343 		return -1;
344 	accent = number;
345 	if (map->acc[accent].accchar != 0) {
346 		/* this entry has already been defined before! */
347 		errx(1, "duplicated accent key definition");
348 	}
349 
350 	switch ((token = yylex())) {
351 	case TLET:
352 		map->acc[accent].accchar = letter;
353 		break;
354 	case TNUM:
355 		map->acc[accent].accchar = number;
356 		break;
357 	default:
358 		return -1;
359 	}
360 
361 	for (i = 0; (token = yylex()) == '(';) {
362 		switch ((token = yylex())) {
363 		case TLET:
364 			c1 = letter;
365 			break;
366 		case TNUM:
367 			c1 = number;
368 			break;
369 		default:
370 			return -1;
371 		}
372 		switch ((token = yylex())) {
373 		case TLET:
374 			c2 = letter;
375 			break;
376 		case TNUM:
377 			c2 = number;
378 			break;
379 		default:
380 			return -1;
381 		}
382 		if ((token = yylex()) != ')')
383 			return -1;
384 		if (i >= NUM_ACCENTCHARS) {
385 			warnx("too many accented characters, ignored");
386 			continue;
387 		}
388 		map->acc[accent].map[i][0] = c1;
389 		map->acc[accent].map[i][1] = c2;
390 		++i;
391 	}
392 	return (accent + 1);
393 }
394 
395 static void
396 print_entry(FILE *fp, int value)
397 {
398 	int val = value & ~SPECIAL;
399 
400 	switch (value) {
401 	case NOP | SPECIAL:
402 		fprintf(fp, " nop   ");
403 		break;
404 	case LSH | SPECIAL:
405 		fprintf(fp, " lshift");
406 		break;
407 	case RSH | SPECIAL:
408 		fprintf(fp, " rshift");
409 		break;
410 	case CLK | SPECIAL:
411 		fprintf(fp, " clock ");
412 		break;
413 	case NLK | SPECIAL:
414 		fprintf(fp, " nlock ");
415 		break;
416 	case SLK | SPECIAL:
417 		fprintf(fp, " slock ");
418 		break;
419 	case BTAB | SPECIAL:
420 		fprintf(fp, " btab  ");
421 		break;
422 	case LALT | SPECIAL:
423 		fprintf(fp, " lalt  ");
424 		break;
425 	case LCTR | SPECIAL:
426 		fprintf(fp, " lctrl ");
427 		break;
428 	case NEXT | SPECIAL:
429 		fprintf(fp, " nscr  ");
430 		break;
431 	case PREV | SPECIAL:
432 		fprintf(fp, " pscr  ");
433 		break;
434 	case RCTR | SPECIAL:
435 		fprintf(fp, " rctrl ");
436 		break;
437 	case RALT | SPECIAL:
438 		fprintf(fp, " ralt  ");
439 		break;
440 	case ALK | SPECIAL:
441 		fprintf(fp, " alock ");
442 		break;
443 	case ASH | SPECIAL:
444 		fprintf(fp, " ashift");
445 		break;
446 	case META | SPECIAL:
447 		fprintf(fp, " meta  ");
448 		break;
449 	case RBT | SPECIAL:
450 		fprintf(fp, " boot  ");
451 		break;
452 	case DBG | SPECIAL:
453 		fprintf(fp, " debug ");
454 		break;
455 	case SUSP | SPECIAL:
456 		fprintf(fp, " susp  ");
457 		break;
458 	case SPSC | SPECIAL:
459 		fprintf(fp, " saver ");
460 		break;
461 	case PNC | SPECIAL:
462 		fprintf(fp, " panic ");
463 		break;
464 	case LSHA | SPECIAL:
465 		fprintf(fp, " lshifta");
466 		break;
467 	case RSHA | SPECIAL:
468 		fprintf(fp, " rshifta");
469 		break;
470 	case LCTRA | SPECIAL:
471 		fprintf(fp, " lctrla");
472 		break;
473 	case RCTRA | SPECIAL:
474 		fprintf(fp, " rctrla");
475 		break;
476 	case LALTA | SPECIAL:
477 		fprintf(fp, " lalta ");
478 		break;
479 	case RALTA | SPECIAL:
480 		fprintf(fp, " ralta ");
481 		break;
482 	case HALT | SPECIAL:
483 		fprintf(fp, " halt  ");
484 		break;
485 	case PDWN | SPECIAL:
486 		fprintf(fp, " pdwn  ");
487 		break;
488 	case PASTE | SPECIAL:
489 		fprintf(fp, " paste ");
490 		break;
491 	default:
492 		if (value & SPECIAL) {
493 		 	if (val >= F_FN && val <= L_FN)
494 				fprintf(fp, " fkey%02d", val - F_FN + 1);
495 		 	else if (val >= F_SCR && val <= L_SCR)
496 				fprintf(fp, " scr%02d ", val - F_SCR + 1);
497 		 	else if (val >= F_ACC && val <= L_ACC)
498 				fprintf(fp, " %-6s", acc_names[val - F_ACC]);
499 			else if (hex)
500 				fprintf(fp, " 0x%02x  ", val);
501 			else
502 				fprintf(fp, " %3d   ", val);
503 		}
504 		else {
505 			if (val < ' ')
506 				fprintf(fp, " %s   ", ctrl_names[val]);
507 			else if (val == 127)
508 				fprintf(fp, " del   ");
509 			else if (isascii(val) && isprint(val))
510 				fprintf(fp, " '%c'   ", val);
511 			else if (hex)
512 				fprintf(fp, " 0x%02x  ", val);
513 			else
514 				fprintf(fp, " %3d   ", val);
515 		}
516 	}
517 }
518 
519 static void
520 print_key_definition_line(FILE *fp, int scancode, struct keyent_t *key)
521 {
522 	int i;
523 
524 	/* print scancode number */
525 	if (hex)
526 		fprintf(fp, " 0x%02x  ", scancode);
527 	else
528 		fprintf(fp, "  %03d  ", scancode);
529 
530 	/* print key definitions */
531 	for (i=0; i<NUM_STATES; i++) {
532 		if (key->spcl & (0x80 >> i))
533 			print_entry(fp, key->map[i] | SPECIAL);
534 		else
535 			print_entry(fp, key->map[i]);
536 	}
537 
538 	/* print lock state key def */
539 	switch (key->flgs) {
540 	case 0:
541 		fprintf(fp, "  O\n");
542 		break;
543 	case 1:
544 		fprintf(fp, "  C\n");
545 		break;
546 	case 2:
547 		fprintf(fp, "  N\n");
548 		break;
549 	case 3:
550 		fprintf(fp, "  B\n");
551 		break;
552 	}
553 }
554 
555 static void
556 print_accent_definition_line(FILE *fp, int accent, struct acc_t *key)
557 {
558 	int c;
559 	int i;
560 
561 	if (key->accchar == 0)
562 		return;
563 
564 	/* print accent number */
565 	fprintf(fp, "  %-6s", acc_names[accent]);
566 	if (isascii(key->accchar) && isprint(key->accchar))
567 		fprintf(fp, "'%c'  ", key->accchar);
568 	else if (hex)
569 		fprintf(fp, "0x%02x ", key->accchar);
570 	else
571 		fprintf(fp, "%03d  ", key->accchar);
572 
573 	for (i = 0; i < NUM_ACCENTCHARS; ++i) {
574 		c = key->map[i][0];
575 		if (c == 0)
576 			break;
577 		if ((i > 0) && ((i % 4) == 0))
578 			fprintf(fp, "\n             ");
579 		if (isascii(c) && isprint(c))
580 			fprintf(fp, "( '%c' ", c);
581 		else if (hex)
582 			fprintf(fp, "(0x%02x ", c);
583 		else
584 			fprintf(fp, "( %03d ", c);
585 		c = key->map[i][1];
586 		if (isascii(c) && isprint(c))
587 			fprintf(fp, "'%c' ) ", c);
588 		else if (hex)
589 			fprintf(fp, "0x%02x) ", c);
590 		else
591 			fprintf(fp, "%03d ) ", c);
592 	}
593 	fprintf(fp, "\n");
594 }
595 
596 static void
597 dump_entry(int value)
598 {
599 	if (value & SPECIAL) {
600 		value &= ~SPECIAL;
601 		switch (value) {
602 		case NOP:
603 			printf("  NOP, ");
604 			break;
605 		case LSH:
606 			printf("  LSH, ");
607 			break;
608 		case RSH:
609 			printf("  RSH, ");
610 			break;
611 		case CLK:
612 			printf("  CLK, ");
613 			break;
614 		case NLK:
615 			printf("  NLK, ");
616 			break;
617 		case SLK:
618 			printf("  SLK, ");
619 			break;
620 		case BTAB:
621 			printf(" BTAB, ");
622 			break;
623 		case LALT:
624 			printf(" LALT, ");
625 			break;
626 		case LCTR:
627 			printf(" LCTR, ");
628 			break;
629 		case NEXT:
630 			printf(" NEXT, ");
631 			break;
632 		case PREV:
633 			printf(" PREV, ");
634 			break;
635 		case RCTR:
636 			printf(" RCTR, ");
637 			break;
638 		case RALT:
639 			printf(" RALT, ");
640 			break;
641 		case ALK:
642 			printf("  ALK, ");
643 			break;
644 		case ASH:
645 			printf("  ASH, ");
646 			break;
647 		case META:
648 			printf(" META, ");
649 			break;
650 		case RBT:
651 			printf("  RBT, ");
652 			break;
653 		case DBG:
654 			printf("  DBG, ");
655 			break;
656 		case SUSP:
657 			printf(" SUSP, ");
658 			break;
659 		case SPSC:
660 			printf(" SPSC, ");
661 			break;
662 		case PNC:
663 			printf("  PNC, ");
664 			break;
665 		case LSHA:
666 			printf(" LSHA, ");
667 			break;
668 		case RSHA:
669 			printf(" RSHA, ");
670 			break;
671 		case LCTRA:
672 			printf("LCTRA, ");
673 			break;
674 		case RCTRA:
675 			printf("RCTRA, ");
676 			break;
677 		case LALTA:
678 			printf("LALTA, ");
679 			break;
680 		case RALTA:
681 			printf("RALTA, ");
682 			break;
683 		case HALT:
684 			printf(" HALT, ");
685 			break;
686 		case PDWN:
687 			printf(" PDWN, ");
688 			break;
689 		case PASTE:
690 			printf("PASTE, ");
691 			break;
692 		default:
693 	 		if (value >= F_FN && value <= L_FN)
694 				printf(" F(%2d),", value - F_FN + 1);
695 	 		else if (value >= F_SCR && value <= L_SCR)
696 				printf(" S(%2d),", value - F_SCR + 1);
697 	 		else if (value >= F_ACC && value <= L_ACC)
698 				printf(" %-4s, ", acc_names_u[value - F_ACC]);
699 			else
700 				printf(" 0x%02X, ", value);
701 			break;
702 		}
703 	} else if (value == '\'') {
704 		printf(" '\\'', ");
705 	} else if (value == '\\') {
706 		printf(" '\\\\', ");
707 	} else if (isascii(value) && isprint(value)) {
708 		printf("  '%c', ", value);
709 	} else {
710 		printf(" 0x%02X, ", value);
711 	}
712 }
713 
714 static void
715 dump_key_definition(char *name, keymap_t *keymap)
716 {
717 	int	i, j;
718 
719 	printf("static keymap_t keymap_%s = { 0x%02x, {\n",
720 	       name, (unsigned)keymap->n_keys);
721 	printf(
722 "/*                                                         alt\n"
723 " * scan                       cntrl          alt    alt   cntrl\n"
724 " * code  base   shift  cntrl  shift   alt   shift  cntrl  shift    spcl flgs\n"
725 " * ---------------------------------------------------------------------------\n"
726 " */\n");
727 	for (i = 0; i < keymap->n_keys; i++) {
728 		printf("/*%02x*/{{", i);
729 		for (j = 0; j < NUM_STATES; j++) {
730 			if (keymap->key[i].spcl & (0x80 >> j))
731 				dump_entry(keymap->key[i].map[j] | SPECIAL);
732 			else
733 				dump_entry(keymap->key[i].map[j]);
734 		}
735 		printf("}, 0x%02X,0x%02X },\n",
736 		       (unsigned)keymap->key[i].spcl,
737 		       (unsigned)keymap->key[i].flgs);
738 	}
739 	printf("} };\n\n");
740 }
741 
742 static void
743 dump_accent_definition(char *name, accentmap_t *accentmap)
744 {
745 	int i, j;
746 	int c;
747 
748 	printf("static accentmap_t accentmap_%s = { %d",
749 		name, accentmap->n_accs);
750 	if (accentmap->n_accs <= 0) {
751 		printf(" };\n\n");
752 		return;
753 	}
754 	printf(", {\n");
755 	for (i = 0; i < NUM_DEADKEYS; i++) {
756 		printf("    /* %s=%d */\n    {", acc_names[i], i);
757 		c = accentmap->acc[i].accchar;
758 		if (c == '\'')
759 			printf(" '\\'', {");
760 		else if (c == '\\')
761 			printf(" '\\\\', {");
762 		else if (isascii(c) && isprint(c))
763 			printf("  '%c', {", c);
764 		else if (c == 0) {
765 			printf(" 0x00 }, \n");
766 			continue;
767 		} else
768 			printf(" 0x%02x, {", c);
769 		for (j = 0; j < NUM_ACCENTCHARS; j++) {
770 			c = accentmap->acc[i].map[j][0];
771 			if (c == 0)
772 				break;
773 			if ((j > 0) && ((j % 4) == 0))
774 				printf("\n\t     ");
775 			if (isascii(c) && isprint(c))
776 				printf(" {  '%c',", c);
777 			else
778 				printf(" { 0x%02x,", c);
779 			printf("0x%02x },", accentmap->acc[i].map[j][1]);
780 		}
781 		printf(" }, },\n");
782 	}
783 	printf("} };\n\n");
784 }
785 
786 static void
787 add_keymap_path(const char *path)
788 {
789 	struct pathent* pe;
790 	size_t len;
791 
792 	len = strlen(path);
793 	if ((pe = malloc(sizeof(*pe))) == NULL ||
794 	    (pe->path = malloc(len + 2)) == NULL)
795 		err(1, "malloc");
796 	memcpy(pe->path, path, len);
797 	if (len > 0 && path[len - 1] != '/')
798 		pe->path[len++] = '/';
799 	pe->path[len] = '\0';
800 	STAILQ_INSERT_TAIL(&pathlist, pe, next);
801 }
802 
803 #ifdef OPIO_DEADKEYMAP
804 static void
805 to_old_accentmap(accentmap_t *from, oaccentmap_t *to)
806 {
807 	int i, j;
808 
809 	to->n_accs = from->n_accs;
810 	for (i = 0; i < NUM_DEADKEYS; i++) {
811 		for (j = 0; j < NUM_ACCENTCHARS; j++) {
812 			to->acc[i].map[j][0] = from->acc[i].map[j][0];
813 			to->acc[i].map[j][1] = from->acc[i].map[j][1];
814 			to->acc[i].accchar = from->acc[i].accchar;
815 		}
816 	}
817 }
818 #endif /* OPIO_DEADKEYMAP */
819 
820 static void
821 load_keymap(char *opt, int dumponly)
822 {
823 	keymap_t keymap;
824 	accentmap_t accentmap;
825 #ifdef OPIO_DEADKEYMAP
826 	oaccentmap_t oaccentmap;
827 #endif /* OPIO_DEADKEYMAP */
828 	struct pathent *pe;
829 	FILE	*file;
830 	int	j;
831 	char	*name, *cp;
832 	char	blank[] = "", keymap_path[] = KEYMAP_PATH;
833 	char	vt_keymap_path[] = VT_KEYMAP_PATH, dotkbd[] = ".kbd";
834 	char	*postfix[] = {blank, dotkbd, NULL};
835 
836 	if (!paths_configured) {
837 		cp = getenv("KEYMAP_PATH");
838 		if (cp != NULL)
839 			add_keymap_path(cp);
840 		add_keymap_path("");
841 		if (is_vt4())
842 			add_keymap_path(vt_keymap_path);
843 		else
844 			add_keymap_path(keymap_path);
845 		paths_configured = 1;
846 	}
847 
848 	file = NULL;
849 	STAILQ_FOREACH(pe, &pathlist, next) {
850 		for (j=0; postfix[j] && file == NULL; j++) {
851 			name = mkfullname(pe->path, opt, postfix[j]);
852 			file = fopen(name, "r");
853 			if (file != NULL)
854 				break;
855 		}
856 	}
857 	if (file == NULL) {
858 		warn("keymap file \"%s\" not found", opt);
859 		return;
860 	}
861 	memset(&keymap, 0, sizeof(keymap));
862 	memset(&accentmap, 0, sizeof(accentmap));
863 	token = -1;
864 	while (1) {
865 		if (get_definition_line(file, &keymap, &accentmap) < 0)
866 			break;
867     	}
868 	if (dumponly) {
869 		/* fix up the filename to make it a valid C identifier */
870 		for (cp = opt; *cp; cp++)
871 			if (!isalpha(*cp) && !isdigit(*cp)) *cp = '_';
872 		printf("/*\n"
873 		       " * Automatically generated from %s.\n"
874 	               " * DO NOT EDIT!\n"
875 		       " */\n", name);
876 		dump_key_definition(opt, &keymap);
877 		dump_accent_definition(opt, &accentmap);
878 		return;
879 	}
880 	if ((keymap.n_keys > 0) && (ioctl(0, PIO_KEYMAP, &keymap) < 0)) {
881 		warn("setting keymap");
882 		fclose(file);
883 		return;
884 	}
885 	if ((accentmap.n_accs > 0)
886 	    && (ioctl(0, PIO_DEADKEYMAP, &accentmap) < 0)) {
887 #ifdef OPIO_DEADKEYMAP
888 		to_old_accentmap(&accentmap, &oaccentmap);
889 		if (ioctl(0, OPIO_DEADKEYMAP, &oaccentmap) < 0)
890 #endif /* OGIO_DEADKEYMAP */
891 		{
892 			warn("setting accentmap");
893 			fclose(file);
894 			return;
895 		}
896 	}
897 }
898 
899 #ifdef OPIO_DEADKEYMAP
900 static void
901 to_new_accentmap(oaccentmap_t *from, accentmap_t *to)
902 {
903 	int i, j;
904 
905 	to->n_accs = from->n_accs;
906 	for (i = 0; i < NUM_DEADKEYS; i++) {
907 		for (j = 0; j < NUM_ACCENTCHARS; j++) {
908 			to->acc[i].map[j][0] = from->acc[i].map[j][0];
909 			to->acc[i].map[j][1] = from->acc[i].map[j][1];
910 			to->acc[i].accchar = from->acc[i].accchar;
911 		}
912 	}
913 }
914 #endif /* OPIO_DEADKEYMAP */
915 
916 static void
917 print_keymap(void)
918 {
919 	keymap_t keymap;
920 	accentmap_t accentmap;
921 #ifdef OGIO_DEADKEYMAP
922 	oaccentmap_t oaccentmap;
923 #endif /* OPIO_DEADKEYMAP */
924 	int i;
925 
926 	if (ioctl(0, GIO_KEYMAP, &keymap) < 0)
927 		err(1, "getting keymap");
928 	if (ioctl(0, GIO_DEADKEYMAP, &accentmap) < 0) {
929 #ifdef OGIO_DEADKEYMAP
930 		if (ioctl(0, OGIO_DEADKEYMAP, &oaccentmap) == 0)
931 			to_new_accentmap(&oaccentmap, &accentmap);
932 		else
933 #endif /* OGIO_DEADKEYMAP */
934 			memset(&accentmap, 0, sizeof(accentmap));
935 	}
936     	printf(
937 "#                                                         alt\n"
938 "# scan                       cntrl          alt    alt   cntrl lock\n"
939 "# code  base   shift  cntrl  shift  alt    shift  cntrl  shift state\n"
940 "# ------------------------------------------------------------------\n"
941     	);
942 	for (i=0; i<keymap.n_keys; i++)
943 		print_key_definition_line(stdout, i, &keymap.key[i]);
944 
945 	printf("\n");
946 	for (i = 0; i < NUM_DEADKEYS; i++)
947 		print_accent_definition_line(stdout, i, &accentmap.acc[i]);
948 
949 }
950 
951 static void
952 load_default_functionkeys(void)
953 {
954 	fkeyarg_t fkey;
955 	int i;
956 
957 	for (i=0; i<NUM_FKEYS; i++) {
958 		fkey.keynum = i;
959 		strcpy(fkey.keydef, fkey_table[i]);
960 		fkey.flen = strlen(fkey_table[i]);
961 		if (ioctl(0, SETFKEY, &fkey) < 0)
962 			warn("setting function key");
963 	}
964 }
965 
966 static void
967 set_functionkey(char *keynumstr, char *string)
968 {
969 	fkeyarg_t fkey;
970 
971 	if (!strcmp(keynumstr, "load") && !strcmp(string, "default")) {
972 		load_default_functionkeys();
973 		return;
974 	}
975 	fkey.keynum = atoi(keynumstr);
976 	if (fkey.keynum < 1 || fkey.keynum > NUM_FKEYS) {
977 		warnx("function key number must be between 1 and %d",
978 			NUM_FKEYS);
979 		return;
980 	}
981 	if ((fkey.flen = strlen(string)) > MAXFK) {
982 		warnx("function key string too long (%d > %d)",
983 			fkey.flen, MAXFK);
984 		return;
985 	}
986 	strncpy(fkey.keydef, string, MAXFK);
987 	fkey.keynum -= 1;
988 	if (ioctl(0, SETFKEY, &fkey) < 0)
989 		warn("setting function key");
990 }
991 
992 static void
993 set_bell_values(char *opt)
994 {
995 	int bell, duration, pitch;
996 
997 	bell = 0;
998 	duration = 0;
999 	pitch = 0;
1000 	if (!strncmp(opt, "quiet.", 6)) {
1001 		bell = CONS_QUIET_BELL;
1002 		opt += 6;
1003 	}
1004 	if (!strcmp(opt, "visual"))
1005 		bell |= CONS_VISUAL_BELL;
1006 	else if (!strcmp(opt, "normal"))
1007 		duration = 5, pitch = 800;
1008 	else if (!strcmp(opt, "off"))
1009 		duration = 0, pitch = 0;
1010 	else {
1011 		char		*v1;
1012 
1013 		bell = 0;
1014 		duration = strtol(opt, &v1, 0);
1015 		if ((duration < 0) || (*v1 != '.'))
1016 			goto badopt;
1017 		opt = ++v1;
1018 		pitch = strtol(opt, &v1, 0);
1019 		if ((pitch < 0) || (*opt == '\0') || (*v1 != '\0')) {
1020 badopt:
1021 			warnx("argument to -b must be duration.pitch or [quiet.]visual|normal|off");
1022 			return;
1023 		}
1024 		if (pitch != 0)
1025 			pitch = 1193182 / pitch;	/* in Hz */
1026 		duration /= 10;	/* in 10 m sec */
1027 	}
1028 
1029 	ioctl(0, CONS_BELLTYPE, &bell);
1030 	if (duration > 0 && pitch > 0)
1031 		fprintf(stderr, "\e[=%d;%dB", pitch, duration);
1032 }
1033 
1034 static void
1035 set_keyrates(char *opt)
1036 {
1037 	int arg[2];
1038 	int repeat;
1039 	int delay;
1040 	int r, d;
1041 
1042 	if (!strcmp(opt, "slow")) {
1043 		delay = 1000;
1044 		repeat = 504;
1045 		d = 3;
1046 		r = 31;
1047 	} else if (!strcmp(opt, "normal")) {
1048 		delay = 500;
1049 		repeat = 126;
1050 		d = 1;
1051 		r = 15;
1052 	} else if (!strcmp(opt, "fast")) {
1053 		delay = 0;
1054 		repeat = 0;
1055 		d = 0;
1056 		r = 0;
1057 	} else {
1058 		int		n;
1059 		char		*v1;
1060 
1061 		delay = strtol(opt, &v1, 0);
1062 		if ((delay < 0) || (*v1 != '.'))
1063 			goto badopt;
1064 		opt = ++v1;
1065 		repeat = strtol(opt, &v1, 0);
1066 		if ((repeat < 0) || (*opt == '\0') || (*v1 != '\0')) {
1067 badopt:
1068 			warnx("argument to -r must be delay.repeat or slow|normal|fast");
1069 			return;
1070 		}
1071 		for (n = 0; n < ndelays - 1; n++)
1072 			if (delay <= kbdelays[n])
1073 				break;
1074 		d = n;
1075 		for (n = 0; n < nrepeats - 1; n++)
1076 			if (repeat <= kbrates[n])
1077 				break;
1078 		r = n;
1079 	}
1080 
1081 	arg[0] = delay;
1082 	arg[1] = repeat;
1083 	if (ioctl(0, KDSETREPEAT, arg)) {
1084 		warn("fallback, setting keyboard rate via legacy interface (KDSETRAD), will be removed soon");
1085 		if (ioctl(0, KDSETRAD, (d << 5) | r))
1086 			warn("setting keyboard rate");
1087 	}
1088 }
1089 
1090 static const char *
1091 get_kbd_type_name(int type)
1092 {
1093 	static struct {
1094 		int type;
1095 		const char *name;
1096 	} name_table[] = {
1097 		{ KB_84,	"AT 84" },
1098 		{ KB_101,	"AT 101/102" },
1099 		{ KB_OTHER,	"generic" },
1100 	};
1101 	unsigned int i;
1102 
1103 	for (i = 0; i < sizeof(name_table)/sizeof(name_table[0]); ++i) {
1104 		if (type == name_table[i].type)
1105 			return name_table[i].name;
1106 	}
1107 	return "unknown";
1108 }
1109 
1110 static void
1111 show_kbd_info(void)
1112 {
1113 	keyboard_info_t info;
1114 
1115 	if (ioctl(0, KDGKBINFO, &info) == -1) {
1116 		warn("unable to obtain keyboard information");
1117 		return;
1118 	}
1119 	printf("kbd%d:\n", info.kb_index);
1120 	printf("    %.*s%d, type:%s (%d)\n",
1121 		(int)sizeof(info.kb_name), info.kb_name, info.kb_unit,
1122 		get_kbd_type_name(info.kb_type), info.kb_type);
1123 }
1124 
1125 static void
1126 set_keyboard(char *device)
1127 {
1128 	keyboard_info_t info;
1129 	int fd;
1130 
1131 	fd = open(device, O_RDONLY);
1132 	if (fd < 0) {
1133 		warn("cannot open %s", device);
1134 		return;
1135 	}
1136 	if (ioctl(fd, KDGKBINFO, &info) == -1) {
1137 		warn("unable to obtain keyboard information");
1138 		close(fd);
1139 		return;
1140 	}
1141 	/*
1142 	 * The keyboard device driver won't release the keyboard by
1143 	 * the following ioctl, but it automatically will, when the device
1144 	 * is closed.  So, we don't check error here.
1145 	 */
1146 	ioctl(fd, CONS_RELKBD, 0);
1147 	close(fd);
1148 #if 1
1149 	printf("kbd%d\n", info.kb_index);
1150 	printf("    %.*s%d, type:%s (%d)\n",
1151 		(int)sizeof(info.kb_name), info.kb_name, info.kb_unit,
1152 		get_kbd_type_name(info.kb_type), info.kb_type);
1153 #endif
1154 
1155 	if (ioctl(0, CONS_SETKBD, info.kb_index) == -1)
1156 		warn("unable to set keyboard");
1157 }
1158 
1159 static void
1160 release_keyboard(void)
1161 {
1162 	keyboard_info_t info;
1163 
1164 	/*
1165 	 * If stdin is not associated with a keyboard, the following ioctl
1166 	 * will fail.
1167 	 */
1168 	if (ioctl(0, KDGKBINFO, &info) == -1) {
1169 		warn("unable to obtain keyboard information");
1170 		return;
1171 	}
1172 #if 1
1173 	printf("kbd%d\n", info.kb_index);
1174 	printf("    %.*s%d, type:%s (%d)\n",
1175 		(int)sizeof(info.kb_name), info.kb_name, info.kb_unit,
1176 		get_kbd_type_name(info.kb_type), info.kb_type);
1177 #endif
1178 	if (ioctl(0, CONS_RELKBD, 0) == -1)
1179 		warn("unable to release the keyboard");
1180 }
1181 
1182 static void
1183 mux_keyboard(u_int op, char *kbd)
1184 {
1185 	keyboard_info_t	info;
1186 	char		*unit, *ep;
1187 
1188 	/*
1189 	 * If stdin is not associated with a keyboard, the following ioctl
1190 	 * will fail.
1191 	 */
1192 	if (ioctl(0, KDGKBINFO, &info) == -1) {
1193 		warn("unable to obtain keyboard information");
1194 		return;
1195 	}
1196 #if 1
1197 	printf("kbd%d\n", info.kb_index);
1198 	printf("    %.*s%d, type:%s (%d)\n",
1199 		(int)sizeof(info.kb_name), info.kb_name, info.kb_unit,
1200 		get_kbd_type_name(info.kb_type), info.kb_type);
1201 #endif
1202 	/*
1203 	 * split kbd into name and unit. find the right most part of the
1204 	 * kbd string that consist of only digits.
1205 	 */
1206 
1207 	memset(&info, 0, sizeof(info));
1208 
1209 	info.kb_unit = -1;
1210 	ep = kbd - 1;
1211 
1212 	do {
1213 		unit = strpbrk(ep + 1, "0123456789");
1214 		if (unit != NULL) {
1215 			info.kb_unit = strtol(unit, &ep, 10);
1216 			if (*ep != '\0')
1217 				info.kb_unit = -1;
1218 		}
1219 	} while (unit != NULL && info.kb_unit == -1);
1220 
1221 	if (info.kb_unit == -1) {
1222 		warnx("unable to find keyboard driver unit in '%s'", kbd);
1223 		return;
1224 	}
1225 
1226 	if (unit == kbd) {
1227 		warnx("unable to find keyboard driver name in '%s'", kbd);
1228 		return;
1229 	}
1230 	if (unit - kbd >= (int) sizeof(info.kb_name)) {
1231 		warnx("keyboard name '%s' is too long", kbd);
1232 		return;
1233 	}
1234 
1235 	strncpy(info.kb_name, kbd, unit - kbd);
1236 
1237 	/*
1238 	 * If stdin is not associated with a kbdmux(4) keyboard, the following
1239 	 * ioctl will fail.
1240 	 */
1241 
1242 	if (ioctl(0, op, &info) == -1)
1243 		warn("unable to (un)mux the keyboard");
1244 }
1245 
1246 static void
1247 usage(void)
1248 {
1249 	fprintf(stderr, "%s\n%s\n%s\n",
1250 "usage: kbdcontrol [-dFKix] [-A name] [-a name] [-b duration.pitch | [quiet.]belltype]",
1251 "                  [-r delay.repeat | speed] [-l mapfile] [-f # string]",
1252 "                  [-k device] [-L mapfile] [-P path]");
1253 	exit(1);
1254 }
1255 
1256 
1257 int
1258 main(int argc, char **argv)
1259 {
1260 	const char	*optstring = "A:a:b:df:iKk:Fl:L:P:r:x";
1261 	int		opt;
1262 
1263 	/* Collect any -P arguments, regardless of where they appear. */
1264 	while ((opt = getopt(argc, argv, optstring)) != -1) {
1265 		if (opt == 'P')
1266 			add_keymap_path(optarg);
1267 		if (opt == '?')
1268 			usage();
1269 	}
1270 
1271 	optind = optreset = 1;
1272 	while ((opt = getopt(argc, argv, optstring)) != -1)
1273 		switch(opt) {
1274 		case 'A':
1275 		case 'a':
1276 			mux_keyboard((opt == 'A')? KBRELKBD : KBADDKBD, optarg);
1277 			break;
1278 		case 'b':
1279 			set_bell_values(optarg);
1280 			break;
1281 		case 'd':
1282 			print_keymap();
1283 			break;
1284 		case 'l':
1285 			load_keymap(optarg, 0);
1286 			break;
1287 		case 'L':
1288 			load_keymap(optarg, 1);
1289 			break;
1290 		case 'P':
1291 			break;
1292 		case 'f':
1293 			set_functionkey(optarg,
1294 			    nextarg(argc, argv, &optind, 'f'));
1295 			break;
1296 		case 'F':
1297 			load_default_functionkeys();
1298 			break;
1299 		case 'i':
1300 			show_kbd_info();
1301 			break;
1302 		case 'K':
1303 			release_keyboard();
1304 			break;
1305 		case 'k':
1306 			set_keyboard(optarg);
1307 			break;
1308 		case 'r':
1309 			set_keyrates(optarg);
1310 			break;
1311 		case 'x':
1312 			hex = 1;
1313 			break;
1314 		default:
1315 			usage();
1316 		}
1317 	if ((optind != argc) || (argc == 1))
1318 		usage();
1319 	exit(0);
1320 }
1321