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