usbhidaction.c revision 212048
1331722Seadler/*      $NetBSD: usbhidaction.c,v 1.8 2002/06/11 06:06:21 itojun Exp $ */
2153030Sgrehan/*	$FreeBSD: head/usr.bin/usbhidaction/usbhidaction.c 212048 2010-08-31 07:19:10Z kevlo $ */
3153030Sgrehan
4153030Sgrehan/*
5153030Sgrehan * Copyright (c) 2000, 2002 The NetBSD Foundation, Inc.
6153030Sgrehan * All rights reserved.
7153030Sgrehan *
8153030Sgrehan * This code is derived from software contributed to The NetBSD Foundation
9153030Sgrehan * by Lennart Augustsson <lennart@augustsson.net>.
10153030Sgrehan *
11153030Sgrehan * Redistribution and use in source and binary forms, with or without
12153030Sgrehan * modification, are permitted provided that the following conditions
13153030Sgrehan * are met:
14153030Sgrehan * 1. Redistributions of source code must retain the above copyright
15153030Sgrehan *    notice, this list of conditions and the following disclaimer.
16153030Sgrehan * 2. Redistributions in binary form must reproduce the above copyright
17153030Sgrehan *    notice, this list of conditions and the following disclaimer in the
18153030Sgrehan *    documentation and/or other materials provided with the distribution.
19153030Sgrehan *
20153030Sgrehan * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
21153030Sgrehan * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22153030Sgrehan * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23153030Sgrehan * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
24153030Sgrehan * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25153030Sgrehan * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26153030Sgrehan * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27153030Sgrehan * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28153030Sgrehan * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29153030Sgrehan * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30153030Sgrehan * POSSIBILITY OF SUCH DAMAGE.
31153030Sgrehan */
32153030Sgrehan
33153030Sgrehan#include <stdio.h>
34153030Sgrehan#include <stdlib.h>
35153030Sgrehan#include <string.h>
36153030Sgrehan#include <ctype.h>
37153030Sgrehan#include <err.h>
38153030Sgrehan#include <fcntl.h>
39153030Sgrehan#include <limits.h>
40153030Sgrehan#include <unistd.h>
41153030Sgrehan#include <sys/types.h>
42153030Sgrehan#include <dev/usb/usbhid.h>
43153030Sgrehan#include <usbhid.h>
44153030Sgrehan#include <syslog.h>
45153030Sgrehan#include <signal.h>
46153030Sgrehan#include <errno.h>
47153030Sgrehan#include <sys/stat.h>
48153030Sgrehan
49153030Sgrehanstatic int	verbose = 0;
50153030Sgrehanstatic int	isdemon = 0;
51153030Sgrehanstatic int	reparse = 1;
52153030Sgrehanstatic const char *	pidfile = "/var/run/usbaction.pid";
53153030Sgrehan
54153030Sgrehanstruct command {
55153030Sgrehan	struct command *next;
56153030Sgrehan	int line;
57153030Sgrehan
58153030Sgrehan	struct hid_item item;
59153030Sgrehan	int value;
60153030Sgrehan	int lastseen;
61153030Sgrehan	int lastused;
62153030Sgrehan	int debounce;
63153030Sgrehan	char anyvalue;
64153030Sgrehan	char *name;
65153030Sgrehan	char *action;
66153030Sgrehan};
67153030Sgrehanstruct command *commands;
68153030Sgrehan
69153030Sgrehan#define SIZE 4000
70153030Sgrehan
71153030Sgrehanvoid usage(void);
72153030Sgrehanstruct command *parse_conf(const char *, report_desc_t, int, int);
73153030Sgrehanvoid docmd(struct command *, int, const char *, int, char **);
74153030Sgrehanvoid freecommands(struct command *);
75153030Sgrehan
76153030Sgrehanstatic void
77153030Sgrehansighup(int sig __unused)
78153030Sgrehan{
79153030Sgrehan	reparse = 1;
80153030Sgrehan}
81153030Sgrehan
82153030Sgrehanint
83153030Sgrehanmain(int argc, char **argv)
84153030Sgrehan{
85153030Sgrehan	const char *conf = NULL;
86153030Sgrehan	const char *dev = NULL;
87153030Sgrehan	const char *table = NULL;
88153030Sgrehan	int fd, fp, ch, n, val, i;
89153030Sgrehan	size_t sz, sz1;
90153030Sgrehan	int demon, ignore, dieearly;
91153030Sgrehan	report_desc_t repd;
92153030Sgrehan	char buf[100];
93153030Sgrehan	char devnamebuf[PATH_MAX];
94153030Sgrehan	struct command *cmd;
95153030Sgrehan	int reportid;
96153030Sgrehan
97153030Sgrehan	demon = 1;
98153030Sgrehan	ignore = 0;
99153030Sgrehan	dieearly = 0;
100153030Sgrehan	while ((ch = getopt(argc, argv, "c:def:ip:t:v")) != -1) {
101153030Sgrehan		switch(ch) {
102153030Sgrehan		case 'c':
103153030Sgrehan			conf = optarg;
104153030Sgrehan			break;
105153030Sgrehan		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, "%ld\n",
169			    (long)getpid());
170			if (sz1 > sizeof buf)
171				sz1 = sizeof buf;
172			write(fp, buf, sz1);
173			close(fp);
174		} else
175			err(1, "%s", pidfile);
176		if (daemon(0, 0) < 0)
177			err(1, "daemon()");
178		isdemon = 1;
179	}
180
181	for(;;) {
182		n = read(fd, buf, sz);
183		if (verbose > 2) {
184			printf("read %d bytes:", n);
185			for (i = 0; i < n; i++)
186				printf(" %02x", buf[i]);
187			printf("\n");
188		}
189		if (n < 0) {
190			if (verbose)
191				err(1, "read");
192			else
193				exit(1);
194		}
195#if 0
196		if (n != sz) {
197			err(2, "read size");
198		}
199#endif
200		for (cmd = commands; cmd; cmd = cmd->next) {
201			val = hid_get_data(buf, &cmd->item);
202			if (cmd->value != val && cmd->anyvalue == 0)
203				goto next;
204			if ((cmd->debounce == 0) ||
205			    ((cmd->debounce == 1) && ((cmd->lastseen == -1) ||
206					       (cmd->lastseen != val)))) {
207				docmd(cmd, val, dev, argc, argv);
208				goto next;
209			}
210			if ((cmd->debounce > 1) &&
211			    ((cmd->lastused == -1) ||
212			     (abs(cmd->lastused - val) >= cmd->debounce))) {
213				docmd(cmd, val, dev, argc, argv);
214				cmd->lastused = val;
215				goto next;
216			}
217next:
218			cmd->lastseen = val;
219		}
220
221		if (dieearly)
222			exit(0);
223
224		if (reparse) {
225			struct command *cmds =
226			    parse_conf(conf, repd, reportid, ignore);
227			if (cmds) {
228				freecommands(commands);
229				commands = cmds;
230			}
231			reparse = 0;
232		}
233	}
234
235	exit(0);
236}
237
238void
239usage(void)
240{
241
242	fprintf(stderr, "Usage: %s [-deiv] -c config_file -f hid_dev "
243		"[-p pidfile] [-t tablefile]\n", getprogname());
244	exit(1);
245}
246
247static int
248peek(FILE *f)
249{
250	int c;
251
252	c = getc(f);
253	if (c != EOF)
254		ungetc(c, f);
255	return c;
256}
257
258struct command *
259parse_conf(const char *conf, report_desc_t repd, int reportid, int ignore)
260{
261	FILE *f;
262	char *p;
263	int line;
264	char buf[SIZE], name[SIZE], value[SIZE], debounce[SIZE], action[SIZE];
265	char usbuf[SIZE], coll[SIZE];
266	struct command *cmd, *cmds;
267	struct hid_data *d;
268	struct hid_item h;
269	int u, lo, hi, range;
270
271
272	f = fopen(conf, "r");
273	if (f == NULL)
274		err(1, "%s", conf);
275
276	cmds = NULL;
277	for (line = 1; ; line++) {
278		if (fgets(buf, sizeof buf, f) == NULL)
279			break;
280		if (buf[0] == '#' || buf[0] == '\n')
281			continue;
282		p = strchr(buf, '\n');
283		while (p && isspace(peek(f))) {
284			if (fgets(p, sizeof buf - strlen(buf), f) == NULL)
285				break;
286			p = strchr(buf, '\n');
287		}
288		if (p)
289			*p = 0;
290		if (sscanf(buf, "%s %s %s %[^\n]",
291			   name, value, debounce, action) != 4) {
292			if (isdemon) {
293				syslog(LOG_WARNING, "config file `%s', line %d"
294				       ", syntax error: %s", conf, line, buf);
295				freecommands(cmds);
296				return (NULL);
297			} else {
298				errx(1, "config file `%s', line %d,"
299				     ", syntax error: %s", conf, line, buf);
300			}
301		}
302
303		cmd = malloc(sizeof *cmd);
304		if (cmd == NULL)
305			err(1, "malloc failed");
306		cmd->next = cmds;
307		cmds = cmd;
308		cmd->line = line;
309
310		if (strcmp(value, "*") == 0) {
311			cmd->anyvalue = 1;
312		} else {
313			cmd->anyvalue = 0;
314			if (sscanf(value, "%d", &cmd->value) != 1) {
315				if (isdemon) {
316					syslog(LOG_WARNING,
317					       "config file `%s', line %d, "
318					       "bad value: %s (should be * or a number)\n",
319					       conf, line, value);
320					freecommands(cmds);
321					return (NULL);
322				} else {
323					errx(1, "config file `%s', line %d, "
324					     "bad value: %s (should be * or a number)\n",
325					     conf, line, value);
326				}
327			}
328		}
329
330		if (sscanf(debounce, "%d", &cmd->debounce) != 1) {
331			if (isdemon) {
332				syslog(LOG_WARNING,
333				       "config file `%s', line %d, "
334				       "bad value: %s (should be a number >= 0)\n",
335				       conf, line, debounce);
336				freecommands(cmds);
337				return (NULL);
338			} else {
339				errx(1, "config file `%s', line %d, "
340				     "bad value: %s (should be a number >= 0)\n",
341				     conf, line, debounce);
342			}
343		}
344
345		coll[0] = 0;
346		for (d = hid_start_parse(repd, 1 << hid_input, reportid);
347		     hid_get_item(d, &h); ) {
348			if (verbose > 2)
349				printf("kind=%d usage=%x\n", h.kind, h.usage);
350			if (h.flags & HIO_CONST)
351				continue;
352			switch (h.kind) {
353			case hid_input:
354				if (h.usage_minimum != 0 ||
355				    h.usage_maximum != 0) {
356					lo = h.usage_minimum;
357					hi = h.usage_maximum;
358					range = 1;
359				} else {
360					lo = h.usage;
361					hi = h.usage;
362					range = 0;
363				}
364				for (u = lo; u <= hi; u++) {
365					snprintf(usbuf, sizeof usbuf,  "%s:%s",
366						 hid_usage_page(HID_PAGE(u)),
367						 hid_usage_in_page(u));
368					if (verbose > 2)
369						printf("usage %s\n", usbuf);
370					if (!strcasecmp(usbuf, name))
371						goto foundhid;
372					if (coll[0]) {
373						snprintf(usbuf, sizeof usbuf,
374						  "%s.%s:%s", coll+1,
375						  hid_usage_page(HID_PAGE(u)),
376						  hid_usage_in_page(u));
377						if (verbose > 2)
378							printf("usage %s\n",
379							       usbuf);
380						if (!strcasecmp(usbuf, name))
381							goto foundhid;
382					}
383				}
384				break;
385			case hid_collection:
386				snprintf(coll + strlen(coll),
387				    sizeof coll - strlen(coll),  ".%s:%s",
388				    hid_usage_page(HID_PAGE(h.usage)),
389				    hid_usage_in_page(h.usage));
390				break;
391			case hid_endcollection:
392				if (coll[0])
393					*strrchr(coll, '.') = 0;
394				break;
395			default:
396				break;
397			}
398		}
399		if (ignore) {
400			if (verbose)
401				warnx("ignore item '%s'", name);
402			continue;
403		}
404		if (isdemon) {
405			syslog(LOG_WARNING, "config file `%s', line %d, HID "
406			       "item not found: `%s'\n", conf, line, name);
407			freecommands(cmds);
408			return (NULL);
409		} else {
410			errx(1, "config file `%s', line %d, HID item "
411			     "not found: `%s'\n", conf, line, name);
412		}
413
414	foundhid:
415		hid_end_parse(d);
416		cmd->lastseen = -1;
417		cmd->lastused = -1;
418		cmd->item = h;
419		cmd->name = strdup(name);
420		cmd->action = strdup(action);
421		if (range) {
422			if (cmd->value == 1)
423				cmd->value = u - lo;
424			else
425				cmd->value = -1;
426		}
427
428		if (verbose)
429			printf("PARSE:%d %s, %d, '%s'\n", cmd->line, name,
430			       cmd->value, cmd->action);
431	}
432	fclose(f);
433	return (cmds);
434}
435
436void
437docmd(struct command *cmd, int value, const char *hid, int argc, char **argv)
438{
439	char cmdbuf[SIZE], *p, *q;
440	size_t len;
441	int n, r;
442
443	for (p = cmd->action, q = cmdbuf; *p && q < &cmdbuf[SIZE-1]; ) {
444		if (*p == '$') {
445			p++;
446			len = &cmdbuf[SIZE-1] - q;
447			if (isdigit(*p)) {
448				n = strtol(p, &p, 10) - 1;
449				if (n >= 0 && n < argc) {
450					strncpy(q, argv[n], len);
451					q += strlen(q);
452				}
453			} else if (*p == 'V') {
454				p++;
455				snprintf(q, len, "%d", value);
456				q += strlen(q);
457			} else if (*p == 'N') {
458				p++;
459				strncpy(q, cmd->name, len);
460				q += strlen(q);
461			} else if (*p == 'H') {
462				p++;
463				strncpy(q, hid, len);
464				q += strlen(q);
465			} else if (*p) {
466				*q++ = *p++;
467			}
468		} else {
469			*q++ = *p++;
470		}
471	}
472	*q = 0;
473
474	if (verbose)
475		printf("system '%s'\n", cmdbuf);
476	r = system(cmdbuf);
477	if (verbose > 1 && r)
478		printf("return code = 0x%x\n", r);
479}
480
481void
482freecommands(struct command *cmd)
483{
484	struct command *next;
485
486	while (cmd) {
487		next = cmd->next;
488		free(cmd);
489		cmd = next;
490	}
491}
492