usbhidaction.c revision 203971
1/*      $NetBSD: usbhidaction.c,v 1.8 2002/06/11 06:06:21 itojun Exp $ */
2/*	$FreeBSD: head/usr.bin/usbhidaction/usbhidaction.c 203971 2010-02-16 21:43:57Z imp $ */
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;
96
97	demon = 1;
98	ignore = 0;
99	dieearly = 0;
100	while ((ch = getopt(argc, argv, "c:def:ip: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 't':
121			table = optarg;
122			break;
123		case 'v':
124			demon = 0;
125			verbose++;
126			break;
127		case '?':
128		default:
129			usage();
130		}
131	}
132	argc -= optind;
133	argv += optind;
134
135	if (conf == NULL || dev == NULL)
136		usage();
137
138	hid_init(table);
139
140	if (dev[0] != '/') {
141		snprintf(devnamebuf, sizeof(devnamebuf), "/dev/%s%s",
142			 isdigit(dev[0]) ? "uhid" : "", dev);
143		dev = devnamebuf;
144	}
145
146	fd = open(dev, O_RDWR);
147	if (fd < 0)
148		err(1, "%s", dev);
149	reportid = hid_get_report_id(fd);
150	repd = hid_get_report_desc(fd);
151	if (repd == NULL)
152		err(1, "hid_get_report_desc() failed");
153
154	commands = parse_conf(conf, repd, reportid, ignore);
155
156	sz = (size_t)hid_report_size(repd, hid_input, reportid);
157
158	if (verbose)
159		printf("report size %zu\n", sz);
160	if (sz > sizeof buf)
161		errx(1, "report too large");
162
163	(void)signal(SIGHUP, sighup);
164
165	if (demon) {
166		fp = open(pidfile, O_WRONLY|O_CREAT, S_IRUSR|S_IRGRP|S_IROTH);
167		if (fp >= 0) {
168			sz1 = snprintf(buf, sizeof buf, "%d\n", getpid());
169			if (sz1 > sizeof buf)
170				sz1 = sizeof buf;
171			write(fp, buf, sz1);
172			close(fp);
173		} else
174			err(1, "%s", pidfile);
175		if (daemon(0, 0) < 0)
176			err(1, "daemon()");
177		isdemon = 1;
178	}
179
180	for(;;) {
181		n = read(fd, buf, sz);
182		if (verbose > 2) {
183			printf("read %d bytes:", n);
184			for (i = 0; i < n; i++)
185				printf(" %02x", buf[i]);
186			printf("\n");
187		}
188		if (n < 0) {
189			if (verbose)
190				err(1, "read");
191			else
192				exit(1);
193		}
194#if 0
195		if (n != sz) {
196			err(2, "read size");
197		}
198#endif
199		for (cmd = commands; cmd; cmd = cmd->next) {
200			val = hid_get_data(buf, &cmd->item);
201			if (cmd->value != val && cmd->anyvalue == 0)
202				goto next;
203			if ((cmd->debounce == 0) ||
204			    ((cmd->debounce == 1) && ((cmd->lastseen == -1) ||
205					       (cmd->lastseen != val)))) {
206				docmd(cmd, val, dev, argc, argv);
207				goto next;
208			}
209			if ((cmd->debounce > 1) &&
210			    ((cmd->lastused == -1) ||
211			     (abs(cmd->lastused - val) >= cmd->debounce))) {
212				docmd(cmd, val, dev, argc, argv);
213				cmd->lastused = val;
214				goto next;
215			}
216next:
217			cmd->lastseen = val;
218		}
219
220		if (dieearly)
221			exit(0);
222
223		if (reparse) {
224			struct command *cmds =
225			    parse_conf(conf, repd, reportid, ignore);
226			if (cmds) {
227				freecommands(commands);
228				commands = cmds;
229			}
230			reparse = 0;
231		}
232	}
233
234	exit(0);
235}
236
237void
238usage(void)
239{
240
241	fprintf(stderr, "Usage: %s [-deiv] -c config_file -f hid_dev "
242		"[-p pidfile] [-t tablefile]\n", getprogname());
243	exit(1);
244}
245
246static int
247peek(FILE *f)
248{
249	int c;
250
251	c = getc(f);
252	if (c != EOF)
253		ungetc(c, f);
254	return c;
255}
256
257struct command *
258parse_conf(const char *conf, report_desc_t repd, int reportid, int ignore)
259{
260	FILE *f;
261	char *p;
262	int line;
263	char buf[SIZE], name[SIZE], value[SIZE], debounce[SIZE], action[SIZE];
264	char usbuf[SIZE], coll[SIZE];
265	struct command *cmd, *cmds;
266	struct hid_data *d;
267	struct hid_item h;
268	int u, lo, hi, range;
269
270
271	f = fopen(conf, "r");
272	if (f == NULL)
273		err(1, "%s", conf);
274
275	cmds = NULL;
276	for (line = 1; ; line++) {
277		if (fgets(buf, sizeof buf, f) == NULL)
278			break;
279		if (buf[0] == '#' || buf[0] == '\n')
280			continue;
281		p = strchr(buf, '\n');
282		while (p && isspace(peek(f))) {
283			if (fgets(p, sizeof buf - strlen(buf), f) == NULL)
284				break;
285			p = strchr(buf, '\n');
286		}
287		if (p)
288			*p = 0;
289		if (sscanf(buf, "%s %s %s %[^\n]",
290			   name, value, debounce, action) != 4) {
291			if (isdemon) {
292				syslog(LOG_WARNING, "config file `%s', line %d"
293				       ", syntax error: %s", conf, line, buf);
294				freecommands(cmds);
295				return (NULL);
296			} else {
297				errx(1, "config file `%s', line %d,"
298				     ", syntax error: %s", conf, line, buf);
299			}
300		}
301
302		cmd = malloc(sizeof *cmd);
303		if (cmd == NULL)
304			err(1, "malloc failed");
305		cmd->next = cmds;
306		cmds = cmd;
307		cmd->line = line;
308
309		if (strcmp(value, "*") == 0) {
310			cmd->anyvalue = 1;
311		} else {
312			cmd->anyvalue = 0;
313			if (sscanf(value, "%d", &cmd->value) != 1) {
314				if (isdemon) {
315					syslog(LOG_WARNING,
316					       "config file `%s', line %d, "
317					       "bad value: %s (should be * or a number)\n",
318					       conf, line, value);
319					freecommands(cmds);
320					return (NULL);
321				} else {
322					errx(1, "config file `%s', line %d, "
323					     "bad value: %s (should be * or a number)\n",
324					     conf, line, value);
325				}
326			}
327		}
328
329		if (sscanf(debounce, "%d", &cmd->debounce) != 1) {
330			if (isdemon) {
331				syslog(LOG_WARNING,
332				       "config file `%s', line %d, "
333				       "bad value: %s (should be a number >= 0)\n",
334				       conf, line, debounce);
335				freecommands(cmds);
336				return (NULL);
337			} else {
338				errx(1, "config file `%s', line %d, "
339				     "bad value: %s (should be a number >= 0)\n",
340				     conf, line, debounce);
341			}
342		}
343
344		coll[0] = 0;
345		for (d = hid_start_parse(repd, 1 << hid_input, reportid);
346		     hid_get_item(d, &h); ) {
347			if (verbose > 2)
348				printf("kind=%d usage=%x\n", h.kind, h.usage);
349			if (h.flags & HIO_CONST)
350				continue;
351			switch (h.kind) {
352			case hid_input:
353				if (h.usage_minimum != 0 ||
354				    h.usage_maximum != 0) {
355					lo = h.usage_minimum;
356					hi = h.usage_maximum;
357					range = 1;
358				} else {
359					lo = h.usage;
360					hi = h.usage;
361					range = 0;
362				}
363				for (u = lo; u <= hi; u++) {
364					snprintf(usbuf, sizeof usbuf,  "%s:%s",
365						 hid_usage_page(HID_PAGE(u)),
366						 hid_usage_in_page(u));
367					if (verbose > 2)
368						printf("usage %s\n", usbuf);
369					if (!strcasecmp(usbuf, name))
370						goto foundhid;
371					if (coll[0]) {
372						snprintf(usbuf, sizeof usbuf,
373						  "%s.%s:%s", coll+1,
374						  hid_usage_page(HID_PAGE(u)),
375						  hid_usage_in_page(u));
376						if (verbose > 2)
377							printf("usage %s\n",
378							       usbuf);
379						if (!strcasecmp(usbuf, name))
380							goto foundhid;
381					}
382				}
383				break;
384			case hid_collection:
385				snprintf(coll + strlen(coll),
386				    sizeof coll - strlen(coll),  ".%s:%s",
387				    hid_usage_page(HID_PAGE(h.usage)),
388				    hid_usage_in_page(h.usage));
389				break;
390			case hid_endcollection:
391				if (coll[0])
392					*strrchr(coll, '.') = 0;
393				break;
394			default:
395				break;
396			}
397		}
398		if (ignore) {
399			if (verbose)
400				warnx("ignore item '%s'", name);
401			continue;
402		}
403		if (isdemon) {
404			syslog(LOG_WARNING, "config file `%s', line %d, HID "
405			       "item not found: `%s'\n", conf, line, name);
406			freecommands(cmds);
407			return (NULL);
408		} else {
409			errx(1, "config file `%s', line %d, HID item "
410			     "not found: `%s'\n", conf, line, name);
411		}
412
413	foundhid:
414		hid_end_parse(d);
415		cmd->lastseen = -1;
416		cmd->lastused = -1;
417		cmd->item = h;
418		cmd->name = strdup(name);
419		cmd->action = strdup(action);
420		if (range) {
421			if (cmd->value == 1)
422				cmd->value = u - lo;
423			else
424				cmd->value = -1;
425		}
426
427		if (verbose)
428			printf("PARSE:%d %s, %d, '%s'\n", cmd->line, name,
429			       cmd->value, cmd->action);
430	}
431	fclose(f);
432	return (cmds);
433}
434
435void
436docmd(struct command *cmd, int value, const char *hid, int argc, char **argv)
437{
438	char cmdbuf[SIZE], *p, *q;
439	size_t len;
440	int n, r;
441
442	for (p = cmd->action, q = cmdbuf; *p && q < &cmdbuf[SIZE-1]; ) {
443		if (*p == '$') {
444			p++;
445			len = &cmdbuf[SIZE-1] - q;
446			if (isdigit(*p)) {
447				n = strtol(p, &p, 10) - 1;
448				if (n >= 0 && n < argc) {
449					strncpy(q, argv[n], len);
450					q += strlen(q);
451				}
452			} else if (*p == 'V') {
453				p++;
454				snprintf(q, len, "%d", value);
455				q += strlen(q);
456			} else if (*p == 'N') {
457				p++;
458				strncpy(q, cmd->name, len);
459				q += strlen(q);
460			} else if (*p == 'H') {
461				p++;
462				strncpy(q, hid, len);
463				q += strlen(q);
464			} else if (*p) {
465				*q++ = *p++;
466			}
467		} else {
468			*q++ = *p++;
469		}
470	}
471	*q = 0;
472
473	if (verbose)
474		printf("system '%s'\n", cmdbuf);
475	r = system(cmdbuf);
476	if (verbose > 1 && r)
477		printf("return code = 0x%x\n", r);
478}
479
480void
481freecommands(struct command *cmd)
482{
483	struct command *next;
484
485	while (cmd) {
486		next = cmd->next;
487		free(cmd);
488		cmd = next;
489	}
490}
491