1 /*
2  *  ir-ctl.c - Program to send and receive IR using lirc interface
3  *
4  *  Copyright (C) 2016 Sean Young <sean@mess.org>
5  *
6  *  This program is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation, version 2 of the License.
9  *
10  *  This program is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *  GNU General Public License for more details.
14  */
15 
16 #include <stdio.h>
17 #include <unistd.h>
18 #include <stdlib.h>
19 #include <stdbool.h>
20 #include <stdint.h>
21 #include <string.h>
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <sys/ioctl.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <argp.h>
28 #include <sysexits.h>
29 
30 #include <config.h>
31 
32 #include <linux/lirc.h>
33 
34 #include "ir-encode.h"
35 #include "keymap.h"
36 #include "bpf_encoder.h"
37 
38 #ifdef ENABLE_NLS
39 # define _(string) gettext(string)
40 # include <stdio.h>
41 # include <locale.h>
42 # include <langinfo.h>
43 # include <iconv.h>
44 #else
45 # include <string.h>
46 # define _(string) string
47 #endif
48 
49 # define N_(string) string
50 
51 /* taken from glibc unistd.h */
52 #ifndef TEMP_FAILURE_RETRY
53 #define TEMP_FAILURE_RETRY(expression) \
54     ({ long int __result;                                                     \
55        do __result = (long int) (expression);                                 \
56        while (__result == -1L && errno == EINTR);                             \
57        __result; })
58 #endif
59 
60 /* See drivers/media/rc/lirc_dev.c line 22 */
61 #define LIRCBUF_SIZE 1024
62 #define IR_DEFAULT_TIMEOUT 125000
63 #define UNSET UINT32_MAX
64 
65 const char *argp_program_version = "IR ctl version " V4L_UTILS_VERSION;
66 const char *argp_program_bug_address = "Sean Young <sean@mess.org>";
67 
68 /*
69  * Since this program drives the lirc interface, use the same terminology
70  */
71 struct send {
72 	struct send *next;
73 	const char *fname;
74 	bool is_scancode;
75 	bool is_keycode;
76 	union {
77 		struct {
78 			unsigned carrier;
79 			unsigned len;
80 			unsigned buf[LIRCBUF_SIZE];
81 		};
82 		struct {
83 			unsigned scancode;
84 			unsigned protocol;
85 		};
86 		char	keycode[1];
87 	};
88 };
89 
90 struct arguments {
91 	char *device;
92 	bool features;
93 	bool receive;
94 	bool verbose;
95 	bool mode2;
96 	struct keymap *keymap;
97 	struct send *send;
98 	bool oneshot;
99 	char *savetofile;
100 	int wideband;
101 	unsigned carrier_low, carrier_high;
102 	unsigned timeout;
103 	unsigned gap;
104 	int carrier_reports;
105 	unsigned carrier;
106 	unsigned duty;
107 	unsigned emitters;
108 	bool work_to_do;
109 };
110 
111 static const struct argp_option options[] = {
112 	{ "device",	'd',	N_("DEV"),	0,	N_("lirc device to use") },
113 	{ "features",	'f',	0,		0,	N_("list lirc device features") },
114 	{ "receive",	'r',	N_("FILE"),	OPTION_ARG_OPTIONAL,	N_("receive IR to stdout or file") },
115 	{ "send",	's',	N_("FILE"),	0,	N_("send IR pulse and space file") },
116 	{ "scancode",	'S',	N_("SCANCODE"),	0,	N_("send IR scancode in protocol specified") },
117 	{ "keycode",	'K',	N_("KEYCODE"),	0,	N_("send IR keycode from keymap") },
118 	{ "verbose",	'v',	0,		0,	N_("verbose output") },
119 		{ .doc = N_("Receiving options:") },
120 	{ "one-shot",	'1',	0,		0,	N_("end receiving after first message") },
121 	{ "mode2",	2,	0,		0,	N_("output in mode2 format") },
122 	{ "wideband",	'w',	0,		0,	N_("use wideband receiver aka learning mode") },
123 	{ "narrowband",	'n',	0,		0,	N_("use narrowband receiver, disable learning mode") },
124 	{ "carrier-range", 'R', N_("RANGE"),	0,	N_("set receiver carrier range") },
125 	{ "measure-carrier", 'm', 0,		0,	N_("report carrier frequency") },
126 	{ "no-measure-carrier", 'M', 0,		0,	N_("disable reporting carrier frequency") },
127 	{ "timeout",	't',	N_("TIMEOUT"),	0,	N_("set receiving timeout") },
128 		{ .doc = N_("Sending options:") },
129 	{ "keymap",	'k',	N_("KEYMAP"),	0,	N_("use keymap to send key from") },
130 	{ "carrier",	'c',	N_("CARRIER"),	0,	N_("set send carrier") },
131 	{ "duty-cycle",	'D',	N_("DUTY"),	0,	N_("set send duty cycle") },
132 	{ "emitters",	'e',	N_("EMITTERS"),	0,	N_("set send emitters") },
133 	{ "gap",	'g',	N_("GAP"),	0,	N_("set gap between files or scancodes") },
134 	{ }
135 };
136 
137 static const char args_doc[] = N_(
138 	"--features\n"
139 	"--receive [save to file]\n"
140 	"--send [file to send]\n"
141 	"--scancode [scancode to send]\n"
142 	"--keycode [keycode to send]\n"
143 	"[to set lirc option]");
144 
145 static const char doc[] = N_(
146 	"\nReceive IR, send IR and list features of lirc device\n"
147 	"You will need permission on /dev/lirc for the program to work\n"
148 	"\nOn the options below, the arguments are:\n"
149 	"  DEV      - the /dev/lirc* device to use\n"
150 	"  FILE     - a text file containing pulses and spaces\n"
151 	"  CARRIER  - the carrier frequency to use for sending\n"
152 	"  DUTY     - the duty cycle to use for sending\n"
153 	"  EMITTERS - comma separated list of emitters to use for sending, e.g. 1,2\n"
154 	"  GAP      - gap between sending in microseconds\n"
155 	"  RANGE    - set range of accepted carrier frequencies, e.g. 20000-40000\n"
156 	"  TIMEOUT  - set length of space before receiving stops in microseconds\n"
157 	"  KEYCODE  - key code in keymap\n"
158 	"  SCANCODE - protocol:scancode, e.g. nec:0xa814\n"
159 	"  KEYMAP   - a rc keymap file from which to send keys\n\n"
160 	"Note that most lirc setting have global state, i.e. the device will remain\n"
161 	"in this state until set otherwise.");
162 
strtoint(const char * p,const char * unit,unsigned * ret)163 static bool strtoint(const char *p, const char *unit, unsigned *ret)
164 {
165 	char *end;
166 	long arg = strtol(p, &end, 10);
167 	if (end == NULL || (end[0] != 0 && strcasecmp(end, unit) != 0))
168 		return false;
169 
170 	if (arg < 0 || arg >= 0xffffff)
171 		return false;
172 
173 	*ret = arg;
174 	return true;
175 }
176 
strtoscancode(const char * p,unsigned * ret)177 static bool strtoscancode(const char *p, unsigned *ret)
178 {
179 	char *end;
180 	long long arg = strtoll(p, &end, 0);
181 	if (end == NULL || end[0] != 0)
182 		return false;
183 
184 	if (arg < 0 || arg > 0xffffffff)
185 		return false;
186 
187 	*ret = arg;
188 	return true;
189 }
190 
parse_emitters(char * p)191 static unsigned parse_emitters(char *p)
192 {
193 	unsigned emit = 0;
194 	static const char *sep = " ,;:";
195 	char *saveptr, *q;
196 
197 	q = strtok_r(p, sep, &saveptr);
198 	while (q) {
199 		char *endptr;
200 		long e = strtol(q, &endptr, 10);
201 		if ((endptr && *endptr) || e <= 0 || e > 32)
202 			return 0;
203 
204 		emit |= 1 << (e - 1);
205 		q = strtok_r(NULL, sep, &saveptr);
206 	}
207 
208 	return emit;
209 }
210 
read_file_pulse_space(struct arguments * args,const char * fname,FILE * input)211 static struct send *read_file_pulse_space(struct arguments *args, const char *fname, FILE *input)
212 {
213 	bool expect_pulse = true;
214 	int lineno = 0, lastspace = 0;
215 	char line[1024];
216 	int len = 0;
217 	static const char whitespace[] = " \n\r\t";
218 	struct send *f;
219 
220 	f = malloc(sizeof(*f));
221 	if (f == NULL) {
222 		fprintf(stderr, _("Failed to allocate memory\n"));
223 		return NULL;
224 	}
225 	f->is_scancode = false;
226 	f->is_keycode = false;
227 	f->carrier = UNSET;
228 	f->fname = fname;
229 
230 	while (fgets(line, sizeof(line), input)) {
231 		char *p, *saveptr;
232 		lineno++;
233 		char *keyword = strtok_r(line, whitespace, &saveptr);
234 
235 		if (keyword == NULL || *keyword == 0 || *keyword == '#' ||
236 				(keyword[0] == '/' && keyword[1] == '/'))
237 			continue;
238 
239 		p = strtok_r(NULL, whitespace, &saveptr);
240 		if (p == NULL) {
241 			fprintf(stderr, _("warning: %s:%d: missing argument\n"), fname, lineno);
242 			continue;
243 		}
244 
245 		if (strcmp(keyword, "scancode") == 0) {
246 			enum rc_proto proto;
247 			unsigned scancode, carrier;
248 			char *scancodestr;
249 
250 			if (!expect_pulse) {
251 				f->buf[len++] = args->gap;
252 				expect_pulse = true;
253 			}
254 
255 			scancodestr = strchr(p, ':');
256 			if (!scancodestr) {
257 				fprintf(stderr, _("error: %s:%d: scancode argument '%s' should be in protocol:scancode format\n"), fname, lineno, p);
258 				fclose(input);
259 				free(f);
260 				return NULL;
261 			}
262 
263 			*scancodestr++ = 0;
264 
265 			if (!protocol_match(p, &proto)) {
266 				fprintf(stderr, _("error: %s:%d: protocol '%s' not found\n"), fname, lineno, p);
267 				fclose(input);
268 				free(f);
269 				return NULL;
270 			}
271 
272 			if (!strtoscancode(scancodestr, &scancode)) {
273 				fprintf(stderr, _("error: %s:%d: invalid scancode '%s'\n"), fname, lineno, scancodestr);
274 				fclose(input);
275 				free(f);
276 				return NULL;
277 			}
278 
279 			if (!protocol_encoder_available(proto)) {
280 				fprintf(stderr, _("error: %s:%d: no encoder available for `%s'\n"), fname, lineno, protocol_name(proto));
281 				fclose(input);
282 				free(f);
283 				return NULL;
284 			}
285 
286 			protocol_scancode_valid(&proto, &scancode);
287 
288 			if (len + protocol_max_size(proto) >= LIRCBUF_SIZE) {
289 				fprintf(stderr, _("error: %s:%d: too much IR for one transmit\n"), fname, lineno);
290 				fclose(input);
291 				free(f);
292 				return NULL;
293 			}
294 
295 			carrier = protocol_carrier(proto);
296 			if (f->carrier && f->carrier != carrier)
297 				fprintf(stderr, _("error: %s:%d: carrier already specified\n"), fname, lineno);
298 			else
299 				f->carrier = carrier;
300 
301 			len += protocol_encode(proto, scancode, f->buf + len);
302 			expect_pulse = false;
303 			continue;
304 		}
305 
306 		unsigned int arg;
307 		if (!strtoint(p, "", &arg)) {
308 			fprintf(stderr, _("warning: %s:%d: invalid argument '%s'\n"), fname, lineno, p);
309 			continue;
310 		}
311 
312 		p = strtok_r(NULL, whitespace, &saveptr);
313 		if (p && p[0] != '#' && !(p[0] == '/' && p[1] == '/')) {
314 			fprintf(stderr, _("warning: %s:%d: '%s' unexpected\n"), fname, lineno, p);
315 			continue;
316 		}
317 
318 		if (strcmp(keyword, "space") == 0) {
319 			if (arg == 0) {
320 				fprintf(stderr, _("warning: %s:%d: invalid argument to space '%d'\n"), fname, lineno, arg);
321 				continue;
322 			}
323 			if (expect_pulse) {
324 				if (len == 0) {
325 					fprintf(stderr, _("warning: %s:%d: leading space ignored\n"),
326 						fname, lineno);
327 				} else {
328 					f->buf[len-1] += arg;
329 				}
330 			} else {
331 				f->buf[len++] = arg;
332 			}
333 			lastspace = lineno;
334 			expect_pulse = true;
335 		} else if (strcmp(keyword, "pulse") == 0) {
336 			if (arg == 0) {
337 				fprintf(stderr, _("warning: %s:%d: invalid argument to pulse '%d'\n"), fname, lineno, arg);
338 				continue;
339 			}
340 			if (!expect_pulse)
341 				f->buf[len-1] += arg;
342 			else
343 				f->buf[len++] = arg;
344 			expect_pulse = false;
345 		} else if (strcmp(keyword, "carrier") == 0) {
346 			if (f->carrier != UNSET && f->carrier != arg) {
347 				fprintf(stderr, _("warning: %s:%d: carrier already specified\n"), fname, lineno);
348 			} else {
349 				f->carrier = arg;
350 			}
351 		} else {
352 			fprintf(stderr, _("warning: %s:%d: unknown keyword '%s' ignored\n"), fname, lineno, keyword);
353 			continue;
354 		}
355 
356 		if (len >= LIRCBUF_SIZE) {
357 			fprintf(stderr, _("warning: %s:%d: IR cannot exceed %u edges\n"), fname, lineno, LIRCBUF_SIZE);
358 			break;
359 		}
360 	}
361 
362 	fclose(input);
363 
364 	if (len == 0) {
365 		fprintf(stderr, _("%s: no pulses or spaces found\n"), fname);
366 		free(f);
367 		return NULL;
368 	}
369 
370 	if ((len % 2) == 0) {
371 		fprintf(stderr, _("warning: %s:%d: trailing space ignored\n"),
372 							fname, lastspace);
373 		len--;
374 	}
375 
376 	f->len = len;
377 
378 	return f;
379 }
380 
read_file_raw(struct arguments * args,const char * fname,FILE * input)381 static struct send *read_file_raw(struct arguments *args, const char *fname, FILE *input)
382 {
383 	int lineno = 0, lastspace = 0;
384 	char line[1024];
385 	int len = 0;
386 	static const char whitespace[] = " \n\r\t,";
387 	struct send *f;
388 
389 	f = malloc(sizeof(*f));
390 	if (f == NULL) {
391 		fprintf(stderr, _("Failed to allocate memory\n"));
392 		fclose(input);
393 		return NULL;
394 	}
395 	f->is_scancode = false;
396 	f->is_keycode = false;
397 	f->carrier = UNSET;
398 	f->fname = fname;
399 
400 	while (fgets(line, sizeof(line), input)) {
401 		long int value;
402 		char *p, *saveptr;
403 		lineno++;
404 		char *keyword = strtok_r(line, whitespace, &saveptr);
405 
406 		for (;;) {
407 			if (keyword == NULL || *keyword == 0 || *keyword == '#' ||
408 			    (keyword[0] == '/' && keyword[1] == '/'))
409 				break;
410 
411 			value = strtol(keyword, &p, 10);
412 			if (errno || *p) {
413 				fprintf(stderr, _("%s:%d: error: expected integer, got `%s'\n"),
414 					fname, lineno, keyword);
415 				fclose(input);
416 				free(f);
417 				return NULL;
418 			}
419 
420 			if (len % 2) {
421 				if (keyword[0] == '+') {
422 					fprintf(stderr, _("%s:%d: error: pulse found where space expected `%s'\n"), fname, lineno, keyword);
423 					free(f);
424 					return NULL;
425 				}
426 				if (keyword[0] == '-')
427 					value = -value;
428 			} else {
429 				if (keyword[0] == '-') {
430 					fprintf(stderr, _("%s:%d: error: space found where pulse expected `%s'\n"), fname, lineno, keyword);
431 					fclose(input);
432 					free(f);
433 					return NULL;
434 				}
435 				lastspace = lineno;
436 			}
437 
438 			if (value <= 0 || value >= LIRC_VALUE_MASK) {
439 				fprintf(stderr, _("%s:%d: error: value `%s' out of range\n"), fname, lineno, keyword);
440 				fclose(input);
441 				free(f);
442 				return NULL;
443 			}
444 
445 			f->buf[len++] = value;
446 
447 			if (len >= LIRCBUF_SIZE) {
448 				fprintf(stderr, _("warning: %s:%d: IR cannot exceed %u edges\n"), fname, lineno, LIRCBUF_SIZE);
449 				break;
450 			}
451 
452 			keyword = strtok_r(NULL, whitespace, &saveptr);
453 		}
454 	}
455 
456 	fclose(input);
457 
458 	if (len == 0) {
459 		fprintf(stderr, _("%s: no pulses or spaces found\n"), fname);
460 		free(f);
461 		return NULL;
462 	}
463 
464 	if ((len % 2) == 0) {
465 		fprintf(stderr, _("warning: %s:%d: trailing space ignored\n"),
466 							fname, lastspace);
467 		len--;
468 	}
469 
470 	f->len = len;
471 
472 	return f;
473 }
474 
read_file(struct arguments * args,const char * fname)475 static struct send *read_file(struct arguments *args, const char *fname)
476 {
477 	FILE *input = fopen(fname, "r");
478 	char line[1024];
479 
480 	if (!input) {
481 		fprintf(stderr, _("%s: could not open: %m\n"), fname);
482 		return NULL;
483 	}
484 
485 	while (fgets(line, sizeof(line), input)) {
486 		int start = 0;
487 
488 		while (isspace(line[start]))
489 			start++;
490 
491 		switch (line[start]) {
492 		case '/':
493 			if (line[start+1] != '/')
494 				break;
495 		case 0:
496 		case '#':
497 			continue;
498 		case '+':
499 		case '-':
500 		case '0' ... '9':
501 			rewind(input);
502 			return read_file_raw(args, fname, input);
503 		default:
504 			rewind(input);
505 			return read_file_pulse_space(args, fname, input);
506 		}
507 	}
508 
509 	fclose(input);
510 
511 	fprintf(stderr, _("%s: file is empty\n"), fname);
512 
513 	return NULL;
514 }
515 
read_scancode(const char * name)516 static struct send *read_scancode(const char *name)
517 {
518 	enum rc_proto proto;
519 	struct send *f;
520 	unsigned scancode;
521 	char *pstr;
522 	char *p = strchr(name, ':');
523 
524 	if (!p) {
525 		fprintf(stderr, _("error: scancode '%s' must be in protocol:scancode format\n"), name);
526 		return NULL;
527 	}
528 
529 	pstr = strndup(name, p - name);
530 
531 	if (!protocol_match(pstr, &proto)) {
532 		fprintf(stderr, _("error: protocol '%s' not found\n"), pstr);
533 		free(pstr);
534 		return NULL;
535 	}
536 	free(pstr);
537 
538 	if (!strtoscancode(p + 1, &scancode)) {
539 		fprintf(stderr, _("error: invalid scancode '%s'\n"), p + 1);
540 		return NULL;
541 	}
542 
543 	protocol_scancode_valid(&proto, &scancode);
544 
545 	f = malloc(sizeof(*f));
546 	if (f == NULL) {
547 		fprintf(stderr, _("Failed to allocate memory\n"));
548 		return NULL;
549 	}
550 
551 	f->is_scancode = true;
552 	f->is_keycode = false;
553 	f->scancode = scancode;
554 	f->protocol = proto;
555 
556 	return f;
557 }
558 
parse_opt(int k,char * arg,struct argp_state * state)559 static int parse_opt(int k, char *arg, struct argp_state *state)
560 {
561 	struct arguments *arguments = state->input;
562 	struct keymap *map;
563 	struct send *s;
564 
565 	switch (k) {
566 	case 'f':
567 		if (arguments->receive || arguments->send)
568 			argp_error(state, _("features can not be combined with receive or send option"));
569 		arguments->features = true;
570 		break;
571 	// receiving
572 	case 'r':
573 		if (arguments->features || arguments->send)
574 			argp_error(state, _("receive can not be combined with features or send option"));
575 
576 		arguments->receive = true;
577 		if (arg) {
578 			if (arguments->savetofile)
579 				argp_error(state, _("receive filename already set"));
580 
581 			arguments->savetofile = arg;
582 		}
583 		break;
584 	case '1':
585 		arguments->oneshot = true;
586 		break;
587 	case 2:
588 		arguments->mode2 = true;
589 		break;
590 	case 'v':
591 		arguments->verbose = true;
592 		break;
593 	case 'm':
594 		if (arguments->carrier_reports == 2)
595 			argp_error(state, _("cannot enable and disable carrier reports"));
596 
597 		arguments->carrier_reports = 1;
598 		break;
599 	case 'M':
600 		if (arguments->carrier_reports == 1)
601 			argp_error(state, _("cannot enable and disable carrier reports"));
602 
603 		arguments->carrier_reports = 2;
604 		break;
605 	case 'n':
606 		if (arguments->wideband)
607 			argp_error(state, _("cannot use narrowband and wideband receiver at once"));
608 
609 		arguments->wideband = 2;
610 		break;
611 	case 'w':
612 		if (arguments->wideband)
613 			argp_error(state, _("cannot use narrowband and wideband receiver at once"));
614 
615 		arguments->wideband = 1;
616 		break;
617 	case 'R': {
618 		long low, high;
619 		char *end;
620 
621 		low = strtol(arg, &end, 10);
622 		if (end == NULL || end[0] != '-')
623 			argp_error(state, _("cannot parse carrier range `%s'"), arg);
624 		high = strtol(end + 1, &end, 10);
625 		if (end[0] != 0 || low <= 0 || low >= high || high > 1000000)
626 			argp_error(state, _("cannot parse carrier range `%s'"), arg);
627 
628 		arguments->carrier_low = low;
629 		arguments->carrier_high = high;
630 		break;
631 	}
632 	case 't':
633 		if (!strtoint(arg, "µs", &arguments->timeout))
634 			argp_error(state, _("cannot parse timeout `%s'"), arg);
635 		break;
636 
637 	// sending
638 	case 'd':
639 		arguments->device = arg;
640 		break;
641 	case 'c':
642 		if (!strtoint(arg, "Hz", &arguments->carrier))
643 			argp_error(state, _("cannot parse carrier `%s'"), arg);
644 		break;
645 	case 'e':
646 		arguments->emitters = parse_emitters(arg);
647 		if (arguments->emitters == 0)
648 			argp_error(state, _("cannot parse emitters `%s'"), arg);
649 		break;
650 	case 'g':
651 		if (!strtoint(arg, "", &arguments->gap) || arguments->gap == 0)
652 			argp_error(state, _("cannot parse gap `%s'"), arg);
653 		break;
654 	case 'D':
655 		if (!strtoint(arg, "%", &arguments->duty) ||
656 		     arguments->duty == 0 || arguments->duty >= 100)
657 			argp_error(state, _("invalid duty cycle `%s'"), arg);
658 		break;
659 	case 's':
660 		if (arguments->receive || arguments->features)
661 			argp_error(state, _("send can not be combined with receive or features option"));
662 		s = read_file(arguments, arg);
663 		if (s == NULL)
664 			exit(EX_DATAERR);
665 
666 		s->next = NULL;
667 		if (arguments->send == NULL)
668 			arguments->send = s;
669 		else {
670 			struct send *p = arguments->send;
671 			while (p->next) p = p->next;
672 			p->next = s;
673 		}
674 		break;
675 	case 'S':
676 		if (arguments->receive || arguments->features)
677 			argp_error(state, _("send can not be combined with receive or features option"));
678 		s = read_scancode(arg);
679 		if (s == NULL)
680 			exit(EX_DATAERR);
681 
682 		s->next = NULL;
683 		if (arguments->send == NULL)
684 			arguments->send = s;
685 		else {
686 			struct send *p = arguments->send;
687 			while (p->next) p = p->next;
688 			p->next = s;
689 		}
690 		break;
691 
692 	case 'K':
693 		if (arguments->receive || arguments->features)
694 			argp_error(state, _("key send can not be combined with receive or features option"));
695 		s = malloc(sizeof(*s) + strlen(arg));
696 		if (s == NULL)
697 			exit(EX_DATAERR);
698 
699 		s->next = NULL;
700 		strcpy(s->keycode, arg);
701 		s->is_scancode = false;
702 		s->is_keycode = true;
703 		if (arguments->send == NULL)
704 			arguments->send = s;
705 		else {
706 			struct send *p = arguments->send;
707 			while (p->next) p = p->next;
708 			p->next = s;
709 		}
710 		break;
711 
712 	case 'k':
713 		if (parse_keymap(arg, &map, arguments->verbose))
714 			exit(EX_DATAERR);
715 		if (arguments->keymap == NULL)
716 			arguments->keymap = map;
717 		else {
718 			// add to end of list of keymaps
719 			struct keymap *p = arguments->keymap;
720 			while (p->next) p = p->next;
721 			p->next = map;
722 		}
723 		break;
724 
725 	case ARGP_KEY_END:
726 		if (!arguments->work_to_do)
727 			argp_usage(state);
728 
729 		break;
730 	default:
731 		return ARGP_ERR_UNKNOWN;
732 	}
733 
734 	if (k != '1' && k != 'd' && k != 'v' && k != 'k' && k != 2)
735 		arguments->work_to_do = true;
736 
737 	return 0;
738 }
739 
convert_keycode(struct keymap * map,const char * keycode)740 static struct send* convert_keycode(struct keymap *map, const char *keycode)
741 {
742 	struct send *s = NULL;
743 	int count = 0;
744 
745 	for (;map; map = map->next) {
746 		struct scancode_entry *se;
747 		struct raw_entry *re;
748 
749 		for (re = map->raw; re; re = re->next) {
750 			if (strcmp(re->keycode, keycode))
751 				continue;
752 
753 			count++;
754 
755 			if (!s) {
756 				s = malloc(sizeof(*s) + re->raw_length * sizeof(int));
757 				s->len = re->raw_length;
758 				memcpy(s->buf, re->raw, s->len * sizeof(int));
759 				s->is_scancode = false;
760 				s->is_keycode = false;
761 				s->carrier = keymap_param(map, "carrier", 0);
762 				s->next = NULL;
763 			}
764 		}
765 
766 		for (se = map->scancode; se; se = se->next) {
767 			int buf[LIRCBUF_SIZE], length;
768 			const char *proto_str;
769 			enum rc_proto proto;
770 
771 			if (strcmp(se->keycode, keycode))
772 				continue;
773 
774 			count++;
775 
776 			if (s)
777 				continue;
778 
779 			proto_str = map->variant ?: map->protocol;
780 
781 			if (protocol_match(proto_str, &proto)) {
782 				s = malloc(sizeof(*s));
783 				s->protocol = proto;
784 				s->scancode = se->scancode;
785 				s->is_scancode = true;
786 				s->is_keycode = false;
787 				s->next = NULL;
788 			} else if (encode_bpf_protocol(map, se->scancode,
789 						       buf, &length)) {
790 				s = malloc(sizeof(*s) + sizeof(int) * length);
791 				s->len = length;
792 				memcpy(s->buf, buf, length * sizeof(int));
793 				s->is_scancode = false;
794 				s->is_keycode = false;
795 				s->carrier = keymap_param(map, "carrier", 0);
796 				s->next = NULL;
797 			} else {
798 				fprintf(stderr, _("error: protocol '%s' not supported\n"), proto_str);
799 				return NULL;
800 			}
801 		}
802 	}
803 
804 	if (!s) {
805 		fprintf(stderr, _("error: keycode `%s' not found in keymap\n"), keycode);
806 		return NULL;
807 	}
808 
809 	if (count > 1)
810 		fprintf(stderr, _("warning: keycode `%s' has %d definitions in keymaps, using first\n"), keycode, count);
811 
812 	return s;
813 }
814 
815 static const struct argp argp = {
816 	.options = options,
817 	.parser = parse_opt,
818 	.args_doc = args_doc,
819 	.doc = doc
820 };
821 
open_lirc(const char * fname,unsigned * features)822 static int open_lirc(const char *fname, unsigned *features)
823 {
824 	int fd;
825 
826 	fd = TEMP_FAILURE_RETRY(open(fname, O_RDWR | O_CLOEXEC));
827 	if (fd == -1) {
828 		fprintf(stderr, _("%s: cannot open: %m\n"), fname);
829 		return -1;
830 	}
831 
832 	struct stat st;
833 	int rc = TEMP_FAILURE_RETRY(fstat(fd, &st));
834 	if (rc) {
835 		fprintf(stderr, _("%s: cannot stat: %m\n"), fname);
836 		close(fd);
837 		return -1;
838 	}
839 
840 	if ((st.st_mode & S_IFMT) != S_IFCHR) {
841 		fprintf(stderr, _("%s: not character device\n"), fname);
842 		close(fd);
843 		return -1;
844 	}
845 
846 	rc = ioctl(fd, LIRC_GET_FEATURES, features);
847 	if (rc) {
848 		fprintf(stderr, _("%s: failed to get lirc features: %m\n"), fname);
849 		close(fd);
850 		return -1;
851 	}
852 
853 	return fd;
854 }
855 
lirc_set_send_carrier(int fd,const char * devname,unsigned features,unsigned carrier)856 static void lirc_set_send_carrier(int fd, const char *devname, unsigned features, unsigned carrier)
857 {
858 	if (features & LIRC_CAN_SET_SEND_CARRIER) {
859 		int rc = ioctl(fd, LIRC_SET_SEND_CARRIER, &carrier);
860 		if (rc < 0)
861 			fprintf(stderr, _("warning: %s: failed to set carrier: %m\n"), devname);
862 		if (rc != 0)
863 			fprintf(stderr, _("warning: %s: set send carrier returned %d, should return 0\n"), devname, rc);
864 	} else
865 		fprintf(stderr, _("warning: %s: does not support setting send carrier\n"), devname);
866 }
867 
lirc_options(struct arguments * args,int fd,unsigned features)868 static int lirc_options(struct arguments *args, int fd, unsigned features)
869 {
870 	const char *dev = args->device;
871 	int rc;
872 
873 	if (args->timeout != UNSET) {
874 		if (features & LIRC_CAN_SET_REC_TIMEOUT) {
875 			rc = ioctl(fd, LIRC_SET_REC_TIMEOUT, &args->timeout);
876 			if (rc)
877 				fprintf(stderr, _("%s: failed to set receiving timeout\n"), dev);
878 		} else
879 			fprintf(stderr, _("%s: device does not support setting timeout\n"), dev);
880 	}
881 
882 	if (args->wideband) {
883 		unsigned on = args->wideband == 1;
884 		if (features & LIRC_CAN_USE_WIDEBAND_RECEIVER) {
885 			rc = ioctl(fd, LIRC_SET_WIDEBAND_RECEIVER, &on);
886 			if (rc)
887 				fprintf(stderr, _("%s: failed to set wideband receiver %s\n"), dev, on ? _("on") : _("off"));
888 		} else
889 			fprintf(stderr, _("%s: device does not have wideband receiver\n"), dev);
890 	}
891 
892 	if (args->carrier_reports) {
893 		unsigned on = args->carrier_reports == 1;
894 		if (features & LIRC_CAN_MEASURE_CARRIER) {
895 			rc = ioctl(fd, LIRC_SET_MEASURE_CARRIER_MODE, &on);
896 			if (rc)
897 				fprintf(stderr, _("%s: failed to set carrier reports %s\n"), dev, on ? _("on") : _("off"));
898 		} else
899 			fprintf(stderr, _("%s: device cannot measure carrier\n"), dev);
900 	}
901 
902 	if (features & LIRC_CAN_REC_MODE2) {
903 		unsigned on = 1;
904 		rc = ioctl(fd, LIRC_SET_REC_TIMEOUT_REPORTS, &on);
905 		if (rc)
906 			fprintf(stderr, _("%s: failed to enable timeout reports: %m\n"), dev);
907 	}
908 
909 	if (args->carrier_low) {
910 		if (features & LIRC_CAN_SET_REC_CARRIER_RANGE) {
911 			rc = ioctl(fd, LIRC_SET_REC_CARRIER_RANGE, &args->carrier_low);
912 			if (rc)
913 				fprintf(stderr, _("%s: failed to set low carrier range: %m\n"), dev);
914 			rc = ioctl(fd, LIRC_SET_REC_CARRIER, &args->carrier_high);
915 			if (rc)
916 				fprintf(stderr, _("%s: failed to set high carrier range: %m\n"), dev);
917 		} else
918 			fprintf(stderr, _("%s: device does not support setting receiver carrier range\n"), dev);
919 	}
920 
921 	if (args->carrier != UNSET)
922 		lirc_set_send_carrier(fd, dev, features, args->carrier);
923 
924 	if (args->duty) {
925 		if (features & LIRC_CAN_SET_SEND_DUTY_CYCLE) {
926 			rc = ioctl(fd, LIRC_SET_SEND_DUTY_CYCLE, &args->duty);
927 			if (rc)
928 				fprintf(stderr, _("warning: %s: failed to set duty cycle: %m\n"), dev);
929 		} else
930 			fprintf(stderr, _("warning: %s: does not support setting send duty cycle\n"), dev);
931 	}
932 
933 	if (args->emitters) {
934 		if (features & LIRC_CAN_SET_TRANSMITTER_MASK) {
935 			rc = ioctl(fd, LIRC_SET_TRANSMITTER_MASK, &args->emitters);
936 			if (rc > 0)
937 				fprintf(stderr, _("warning: %s: failed to set send transmitters: only %d available\n"), dev, rc);
938 			else if (rc < 0)
939 				fprintf(stderr, _("warning: %s: failed to set send transmitters: %m\n"), dev);
940 		} else
941 			fprintf(stderr, _("warning: %s: does not support setting send transmitters\n"), dev);
942 	}
943 
944 
945 	return 0;
946 }
947 
lirc_features(struct arguments * args,int fd,unsigned features)948 static void lirc_features(struct arguments *args, int fd, unsigned features)
949 {
950 	const char *dev = args->device;
951 	unsigned resolution = 0, mode = LIRC_MODE_SCANCODE;
952 	int rc;
953 
954 	if (features & LIRC_CAN_GET_REC_RESOLUTION) {
955 		rc = ioctl(fd, LIRC_GET_REC_RESOLUTION, &resolution);
956 		if (rc == 0 && resolution == 0)
957 			fprintf(stderr, _("warning: %s: device returned resolution of 0\n"), dev);
958 		else if (rc)
959 			fprintf(stderr, _("warning: %s: unexpected error while retrieving resolution: %m\n"), dev);
960 	}
961 
962 	printf(_("Receive features %s:\n"), dev);
963 	if (features & LIRC_CAN_REC_SCANCODE) {
964 		printf(_(" - Device can receive scancodes\n"));
965 	} else if (features & LIRC_CAN_REC_MODE2) {
966 		printf(_(" - Device can receive raw IR\n"));
967 		if (ioctl(fd, LIRC_SET_REC_MODE, &mode) == 0)
968 			printf(_(" - Can report decoded scancodes and protocol\n"));
969 		if (resolution)
970 			printf(_(" - Resolution %u microseconds\n"), resolution);
971 		if (features & LIRC_CAN_SET_REC_CARRIER)
972 			printf(_(" - Set receive carrier\n"));
973 		if (features & LIRC_CAN_USE_WIDEBAND_RECEIVER)
974 			printf(_(" - Use wideband receiver\n"));
975 		if (features & LIRC_CAN_MEASURE_CARRIER)
976 			printf(_(" - Can measure carrier\n"));
977 
978 		// This ioctl is only supported from kernel 4.18 onwards
979 		unsigned timeout;
980 		int rc = ioctl(fd, LIRC_GET_REC_TIMEOUT, &timeout);
981 		if (rc == 0) {
982 			if (timeout == 0)
983 				printf(_(" - Receiving timeout not set\n"));
984 			else
985 				printf(_(" - Receiving timeout %u microseconds\n"), timeout);
986 		}
987 
988 		if (features & LIRC_CAN_SET_REC_TIMEOUT) {
989 			unsigned min_timeout, max_timeout;
990 
991 			rc = ioctl(fd, LIRC_GET_MIN_TIMEOUT, &min_timeout);
992 			if (rc) {
993 				fprintf(stderr, _("warning: %s: device supports setting receiving timeout but LIRC_GET_MIN_TIMEOUT returns: %m\n"), dev);
994 				min_timeout = 0;
995 			} else if (min_timeout == 0)
996 				fprintf(stderr, _("warning: %s: device supports setting receiving timeout but min timeout is 0\n"), dev);
997 			rc = ioctl(fd, LIRC_GET_MAX_TIMEOUT, &max_timeout);
998 			if (rc) {
999 				fprintf(stderr, _("warning: %s: device supports setting receiving timeout but LIRC_GET_MAX_TIMEOUT returns: %m\n"), dev);
1000 				max_timeout = 0;
1001 			} else if (max_timeout == 0) {
1002 				fprintf(stderr, _("warning: %s: device supports setting receiving timeout but max timeout is 0\n"), dev);
1003 			}
1004 
1005 			if (min_timeout || max_timeout)
1006 				printf(_(" - Can set receiving timeout min %u microseconds, max %u microseconds\n"), min_timeout, max_timeout);
1007 		}
1008 	} else if (features & LIRC_CAN_REC_LIRCCODE) {
1009 		printf(_(" - Device can receive using device dependent LIRCCODE mode (not supported)\n"));
1010 	} else {
1011 		printf(_(" - Device cannot receive\n"));
1012 	}
1013 
1014 	printf(_("Send features %s:\n"), dev);
1015 	if (features & LIRC_CAN_SEND_PULSE) {
1016 		printf(_(" - Device can send raw IR\n"));
1017 		if (ioctl(fd, LIRC_SET_SEND_MODE, &mode) == 0)
1018 			printf(_(" - IR scancode encoder\n"));
1019 		if (features & LIRC_CAN_SET_SEND_CARRIER)
1020 			printf(_(" - Set carrier\n"));
1021 		if (features & LIRC_CAN_SET_SEND_DUTY_CYCLE)
1022 			printf(_(" - Set duty cycle\n"));
1023 		if (features & LIRC_CAN_SET_TRANSMITTER_MASK) {
1024 			unsigned mask = ~0;
1025 			rc = ioctl(fd, LIRC_SET_TRANSMITTER_MASK, &mask);
1026 			if (rc == 0)
1027 				fprintf(stderr, _("warning: %s: device supports setting transmitter mask but returns 0 as number of transmitters\n"), dev);
1028 			else if (rc < 0)
1029 				fprintf(stderr, _("warning: %s: device supports setting transmitter mask but returns: %m\n"), dev);
1030 			else
1031 				printf(_(" - Set transmitter (%d available)\n"), rc);
1032 		}
1033 	} else if (features & LIRC_CAN_SEND_LIRCCODE) {
1034 		printf(_(" - Device can send using device dependent LIRCCODE mode (not supported)\n"));
1035 	} else {
1036 		printf(_(" - Device cannot send\n"));
1037 	}
1038 }
1039 
lirc_send(struct arguments * args,int fd,unsigned features,struct send * f)1040 static int lirc_send(struct arguments *args, int fd, unsigned features, struct send *f)
1041 {
1042 	const char *dev = args->device;
1043 	int rc, mode;
1044 	ssize_t ret;
1045 
1046 	if (!(features & LIRC_CAN_SEND_PULSE)) {
1047 		fprintf(stderr, _("%s: device cannot send\n"), dev);
1048 		return EX_UNAVAILABLE;
1049 	}
1050 
1051 	if (f->is_scancode) {
1052 		if (args->verbose)
1053 			printf("Sending to kernel encoder protocol:%s scancode:0x%x\n",
1054 			       protocol_name(f->protocol), f->scancode);
1055 
1056 		mode = LIRC_MODE_SCANCODE;
1057 		rc = ioctl(fd, LIRC_SET_SEND_MODE, &mode);
1058 		if (rc == 0) {
1059 			struct lirc_scancode sc = {
1060 				.scancode = f->scancode,
1061 				.rc_proto = f->protocol,
1062 				.flags = 0
1063 			};
1064 			ret = TEMP_FAILURE_RETRY(write(fd, &sc, sizeof sc));
1065 			if (ret > 0)
1066 				return 0;
1067 		}
1068 	}
1069 
1070 	mode = LIRC_MODE_PULSE;
1071 	rc = ioctl(fd, LIRC_SET_SEND_MODE, &mode);
1072 	if (rc) {
1073 		fprintf(stderr, _("%s: cannot set send mode\n"), dev);
1074 		return EX_UNAVAILABLE;
1075 	}
1076 
1077 	if (f->is_scancode) {
1078 		// encode scancode
1079 		enum rc_proto proto = f->protocol;
1080 		if (!protocol_encoder_available(proto)) {
1081 			fprintf(stderr, _("%s: no encoder available for `%s'\n"),
1082 				dev, protocol_name(proto));
1083 			return EX_UNAVAILABLE;
1084 		}
1085 		f->len = protocol_encode(f->protocol, f->scancode, f->buf);
1086 		f->carrier = protocol_carrier(proto);
1087 	}
1088 
1089 	if (args->carrier != UNSET) {
1090 		if (f->carrier != UNSET)
1091 			fprintf(stderr, _("warning: carrier specified but overwritten on command line\n"));
1092 		lirc_set_send_carrier(fd, dev, features, args->carrier);
1093 	} else if (f->carrier != UNSET)
1094 		lirc_set_send_carrier(fd, dev, features, f->carrier);
1095 
1096 	size_t size = f->len * sizeof(unsigned);
1097 	if (args->verbose) {
1098 		int i;
1099 		printf("Sending:");
1100 		for (i=0; i<f->len; i++)
1101 			printf("%s%u", i & 1 ? " -" : " +", f->buf[i]);
1102 		putchar('\n');
1103 	}
1104 	ret = TEMP_FAILURE_RETRY(write(fd, f->buf, size));
1105 	if (ret < 0) {
1106 		fprintf(stderr, _("%s: failed to send: %m\n"), dev);
1107 		return EX_IOERR;
1108 	}
1109 
1110 	if (size < ret) {
1111 		fprintf(stderr, _("warning: %s: sent %zd out %zd edges\n"),
1112 				dev,
1113 				ret / sizeof(unsigned),
1114 				size / sizeof(unsigned));
1115 		return EX_IOERR;
1116 	}
1117 	if (args->verbose)
1118 		printf("Successfully sent\n");
1119 
1120 	return 0;
1121 }
1122 
lirc_receive(struct arguments * args,int fd,unsigned features)1123 int lirc_receive(struct arguments *args, int fd, unsigned features)
1124 {
1125 	char *dev = args->device;
1126 	FILE *out = stdout;
1127 	int rc = EX_IOERR;
1128 	int mode = LIRC_MODE_MODE2;
1129 
1130 	if (!(features & LIRC_CAN_REC_MODE2)) {
1131 		fprintf(stderr, _("%s: device cannot receive raw ir\n"), dev);
1132 		return EX_UNAVAILABLE;
1133 	}
1134 
1135 	// kernel v4.8 and v4.9 return ENOTTY
1136 	if (ioctl(fd, LIRC_SET_REC_MODE, &mode) && errno != ENOTTY) {
1137 		fprintf(stderr, _("%s: failed to set receive mode: %m\n"), dev);
1138 		return EX_IOERR;
1139 	}
1140 
1141 	if (args->savetofile) {
1142 		out = fopen(args->savetofile, "w");
1143 		if (!out) {
1144 			fprintf(stderr, _("%s: failed to open for writing: %m\n"), args->savetofile);
1145 			return EX_CANTCREAT;
1146 		}
1147 	}
1148 	unsigned buf[LIRCBUF_SIZE];
1149 
1150 	bool keep_reading = true;
1151 	bool leading_space = true;
1152 	unsigned carrier = 0;
1153 
1154 	while (keep_reading) {
1155 		ssize_t ret = TEMP_FAILURE_RETRY(read(fd, buf, sizeof(buf)));
1156 		if (ret < 0) {
1157 			fprintf(stderr, _("%s: failed read: %m\n"), dev);
1158 			goto err;
1159 		}
1160 
1161 		if (ret == 0 || ret % sizeof(unsigned)) {
1162 			fprintf(stderr, _("%s: read returned %zd bytes\n"),
1163 								dev, ret);
1164 			goto err;
1165 		}
1166 
1167 		for (int i=0; i<ret / sizeof(unsigned); i++) {
1168 			unsigned val = buf[i] & LIRC_VALUE_MASK;
1169 			unsigned msg = buf[i] & LIRC_MODE2_MASK;
1170 
1171 			// FIXME: the kernel often send us a space after
1172 			// the IR receiver comes out of idle mode. This
1173 			// is meaningless, maybe fix the kernel?
1174 			if (leading_space && msg == LIRC_MODE2_SPACE)
1175 				continue;
1176 
1177 			leading_space = false;
1178 			if (args->oneshot &&
1179 				(msg == LIRC_MODE2_TIMEOUT ||
1180 				(msg == LIRC_MODE2_SPACE && val > 19000))) {
1181 				keep_reading = false;
1182 				break;
1183 			}
1184 
1185 			if (args->mode2) {
1186 				switch (msg) {
1187 				case LIRC_MODE2_TIMEOUT:
1188 					fprintf(out, "timeout %u\n", val);
1189 					leading_space = true;
1190 					break;
1191 				case LIRC_MODE2_PULSE:
1192 					fprintf(out, "pulse %u\n", val);
1193 					break;
1194 				case LIRC_MODE2_SPACE:
1195 					fprintf(out, "space %u\n", val);
1196 					break;
1197 				case LIRC_MODE2_FREQUENCY:
1198 					fprintf(out, "carrier %u\n", val);
1199 					break;
1200 				}
1201 			} else {
1202 				switch (msg) {
1203 				case LIRC_MODE2_TIMEOUT:
1204 					if (carrier)
1205 						fprintf(out, "# carrier %uHz, timeout %u\n", carrier, val);
1206 					else
1207 						fprintf(out, "# timeout %u\n", val);
1208 					leading_space = true;
1209 					carrier = 0;
1210 					break;
1211 				case LIRC_MODE2_PULSE:
1212 					fprintf(out, "+%u ", val);
1213 					break;
1214 				case LIRC_MODE2_SPACE:
1215 					fprintf(out, "-%u ", val);
1216 					break;
1217 				case LIRC_MODE2_FREQUENCY:
1218 					carrier = val;
1219 					break;
1220 				}
1221 			}
1222 
1223 			fflush(out);
1224 		}
1225 	}
1226 
1227 	rc = 0;
1228 err:
1229 	if (args->savetofile)
1230 		fclose(out);
1231 
1232 	return rc;
1233 }
1234 
main(int argc,char * argv[])1235 int main(int argc, char *argv[])
1236 {
1237 	struct arguments args = {
1238 		.gap = IR_DEFAULT_TIMEOUT,
1239 		.carrier = UNSET,
1240 		.timeout = UNSET,
1241 	};
1242 
1243 #ifdef ENABLE_NLS
1244         setlocale (LC_ALL, "");
1245         bindtextdomain (PACKAGE, LOCALEDIR);
1246         textdomain (PACKAGE);
1247 #endif
1248 
1249 	argp_parse(&argp, argc, argv, 0, 0, &args);
1250 
1251 	if (args.device == NULL)
1252 		args.device = "/dev/lirc0";
1253 
1254 	int rc, fd;
1255 	unsigned features;
1256 
1257 	fd = open_lirc(args.device, &features);
1258 	if (fd < 0)
1259 		exit(EX_NOINPUT);
1260 
1261 	rc = lirc_options(&args, fd, features);
1262 	if (rc)
1263 		exit(EX_IOERR);
1264 
1265 	struct send *s = args.send;
1266 	while (s) {
1267 		struct send *next = s->next;
1268 		if (s != args.send)
1269 			usleep(args.gap);
1270 
1271 		if (s->is_keycode) {
1272 			struct send *k;
1273 
1274 			if (!args.keymap) {
1275 				fprintf(stderr, _("error: no keymap specified\n"));
1276 				exit(EX_DATAERR);
1277 			}
1278 
1279 			k = convert_keycode(args.keymap, s->keycode);
1280 			if (!k)
1281 				exit(EX_DATAERR);
1282 
1283 			free(s);
1284 			s = k;
1285 		}
1286 
1287 		rc = lirc_send(&args, fd, features, s);
1288 		if (rc) {
1289 			close(fd);
1290 			exit(rc);
1291 		}
1292 
1293 		free(s);
1294 		s = next;
1295 	}
1296 
1297 	if (args.receive) {
1298 		rc = lirc_receive(&args, fd, features);
1299 		if (rc) {
1300 			close(fd);
1301 			exit(rc);
1302 		}
1303 	}
1304 
1305 	if (args.features)
1306 		lirc_features(&args, fd, features);
1307 
1308 	free_keymap(args.keymap);
1309 	close(fd);
1310 
1311 	return 0;
1312 }
1313