xref: /freebsd/usr.bin/usbhidaction/usbhidaction.c (revision 4c8945a06b01a5c8122cdeb402af36bb46a06acc)
1 /*      $NetBSD: usbhidaction.c,v 1.8 2002/06/11 06:06:21 itojun Exp $ */
2 /*	$FreeBSD$ */
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 
49 static int	verbose = 0;
50 static int	isdemon = 0;
51 static int	reparse = 1;
52 static const char *	pidfile = "/var/run/usbaction.pid";
53 
54 struct 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 };
67 struct command *commands;
68 
69 #define SIZE 4000
70 
71 void usage(void);
72 struct command *parse_conf(const char *, report_desc_t, int, int);
73 void docmd(struct command *, int, const char *, int, char **);
74 void freecommands(struct command *);
75 
76 static void
77 sighup(int sig __unused)
78 {
79 	reparse = 1;
80 }
81 
82 int
83 main(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, "%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 			}
217 next:
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 
238 void
239 usage(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 
247 static int
248 peek(FILE *f)
249 {
250 	int c;
251 
252 	c = getc(f);
253 	if (c != EOF)
254 		ungetc(c, f);
255 	return c;
256 }
257 
258 struct command *
259 parse_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 
436 void
437 docmd(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 
481 void
482 freecommands(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