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