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