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