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