1 /* keytable.c - This program allows checking/replacing keys at IR
2 
3    Copyright (C) 2006-2010 Mauro Carvalho Chehab
4 
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation, version 2 of the License.
8 
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13  */
14 
15 #include <config.h>
16 #include <ctype.h>
17 #include <errno.h>
18 #include <fcntl.h>
19 #include <stdio.h>
20 #include <unistd.h>
21 #include <poll.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <linux/input.h>
25 #include <linux/lirc.h>
26 #include <sys/ioctl.h>
27 #include <sys/types.h>
28 #include <sys/resource.h>
29 #include <sys/stat.h>
30 #include <dirent.h>
31 #include <argp.h>
32 #include <time.h>
33 #include <stdbool.h>
34 
35 #include "ir-encode.h"
36 #include "parse.h"
37 #include "keymap.h"
38 
39 #ifdef HAVE_BPF
40 #include "bpf.h"
41 #include "bpf_load.h"
42 #endif
43 
44 #ifdef ENABLE_NLS
45 # define _(string) gettext(string)
46 # include <stdio.h>
47 # include <locale.h>
48 # include <langinfo.h>
49 # include <iconv.h>
50 #else
51 # define _(string) string
52 #endif
53 
54 # define N_(string) string
55 
56 struct input_keymap_entry_v2 {
57 #define KEYMAP_BY_INDEX	(1 << 0)
58 	u_int8_t  flags;
59 	u_int8_t  len;
60 	u_int16_t index;
61 	u_int32_t keycode;
62 	u_int8_t  scancode[32];
63 };
64 
65 #ifndef input_event_sec
66 #define input_event_sec time.tv_sec
67 #define input_event_usec time.tv_usec
68 #endif
69 
70 #define IR_PROTOCOLS_USER_DIR IR_KEYTABLE_USER_DIR "/protocols"
71 #define IR_PROTOCOLS_SYSTEM_DIR IR_KEYTABLE_SYSTEM_DIR "/protocols"
72 
73 #ifndef EVIOCSCLOCKID
74 #define EVIOCSCLOCKID		_IOW('E', 0xa0, int)
75 #endif
76 
77 #ifndef EVIOCGKEYCODE_V2
78 #define EVIOCGKEYCODE_V2	_IOR('E', 0x04, struct input_keymap_entry_v2)
79 #define EVIOCSKEYCODE_V2	_IOW('E', 0x04, struct input_keymap_entry_v2)
80 #endif
81 
82 struct keytable_entry {
83 	// 64 bit int which can printed with %llx
84 	unsigned long long scancode;
85 	u_int32_t keycode;
86 	struct keytable_entry *next;
87 };
88 
89 // Whenever for each key which has a raw entry rather than a scancode,
90 // we need to assign a globally unique scancode for dealing with reading
91 // more than keymap with raw entries.
92 static int raw_scancode = 0;
93 
94 struct keytable_entry *keytable = NULL;
95 struct raw_entry *rawtable = NULL;
96 
97 struct uevents {
98 	char		*key;
99 	char		*value;
100 	struct uevents	*next;
101 };
102 
103 struct cfgfile {
104 	char		*driver;
105 	char		*table;
106 	char		*fname;
107 	struct cfgfile	*next;
108 };
109 
110 struct sysfs_names {
111 	char			*name;
112 	struct sysfs_names	*next;
113 };
114 
115 enum rc_type {
116 	UNKNOWN_TYPE,
117 	SOFTWARE_DECODER,
118 	HARDWARE_DECODER,
119 };
120 
121 enum sysfs_ver {
122 	VERSION_1,	/* has nodes protocol, enabled */
123 	VERSION_2,	/* has node protocols */
124 };
125 
126 enum sysfs_protocols {
127 	SYSFS_UNKNOWN		= (1 << 0),
128 	SYSFS_OTHER		= (1 << 1),
129 	SYSFS_LIRC		= (1 << 2),
130 	SYSFS_RC5		= (1 << 3),
131 	SYSFS_RC5_SZ		= (1 << 4),
132 	SYSFS_JVC		= (1 << 5),
133 	SYSFS_SONY		= (1 << 6),
134 	SYSFS_NEC		= (1 << 7),
135 	SYSFS_SANYO		= (1 << 8),
136 	SYSFS_MCE_KBD		= (1 << 9),
137 	SYSFS_RC6		= (1 << 10),
138 	SYSFS_SHARP		= (1 << 11),
139 	SYSFS_XMP		= (1 << 12),
140 	SYSFS_CEC		= (1 << 13),
141 	SYSFS_IMON		= (1 << 14),
142 	SYSFS_RCMM		= (1 << 15),
143 	SYSFS_XBOX_DVD		= (1 << 16),
144 	SYSFS_INVALID		= 0,
145 };
146 
147 struct protocol_map_entry {
148 	const char *name;
149 	const char *sysfs1_name;
150 	enum sysfs_protocols sysfs_protocol;
151 };
152 
153 const struct protocol_map_entry protocol_map[] = {
154 	{ "unknown",	NULL,		SYSFS_UNKNOWN	},
155 	{ "other",	NULL,		SYSFS_OTHER	},
156 	{ "lirc",	NULL,		SYSFS_LIRC	},
157 	{ "rc-5",	"/rc5_decoder",	SYSFS_RC5	},
158 	{ "rc-5x",	NULL,		SYSFS_INVALID	},
159 	{ "rc-5-sz",	NULL,		SYSFS_RC5_SZ	},
160 	{ "jvc",	"/jvc_decoder",	SYSFS_JVC	},
161 	{ "sony",	"/sony_decoder",SYSFS_SONY	},
162 	{ "sony12",	NULL,		SYSFS_INVALID	},
163 	{ "sony15",	NULL,		SYSFS_INVALID	},
164 	{ "sony20",	NULL,		SYSFS_INVALID	},
165 	{ "nec",	"/nec_decoder",	SYSFS_NEC	},
166 	{ "sanyo",	NULL,		SYSFS_SANYO	},
167 	{ "mce_kbd",	NULL,		SYSFS_MCE_KBD	},
168 	{ "rc-6",	"/rc6_decoder",	SYSFS_RC6	},
169 	{ "rc-6-0",	NULL,		SYSFS_INVALID	},
170 	{ "rc-6-6a-20",	NULL,		SYSFS_INVALID	},
171 	{ "rc-6-6a-24",	NULL,		SYSFS_INVALID	},
172 	{ "rc-6-6a-32",	NULL,		SYSFS_INVALID	},
173 	{ "rc-6-mce",	NULL,		SYSFS_INVALID	},
174 	{ "sharp",	NULL,		SYSFS_SHARP	},
175 	{ "xmp",	"/xmp_decoder",	SYSFS_XMP	},
176 	{ "cec",	NULL,		SYSFS_CEC	},
177 	{ "imon",	NULL,		SYSFS_IMON	},
178 	{ "rc-mm",	NULL,		SYSFS_RCMM	},
179 	{ "xbox-dvd",	NULL,		SYSFS_XBOX_DVD	},
180 	{ NULL,		NULL,		SYSFS_INVALID	},
181 };
182 
protocol_like(const char * a,const char * b)183 static bool protocol_like(const char *a, const char *b)
184 {
185 	while (*a && *b) {
186 		if (*a == '-' || *a == '_')
187 			a++;
188 		if (*b == '-' || *b == '_')
189 			b++;
190 		if (tolower(*a) != tolower(*b))
191 			return false;
192 		a++; b++;
193 	}
194 
195 	return !*a && !*b;
196 }
197 
parse_sysfs_protocol(const char * name,bool all_allowed)198 static enum sysfs_protocols parse_sysfs_protocol(const char *name, bool all_allowed)
199 {
200 	const struct protocol_map_entry *pme;
201 
202 	if (!name)
203 		return SYSFS_INVALID;
204 
205 	if (all_allowed && !strcasecmp(name, "all"))
206 		return ~0;
207 
208 	for (pme = protocol_map; pme->name; pme++) {
209 		if (protocol_like(name, pme->name))
210 			return pme->sysfs_protocol;
211 	}
212 
213 	return SYSFS_INVALID;
214 }
215 
write_sysfs_protocols(enum sysfs_protocols protocols,FILE * fp,const char * fmt)216 static void write_sysfs_protocols(enum sysfs_protocols protocols, FILE *fp, const char *fmt)
217 {
218 	const struct protocol_map_entry *pme;
219 
220 	for (pme = protocol_map; pme->name; pme++) {
221 		if (!(protocols & pme->sysfs_protocol))
222 			continue;
223 
224 		fprintf(fp, fmt, pme->name);
225 		protocols &= ~pme->sysfs_protocol;
226 	}
227 }
228 
parse_code(const char * string)229 static int parse_code(const char *string)
230 {
231 	struct parse_event *p;
232 
233 	for (p = key_events; p->name != NULL; p++) {
234 		if (!strcasecmp(p->name, string))
235 			return p->value;
236 	}
237 	return -1;
238 }
239 
240 const char *argp_program_version = "IR keytable control version " V4L_UTILS_VERSION;
241 const char *argp_program_bug_address = "Mauro Carvalho Chehab <mchehab@kernel.org>";
242 
243 static const char doc[] = N_(
244 	"\nLists Remote Controller devices, loads rc keymaps, tests events, and adjusts\n"
245 	"other Remote Controller options. Rather than loading a rc keymap, it is also\n"
246 	"possible to set protocol decoders and set rc scancode to keycode mappings\n"
247 	"directly.\n"
248 
249 	"You need to have read permissions on /dev/input for the program to work\n"
250 	"\nOn the options below, the arguments are:\n"
251 	"  SYSDEV    - the rc device as found at /sys/class/rc\n"
252 	"  KEYMAP    - a keymap file with protocols and scancode to keycode mappings\n"
253 	"  SCANKEY   - a set of scancode1=keycode1,scancode2=keycode2.. value pairs\n"
254 	"  PROTOCOL  - protocol name (nec, rc-5, rc-6, jvc, sony, sanyo, rc-5-sz, lirc,\n"
255 	"              sharp, mce_kbd, xmp, imon, rc-mm, other, all) to be enabled,\n"
256 	"              or a bpf protocol name or file\n"
257 	"  DELAY     - Delay before repeating a keystroke\n"
258 	"  PERIOD    - Period to repeat a keystroke\n"
259 	"  PARAMETER - a set of name1=number1[,name2=number2]... for the BPF prototcol\n"
260 	"  CFGFILE   - configuration file that associates a driver/table name with\n"
261 	"              a keymap file\n"
262 	"\nOptions can be combined together.");
263 
264 static const struct argp_option options[] = {
265 	{"verbose",	'v',	0,		0,	N_("enables debug messages"), 0},
266 	{"clear",	'c',	0,		0,	N_("Clears the scancode to keycode mappings"), 0},
267 	{"sysdev",	's',	N_("SYSDEV"),	0,	N_("rc device to control, defaults to rc0 if not specified"), 0},
268 	{"test",	't',	0,		0,	N_("test if IR is generating events"), 0},
269 	{"read",	'r',	0,		0,	N_("reads the current scancode/keycode mapping"), 0},
270 	{"write",	'w',	N_("KEYMAP"),	0,	N_("write (adds) the keymap from the specified file"), 0},
271 	{"set-key",	'k',	N_("SCANKEY"),	0,	N_("Change scan/key pairs"), 0},
272 	{"protocol",	'p',	N_("PROTOCOL"),	0,	N_("Protocol to enable (the other ones will be disabled). To enable more than one, use the option more than one time"), 0},
273 	{"parameter",	'e',	N_("PARAMETER"), 0,	N_("Set a parameter for the protocol decoder")},
274 	{"delay",	'D',	N_("DELAY"),	0,	N_("Sets the delay before repeating a keystroke"), 0},
275 	{"period",	'P',	N_("PERIOD"),	0,	N_("Sets the period to repeat a keystroke"), 0},
276 	{"auto-load",	'a',	N_("CFGFILE"),	0,	N_("Auto-load keymaps, based on a configuration file. Only works with --sysdev."), 0},
277 	{"test-keymap",	1,	N_("KEYMAP"),	0,	N_("Test if keymap is valid"), 0},
278 	{"help",        '?',	0,		0,	N_("Give this help list"), -1},
279 	{"usage",	-3,	0,		0,	N_("Give a short usage message")},
280 	{"version",	'V',	0,		0,	N_("Print program version"), -1},
281 	{ 0, 0, 0, 0, 0, 0 }
282 };
283 
284 static const char args_doc[] = N_("");
285 
286 /* Static vars to store the parameters */
287 static char *devclass = NULL;
288 static int readtable = 0;
289 static int clear = 0;
290 int debug = 0;
291 static int test = 0;
292 static int delay = -1;
293 static int period = -1;
294 static int test_keymap = 0;
295 static enum sysfs_protocols ch_proto = 0;
296 
297 struct bpf_protocol {
298 	struct bpf_protocol *next;
299 	struct protocol_param *param;
300 	char *name;
301 };
302 
303 static struct bpf_protocol *bpf_protocol;
304 static struct protocol_param *bpf_parameter;
305 
306 struct cfgfile cfg = {
307 	NULL, NULL, NULL, NULL
308 };
309 
310 /*
311  * Stores the input layer protocol version
312  */
313 static int input_protocol_version = 0;
314 
315 /*
316  * Values that are read only via sysfs node
317  */
318 static int sysfs = 0;
319 
320 struct rc_device {
321 	char *sysfs_name;	/* Device sysfs node name */
322 	char *input_name;	/* Input device file name */
323 	char *lirc_name;	/* Lirc device file name */
324 	char *drv_name;		/* Kernel driver that implements it */
325 	char *dev_name;		/* Kernel device name */
326 	char *keytable_name;	/* Keycode table name */
327 
328 	enum sysfs_ver version; /* sysfs version */
329 	enum rc_type type;	/* Software (raw) or hardware decoder */
330 	enum sysfs_protocols supported, current; /* Current and supported IR protocols */
331 };
332 
compare_parameters(struct protocol_param * a,struct protocol_param * b)333 static bool compare_parameters(struct protocol_param *a, struct protocol_param *b)
334 {
335 	struct protocol_param *b2;
336 
337 	for (; a; a = a->next) {
338 		for (b2 = b; b2; b2 = b2->next) {
339 			if (!strcmp(a->name, b2->name) &&
340 			    a->value == b2->value) {
341 				break;
342 			}
343 		}
344 
345 		if (!b2) {
346 			return false;
347 		}
348 	}
349 
350 	return true;
351 }
352 
353 /*
354  * Sometimes, a toml will list the same remote protocol several times with
355  * different scancodes. This will because they are different remotes but
356  * use the same protocol. Do not load one BPF per remote.
357  */
add_bpf_protocol(struct bpf_protocol * new)358 static void add_bpf_protocol(struct bpf_protocol *new)
359 {
360 	struct bpf_protocol *a;
361 
362 	for (a = bpf_protocol; a; a = a->next) {
363 		if (strcmp(a->name, new->name))
364 			continue;
365 
366 		if (compare_parameters(a->param, new->param) &&
367 		    compare_parameters(new->param, a->param))
368 			return;
369 	}
370 
371 	new->next = bpf_protocol;
372 	bpf_protocol = new;
373 }
374 
add_keymap(struct keymap * map,const char * fname)375 static int add_keymap(struct keymap *map, const char *fname)
376 {
377 	for (; map; map = map->next) {
378 		enum sysfs_protocols protocol;
379 		struct keytable_entry *ke;
380 		struct scancode_entry *se;
381 		struct raw_entry *re, *re_next;
382 
383 		protocol = parse_sysfs_protocol(map->protocol, false);
384 		if (protocol == SYSFS_INVALID) {
385 			struct bpf_protocol *b;
386 
387 			b = malloc(sizeof(*b));
388 			b->name = strdup(map->protocol);
389 			b->param = map->param;
390 			/* steal param */
391 			map->param = NULL;
392 			add_bpf_protocol(b);
393 		} else {
394 			ch_proto |= protocol;
395 		}
396 
397 		for (se = map->scancode; se; se = se->next) {
398 			int value;
399 			char *p;
400 
401 			value = parse_code(se->keycode);
402 			if (debug)
403 				fprintf(stderr, _("\tvalue=%d\n"), value);
404 
405 			if (value == -1) {
406 				value = strtol(se->keycode, &p, 0);
407 				if (errno || *p) {
408 					fprintf(stderr, _("%s: keycode `%s' not recognised, no mapping for scancode 0x04%llx\n"), fname, se->keycode, (unsigned long long)se->scancode);
409 					continue;
410 				}
411 			}
412 
413 			ke = malloc(sizeof(*ke));
414 			ke->scancode = se->scancode;
415 			ke->keycode = value;
416 			ke->next = keytable;
417 
418 			keytable = ke;
419 		}
420 
421 		for (re = map->raw; re; re = re_next) {
422 			int value;
423 			char *p;
424 
425 			re_next = re->next;
426 
427 			value = parse_code(re->keycode);
428 			if (debug)
429 				fprintf(stderr, _("\tvalue=%d\n"), value);
430 
431 			if (value == -1) {
432 				value = strtol(re->keycode, &p, 0);
433 				if (errno || *p) {
434 					fprintf(stderr, _("%s: keycode `%s' not recognised, no mapping\n"), fname, re->keycode);
435 					continue;
436 				}
437 			}
438 
439 			ke = malloc(sizeof(*ke));
440 			ke->scancode = raw_scancode;
441 			ke->keycode = value;
442 			ke->next = keytable;
443 
444 			keytable = ke;
445 
446 			re->scancode = raw_scancode++;
447 			re->next = rawtable;
448 			rawtable = re;
449 		}
450 
451 		/* Steal the raw entries */
452 		map->raw = NULL;
453 	}
454 
455 	return 0;
456 }
457 
parse_cfgfile(char * fname)458 static int parse_cfgfile(char *fname)
459 {
460 	FILE *fin;
461 	int line = 0;
462 	char s[2048];
463 	char *driver, *table, *filename;
464 	struct cfgfile *nextcfg = &cfg;
465 
466 	if (debug)
467 		fprintf(stderr, _("Parsing %s config file\n"), fname);
468 
469 	fin = fopen(fname, "r");
470 	if (!fin) {
471 		perror(_("opening keycode file"));
472 		return errno;
473 	}
474 
475 	while (fgets(s, sizeof(s), fin)) {
476 		char *p = s;
477 
478 		line++;
479 		while (*p == ' ' || *p == '\t')
480 			p++;
481 
482 		if (*p == '\n' || *p == '#')
483 			continue;
484 
485 		driver = strtok(p, "\t ");
486 		if (!driver)
487 			goto err_einval;
488 
489 		table = strtok(NULL, "\t ");
490 		if (!table)
491 			goto err_einval;
492 
493 		filename = strtok(NULL, "\t #\n");
494 		if (!filename)
495 			goto err_einval;
496 
497 		if (debug)
498 			fprintf(stderr, _("Driver %s, Table %s => file %s\n"),
499 				driver, table, filename);
500 
501 		nextcfg->driver = malloc(strlen(driver) + 1);
502 		strcpy(nextcfg->driver, driver);
503 
504 		nextcfg->table = malloc(strlen(table) + 1);
505 		strcpy(nextcfg->table, table);
506 
507 		nextcfg->fname = malloc(strlen(filename) + 1);
508 		strcpy(nextcfg->fname, filename);
509 
510 		nextcfg->next = calloc(1, sizeof(*nextcfg));
511 		if (!nextcfg->next) {
512 			perror("parse_cfgfile");
513 			return ENOMEM;
514 		}
515 		nextcfg = nextcfg->next;
516 	}
517 	fclose(fin);
518 
519 	return 0;
520 
521 err_einval:
522 	fprintf(stderr, _("Invalid parameter on line %d of %s\n"),
523 		line, fname);
524 	return EINVAL;
525 
526 }
527 
parse_opt(int k,char * arg,struct argp_state * state)528 static int parse_opt(int k, char *arg, struct argp_state *state)
529 {
530 	char *p;
531 	long key;
532 	int rc;
533 
534 	switch (k) {
535 	case 'v':
536 		debug++;
537 		break;
538 	case 't':
539 		test++;
540 		break;
541 	case 'c':
542 		clear++;
543 		break;
544 	case 'D':
545 		delay = strtol(arg, &p, 10);
546 		if (!p || *p || delay < 0)
547 			argp_error(state, _("Invalid delay: %s"), arg);
548 		break;
549 	case 'P':
550 		period = strtol(arg, &p, 10);
551 		if (!p || *p || period < 0)
552 			argp_error(state, _("Invalid period: %s"), arg);
553 		break;
554 	case 's':
555 		devclass = arg;
556 		break;
557 	case 'r':
558 		readtable++;
559 		break;
560 	case 'w': {
561 		struct keymap *map = NULL;
562 
563 		rc = parse_keymap(arg, &map, debug);
564 		if (rc) {
565 			argp_error(state, _("Failed to read table file %s"), arg);
566 			break;
567 		}
568 		if (map->name)
569 			fprintf(stderr, _("Read %s table\n"), map->name);
570 
571 		add_keymap(map, arg);
572 		free_keymap(map);
573 		break;
574 	}
575 	case 'a': {
576 		rc = parse_cfgfile(arg);
577 		if (rc)
578 			argp_error(state, _("Failed to read config file %s"), arg);
579 		break;
580 	}
581 	case 'k':
582 		p = strtok(arg, ":=");
583 		do {
584 			struct keytable_entry *ke;
585 
586 			if (!p) {
587 				argp_error(state, _("Missing scancode: %s"), arg);
588 				break;
589 			}
590 
591 			ke = calloc(1, sizeof(*ke));
592 			if (!ke) {
593 				perror(_("No memory!\n"));
594 				return ENOMEM;
595 			}
596 
597 			ke->scancode = strtoull(p, NULL, 0);
598 			if (errno) {
599 				free(ke);
600 				argp_error(state, _("Invalid scancode: %s"), p);
601 				break;
602 			}
603 
604 			p = strtok(NULL, ",;");
605 			if (!p) {
606 				free(ke);
607 				argp_error(state, _("Missing keycode"));
608 				break;
609 			}
610 
611 			key = parse_code(p);
612 			if (key == -1) {
613 				key = strtol(p, NULL, 0);
614 				if (errno) {
615 					free(ke);
616 					argp_error(state, _("Unknown keycode: %s"), p);
617 					break;
618 				}
619 			}
620 
621 			ke->keycode = key;
622 
623 			if (debug)
624 				fprintf(stderr, _("scancode 0x%04llx=%u\n"),
625 					ke->scancode, ke->keycode);
626 
627 			ke->next = keytable;
628 			keytable = ke;
629 
630 			p = strtok(NULL, ":=");
631 		} while (p);
632 		break;
633 	case 'p':
634 		for (p = strtok(arg, ",;"); p; p = strtok(NULL, ",;")) {
635 			enum sysfs_protocols protocol;
636 
637 			protocol = parse_sysfs_protocol(p, true);
638 			if (protocol == SYSFS_INVALID) {
639 				struct bpf_protocol *b;
640 
641 				b = malloc(sizeof(*b));
642 				b->name = strdup(p);
643 				b->param = NULL;
644 				b->next = bpf_protocol;
645 				bpf_protocol = b;
646 			}
647 			else {
648 				ch_proto |= protocol;
649 			}
650 		}
651 		break;
652 	case 'e':
653 		p = strtok(arg, ":=");
654 		do {
655 			struct protocol_param *param;
656 
657 			if (!p) {
658 				argp_error(state, _("Missing parameter name: %s"), arg);
659 				break;
660 			}
661 
662 			param = malloc(sizeof(*param));
663 			if (!p) {
664 				perror(_("No memory!\n"));
665 				return ENOMEM;
666 			}
667 
668 			param->name = strdup(p);
669 
670 			p = strtok(NULL, ",;");
671 			if (!p) {
672 				free(param);
673 				argp_error(state, _("Missing value"));
674 				break;
675 			}
676 
677 			param->value = strtol(p, NULL, 0);
678 			if (errno) {
679 				free(param);
680 				argp_error(state, _("Unknown keycode: %s"), p);
681 				break;
682 			}
683 
684 			if (debug)
685 				fprintf(stderr, _("parameter %s=%ld\n"),
686 					param->name, param->value);
687 
688 			param->next = bpf_parameter;
689 			bpf_parameter = param;
690 
691 			p = strtok(NULL, ":=");
692 		} while (p);
693 		break;
694 	case 1:
695 		test_keymap++;
696 		struct keymap *map ;
697 
698 		rc = parse_keymap(arg, &map, debug);
699 		if (rc)
700 			argp_error(state, _("Failed to read table file %s"), arg);
701 		add_keymap(map, arg);
702 		free_keymap(map);
703 		break;
704 	case '?':
705 		argp_state_help(state, state->out_stream,
706 				ARGP_HELP_SHORT_USAGE | ARGP_HELP_LONG
707 				| ARGP_HELP_DOC);
708 		fprintf(state->out_stream, _("\nReport bugs to %s.\n"), argp_program_bug_address);
709 		exit(0);
710 	case 'V':
711 		fprintf (state->out_stream, "%s\n", argp_program_version);
712 		exit(0);
713 	case -3:
714 		argp_state_help(state, state->out_stream, ARGP_HELP_USAGE);
715 		exit(0);
716 	default:
717 		return ARGP_ERR_UNKNOWN;
718 	}
719 
720 	return 0;
721 }
722 
723 static struct argp argp = {
724 	.options = options,
725 	.parser = parse_opt,
726 	.args_doc = args_doc,
727 	.doc = doc,
728 };
729 
prtcode(unsigned long long scancode,int keycode)730 static void prtcode(unsigned long long scancode, int keycode)
731 {
732 	struct parse_event *p;
733 
734 	for (p = key_events; p->name != NULL; p++) {
735 		if (p->value == keycode) {
736 			printf(_("scancode 0x%04llx = %s (0x%02x)\n"), scancode, p->name, keycode);
737 			return;
738 		}
739 	}
740 
741 	if (isprint (keycode))
742 		printf(_("scancode 0x%04llx = '%c' (0x%02x)\n"), scancode, keycode, keycode);
743 	else
744 		printf(_("scancode 0x%04llx = 0x%02x\n"), scancode, keycode);
745 }
746 
free_names(struct sysfs_names * names)747 static void free_names(struct sysfs_names *names)
748 {
749 	struct sysfs_names *old;
750 	do {
751 		old = names;
752 		names = names->next;
753 		if (old->name)
754 			free(old->name);
755 		free(old);
756 	} while (names);
757 }
758 
seek_sysfs_dir(char * dname,char * node_name)759 static struct sysfs_names *seek_sysfs_dir(char *dname, char *node_name)
760 {
761 	DIR             	*dir;
762 	struct dirent   	*entry;
763 	struct sysfs_names	*names, *cur_name;
764 
765 	names = calloc(sizeof(*names), 1);
766 
767 	cur_name = names;
768 
769 	dir = opendir(dname);
770 	if (!dir) {
771 		perror(dname);
772 		return NULL;
773 	}
774 	entry = readdir(dir);
775 	while (entry) {
776 		if (!node_name || !strncmp(entry->d_name, node_name, strlen(node_name))) {
777 			cur_name->name = malloc(strlen(dname) + strlen(entry->d_name) + 2);
778 			if (!cur_name->name)
779 				goto err;
780 			strcpy(cur_name->name, dname);
781 			strcat(cur_name->name, entry->d_name);
782 			if (node_name)
783 				strcat(cur_name->name, "/");
784 			cur_name->next = calloc(sizeof(*cur_name), 1);
785 			if (!cur_name->next)
786 				goto err;
787 			cur_name = cur_name->next;
788 		}
789 		entry = readdir(dir);
790 	}
791 	closedir(dir);
792 
793 	if (names == cur_name) {
794 		if (debug)
795 			fprintf(stderr, _("Couldn't find any node at %s%s*.\n"),
796 				dname, node_name);
797 
798 		free (names);
799 		names = NULL;
800 	}
801 	return names;
802 
803 err:
804 	perror(_("Seek dir"));
805 	free_names(names);
806 	return NULL;
807 }
808 
free_uevent(struct uevents * uevent)809 static void free_uevent(struct uevents *uevent)
810 {
811 	struct uevents *old;
812 	do {
813 		old = uevent;
814 		uevent = uevent->next;
815 		if (old->key)
816 			free(old->key);
817 		if (old->value)
818 			free(old->value);
819 		free(old);
820 	} while (uevent);
821 }
822 
read_sysfs_uevents(char * dname)823 static struct uevents *read_sysfs_uevents(char *dname)
824 {
825 	FILE		*fp;
826 	struct uevents	*next, *uevent;
827 	char		*event = "uevent", *file, s[4096];
828 
829 	next = uevent = calloc(1, sizeof(*uevent));
830 
831 	file = malloc(strlen(dname) + strlen(event) + 1);
832 	strcpy(file, dname);
833 	strcat(file, event);
834 
835 	if (debug)
836 		fprintf(stderr, _("Parsing uevent %s\n"), file);
837 
838 
839 	fp = fopen(file, "r");
840 	if (!fp) {
841 		perror(file);
842 		free(file);
843 		return NULL;
844 	}
845 	while (fgets(s, sizeof(s), fp)) {
846 		char *p = strtok(s, "=");
847 		if (!p)
848 			continue;
849 		next->key = malloc(strlen(p) + 1);
850 		if (!next->key) {
851 			perror("next->key");
852 			free(file);
853 			free_uevent(uevent);
854 			return NULL;
855 		}
856 		strcpy(next->key, p);
857 
858 		p = strtok(NULL, "\n");
859 		if (!p) {
860 			fprintf(stderr, _("Error on uevent information\n"));
861 			fclose(fp);
862 			free(file);
863 			free_uevent(uevent);
864 			return NULL;
865 		}
866 		next->value = malloc(strlen(p) + 1);
867 		if (!next->value) {
868 			perror("next->value");
869 			free(file);
870 			free_uevent(uevent);
871 			return NULL;
872 		}
873 		strcpy(next->value, p);
874 
875 		if (debug)
876 			fprintf(stderr, _("%s uevent %s=%s\n"), file, next->key, next->value);
877 
878 		next->next = calloc(1, sizeof(*next));
879 		if (!next->next) {
880 			perror("next->next");
881 			free(file);
882 			free_uevent(uevent);
883 			return NULL;
884 		}
885 		next = next->next;
886 	}
887 	fclose(fp);
888 	free(file);
889 
890 	return uevent;
891 }
892 
find_device(char * name)893 static struct sysfs_names *find_device(char *name)
894 {
895 	char		dname[256];
896 	char		*input = "rc";
897 	static struct sysfs_names *names, *cur;
898 	/*
899 	 * Get event sysfs node
900 	 */
901 	snprintf(dname, sizeof(dname), "/sys/class/rc/");
902 
903 	names = seek_sysfs_dir(dname, input);
904 	if (!names) {
905 		fprintf(stderr, _("No devices found\n"));
906 		return NULL;
907 	}
908 
909 	if (debug) {
910 		for (cur = names; cur->next; cur = cur->next) {
911 			fprintf(stderr, _("Found device %s\n"), cur->name);
912 		}
913 	}
914 
915 	if (name) {
916 		static struct sysfs_names *tmp;
917 		char *p, *n;
918 		int found = 0;
919 
920 		n = malloc(strlen(name) + 2);
921 		strcpy(n, name);
922 		strcat(n,"/");
923 		for (cur = names; cur->next; cur = cur->next) {
924 			if (cur->name) {
925 				p = cur->name + strlen(dname);
926 				if (p && !strcmp(p, n)) {
927 					found = 1;
928 					break;
929 				}
930 			}
931 		}
932 		free(n);
933 		if (!found) {
934 			free_names(names);
935 			fprintf(stderr, _("Not found device %s\n"), name);
936 			return NULL;
937 		}
938 		tmp = calloc(sizeof(*names), 1);
939 		tmp->name = cur->name;
940 		cur->name = NULL;
941 		free_names(names);
942 		return tmp;
943 	}
944 
945 	return names;
946 }
947 
948 /*
949  * If an rcdev does not have a decoder for a protocol, try to load a bpf
950  * replacement.
951  */
load_bpf_for_unsupported(enum sysfs_protocols protocols,enum sysfs_protocols supported)952 static enum sysfs_protocols load_bpf_for_unsupported(enum sysfs_protocols protocols, enum sysfs_protocols supported)
953 {
954 	const struct protocol_map_entry *pme;
955 	struct bpf_protocol *b;
956 
957 	for (pme = protocol_map; pme->name; pme++) {
958 		// So far, we only have a replacement for the xbox_dvd
959 		// protocol
960 		if (pme->sysfs_protocol != SYSFS_XBOX_DVD)
961 			continue;
962 
963 		if (!(protocols & pme->sysfs_protocol) ||
964 		    (supported & pme->sysfs_protocol))
965 			continue;
966 
967 		b = malloc(sizeof(*b));
968 		b->name = strdup(pme->name);
969 		b->param = NULL;
970 		add_bpf_protocol(b);
971 
972 		protocols &= ~pme->sysfs_protocol;
973 	}
974 
975 	return protocols;
976 }
977 
v1_get_hw_protocols(char * name)978 static enum sysfs_protocols v1_get_hw_protocols(char *name)
979 {
980 	FILE *fp;
981 	char *p, buf[4096];
982 	enum sysfs_protocols protocols = 0;
983 
984 	fp = fopen(name, "r");
985 	if (!fp) {
986 		perror(name);
987 		return 0;
988 	}
989 
990 	if (!fgets(buf, sizeof(buf), fp)) {
991 		perror(name);
992 		fclose(fp);
993 		return 0;
994 	}
995 
996 	for (p = strtok(buf, " \n"); p; p = strtok(NULL, " \n")) {
997 		enum sysfs_protocols protocol;
998 
999 		if (debug)
1000 			fprintf(stderr, _("%s protocol %s\n"), name, p);
1001 
1002 		protocol = parse_sysfs_protocol(p, false);
1003 		if (protocol == SYSFS_INVALID)
1004 			protocol = SYSFS_OTHER;
1005 
1006 		protocols |= protocol;
1007 	}
1008 
1009 	fclose(fp);
1010 
1011 	return protocols;
1012 }
1013 
v1_set_hw_protocols(struct rc_device * rc_dev)1014 static int v1_set_hw_protocols(struct rc_device *rc_dev)
1015 {
1016 	FILE *fp;
1017 	char name[4096];
1018 
1019 	strcpy(name, rc_dev->sysfs_name);
1020 	strcat(name, "/protocol");
1021 
1022 	fp = fopen(name, "w");
1023 	if (!fp) {
1024 		perror(name);
1025 		return errno;
1026 	}
1027 
1028 	write_sysfs_protocols(rc_dev->current, fp, "%s ");
1029 
1030 	fprintf(fp, "\n");
1031 
1032 	fclose(fp);
1033 
1034 	return 0;
1035 }
1036 
v1_get_sw_enabled_protocol(char * dirname)1037 static int v1_get_sw_enabled_protocol(char *dirname)
1038 {
1039 	FILE *fp;
1040 	char *p, buf[4096], name[512];
1041 	int rc;
1042 
1043 	strcpy(name, dirname);
1044 	strcat(name, "/enabled");
1045 
1046 	fp = fopen(name, "r");
1047 	if (!fp) {
1048 		perror(name);
1049 		return 0;
1050 	}
1051 
1052 	if (!fgets(buf, sizeof(buf), fp)) {
1053 		perror(name);
1054 		fclose(fp);
1055 		return 0;
1056 	}
1057 
1058 	if (fclose(fp)) {
1059 		perror(name);
1060 		return errno;
1061 	}
1062 
1063 	p = strtok(buf, " \n");
1064 	if (!p) {
1065 		fprintf(stderr, _("%s has invalid content: '%s'\n"), name, buf);
1066 		return 0;
1067 	}
1068 
1069 	rc = atoi(p);
1070 
1071 	if (debug)
1072 		fprintf(stderr, _("protocol %s is %s\n"),
1073 			name, rc? _("enabled") : _("disabled"));
1074 
1075 	if (atoi(p) == 1)
1076 		return 1;
1077 
1078 	return 0;
1079 }
1080 
v1_set_sw_enabled_protocol(struct rc_device * rc_dev,const char * dirname,int enabled)1081 static int v1_set_sw_enabled_protocol(struct rc_device *rc_dev,
1082 				      const char *dirname, int enabled)
1083 {
1084 	FILE *fp;
1085 	char name[512];
1086 
1087 	strcpy(name, rc_dev->sysfs_name);
1088 	strcat(name, dirname);
1089 	strcat(name, "/enabled");
1090 
1091 	fp = fopen(name, "w");
1092 	if (!fp) {
1093 		perror(name);
1094 		return errno;
1095 	}
1096 
1097 	if (enabled)
1098 		fprintf(fp, "1");
1099 	else
1100 		fprintf(fp, "0");
1101 
1102 	if (fclose(fp)) {
1103 		perror(name);
1104 		return errno;
1105 	}
1106 
1107 	return 0;
1108 }
1109 
v2_get_protocols(struct rc_device * rc_dev,char * name)1110 static enum sysfs_protocols v2_get_protocols(struct rc_device *rc_dev, char *name)
1111 {
1112 	FILE *fp;
1113 	char *p, buf[4096];
1114 	int enabled;
1115 
1116 	fp = fopen(name, "r");
1117 	if (!fp) {
1118 		perror(name);
1119 		return 0;
1120 	}
1121 
1122 	if (!fgets(buf, sizeof(buf), fp)) {
1123 		perror(name);
1124 		fclose(fp);
1125 		return 0;
1126 	}
1127 
1128 	for (p = strtok(buf, " \n"); p; p = strtok(NULL, " \n")) {
1129 		enum sysfs_protocols protocol;
1130 
1131 		if (*p == '[') {
1132 			enabled = 1;
1133 			p++;
1134 			p[strlen(p)-1] = '\0';
1135 		} else
1136 			enabled = 0;
1137 
1138 		if (debug)
1139 			fprintf(stderr, _("%s protocol %s (%s)\n"), name, p,
1140 				enabled? _("enabled") : _("disabled"));
1141 
1142 		protocol = parse_sysfs_protocol(p, false);
1143 		if (protocol == SYSFS_INVALID)
1144 			protocol = SYSFS_OTHER;
1145 
1146 		rc_dev->supported |= protocol;
1147 		if (enabled)
1148 			rc_dev->current |= protocol;
1149 
1150 	}
1151 
1152 	fclose(fp);
1153 
1154 	return 0;
1155 }
1156 
v2_set_protocols(struct rc_device * rc_dev)1157 static int v2_set_protocols(struct rc_device *rc_dev)
1158 {
1159 	FILE *fp;
1160 	char name[4096];
1161 	struct stat st;
1162 
1163 	strcpy(name, rc_dev->sysfs_name);
1164 	strcat(name, "/protocols");
1165 
1166 	if (!stat(name, &st) && !(st.st_mode & 0222)) {
1167 		fprintf(stderr, _("Protocols for device can not be changed\n"));
1168 		return EINVAL;
1169 	}
1170 
1171 	fp = fopen(name, "w");
1172 	if (!fp) {
1173 		perror(name);
1174 		return errno;
1175 	}
1176 
1177 	/* Disable all protocols */
1178 	fprintf(fp, "none\n");
1179 
1180 	write_sysfs_protocols(rc_dev->current, fp, "+%s\n");
1181 
1182 	if (fclose(fp)) {
1183 		perror(name);
1184 		return errno;
1185 	}
1186 
1187 	return 0;
1188 }
1189 
get_attribs(struct rc_device * rc_dev,char * sysfs_name)1190 static int get_attribs(struct rc_device *rc_dev, char *sysfs_name)
1191 {
1192 	struct uevents  *uevent;
1193 	char		*input = "input", *event = "event", *lirc = "lirc";
1194 	char		*DEV = "/dev/";
1195 	static struct sysfs_names *input_names, *event_names, *attribs, *cur, *lirc_names;
1196 
1197 	/* Clean the attributes */
1198 	memset(rc_dev, 0, sizeof(*rc_dev));
1199 
1200 	rc_dev->sysfs_name = sysfs_name;
1201 
1202 	lirc_names = seek_sysfs_dir(rc_dev->sysfs_name, lirc);
1203 	if (lirc_names) {
1204 		uevent = read_sysfs_uevents(lirc_names->name);
1205 		free_names(lirc_names);
1206 		if (uevent) {
1207 			while (uevent->next) {
1208 				if (!strcmp(uevent->key, "DEVNAME")) {
1209 					rc_dev->lirc_name = malloc(strlen(uevent->value) + strlen(DEV) + 1);
1210 					strcpy(rc_dev->lirc_name, DEV);
1211 					strcat(rc_dev->lirc_name, uevent->value);
1212 					break;
1213 				}
1214 				uevent = uevent->next;
1215 			}
1216 			free_uevent(uevent);
1217 		}
1218 	}
1219 
1220 	input_names = seek_sysfs_dir(rc_dev->sysfs_name, input);
1221 	if (!input_names)
1222 		return EINVAL;
1223 	if (input_names->next->next) {
1224 		fprintf(stderr, _("Found more than one input interface. This is currently unsupported\n"));
1225 		return EINVAL;
1226 	}
1227 	if (debug)
1228 		fprintf(stderr, _("Input sysfs node is %s\n"), input_names->name);
1229 
1230 	event_names = seek_sysfs_dir(input_names->name, event);
1231 	if (!event_names) {
1232 		fprintf(stderr, _("Couldn't find any node at %s%s*.\n"),
1233 			input_names->name, event);
1234 		free_names(input_names);
1235 		return EINVAL;
1236 	}
1237 	free_names(input_names);
1238 	if (event_names->next->next) {
1239 		free_names(event_names);
1240 		fprintf(stderr, _("Found more than one event interface. This is currently unsupported\n"));
1241 		return EINVAL;
1242 	}
1243 	if (debug)
1244 		fprintf(stderr, _("Event sysfs node is %s\n"), event_names->name);
1245 
1246 	uevent = read_sysfs_uevents(event_names->name);
1247 	free_names(event_names);
1248 	if (!uevent)
1249 		return EINVAL;
1250 
1251 	while (uevent->next) {
1252 		if (!strcmp(uevent->key, "DEVNAME")) {
1253 			rc_dev->input_name = malloc(strlen(uevent->value) + strlen(DEV) + 1);
1254 			strcpy(rc_dev->input_name, DEV);
1255 			strcat(rc_dev->input_name, uevent->value);
1256 			break;
1257 		}
1258 		uevent = uevent->next;
1259 	}
1260 	free_uevent(uevent);
1261 
1262 	if (!rc_dev->input_name) {
1263 		fprintf(stderr, _("Input device name not found.\n"));
1264 		return EINVAL;
1265 	}
1266 
1267 	uevent = read_sysfs_uevents(rc_dev->sysfs_name);
1268 	if (!uevent)
1269 		return EINVAL;
1270 	while (uevent->next) {
1271 		if (!strcmp(uevent->key, "DRV_NAME")) {
1272 			rc_dev->drv_name = malloc(strlen(uevent->value) + 1);
1273 			strcpy(rc_dev->drv_name, uevent->value);
1274 		}
1275 		if (!strcmp(uevent->key, "DEV_NAME")) {
1276 			rc_dev->dev_name = malloc(strlen(uevent->value) + 1);
1277 			strcpy(rc_dev->dev_name, uevent->value);
1278 		}
1279 		if (!strcmp(uevent->key, "NAME")) {
1280 			rc_dev->keytable_name = malloc(strlen(uevent->value) + 1);
1281 			strcpy(rc_dev->keytable_name, uevent->value);
1282 		}
1283 		uevent = uevent->next;
1284 	}
1285 	free_uevent(uevent);
1286 
1287 	if (debug)
1288 		fprintf(stderr, _("input device is %s\n"), rc_dev->input_name);
1289 
1290 	sysfs++;
1291 
1292 	rc_dev->type = SOFTWARE_DECODER;
1293 
1294 	/* Get the other attribs - basically IR decoders */
1295 	attribs = seek_sysfs_dir(rc_dev->sysfs_name, NULL);
1296 	for (cur = attribs; cur->next; cur = cur->next) {
1297 		if (!cur->name)
1298 			continue;
1299 		if (strstr(cur->name, "/protocols")) {
1300 			rc_dev->version = VERSION_2;
1301 			rc_dev->type = UNKNOWN_TYPE;
1302 			v2_get_protocols(rc_dev, cur->name);
1303 		} else if (strstr(cur->name, "/protocol")) {
1304 			rc_dev->version = VERSION_1;
1305 			rc_dev->type = HARDWARE_DECODER;
1306 			rc_dev->current = v1_get_hw_protocols(cur->name);
1307 		} else if (strstr(cur->name, "/supported_protocols")) {
1308 			rc_dev->version = VERSION_1;
1309 			rc_dev->supported = v1_get_hw_protocols(cur->name);
1310 		} else {
1311 			const struct protocol_map_entry *pme;
1312 
1313 			for (pme = protocol_map; pme->name; pme++) {
1314 				if (!pme->sysfs1_name)
1315 					continue;
1316 
1317 				if (strstr(cur->name, pme->sysfs1_name)) {
1318 					rc_dev->supported |= pme->sysfs_protocol;
1319 					if (v1_get_sw_enabled_protocol(cur->name))
1320 						rc_dev->supported |= pme->sysfs_protocol;
1321 					break;
1322 				}
1323 			}
1324 		}
1325 	}
1326 
1327 	return 0;
1328 }
1329 
set_proto(struct rc_device * rc_dev)1330 static int set_proto(struct rc_device *rc_dev)
1331 {
1332 	int rc = 0;
1333 
1334 	if (rc_dev->version == VERSION_2) {
1335 		return v2_set_protocols(rc_dev);
1336 	}
1337 
1338 	rc_dev->current &= rc_dev->supported;
1339 
1340 	if (rc_dev->type == SOFTWARE_DECODER) {
1341 		const struct protocol_map_entry *pme;
1342 
1343 		for (pme = protocol_map; pme->name; pme++) {
1344 			if (!pme->sysfs1_name)
1345 				continue;
1346 
1347 			if (!(rc_dev->supported & pme->sysfs_protocol))
1348 				continue;
1349 
1350 			rc += v1_set_sw_enabled_protocol(rc_dev, pme->sysfs1_name,
1351 							 rc_dev->current & pme->sysfs_protocol);
1352 		}
1353 
1354 	} else {
1355 		rc = v1_set_hw_protocols(rc_dev);
1356 	}
1357 
1358 	return rc;
1359 }
1360 
get_input_protocol_version(int fd)1361 static int get_input_protocol_version(int fd)
1362 {
1363 	if (ioctl(fd, EVIOCGVERSION, &input_protocol_version) < 0) {
1364 		fprintf(stderr,
1365 			_("Unable to query evdev protocol version: %s\n"),
1366 			strerror(errno));
1367 		return errno;
1368 	}
1369 	if (debug)
1370 		fprintf(stderr, _("Input Protocol version: 0x%08x\n"),
1371 			input_protocol_version);
1372 
1373 	return 0;
1374 }
1375 
clear_table(int fd)1376 static void clear_table(int fd)
1377 {
1378 	int i, j;
1379 	u_int32_t codes[2];
1380 	struct input_keymap_entry_v2 entry;
1381 
1382 	/* Clears old table */
1383 	if (input_protocol_version < 0x10001) {
1384 		for (j = 0; j < 256; j++) {
1385 			for (i = 0; i < 256; i++) {
1386 				codes[0] = (j << 8) | i;
1387 				codes[1] = KEY_RESERVED;
1388 				ioctl(fd, EVIOCSKEYCODE, codes);
1389 			}
1390 		}
1391 	} else {
1392 		memset(&entry, '\0', sizeof(entry));
1393 		i = 0;
1394 		do {
1395 			entry.flags = KEYMAP_BY_INDEX;
1396 			entry.keycode = KEY_RESERVED;
1397 			entry.index = 0;
1398 
1399 			i++;
1400 			if (debug)
1401 				fprintf(stderr, _("Deleting entry %d\n"), i);
1402 		} while (ioctl(fd, EVIOCSKEYCODE_V2, &entry) == 0);
1403 	}
1404 }
1405 
add_keys(int fd)1406 static int add_keys(int fd)
1407 {
1408 	int write_cnt = 0;
1409 	struct keytable_entry *ke;
1410 	unsigned codes[2];
1411 
1412 	for (ke = keytable; ke; ke = ke->next) {
1413 		write_cnt++;
1414 		if (debug)
1415 			fprintf(stderr, "\t%04llx=%04x\n",
1416 				ke->scancode, ke->keycode);
1417 
1418 		codes[0] = ke->scancode;
1419 		codes[1] = ke->keycode;
1420 
1421 		if (codes[0] != ke->scancode) {
1422 			// 64 bit scancode
1423 			struct input_keymap_entry_v2 entry = {
1424 				.keycode = ke->keycode,
1425 				.len = sizeof(ke->scancode)
1426 			};
1427 
1428 			memcpy(entry.scancode, &ke->scancode, sizeof(ke->scancode));
1429 
1430 			if (ioctl(fd, EVIOCSKEYCODE_V2, &entry)) {
1431 				fprintf(stderr,
1432 					_("Setting scancode 0x%04llx with 0x%04x via "),
1433 					ke->scancode, ke->keycode);
1434 				perror("EVIOCSKEYCODE");
1435 			}
1436 		} else {
1437 			if (ioctl(fd, EVIOCSKEYCODE, codes)) {
1438 				fprintf(stderr,
1439 					_("Setting scancode 0x%04llx with 0x%04x via "),
1440 					ke->scancode, ke->keycode);
1441 				perror("EVIOCSKEYCODE");
1442 			}
1443 		}
1444 	}
1445 
1446 	while (keytable) {
1447 		ke = keytable;
1448 		keytable = ke->next;
1449 		free(ke);
1450 	}
1451 
1452 	return write_cnt;
1453 }
1454 
display_proto(struct rc_device * rc_dev)1455 static void display_proto(struct rc_device *rc_dev)
1456 {
1457 	if (rc_dev->type == HARDWARE_DECODER)
1458 		fprintf(stderr, _("Current kernel protocols: "));
1459 	else
1460 		fprintf(stderr, _("Enabled kernel protocols: "));
1461 	write_sysfs_protocols(rc_dev->current, stderr, "%s ");
1462 	fprintf(stderr, "\n");
1463 }
1464 
1465 
get_event_name(struct parse_event * event,u_int16_t code)1466 static char *get_event_name(struct parse_event *event, u_int16_t code)
1467 {
1468 	struct parse_event *p;
1469 
1470 	for (p = event; p->name != NULL; p++) {
1471 		if (p->value == code)
1472 			return p->name;
1473 	}
1474 	return "";
1475 }
1476 
print_scancodes(const struct lirc_scancode * scancodes,unsigned count)1477 static void print_scancodes(const struct lirc_scancode *scancodes, unsigned count)
1478 {
1479 	unsigned i;
1480 
1481 	for (i = 0; i < count; i++) {
1482 		const char *p = protocol_name(scancodes[i].rc_proto);
1483 
1484 		printf(_("%llu.%06llu: "),
1485 			scancodes[i].timestamp / 1000000000ull,
1486 			(scancodes[i].timestamp % 1000000000ull) / 1000ull);
1487 
1488 		if (p)
1489 			printf(_("lirc protocol(%s): scancode = 0x%llx"),
1490 				p, scancodes[i].scancode);
1491 		else
1492 			printf(_("lirc protocol(%d): scancode = 0x%llx"),
1493 				scancodes[i].rc_proto, scancodes[i].scancode);
1494 
1495 		if (scancodes[i].flags & LIRC_SCANCODE_FLAG_REPEAT)
1496 			printf(_(" repeat"));
1497 		if (scancodes[i].flags & LIRC_SCANCODE_FLAG_TOGGLE)
1498 			printf(_(" toggle=1"));
1499 
1500 		printf("\n");
1501 	}
1502 }
1503 
test_event(struct rc_device * rc_dev,int fd)1504 static void test_event(struct rc_device *rc_dev, int fd)
1505 {
1506 	struct input_event ev[64];
1507 	struct lirc_scancode sc[64];
1508 	int rd, i, lircfd = -1;
1509 	unsigned mode;
1510 
1511 	/* LIRC reports time in monotonic, set event to same */
1512 	mode = CLOCK_MONOTONIC;
1513 	ioctl(fd, EVIOCSCLOCKID, &mode);
1514 
1515 	if (rc_dev->lirc_name) {
1516 		unsigned mode = LIRC_MODE_SCANCODE;
1517 		lircfd = open(rc_dev->lirc_name, O_RDONLY | O_NONBLOCK);
1518 		if (lircfd == -1) {
1519 			perror(_("Can't open lirc device"));
1520 			return;
1521 		}
1522 		if (ioctl(lircfd, LIRC_SET_REC_MODE, &mode)) {
1523 			/* If we can't set scancode mode, kernel is too old */
1524 			close(lircfd);
1525 			lircfd = -1;
1526 		}
1527 	}
1528 
1529 	printf (_("Testing events. Please, press CTRL-C to abort.\n"));
1530 	while (1) {
1531 		struct pollfd pollstruct[2] = {
1532 			{ .fd = fd, .events = POLLIN },
1533 			{ .fd = lircfd, .events = POLLIN },
1534 		};
1535 
1536 		if (poll(pollstruct, 2, -1) < 0) {
1537 			if (errno == EINTR)
1538 				continue;
1539 
1540 			perror(_("poll returned error"));
1541 		}
1542 
1543 		if (lircfd != -1) {
1544 			rd = read(lircfd, sc, sizeof(sc));
1545 
1546 			if (rd != -1) {
1547 				print_scancodes(sc, rd / sizeof(struct lirc_scancode));
1548 			} else if (errno != EAGAIN) {
1549 				perror(_("Error reading lirc scancode"));
1550 				return;
1551 			}
1552 		}
1553 
1554 		rd = read(fd, ev, sizeof(ev));
1555 
1556 		if (rd < (int) sizeof(struct input_event)) {
1557 			if (errno == EAGAIN)
1558 				continue;
1559 
1560 			perror(_("Error reading event"));
1561 			return;
1562 		}
1563 
1564 		for (i = 0; i < rd / sizeof(struct input_event); i++) {
1565 			printf(_("%ld.%06ld: event type %s(0x%02x)"),
1566 				ev[i].input_event_sec, ev[i].input_event_usec,
1567 				get_event_name(events_type, ev[i].type), ev[i].type);
1568 
1569 			switch (ev[i].type) {
1570 			case EV_SYN:
1571 				printf(".\n");
1572 				break;
1573 			case EV_KEY:
1574 				printf(_(" key_%s: %s(0x%04x)\n"),
1575 					(ev[i].value == 0) ? _("up") : _("down"),
1576 					get_event_name(key_events, ev[i].code),
1577 					ev[i].code);
1578 				break;
1579 			case EV_REL:
1580 				printf(_(": %s (0x%04x) value=%d\n"),
1581 					get_event_name(rel_events, ev[i].code),
1582 					ev[i].code,
1583 					ev[i].value);
1584 				break;
1585 			case EV_ABS:
1586 				printf(_(": %s (0x%04x) value=%d\n"),
1587 					get_event_name(abs_events, ev[i].code),
1588 					ev[i].code,
1589 					ev[i].value);
1590 				break;
1591 			case EV_MSC:
1592 				if (ev[i].code == MSC_SCAN)
1593 					printf(_(": scancode = 0x%02x\n"), ev[i].value);
1594 				else
1595 					printf(_(": code = %s(0x%02x), value = %d\n"),
1596 						get_event_name(msc_events, ev[i].code),
1597 						ev[i].code, ev[i].value);
1598 				break;
1599 			case EV_REP:
1600 				printf(_(": value = %d\n"), ev[i].value);
1601 				break;
1602 			case EV_SW:
1603 			case EV_LED:
1604 			case EV_SND:
1605 			case EV_FF:
1606 			case EV_PWR:
1607 			case EV_FF_STATUS:
1608 			default:
1609 				printf(_(": code = 0x%02x, value = %d\n"),
1610 					ev[i].code, ev[i].value);
1611 				break;
1612 			}
1613 		}
1614 	}
1615 }
1616 
display_table_v1(struct rc_device * rc_dev,int fd)1617 static void display_table_v1(struct rc_device *rc_dev, int fd)
1618 {
1619 	unsigned int i, j;
1620 
1621 	for (j = 0; j < 256; j++) {
1622 		for (i = 0; i < 256; i++) {
1623 			int codes[2];
1624 
1625 			codes[0] = (j << 8) | i;
1626 			if (ioctl(fd, EVIOCGKEYCODE, codes) == -1)
1627 				perror("EVIOCGKEYCODE");
1628 			else if (codes[1] != KEY_RESERVED)
1629 				prtcode(codes[0], codes[1]);
1630 		}
1631 	}
1632 	display_proto(rc_dev);
1633 }
1634 
display_table_v2(struct rc_device * rc_dev,int fd)1635 static void display_table_v2(struct rc_device *rc_dev, int fd)
1636 {
1637 	struct input_keymap_entry_v2 entry = {};
1638 	unsigned long long scancode;
1639 	int i;
1640 
1641 	i = 0;
1642 	do {
1643 		entry.flags = KEYMAP_BY_INDEX;
1644 		entry.index = i;
1645 		entry.len = sizeof(scancode);
1646 
1647 		if (ioctl(fd, EVIOCGKEYCODE_V2, &entry) == -1)
1648 			break;
1649 
1650 		if (entry.len == sizeof(u_int32_t)) {
1651 			u_int32_t temp;
1652 
1653 			memcpy(&temp, entry.scancode, sizeof(temp));
1654 
1655 			scancode = temp;
1656 		} else if (entry.len == sizeof(u_int64_t)) {
1657 			u_int64_t temp;
1658 
1659 			memcpy(&temp, entry.scancode, sizeof(temp));
1660 
1661 			scancode = temp;
1662 		} else {
1663 			printf("error: unknown scancode length %d\n", entry.len);
1664 			continue;
1665 		}
1666 
1667 		prtcode(scancode, entry.keycode);
1668 		i++;
1669 	} while (1);
1670 	display_proto(rc_dev);
1671 }
1672 
display_table(struct rc_device * rc_dev,int fd)1673 static void display_table(struct rc_device *rc_dev, int fd)
1674 {
1675 	if (input_protocol_version < 0x10001)
1676 		display_table_v1(rc_dev, fd);
1677 	else
1678 		display_table_v2(rc_dev, fd);
1679 }
1680 
set_rate(int fd,unsigned int delay,unsigned int period)1681 static int set_rate(int fd, unsigned int delay, unsigned int period)
1682 {
1683 	unsigned int rep[2] = { delay, period };
1684 
1685 	if (ioctl(fd, EVIOCSREP, rep) < 0) {
1686 		perror("evdev ioctl");
1687 		return -1;
1688 	}
1689 
1690 	printf(_("Changed Repeat delay to %d ms and repeat period to %d ms\n"), delay, period);
1691 	return 0;
1692 }
1693 
get_rate(int fd,unsigned int * delay,unsigned int * period)1694 static int get_rate(int fd, unsigned int *delay, unsigned int *period)
1695 {
1696 	unsigned int rep[2];
1697 
1698 	if (ioctl(fd, EVIOCGREP, rep) < 0) {
1699 		perror("evdev ioctl");
1700 		return -1;
1701 	}
1702 	*delay = rep[0];
1703 	*period = rep[1];
1704 	printf(_("Repeat delay = %d ms, repeat period = %d ms\n"), *delay, *period);
1705 	return 0;
1706 }
1707 
show_evdev_attribs(int fd)1708 static void show_evdev_attribs(int fd)
1709 {
1710 	unsigned int delay, period;
1711 
1712 	printf("\t");
1713 	get_rate(fd, &delay, &period);
1714 }
1715 
device_name(int fd,char * prepend)1716 static void device_name(int fd, char *prepend)
1717 {
1718 	char buf[32];
1719 	int rc;
1720 
1721 	rc = ioctl(fd, EVIOCGNAME(sizeof(buf)), buf);
1722 	if (rc >= 0)
1723 		fprintf(stderr,_("%sName: %.*s\n"),prepend, rc, buf);
1724 	else
1725 		perror ("EVIOCGNAME");
1726 }
1727 
device_info(int fd,char * prepend)1728 static void device_info(int fd, char *prepend)
1729 {
1730 	struct input_id id;
1731 	int rc;
1732 
1733 	rc = ioctl(fd, EVIOCGID, &id);
1734 	if (rc >= 0)
1735 		fprintf(stderr,
1736 			_("%sbus: %d, vendor/product: %04x:%04x, version: 0x%04x\n"),
1737 			prepend, id.bustype, id.vendor, id.product, id.version);
1738 	else
1739 		perror ("EVIOCGID");
1740 }
1741 
1742 #ifdef HAVE_BPF
1743 #define MAX_PROGS 64
1744 // This value is what systemd sets PID 1 to, see:
1745 // https://github.com/systemd/systemd/blob/master/src/basic/def.h#L60
1746 #define HIGH_RLIMIT_MEMLOCK (1024ULL*1024ULL*64ULL)
1747 
attach_bpf(const char * lirc_name,const char * bpf_prog,struct protocol_param * param)1748 static bool attach_bpf(const char *lirc_name, const char *bpf_prog, struct protocol_param *param)
1749 {
1750 	unsigned int features;
1751 	struct rlimit rl;
1752 	int fd, ret;
1753 
1754 	fd = open(lirc_name, O_RDONLY);
1755 	if (fd == -1) {
1756 		perror(lirc_name);
1757 		return false;
1758 	}
1759 
1760 	if (ioctl(fd, LIRC_GET_FEATURES, &features)) {
1761 		perror(lirc_name);
1762 		close(fd);
1763 		return false;
1764 	}
1765 
1766 	if (!(features & LIRC_CAN_REC_MODE2)) {
1767 		fprintf(stderr, _("%s: not a raw IR receiver\n"), lirc_name);
1768 		close(fd);
1769 		return false;
1770 	}
1771 
1772 	// BPF programs are charged against RLIMIT_MEMLOCK. We'll need pages
1773 	// for the state, program text, and any raw IR. None of these are
1774 	// particularly large. However, the kernel defaults to 64KB
1775 	// memlock, which is only 16 pages which are mostly used by the
1776 	// time we are trying to load our BPF program.
1777 	rl.rlim_cur = rl.rlim_max = HIGH_RLIMIT_MEMLOCK;
1778 	(void) setrlimit(RLIMIT_MEMLOCK, &rl);
1779 
1780 	ret = load_bpf_file(bpf_prog, fd, param, rawtable);
1781 	close(fd);
1782 
1783 	return ret == 0;
1784 }
1785 
show_bpf(const char * lirc_name)1786 static void show_bpf(const char *lirc_name)
1787 {
1788 	unsigned int prog_ids[MAX_PROGS], count = MAX_PROGS;
1789 	unsigned int features, i;
1790 	int ret, fd, prog_fd;
1791 
1792 	fd = open(lirc_name, O_RDONLY);
1793 	if (fd == -1)
1794 		goto error;
1795 
1796 	if (ioctl(fd, LIRC_GET_FEATURES, &features)) {
1797 		close(fd);
1798 		goto error;
1799 	}
1800 
1801 	if (!(features & LIRC_CAN_REC_MODE2)) {
1802 		// only support for mode2 type raw ir devices
1803 		close(fd);
1804 		return;
1805 	}
1806 
1807 	ret = bpf_prog_query(fd, BPF_LIRC_MODE2, 0, NULL, prog_ids, &count);
1808 	close(fd);
1809 	if (ret) {
1810 		if (errno == EINVAL)
1811 			errno = ENOTSUP;
1812 		goto error;
1813 	}
1814 
1815 	printf(_("\tAttached BPF protocols: "));
1816 	for (i=0; i<count; i++) {
1817 		if (i)
1818 			printf(" ");
1819 		prog_fd = bpf_prog_get_fd_by_id(prog_ids[i]);
1820 		if (prog_fd != -1) {
1821 			struct bpf_prog_info info = {};
1822 			uint32_t info_len = sizeof(info);
1823 
1824 			ret = bpf_obj_get_info_by_fd(prog_fd, &info, &info_len);
1825 			close(prog_fd);
1826 			if (!ret && info.name[0]) {
1827 				printf("%s", info.name);
1828 				continue;
1829 			}
1830 		}
1831 		printf("%d", prog_ids[i]);
1832 	}
1833 	printf(_("\n"));
1834 	return;
1835 error:
1836 	printf(_("\tAttached BPF protocols: %m\n"));
1837 }
1838 
clear_bpf(const char * lirc_name)1839 static void clear_bpf(const char *lirc_name)
1840 {
1841 	unsigned int prog_ids[MAX_PROGS], count = MAX_PROGS;
1842 	unsigned int features, i;
1843 	int ret, prog_fd, fd;
1844 
1845 	fd = open(lirc_name, O_RDONLY);
1846 	if (fd == -1) {
1847 		perror(lirc_name);
1848 		return;
1849 	}
1850 
1851 	if (ioctl(fd, LIRC_GET_FEATURES, &features)) {
1852 		perror(lirc_name);
1853 		close(fd);
1854 		return;
1855 	}
1856 
1857 	if (!(features & LIRC_CAN_REC_MODE2)) {
1858 		// only support for mode2 type raw ir devices
1859 		close(fd);
1860 		return;
1861 	}
1862 
1863 	ret = bpf_prog_query(fd, BPF_LIRC_MODE2, 0, NULL, prog_ids, &count);
1864 	if (ret) {
1865 		close(fd);
1866 		return;
1867 	}
1868 
1869 	for (i = 0; i < count; i++) {
1870 		if (debug)
1871 			fprintf(stderr, _("BPF protocol prog_id %d\n"),
1872 				prog_ids[i]);
1873 		prog_fd = bpf_prog_get_fd_by_id(prog_ids[i]);
1874 		if (prog_fd == -1) {
1875 			printf(_("Failed to get BPF prog id %u: %m\n"),
1876 			       prog_ids[i]);
1877 			continue;
1878 		}
1879 		ret = bpf_prog_detach2(prog_fd, fd, BPF_LIRC_MODE2);
1880 		if (ret)
1881 			printf(("Failed to detach BPF prog id %u: %m\n"),
1882 			       prog_ids[i]);
1883 		close(prog_fd);
1884 	}
1885 	close(fd);
1886 	if (debug)
1887 		fprintf(stderr, _("BPF protocols removed\n"));
1888 }
1889 #else
attach_bpf(const char * lirc_name,const char * bpf_prog,struct protocol_param * param)1890 static bool attach_bpf(const char *lirc_name, const char *bpf_prog, struct protocol_param *param)
1891 {
1892 	fprintf(stderr, _("error: ir-keytable was compiled without BPF support\n"));
1893 	return false;
1894 }
show_bpf(const char * lirc_name)1895 static void show_bpf(const char *lirc_name) {}
clear_bpf(const char * lirc_name)1896 static void clear_bpf(const char *lirc_name) {}
1897 #endif
1898 
show_sysfs_attribs(struct rc_device * rc_dev,char * name)1899 static int show_sysfs_attribs(struct rc_device *rc_dev, char *name)
1900 {
1901 	static struct sysfs_names *names, *cur;
1902 	int fd;
1903 
1904 	names = find_device(name);
1905 	if (!names)
1906 		return -1;
1907 	for (cur = names; cur; cur = cur->next) {
1908 		if (cur->name) {
1909 			if (get_attribs(rc_dev, cur->name))
1910 				continue;
1911 			fprintf(stderr, _("Found %s with:\n"),
1912 				rc_dev->sysfs_name);
1913 			if (rc_dev->dev_name)
1914 				fprintf(stderr, _("\tName: %s\n"),
1915 					rc_dev->dev_name);
1916 			fprintf(stderr, _("\tDriver: %s\n"),
1917 				rc_dev->drv_name);
1918 			fprintf(stderr, _("\tDefault keymap: %s\n"),
1919 				rc_dev->keytable_name);
1920 			fprintf(stderr, _("\tInput device: %s\n"),
1921 				rc_dev->input_name);
1922 			if (rc_dev->lirc_name) {
1923 				fprintf(stderr, _("\tLIRC device: %s\n"),
1924 					rc_dev->lirc_name);
1925 				show_bpf(rc_dev->lirc_name);
1926 			}
1927 			fprintf(stderr, _("\tSupported kernel protocols: "));
1928 			write_sysfs_protocols(rc_dev->supported, stderr, "%s ");
1929 			fprintf(stderr, "\n\t");
1930 			display_proto(rc_dev);
1931 			fd = open(rc_dev->input_name, O_RDONLY);
1932 			if (fd > 0) {
1933 				if (!rc_dev->dev_name)
1934 					device_name(fd, "\t");
1935 				device_info(fd, "\t");
1936 				show_evdev_attribs(fd);
1937 				close(fd);
1938 			} else {
1939 				printf(_("\tExtra capabilities: <access denied>\n"));
1940 			}
1941 		}
1942 	}
1943 	return 0;
1944 }
1945 
find_bpf_file(const char * name)1946 static char *find_bpf_file(const char *name)
1947 {
1948 	struct stat st;
1949 	char *fname;
1950 
1951 	if (!stat(name, &st))
1952 		return strdup(name);
1953 
1954 	if (asprintf(&fname, IR_PROTOCOLS_USER_DIR "/%s.o", name) < 0) {
1955 		fprintf(stderr, _("asprintf failed: %m\n"));
1956 		return NULL;
1957 	}
1958 
1959 	if (stat(fname, &st)) {
1960 		free(fname);
1961 		if (asprintf(&fname, IR_PROTOCOLS_SYSTEM_DIR "/%s.o", name) < 0) {
1962 			fprintf(stderr, _("asprintf failed: %m\n"));
1963 			return NULL;
1964 		}
1965 
1966 		if (stat(fname, &st)) {
1967 			fprintf(stderr, _("Can't find %s bpf protocol in %s or %s\n"), name, IR_KEYTABLE_USER_DIR "/protocols", IR_KEYTABLE_SYSTEM_DIR "/protocols");
1968 			free(fname);
1969 			return NULL;
1970 		}
1971 	}
1972 
1973 	return fname;
1974 }
1975 
bpf_param(struct protocol_param * protocol_param,const char * name,int * val)1976 int bpf_param(struct protocol_param *protocol_param, const char *name, int *val)
1977 {
1978 	struct protocol_param *param = bpf_parameter;
1979 
1980 	while (param) {
1981 		if (strcmp(name, param->name) == 0) {
1982 			*val = param->value;
1983 			return 0;
1984 		}
1985 		param = param->next;
1986 	}
1987 
1988 	while (protocol_param) {
1989 		if (strcmp(name, protocol_param->name) == 0) {
1990 			*val = protocol_param->value;
1991 			return 0;
1992 		}
1993 		protocol_param = protocol_param->next;
1994 	}
1995 
1996 	return -ENOENT;
1997 }
1998 
keymap_to_filename(const char * fname)1999 char* keymap_to_filename(const char *fname)
2000 {
2001 	struct stat st;
2002 	char *p;
2003 
2004 	if (fname[0] == '/' || ((fname[0] == '.') && strchr(fname, '/')))
2005 		return strdup(fname);
2006 
2007 	if (asprintf(&p, IR_KEYTABLE_USER_DIR "/%s", fname) < 0) {
2008 		fprintf(stderr, _("asprintf failed: %m\n"));
2009 		return NULL;
2010 	}
2011 
2012 	if (!stat(p, &st))
2013 		return p;
2014 
2015 	free(p);
2016 	if (asprintf(&p, IR_KEYTABLE_SYSTEM_DIR "/%s", fname) < 0) {
2017 		fprintf(stderr, _("asprintf failed: %m\n"));
2018 		return NULL;
2019 	}
2020 
2021 	if (!stat(p, &st))
2022 		return p;
2023 
2024 	free(p);
2025 
2026 	fprintf(stderr, _("error: Unable to find keymap %s in %s or %s\n"), fname, IR_KEYTABLE_USER_DIR, IR_KEYTABLE_SYSTEM_DIR);
2027 
2028 	return NULL;
2029 }
2030 
main(int argc,char * argv[])2031 int main(int argc, char *argv[])
2032 {
2033 	int dev_from_class = 0, write_cnt;
2034 	int fd;
2035 	static struct sysfs_names *names;
2036 	struct rc_device	  rc_dev;
2037 
2038 #ifdef ENABLE_NLS
2039 	setlocale (LC_ALL, "");
2040 	bindtextdomain (PACKAGE, LOCALEDIR);
2041 	textdomain (PACKAGE);
2042 #endif
2043 
2044 	argp_parse(&argp, argc, argv, ARGP_NO_HELP, 0, 0);
2045 
2046 	if (test_keymap)
2047 		return 0;
2048 
2049 	/* Just list all devices */
2050 	if (!clear && !readtable && !keytable && !ch_proto && !cfg.next && !test && delay < 0 && period < 0 && !bpf_protocol) {
2051 		if (show_sysfs_attribs(&rc_dev, devclass))
2052 			return -1;
2053 
2054 		return 0;
2055 	}
2056 
2057 	if (!devclass)
2058 		devclass = "rc0";
2059 
2060 	if (cfg.next && (clear || keytable || ch_proto)) {
2061 		fprintf (stderr, _("Auto-mode can be used only with --read, --verbose and --sysdev options\n"));
2062 		return -1;
2063 	}
2064 
2065 	names = find_device(devclass);
2066 	if (!names)
2067 		return -1;
2068 	rc_dev.sysfs_name = names->name;
2069 	if (get_attribs(&rc_dev, names->name)) {
2070 		free_names(names);
2071 		return -1;
2072 	}
2073 	names->name = NULL;
2074 	free_names(names);
2075 
2076 	dev_from_class++;
2077 
2078 	if (cfg.next) {
2079 		struct cfgfile *cur;
2080 		struct keymap *map;
2081 		char *fname;
2082 		int rc;
2083 		int matches = 0;
2084 
2085 		for (cur = &cfg; cur->next; cur = cur->next) {
2086 			if ((!rc_dev.drv_name || strcasecmp(cur->driver, rc_dev.drv_name)) && strcasecmp(cur->driver, "*"))
2087 				continue;
2088 			if ((!rc_dev.keytable_name || strcasecmp(cur->table, rc_dev.keytable_name)) && strcasecmp(cur->table, "*"))
2089 				continue;
2090 
2091 			if (debug)
2092 				fprintf(stderr, _("Keymap for %s, %s is on %s file.\n"),
2093 					rc_dev.drv_name, rc_dev.keytable_name,
2094 					cur->fname);
2095 
2096 			fname = keymap_to_filename(cur->fname);
2097 			if (!fname)
2098 				return -1;
2099 
2100 			rc = parse_keymap(fname, &map, debug);
2101 			if (rc < 0) {
2102 				fprintf(stderr, _("Can't load %s keymap\n"), fname);
2103 				free(fname);
2104 				return -1;
2105 			}
2106 			add_keymap(map, fname);
2107 			free_keymap(map);
2108 			if (!keytable) {
2109 				fprintf(stderr, _("Empty keymap %s\n"), fname);
2110 				free(fname);
2111 				return -1;
2112 			}
2113 			free(fname);
2114 			clear = 1;
2115 			matches++;
2116 		}
2117 
2118 		if (!matches) {
2119 			if (debug)
2120 				fprintf(stderr, _("Keymap for %s, %s not found. Keep as-is\n"),
2121 				       rc_dev.drv_name, rc_dev.keytable_name);
2122 			return 0;
2123 		}
2124 	}
2125 
2126 	if (debug)
2127 		fprintf(stderr, _("Opening %s\n"), rc_dev.input_name);
2128 	fd = open(rc_dev.input_name, O_RDONLY | O_NONBLOCK);
2129 	if (fd < 0) {
2130 		perror(rc_dev.input_name);
2131 		return -1;
2132 	}
2133 	if (dev_from_class)
2134 		free(rc_dev.input_name);
2135 	if (get_input_protocol_version(fd))
2136 		return -1;
2137 
2138 	/*
2139 	 * First step: clear, if --clear is specified
2140 	 */
2141 	if (clear) {
2142 		clear_table(fd);
2143 		fprintf(stderr, _("Old keytable cleared\n"));
2144 	}
2145 
2146 	/*
2147 	 * Second step: stores key tables from file or from commandline
2148 	 */
2149 	write_cnt = add_keys(fd);
2150 	if (write_cnt)
2151 		fprintf(stderr, _("Wrote %d keycode(s) to driver\n"), write_cnt);
2152 
2153 	/*
2154 	 * Third step: change protocol
2155 	 */
2156 	if (ch_proto || bpf_protocol) {
2157 		if (rc_dev.lirc_name)
2158 			clear_bpf(rc_dev.lirc_name);
2159 
2160 		rc_dev.current = load_bpf_for_unsupported(ch_proto, rc_dev.supported);
2161 
2162 		if (!set_proto(&rc_dev)) {
2163 			fprintf(stderr, _("Protocols changed to "));
2164 			write_sysfs_protocols(rc_dev.current, stderr, "%s ");
2165 			fprintf(stderr, "\n");
2166 		}
2167 	}
2168 
2169 	if (bpf_protocol) {
2170 		struct bpf_protocol *b;
2171 
2172 		if (!rc_dev.lirc_name) {
2173 			fprintf(stderr, _("Error: unable to attach bpf program, lirc device name was not found\n"));
2174 		}
2175 
2176 		for (b = bpf_protocol; b && rc_dev.lirc_name; b = b->next) {
2177 			char *fname = find_bpf_file(b->name);
2178 
2179 			if (fname) {
2180 				if (attach_bpf(rc_dev.lirc_name, fname, b->param))
2181 					fprintf(stderr, _("Loaded BPF protocol %s\n"), b->name);
2182 				free(fname);
2183 			}
2184 		}
2185 	}
2186 
2187 	/*
2188 	 * Fourth step: display current keytable
2189 	 */
2190 	if (readtable)
2191 		display_table(&rc_dev, fd);
2192 
2193 	/*
2194 	 * Fiveth step: change repeat rate/delay
2195 	 */
2196 	if (delay >= 0 || period >= 0) {
2197 		unsigned int new_delay, new_period;
2198 		get_rate(fd, &new_delay, &new_period);
2199 		if (delay >= 0)
2200 			new_delay = delay;
2201 		if (period >= 0)
2202 			new_period = period;
2203 		set_rate(fd, new_delay, new_period);
2204 	}
2205 
2206 	if (test)
2207 		test_event(&rc_dev, fd);
2208 
2209 	return 0;
2210 }
2211