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