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