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