usbhidaction.c revision 224511
1/*      $NetBSD: usbhidaction.c,v 1.8 2002/06/11 06:06:21 itojun Exp $ */
2/*	$FreeBSD: head/usr.bin/usbhidaction/usbhidaction.c 224511 2011-07-30 13:22:44Z mav $ */
3
4/*
5 * Copyright (c) 2000, 2002 The NetBSD Foundation, Inc.
6 * All rights reserved.
7 *
8 * This code is derived from software contributed to The NetBSD Foundation
9 * by Lennart Augustsson <lennart@augustsson.net>.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 *    notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 *    notice, this list of conditions and the following disclaimer in the
18 *    documentation and/or other materials provided with the distribution.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
24 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 * POSSIBILITY OF SUCH DAMAGE.
31 */
32
33#include <stdio.h>
34#include <stdlib.h>
35#include <string.h>
36#include <ctype.h>
37#include <err.h>
38#include <fcntl.h>
39#include <limits.h>
40#include <unistd.h>
41#include <sys/types.h>
42#include <dev/usb/usbhid.h>
43#include <usbhid.h>
44#include <syslog.h>
45#include <signal.h>
46#include <errno.h>
47#include <sys/stat.h>
48
49static int	verbose = 0;
50static int	isdemon = 0;
51static int	reparse = 1;
52static const char *	pidfile = "/var/run/usbaction.pid";
53
54struct command {
55	struct command *next;
56	int line;
57
58	struct hid_item item;
59	int value;
60	int lastseen;
61	int lastused;
62	int debounce;
63	char anyvalue;
64	char *name;
65	char *action;
66};
67struct command *commands;
68
69#define SIZE 4000
70
71void usage(void);
72struct command *parse_conf(const char *, report_desc_t, int, int);
73void docmd(struct command *, int, const char *, int, char **);
74void freecommands(struct command *);
75
76static void
77sighup(int sig __unused)
78{
79	reparse = 1;
80}
81
82int
83main(int argc, char **argv)
84{
85	const char *conf = NULL;
86	const char *dev = NULL;
87	const char *table = NULL;
88	int fd, fp, ch, n, val, i;
89	size_t sz, sz1;
90	int demon, ignore, dieearly;
91	report_desc_t repd;
92	char buf[100];
93	char devnamebuf[PATH_MAX];
94	struct command *cmd;
95	int reportid = -1;
96
97	demon = 1;
98	ignore = 0;
99	dieearly = 0;
100	while ((ch = getopt(argc, argv, "c:def:ip:r:t:v")) != -1) {
101		switch(ch) {
102		case 'c':
103			conf = optarg;
104			break;
105		case 'd':
106			demon ^= 1;
107			break;
108		case 'e':
109			dieearly = 1;
110			break;
111		case 'i':
112			ignore++;
113			break;
114		case 'f':
115			dev = optarg;
116			break;
117		case 'p':
118			pidfile = optarg;
119			break;
120		case 'r':
121			reportid = atoi(optarg);
122			break;
123		case 't':
124			table = optarg;
125			break;
126		case 'v':
127			demon = 0;
128			verbose++;
129			break;
130		case '?':
131		default:
132			usage();
133		}
134	}
135	argc -= optind;
136	argv += optind;
137
138	if (conf == NULL || dev == NULL)
139		usage();
140
141	hid_init(table);
142
143	if (dev[0] != '/') {
144		snprintf(devnamebuf, sizeof(devnamebuf), "/dev/%s%s",
145			 isdigit(dev[0]) ? "uhid" : "", dev);
146		dev = devnamebuf;
147	}
148
149	fd = open(dev, O_RDWR);
150	if (fd < 0)
151		err(1, "%s", dev);
152	repd = hid_get_report_desc(fd);
153	if (repd == NULL)
154		err(1, "hid_get_report_desc() failed");
155
156	commands = parse_conf(conf, repd, reportid, ignore);
157
158	sz = (size_t)hid_report_size(repd, hid_input, -1);
159
160	if (verbose)
161		printf("report size %zu\n", sz);
162	if (sz > sizeof buf)
163		errx(1, "report too large");
164
165	(void)signal(SIGHUP, sighup);
166
167	if (demon) {
168		fp = open(pidfile, O_WRONLY|O_CREAT, S_IRUSR|S_IRGRP|S_IROTH);
169		if (fp >= 0) {
170			sz1 = snprintf(buf, sizeof buf, "%ld\n",
171			    (long)getpid());
172			if (sz1 > sizeof buf)
173				sz1 = sizeof buf;
174			write(fp, buf, sz1);
175			close(fp);
176		} else
177			err(1, "%s", pidfile);
178		if (daemon(0, 0) < 0)
179			err(1, "daemon()");
180		isdemon = 1;
181	}
182
183	for(;;) {
184		n = read(fd, buf, sz);
185		if (verbose > 2) {
186			printf("read %d bytes:", n);
187			for (i = 0; i < n; i++)
188				printf(" %02x", buf[i]);
189			printf("\n");
190		}
191		if (n < 0) {
192			if (verbose)
193				err(1, "read");
194			else
195				exit(1);
196		}
197#if 0
198		if (n != sz) {
199			err(2, "read size");
200		}
201#endif
202		for (cmd = commands; cmd; cmd = cmd->next) {
203			if (cmd->item.report_ID != 0 &&
204			    buf[0] != cmd->item.report_ID)
205				continue;
206			if (cmd->item.flags & HIO_VARIABLE)
207				val = hid_get_data(buf, &cmd->item);
208			else {
209				uint32_t pos = cmd->item.pos;
210				for (i = 0; i < cmd->item.report_count; i++) {
211					val = hid_get_data(buf, &cmd->item);
212					if (val == cmd->value)
213						break;
214					cmd->item.pos += cmd->item.report_size;
215				}
216				cmd->item.pos = pos;
217				val = (i < cmd->item.report_count) ?
218				    cmd->value : -1;
219			}
220			if (cmd->value != val && cmd->anyvalue == 0)
221				goto next;
222			if ((cmd->debounce == 0) ||
223			    ((cmd->debounce == 1) && ((cmd->lastseen == -1) ||
224					       (cmd->lastseen != val)))) {
225				docmd(cmd, val, dev, argc, argv);
226				goto next;
227			}
228			if ((cmd->debounce > 1) &&
229			    ((cmd->lastused == -1) ||
230			     (abs(cmd->lastused - val) >= cmd->debounce))) {
231				docmd(cmd, val, dev, argc, argv);
232				cmd->lastused = val;
233				goto next;
234			}
235next:
236			cmd->lastseen = val;
237		}
238
239		if (dieearly)
240			exit(0);
241
242		if (reparse) {
243			struct command *cmds =
244			    parse_conf(conf, repd, reportid, ignore);
245			if (cmds) {
246				freecommands(commands);
247				commands = cmds;
248			}
249			reparse = 0;
250		}
251	}
252
253	exit(0);
254}
255
256void
257usage(void)
258{
259
260	fprintf(stderr, "Usage: %s [-deiv] -c config_file -f hid_dev "
261		"[-p pidfile] [-t tablefile]\n", getprogname());
262	exit(1);
263}
264
265static int
266peek(FILE *f)
267{
268	int c;
269
270	c = getc(f);
271	if (c != EOF)
272		ungetc(c, f);
273	return c;
274}
275
276struct command *
277parse_conf(const char *conf, report_desc_t repd, int reportid, int ignore)
278{
279	FILE *f;
280	char *p;
281	int line;
282	char buf[SIZE], name[SIZE], value[SIZE], debounce[SIZE], action[SIZE];
283	char usbuf[SIZE], coll[SIZE];
284	struct command *cmd, *cmds;
285	struct hid_data *d;
286	struct hid_item h;
287	int u, lo, hi, range;
288
289
290	f = fopen(conf, "r");
291	if (f == NULL)
292		err(1, "%s", conf);
293
294	cmds = NULL;
295	for (line = 1; ; line++) {
296		if (fgets(buf, sizeof buf, f) == NULL)
297			break;
298		if (buf[0] == '#' || buf[0] == '\n')
299			continue;
300		p = strchr(buf, '\n');
301		while (p && isspace(peek(f))) {
302			if (fgets(p, sizeof buf - strlen(buf), f) == NULL)
303				break;
304			p = strchr(buf, '\n');
305		}
306		if (p)
307			*p = 0;
308		if (sscanf(buf, "%s %s %s %[^\n]",
309			   name, value, debounce, action) != 4) {
310			if (isdemon) {
311				syslog(LOG_WARNING, "config file `%s', line %d"
312				       ", syntax error: %s", conf, line, buf);
313				freecommands(cmds);
314				return (NULL);
315			} else {
316				errx(1, "config file `%s', line %d,"
317				     ", syntax error: %s", conf, line, buf);
318			}
319		}
320
321		cmd = malloc(sizeof *cmd);
322		if (cmd == NULL)
323			err(1, "malloc failed");
324		cmd->next = cmds;
325		cmds = cmd;
326		cmd->line = line;
327
328		if (strcmp(value, "*") == 0) {
329			cmd->anyvalue = 1;
330		} else {
331			cmd->anyvalue = 0;
332			if (sscanf(value, "%d", &cmd->value) != 1) {
333				if (isdemon) {
334					syslog(LOG_WARNING,
335					       "config file `%s', line %d, "
336					       "bad value: %s (should be * or a number)\n",
337					       conf, line, value);
338					freecommands(cmds);
339					return (NULL);
340				} else {
341					errx(1, "config file `%s', line %d, "
342					     "bad value: %s (should be * or a number)\n",
343					     conf, line, value);
344				}
345			}
346		}
347
348		if (sscanf(debounce, "%d", &cmd->debounce) != 1) {
349			if (isdemon) {
350				syslog(LOG_WARNING,
351				       "config file `%s', line %d, "
352				       "bad value: %s (should be a number >= 0)\n",
353				       conf, line, debounce);
354				freecommands(cmds);
355				return (NULL);
356			} else {
357				errx(1, "config file `%s', line %d, "
358				     "bad value: %s (should be a number >= 0)\n",
359				     conf, line, debounce);
360			}
361		}
362
363		coll[0] = 0;
364		for (d = hid_start_parse(repd, 1 << hid_input, reportid);
365		     hid_get_item(d, &h); ) {
366			if (verbose > 2)
367				printf("kind=%d usage=%x\n", h.kind, h.usage);
368			if (h.flags & HIO_CONST)
369				continue;
370			switch (h.kind) {
371			case hid_input:
372				if (h.usage_minimum != 0 ||
373				    h.usage_maximum != 0) {
374					lo = h.usage_minimum;
375					hi = h.usage_maximum;
376					range = 1;
377				} else {
378					lo = h.usage;
379					hi = h.usage;
380					range = 0;
381				}
382				for (u = lo; u <= hi; u++) {
383					snprintf(usbuf, sizeof usbuf,  "%s:%s",
384						 hid_usage_page(HID_PAGE(u)),
385						 hid_usage_in_page(u));
386					if (verbose > 2)
387						printf("usage %s\n", usbuf);
388					if (!strcasecmp(usbuf, name))
389						goto foundhid;
390					if (coll[0]) {
391						snprintf(usbuf, sizeof usbuf,
392						  "%s.%s:%s", coll+1,
393						  hid_usage_page(HID_PAGE(u)),
394						  hid_usage_in_page(u));
395						if (verbose > 2)
396							printf("usage %s\n",
397							       usbuf);
398						if (!strcasecmp(usbuf, name))
399							goto foundhid;
400					}
401				}
402				break;
403			case hid_collection:
404				snprintf(coll + strlen(coll),
405				    sizeof coll - strlen(coll),  ".%s:%s",
406				    hid_usage_page(HID_PAGE(h.usage)),
407				    hid_usage_in_page(h.usage));
408				break;
409			case hid_endcollection:
410				if (coll[0])
411					*strrchr(coll, '.') = 0;
412				break;
413			default:
414				break;
415			}
416		}
417		if (ignore) {
418			if (verbose)
419				warnx("ignore item '%s'", name);
420			continue;
421		}
422		if (isdemon) {
423			syslog(LOG_WARNING, "config file `%s', line %d, HID "
424			       "item not found: `%s'\n", conf, line, name);
425			freecommands(cmds);
426			return (NULL);
427		} else {
428			errx(1, "config file `%s', line %d, HID item "
429			     "not found: `%s'\n", conf, line, name);
430		}
431
432	foundhid:
433		hid_end_parse(d);
434		cmd->lastseen = -1;
435		cmd->lastused = -1;
436		cmd->item = h;
437		cmd->name = strdup(name);
438		cmd->action = strdup(action);
439		if (range) {
440			if (cmd->value == 1)
441				cmd->value = u - lo;
442			else
443				cmd->value = -1;
444		}
445
446		if (verbose)
447			printf("PARSE:%d %s, %d, '%s'\n", cmd->line, name,
448			       cmd->value, cmd->action);
449	}
450	fclose(f);
451	return (cmds);
452}
453
454void
455docmd(struct command *cmd, int value, const char *hid, int argc, char **argv)
456{
457	char cmdbuf[SIZE], *p, *q;
458	size_t len;
459	int n, r;
460
461	for (p = cmd->action, q = cmdbuf; *p && q < &cmdbuf[SIZE-1]; ) {
462		if (*p == '$') {
463			p++;
464			len = &cmdbuf[SIZE-1] - q;
465			if (isdigit(*p)) {
466				n = strtol(p, &p, 10) - 1;
467				if (n >= 0 && n < argc) {
468					strncpy(q, argv[n], len);
469					q += strlen(q);
470				}
471			} else if (*p == 'V') {
472				p++;
473				snprintf(q, len, "%d", value);
474				q += strlen(q);
475			} else if (*p == 'N') {
476				p++;
477				strncpy(q, cmd->name, len);
478				q += strlen(q);
479			} else if (*p == 'H') {
480				p++;
481				strncpy(q, hid, len);
482				q += strlen(q);
483			} else if (*p) {
484				*q++ = *p++;
485			}
486		} else {
487			*q++ = *p++;
488		}
489	}
490	*q = 0;
491
492	if (verbose)
493		printf("system '%s'\n", cmdbuf);
494	r = system(cmdbuf);
495	if (verbose > 1 && r)
496		printf("return code = 0x%x\n", r);
497}
498
499void
500freecommands(struct command *cmd)
501{
502	struct command *next;
503
504	while (cmd) {
505		next = cmd->next;
506		free(cmd);
507		cmd = next;
508	}
509}
510