kbdmap.c revision 167260
1/*-
2 * Copyright (c) 2002 Jonathan Belson <jon@witchspace.com>
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 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24 * SUCH DAMAGE.
25 */
26
27#include <sys/cdefs.h>
28__FBSDID("$FreeBSD: head/usr.sbin/kbdmap/kbdmap.c 167260 2007-03-06 09:32:41Z kevlo $");
29
30#include <sys/types.h>
31#include <sys/queue.h>
32
33#include <assert.h>
34#include <ctype.h>
35#include <dirent.h>
36#include <limits.h>
37#include <stdio.h>
38#include <stdlib.h>
39#include <string.h>
40#include <stringlist.h>
41#include <unistd.h>
42
43#include "kbdmap.h"
44
45
46static const char *lang_default = DEFAULT_LANG;
47static const char *font;
48static const char *lang;
49static const char *program;
50static const char *keymapdir = DEFAULT_KEYMAP_DIR;
51static const char *fontdir = DEFAULT_FONT_DIR;
52static const char *sysconfig = DEFAULT_SYSCONFIG;
53static const char *font_default = DEFAULT_FONT;
54static const char *font_current;
55static const char *dir;
56static const char *menu = "";
57
58static int x11;
59static int show;
60static int verbose;
61static int print;
62
63
64struct keymap {
65	char	*desc;
66	char	*keym;
67	int	mark;
68	SLIST_ENTRY(keymap) entries;
69};
70static SLIST_HEAD(slisthead, keymap) head = SLIST_HEAD_INITIALIZER(head);
71
72
73/*
74 * Get keymap entry for 'key', or NULL of not found
75 */
76static struct keymap *
77get_keymap(const char *key)
78{
79	struct keymap *km;
80
81	SLIST_FOREACH(km, &head, entries)
82		if (!strcmp(km->keym, key))
83			return km;
84
85	return NULL;
86}
87
88/*
89 * Count the number of keymaps we found
90 */
91static int
92get_num_keymaps(void)
93{
94	struct keymap *km;
95	int count = 0;
96
97	SLIST_FOREACH(km, &head, entries)
98		count++;
99
100	return count;
101}
102
103/*
104 * Remove any keymap with given keym
105 */
106static void
107remove_keymap(const char *keym)
108{
109	struct keymap *km;
110
111	SLIST_FOREACH(km, &head, entries) {
112		if (!strcmp(keym, km->keym)) {
113			SLIST_REMOVE(&head, km, keymap, entries);
114			free(km);
115			break;
116		}
117	}
118}
119
120/*
121 * Add to hash with 'key'
122 */
123static void
124add_keymap(const char *desc, int mark, const char *keym)
125{
126	struct keymap *km, *km_new;
127
128	/* Is there already an entry with this key? */
129	SLIST_FOREACH(km, &head, entries) {
130		if (!strcmp(km->keym, keym)) {
131			/* Reuse this entry */
132			free(km->desc);
133			km->desc = strdup(desc);
134			km->mark = mark;
135			return;
136		}
137	}
138
139	km_new = (struct keymap *) malloc (sizeof(struct keymap));
140	km_new->desc = strdup(desc);
141	km_new->keym = strdup(keym);
142	km_new->mark = mark;
143
144	/* Add to keymap list */
145	SLIST_INSERT_HEAD(&head, km_new, entries);
146}
147
148/*
149 * Figure out the default language to use.
150 */
151static const char *
152get_locale(void)
153{
154	const char *locale;
155
156	if ((locale = getenv("LC_ALL")) == NULL &&
157	    (locale = getenv("LC_CTYPE")) == NULL &&
158	    (locale = getenv("LANG")) == NULL)
159		locale = lang_default;
160
161	/* Check for alias */
162	if (!strcmp(locale, "C"))
163		locale = DEFAULT_LANG;
164
165	return locale;
166}
167
168/*
169 * Extract filename part
170 */
171static const char *
172extract_name(const char *name)
173{
174	char *p;
175
176	p = strrchr(name, '/');
177	if (p != NULL && p[1] != '\0')
178		return p + 1;
179
180	return name;
181}
182
183/*
184 * Return file extension or NULL
185 */
186static char *
187get_extension(const char *name)
188{
189	char *p;
190
191	p = strrchr(name, '.');
192
193	if (p != NULL && p[1] != '\0')
194		return p;
195
196	return NULL;
197}
198
199/*
200 * Read font from /etc/rc.conf else return default.
201 * Freeing the memory is the caller's responsibility.
202 */
203static char *
204get_font(void)
205{
206	char line[256], buf[20];
207	char *fnt = NULL;
208
209	FILE *fp = fopen(sysconfig, "r");
210	if (fp) {
211		while (fgets(line, sizeof(line), fp)) {
212			int a, b, matches;
213
214			if (line[0] == '#')
215				continue;
216
217			matches = sscanf(line,
218			    " font%dx%d = \"%20[-.0-9a-zA-Z_]",
219			    &a, &b, buf);
220			if (matches==3) {
221				if (strcmp(buf, "NO")) {
222					if (fnt)
223						free(fnt);
224					fnt = (char *) malloc(strlen(buf) + 1);
225					strcpy(fnt, buf);
226				}
227			}
228		}
229	} else
230		fprintf(stderr, "Could not open %s for reading\n", sysconfig);
231
232	return fnt;
233}
234
235/*
236 * Set a font using 'vidcontrol'
237 */
238static void
239vidcontrol(const char *fnt)
240{
241	char *tmp, *p, *q;
242	char ch;
243	int i;
244
245	/* syscons test failed */
246	if (x11)
247		return;
248
249	tmp = strdup(fnt);
250
251	/* Extract font size */
252	p = strrchr(tmp, '-');
253	if (p && p[1] != '\0') {
254		p++;
255		/* Remove any '.fnt' extension */
256		if ((q = strstr(p, ".fnt")))
257			*q = '\0';
258
259		/*
260		 * Check font size is valid, with no trailing characters
261		 *  ('&ch' should not be matched)
262		 */
263		if (sscanf(p, "%dx%d%c", &i, &i, &ch) != 2)
264			fprintf(stderr, "Which font size? %s\n", fnt);
265		else {
266			char *cmd;
267			asprintf(&cmd, "vidcontrol -f %s %s", p, fnt);
268			if (verbose)
269				fprintf(stderr, "%s\n", cmd);
270			system(cmd);
271			free(cmd);
272		}
273	} else
274		fprintf(stderr, "Which font size? %s\n", fnt);
275
276	free(tmp);
277}
278
279/*
280 * Execute 'kbdcontrol' with the appropriate arguments
281 */
282static void
283do_kbdcontrol(struct keymap *km)
284{
285	char *kbd_cmd;
286	asprintf(&kbd_cmd, "kbdcontrol -l %s/%s", dir, km->keym);
287
288	if (!x11)
289		system(kbd_cmd);
290
291	printf("keymap=%s\n", km->keym);
292	free(kbd_cmd);
293}
294
295/*
296 * Call 'vidcontrol' with the appropriate arguments
297 */
298static void
299do_vidfont(struct keymap *km)
300{
301	char *vid_cmd, *tmp, *p, *q;
302
303	asprintf(&vid_cmd, "%s/%s", dir, km->keym);
304	vidcontrol(vid_cmd);
305	free(vid_cmd);
306
307	tmp = strdup(km->keym);
308	p = strrchr(tmp, '-');
309	if (p && p[1]!='\0') {
310		p++;
311		q = get_extension(p);
312		if (q) {
313			*q = '\0';
314			printf("font%s=%s\n", p, km->keym);
315		}
316	}
317	free(tmp);
318}
319
320/*
321 * Display dialog from 'keymaps[]'
322 */
323static void
324show_dialog(struct keymap **km_sorted, int num_keymaps)
325{
326	FILE *fp;
327	char *cmd, *dialog;
328	char tmp_name[] = "/tmp/_kbd_lang.XXXX";
329	const char *ext;
330	int fd, i, size;
331
332	fd = mkstemp(tmp_name);
333	if (fd == -1) {
334		fprintf(stderr, "Could not open temporary file \"%s\"\n",
335		    tmp_name);
336		exit(1);
337	}
338	asprintf(&dialog, "/usr/bin/dialog --clear --title \"Keyboard Menu\" "
339			  "--menu \"%s\" -1 -1 10", menu);
340
341	ext = extract_name(dir);
342
343	/* start right font, assume that current font is equal
344	 * to default font in /etc/rc.conf
345	 *
346	 * $font is the font which require the language $lang; e.g.
347	 * russian *need* a koi8 font
348	 * $font_current is the current font from /etc/rc.conf
349	 */
350	if (font && strcmp(font, font_current))
351		vidcontrol(font);
352
353	/* Build up the command */
354	size = 0;
355	for (i=0; i<num_keymaps; i++) {
356		/*
357		 * Each 'font' is passed as ' "font" ""', so allow the
358		 * extra space
359		 */
360		size += strlen(km_sorted[i]->desc) + 6;
361	}
362
363	/* Allow the space for '2> tmpfilename' redirection */
364	size += strlen(tmp_name) + 3;
365
366	cmd = (char *) malloc(strlen(dialog) + size + 1);
367	strcpy(cmd, dialog);
368
369	for (i=0; i<num_keymaps; i++) {
370		strcat(cmd, " \"");
371		strcat(cmd, km_sorted[i]->desc);
372		strcat(cmd, "\"");
373		strcat(cmd, " \"\"");
374	}
375
376	strcat(cmd, " 2>");
377	strcat(cmd, tmp_name);
378
379	/* Show the dialog.. */
380	system(cmd);
381
382	fp = fopen(tmp_name, "r");
383	if (fp) {
384		char choice[64];
385		if (fgets(choice, sizeof(choice), fp) != NULL) {
386			/* Find key for desc */
387			for (i=0; i<num_keymaps; i++) {
388				if (!strcmp(choice, km_sorted[i]->desc)) {
389					if (!strcmp(program, "kbdmap"))
390						do_kbdcontrol(km_sorted[i]);
391					else
392						do_vidfont(km_sorted[i]);
393					break;
394				}
395			}
396		} else {
397			if (font != NULL && strcmp(font, font_current))
398				/* Cancelled, restore old font */
399				vidcontrol(font_current);
400		}
401		fclose(fp);
402	} else
403		fprintf(stderr, "Failed to open temporary file");
404
405	/* Tidy up */
406	remove(tmp_name);
407	free(cmd);
408	free(dialog);
409	close(fd);
410}
411
412/*
413 * Search for 'token' in comma delimited array 'buffer'.
414 * Return true for found, false for not found.
415 */
416static int
417find_token(const char *buffer, const char *token)
418{
419	char *buffer_tmp, *buffer_copy, *inputstring;
420	char **ap;
421	int found;
422
423	buffer_copy = strdup(buffer);
424	buffer_tmp = buffer_copy;
425	inputstring = buffer_copy;
426	ap = &buffer_tmp;
427
428	found = 0;
429
430	while ((*ap = strsep(&inputstring, ",")) != NULL) {
431		if (strcmp(buffer_tmp, token) == 0) {
432			found = 1;
433			break;
434		}
435	}
436
437	free(buffer_copy);
438
439	return found;
440}
441
442/*
443 * Compare function for qsort
444 */
445static int
446compare_keymap(const void *a, const void *b)
447{
448
449	/* We've been passed pointers to pointers, so: */
450	const struct keymap *km1 = *((const struct keymap * const *) a);
451	const struct keymap *km2 = *((const struct keymap * const *) b);
452
453	return strcmp(km1->desc, km2->desc);
454}
455
456/*
457 * Compare function for qsort
458 */
459static int
460compare_lang(const void *a, const void *b)
461{
462	const char *l1 = *((const char * const *) a);
463	const char *l2 = *((const char * const *) b);
464
465	return strcmp(l1, l2);
466}
467
468/*
469 * Change '8x8' to '8x08' so qsort will put it before eg. '8x14'
470 */
471static void
472kludge_desc(struct keymap **km_sorted, int num_keymaps)
473{
474	int i;
475
476	for (i=0; i<num_keymaps; i++) {
477		char *p;
478		char *km = km_sorted[i]->desc;
479		if ((p = strstr(km, "8x8")) != NULL) {
480			int len;
481			int j;
482			int offset;
483
484			offset = p - km;
485
486			/* Make enough space for the extra '0' */
487			len = strlen(km);
488			km = realloc(km, len + 2);
489
490			for (j=len; j!=offset+1; j--)
491				km[j + 1] = km[j];
492
493			km[offset+2] = '0';
494
495			km_sorted[i]->desc = km;
496		}
497	}
498}
499
500/*
501 * Reverse 'kludge_desc()' - change '8x08' back to '8x8'
502 */
503static void
504unkludge_desc(struct keymap **km_sorted, int num_keymaps)
505{
506	int i;
507
508	for (i=0; i<num_keymaps; i++) {
509		char *p;
510		char *km = km_sorted[i]->desc;
511		if ((p = strstr(km, "8x08")) != NULL) {
512			p += 2;
513			while (*p++)
514				p[-1] = p[0];
515
516			km = realloc(km, p - km - 1);
517			km_sorted[i]->desc = km;
518		}
519	}
520}
521
522/*
523 * Return 0 if file exists and is readable, else -1
524 */
525static int
526check_file(const char *keym)
527{
528	int status = 0;
529
530	if (access(keym, R_OK) == -1) {
531		char *fn;
532		asprintf(&fn, "%s/%s", dir, keym);
533		if (access(fn, R_OK) == -1) {
534			if (verbose)
535				fprintf(stderr, "%s not found!\n", fn);
536			status = -1;
537		}
538		free(fn);
539	} else {
540		if (verbose)
541			fprintf(stderr, "No read permission for %s!\n", keym);
542		status = -1;
543	}
544
545	return status;
546}
547
548/*
549 * Read options from the relevent configuration file, then
550 *  present to user.
551 */
552static void
553menu_read(void)
554{
555	const char *lg;
556	char *p;
557	int mark, num_keymaps, items, i;
558	char buffer[256], filename[PATH_MAX];
559	char keym[64], lng[64], desc[64];
560	char dialect[64], lang_abk[64];
561	struct keymap *km;
562	struct keymap **km_sorted;
563	struct dirent *dp;
564	StringList *lang_list;
565	FILE *fp;
566	DIR *dirp;
567
568	lang_list = sl_init();
569
570	sprintf(filename, "%s/INDEX.%s", dir, extract_name(dir));
571
572	/* en_US.ISO8859-1 -> en_..\.ISO8859-1 */
573	strlcpy(dialect, lang, sizeof(dialect));
574	if (strlen(dialect) >= 6 && dialect[2] == '_') {
575		dialect[3] = '.';
576		dialect[4] = '.';
577	}
578
579
580	/* en_US.ISO8859-1 -> en */
581	strlcpy(lang_abk, lang, sizeof(lang_abk));
582	if (strlen(lang_abk) >= 3 && lang_abk[2] == '_')
583		lang_abk[2] = '\0';
584
585	fprintf(stderr, "lang_default = %s\n", lang_default);
586	fprintf(stderr, "dialect = %s\n", dialect);
587	fprintf(stderr, "lang_abk = %s\n", lang_abk);
588
589	fp = fopen(filename, "r");
590	if (fp) {
591		int matches;
592		while (fgets(buffer, sizeof(buffer), fp)) {
593			p = buffer;
594			if (p[0] == '#')
595				continue;
596
597			while (isspace(*p))
598				p++;
599
600			if (*p == '\0')
601				continue;
602
603			/* Parse input, removing newline */
604			matches = sscanf(p, "%64[^:]:%64[^:]:%64[^:\n]",
605			    keym, lng, desc);
606			if (matches == 3) {
607				if (strcmp(keym, "FONT")
608				    && strcmp(keym, "MENU")) {
609					/* Check file exists & is readable */
610					if (check_file(keym) == -1)
611						continue;
612				}
613			}
614
615			if (show) {
616				/*
617				 * Take note of supported languages, which
618				 * might be in a comma-delimited list
619				 */
620				char *tmp = strdup(lng);
621				char *delim = tmp;
622
623				for (delim = tmp; ; ) {
624					char ch = *delim++;
625					if (ch == ',' || ch == '\0') {
626						delim[-1] = '\0';
627						if (!sl_find(lang_list, tmp))
628							sl_add(lang_list, tmp);
629						if (ch == '\0')
630							break;
631						tmp = delim;
632					}
633				}
634			}
635			/* Set empty language to default language */
636			if (lng[0] == '\0')
637				lg = lang_default;
638			else
639				lg = lng;
640
641
642			/* 4) Your choice if it exists
643			 * 3) Long match eg. en_GB.ISO8859-1 is equal to
644			 *      en_..\.ISO8859-1
645			 * 2) short match 'de'
646			 * 1) default langlist 'en'
647			 * 0) any language
648			 *
649			 * Language may be a comma separated list
650			 * A higher match overwrites a lower
651			 * A later entry overwrites a previous if it exists
652			 *     twice in the database
653			 */
654
655			/* Check for favoured language */
656			km = get_keymap(keym);
657			mark = (km) ? km->mark : 0;
658
659			if (find_token(lg, lang))
660				add_keymap(desc, 4, keym);
661			else if (mark <= 3 && find_token(lg, dialect))
662				add_keymap(desc, 3, keym);
663			else if (mark <= 2 && find_token(lg, lang_abk))
664				add_keymap(desc, 2, keym);
665			else if (mark <= 1 && find_token(lg, lang_default))
666				add_keymap(desc, 1, keym);
667			else if (mark <= 0)
668				add_keymap(desc, 0, keym);
669		}
670		fclose(fp);
671
672	} else
673		printf("Could not open file\n");
674
675	if (show) {
676		qsort(lang_list->sl_str, lang_list->sl_cur, sizeof(char*),
677		    compare_lang);
678		printf("Currently supported languages: ");
679		for (i=0; i< (int) lang_list->sl_cur; i++)
680			printf("%s ", lang_list->sl_str[i]);
681		puts("");
682		exit(0);
683	}
684
685	km = get_keymap("MENU");
686	if (km)
687		/* Take note of menu title */
688		menu = strdup(km->desc);
689	km = get_keymap("FONT");
690	if (km)
691		/* Take note of language font */
692		font = strdup(km->desc);
693
694	/* Remove unwanted items from list */
695	remove_keymap("MENU");
696	remove_keymap("FONT");
697
698	/* Look for keymaps not in database */
699	dirp = opendir(dir);
700	if (dirp) {
701		while ((dp = readdir(dirp)) != NULL) {
702			const char *ext = get_extension(dp->d_name);
703			if (ext) {
704				if ((!strcmp(ext, ".fnt") ||
705				    !strcmp(ext, ".kbd")) &&
706				    !get_keymap(dp->d_name)) {
707					char *q;
708
709					/* Remove any .fnt or .kbd extension */
710					q = strdup(dp->d_name);
711					*(get_extension(q)) = '\0';
712					add_keymap(q, 0, dp->d_name);
713					free(q);
714
715					if (verbose)
716						fprintf(stderr,
717						    "'%s' not in database\n",
718						    dp->d_name);
719				}
720			}
721		}
722		closedir(dirp);
723	} else
724		fprintf(stderr, "Could not open directory '%s'\n", dir);
725
726	/* Sort items in keymap */
727	num_keymaps = get_num_keymaps();
728
729	km_sorted = (struct keymap **)
730	    malloc(num_keymaps*sizeof(struct keymap *));
731
732	/* Make array of pointers to items in hash */
733	items = 0;
734	SLIST_FOREACH(km, &head, entries)
735		km_sorted[items++] = km;
736
737	/* Change '8x8' to '8x08' so sort works as we might expect... */
738	kludge_desc(km_sorted, num_keymaps);
739
740	qsort(km_sorted, num_keymaps, sizeof(struct keymap *), compare_keymap);
741
742	/* ...change back again */
743	unkludge_desc(km_sorted, num_keymaps);
744
745	if (print) {
746		for (i=0; i<num_keymaps; i++)
747			printf("%s\n", km_sorted[i]->desc);
748		exit(0);
749	}
750
751	show_dialog(km_sorted, num_keymaps);
752
753	free(km_sorted);
754}
755
756/*
757 * Display usage information and exit
758 */
759static void
760usage(void)
761{
762
763	fprintf(stderr, "usage: %s\t[-K] [-V] [-d|-default] [-h|-help] "
764	    "[-l|-lang language]\n\t\t[-p|-print] [-r|-restore] [-s|-show] "
765	    "[-v|-verbose]\n", program);
766	exit(1);
767}
768
769static void
770parse_args(int argc, char **argv)
771{
772	int i;
773
774	for (i=1; i<argc; i++) {
775		if (argv[i][0] != '-')
776			usage();
777		else if (!strcmp(argv[i], "-help") || !strcmp(argv[i], "-h"))
778			usage();
779		else if (!strcmp(argv[i], "-verbose") || !strcmp(argv[i], "-v"))
780			verbose = 1;
781		else if (!strcmp(argv[i], "-lang") || !strcmp(argv[i], "-l"))
782			if (i + 1 == argc)
783				usage();
784			else
785				lang = argv[++i];
786		else if (!strcmp(argv[i], "-default") || !strcmp(argv[i], "-d"))
787			lang = lang_default;
788		else if (!strcmp(argv[i], "-show") || !strcmp(argv[i], "-s"))
789			show = 1;
790		else if (!strcmp(argv[i], "-print") || !strcmp(argv[i], "-p"))
791			print = 1;
792		else if (!strcmp(argv[i], "-restore") ||
793		    !strcmp(argv[i], "-r")) {
794			vidcontrol(font_current);
795			exit(0);
796		} else if (!strcmp(argv[i], "-K"))
797			dir = keymapdir;
798		else if (!strcmp(argv[i], "-V"))
799			dir = fontdir;
800		else
801			usage();
802	}
803}
804
805/*
806 * A front-end for the 'vidfont' and 'kbdmap' programs.
807 */
808int
809main(int argc, char **argv)
810{
811
812	x11 = system("kbdcontrol -d >/dev/null");
813
814	if (x11) {
815		fprintf(stderr, "You are not on a virtual console - "
816				"expect certain strange side-effects\n");
817		sleep(2);
818	}
819
820	SLIST_INIT(&head);
821
822	lang = get_locale();
823
824	program = extract_name(argv[0]);
825
826	font_current = get_font();
827	if (font_current == NULL)
828		font_current = font_default;
829
830	if (strcmp(program, "kbdmap"))
831		dir = fontdir;
832	else
833		dir = keymapdir;
834
835	/* Parse command line arguments */
836	parse_args(argc, argv);
837
838	/* Read and display options */
839	menu_read();
840
841	return 0;
842}
843