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