Home | History | Annotate | Line # | Download | only in usbhidaction
usbhidaction.c revision 1.19
      1 /*      $NetBSD: usbhidaction.c,v 1.19 2005/07/02 04:05:09 dsainty 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.19 2005/07/02 04:05:09 dsainty 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 int verbose = 0;
     62 int isdemon = 0;
     63 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 struct command *commands;
     76 
     77 #define SIZE 4000
     78 
     79 void usage(void);
     80 struct command *parse_conf(const char *, report_desc_t, int, int);
     81 void docmd(struct command *, int, const char *, int, char **);
     82 void freecommands(struct command *);
     83 
     84 static void
     85 sighup(int sig)
     86 {
     87 	reparse = 1;
     88 }
     89 
     90 int
     91 main(int argc, char **argv)
     92 {
     93 	const char *conf = NULL;
     94 	const char *dev = NULL;
     95 	int fd, ch, sz, n, val, i;
     96 	int demon, ignore;
     97 	report_desc_t repd;
     98 	char buf[100];
     99 	char devnamebuf[PATH_MAX];
    100 	struct command *cmd;
    101 	int reportid;
    102 	const char *table = NULL;
    103 
    104 	setlinebuf(stdout);
    105 
    106 	demon = 1;
    107 	ignore = 0;
    108 	while ((ch = getopt(argc, argv, "c:df:it:v")) != -1) {
    109 		switch(ch) {
    110 		case 'c':
    111 			conf = optarg;
    112 			break;
    113 		case 'd':
    114 			demon ^= 1;
    115 			break;
    116 		case 'i':
    117 			ignore++;
    118 			break;
    119 		case 'f':
    120 			dev = optarg;
    121 			break;
    122 		case 't':
    123 			table = optarg;
    124 			break;
    125 		case 'v':
    126 			demon = 0;
    127 			verbose++;
    128 			break;
    129 		case '?':
    130 		default:
    131 			usage();
    132 		}
    133 	}
    134 	argc -= optind;
    135 	argv += optind;
    136 
    137 	if (conf == NULL || dev == NULL)
    138 		usage();
    139 
    140 	hid_init(table);
    141 
    142 	if (dev[0] != '/') {
    143 		snprintf(devnamebuf, sizeof(devnamebuf), "/dev/%s%s",
    144 			 isdigit((unsigned char)dev[0]) ? "uhid" : "", dev);
    145 		dev = devnamebuf;
    146 	}
    147 
    148 	if (demon && conf[0] != '/')
    149 		errx(1, "config file must have an absolute path, %s", conf);
    150 
    151 	fd = open(dev, O_RDWR);
    152 	if (fd < 0)
    153 		err(1, "%s", dev);
    154 
    155 	/* Avoid passing the device file descriptor to executed commands */
    156 	if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1)
    157 		err(1, "fcntl(F_SETFD, FD_CLOEXEC)");
    158 
    159 	if (ioctl(fd, USB_GET_REPORT_ID, &reportid) < 0)
    160 		reportid = -1;
    161 	repd = hid_get_report_desc(fd);
    162 	if (repd == NULL)
    163 		err(1, "hid_get_report_desc() failed");
    164 
    165 	commands = parse_conf(conf, repd, reportid, ignore);
    166 
    167 	sz = hid_report_size(repd, hid_input, reportid);
    168 
    169 	if (verbose)
    170 		printf("report size %d\n", sz);
    171 	if (sz > sizeof buf)
    172 		errx(1, "report too large");
    173 
    174 	(void)signal(SIGHUP, sighup);
    175 
    176 	if (demon) {
    177 		if (daemon(0, 0) < 0)
    178 			err(1, "daemon()");
    179 		pidfile(NULL);
    180 		isdemon = 1;
    181 	}
    182 
    183 	for(;;) {
    184 		n = read(fd, buf, sz);
    185 		if (verbose > 2) {
    186 			printf("read %d bytes:", n);
    187 			for (i = 0; i < n; i++)
    188 				printf(" %02x", buf[i]);
    189 			printf("\n");
    190 		}
    191 		if (n < 0) {
    192 			if (verbose)
    193 				err(1, "read");
    194 			else
    195 				exit(1);
    196 		}
    197 #if 0
    198 		if (n != sz) {
    199 			err(2, "read size");
    200 		}
    201 #endif
    202 		for (cmd = commands; cmd; cmd = cmd->next) {
    203 			val = hid_get_data(buf, &cmd->item);
    204 			if (cmd->value == val || cmd->anyvalue)
    205 				docmd(cmd, val, dev, argc, argv);
    206 		}
    207 		if (reparse) {
    208 			struct command *cmds =
    209 			    parse_conf(conf, repd, reportid, ignore);
    210 			if (cmds) {
    211 				freecommands(commands);
    212 				commands = cmds;
    213 			}
    214 			reparse = 0;
    215 		}
    216 	}
    217 
    218 	exit(0);
    219 }
    220 
    221 void
    222 usage(void)
    223 {
    224 
    225 	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 		ungetc(c, f);
    238 	return c;
    239 }
    240 
    241 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 usage[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, sizeof buf - strlen(buf), f) == NULL)
    267 				break;
    268 			p = strchr(buf, '\n');
    269 		}
    270 		if (p)
    271 			*p = 0;
    272 		/* XXX SIZE == 4000 */
    273 		if (sscanf(buf, "%3999s %3999s %[^\n]", name, value, action) != 3) {
    274 			if (isdemon) {
    275 				syslog(LOG_WARNING, "config file `%s', line %d"
    276 				       ", syntax error: %s", conf, line, buf);
    277 				freecommands(cmds);
    278 				return (NULL);
    279 			} else {
    280 				errx(1, "config file `%s', line %d,"
    281 				     ", syntax error: %s", conf, line, buf);
    282 			}
    283 		}
    284 
    285 		cmd = malloc(sizeof *cmd);
    286 		if (cmd == NULL)
    287 			err(1, "malloc failed");
    288 		cmd->next = cmds;
    289 		cmds = cmd;
    290 		cmd->line = line;
    291 
    292 		if (strcmp(value, "*") == 0) {
    293 			cmd->anyvalue = 1;
    294 		} else {
    295 			cmd->anyvalue = 0;
    296 			if (sscanf(value, "%d", &cmd->value) != 1) {
    297 				if (isdemon) {
    298 					syslog(LOG_WARNING,
    299 					       "config file `%s', line %d, "
    300 					       "bad value: %s\n",
    301 					       conf, line, value);
    302 					freecommands(cmds);
    303 					return (NULL);
    304 				} else {
    305 					errx(1, "config file `%s', line %d, "
    306 					     "bad value: %s\n",
    307 					     conf, line, value);
    308 				}
    309 			}
    310 		}
    311 
    312 		coll[0] = 0;
    313 		for (d = hid_start_parse(repd, 1 << hid_input, reportid);
    314 		     hid_get_item(d, &h); ) {
    315 			if (verbose > 2)
    316 				printf("kind=%d usage=%x flags=%x\n",
    317 				       h.kind, h.usage, h.flags);
    318 			switch (h.kind) {
    319 			case hid_input:
    320 				if (h.flags & HIO_CONST)
    321 					continue;
    322 				if (h.usage_minimum != 0 ||
    323 				    h.usage_maximum != 0) {
    324 					lo = h.usage_minimum;
    325 					hi = h.usage_maximum;
    326 					range = 1;
    327 				} else {
    328 					lo = h.usage;
    329 					hi = h.usage;
    330 					range = 0;
    331 				}
    332 				for (u = lo; u <= hi; u++) {
    333 					snprintf(usage, sizeof usage,  "%s:%s",
    334 						 hid_usage_page(HID_PAGE(u)),
    335 						 hid_usage_in_page(u));
    336 					if (verbose > 2)
    337 						printf("usage %s\n", usage);
    338 					if (!strcasecmp(usage, name))
    339 						goto foundhid;
    340 					if (coll[0]) {
    341 						snprintf(usage, sizeof usage,
    342 						  "%s.%s:%s", coll+1,
    343 						  hid_usage_page(HID_PAGE(u)),
    344 						  hid_usage_in_page(u));
    345 						if (verbose > 2)
    346 							printf("usage %s\n",
    347 							       usage);
    348 						if (!strcasecmp(usage, name))
    349 							goto foundhid;
    350 					}
    351 				}
    352 				break;
    353 			case hid_collection:
    354 				snprintf(coll + strlen(coll),
    355 				    sizeof coll - strlen(coll),  ".%s:%s",
    356 				    hid_usage_page(HID_PAGE(h.usage)),
    357 				    hid_usage_in_page(h.usage));
    358 				if (verbose > 2)
    359 					printf("coll '%s'\n", coll);
    360 				break;
    361 			case hid_endcollection:
    362 				if (coll[0])
    363 					*strrchr(coll, '.') = 0;
    364 				break;
    365 			default:
    366 				break;
    367 			}
    368 		}
    369 		if (ignore) {
    370 			if (verbose)
    371 				warnx("ignore item '%s'", name);
    372 			continue;
    373 		}
    374 		if (isdemon) {
    375 			syslog(LOG_WARNING, "config file `%s', line %d, HID "
    376 			       "item not found: `%s'", conf, line, name);
    377 			freecommands(cmds);
    378 			return (NULL);
    379 		} else {
    380 			errx(1, "config file `%s', line %d, HID item "
    381 			     "not found: `%s'", conf, line, name);
    382 		}
    383 
    384 	foundhid:
    385 		hid_end_parse(d);
    386 		cmd->item = h;
    387 		cmd->name = strdup(name);
    388 		cmd->action = strdup(action);
    389 		if (range) {
    390 			if (cmd->value == 1)
    391 				cmd->value = u - lo;
    392 			else
    393 				cmd->value = -1;
    394 		}
    395 
    396 		if (verbose)
    397 			printf("PARSE:%d %s, %d, '%s'\n", cmd->line, name,
    398 			       cmd->value, cmd->action);
    399 	}
    400 	fclose(f);
    401 	return (cmds);
    402 }
    403 
    404 void
    405 docmd(struct command *cmd, int value, const char *hid, int argc, char **argv)
    406 {
    407 	char cmdbuf[SIZE], *p, *q;
    408 	size_t len;
    409 	int n, r;
    410 
    411 	for (p = cmd->action, q = cmdbuf; *p && q < &cmdbuf[SIZE-1]; ) {
    412 		if (*p == '$') {
    413 			p++;
    414 			len = &cmdbuf[SIZE-1] - q;
    415 			if (isdigit((unsigned char)*p)) {
    416 				n = strtol(p, &p, 10) - 1;
    417 				if (n >= 0 && n < argc) {
    418 					strncpy(q, argv[n], len);
    419 					q += strlen(q);
    420 				}
    421 			} else if (*p == 'V') {
    422 				p++;
    423 				snprintf(q, len, "%d", value);
    424 				q += strlen(q);
    425 			} else if (*p == 'N') {
    426 				p++;
    427 				strncpy(q, cmd->name, len);
    428 				q += strlen(q);
    429 			} else if (*p == 'H') {
    430 				p++;
    431 				strncpy(q, hid, len);
    432 				q += strlen(q);
    433 			} else if (*p) {
    434 				*q++ = *p++;
    435 			}
    436 		} else {
    437 			*q++ = *p++;
    438 		}
    439 	}
    440 	*q = 0;
    441 
    442 	if (verbose)
    443 		printf("system '%s'\n", cmdbuf);
    444 	r = system(cmdbuf);
    445 	if (verbose > 1 && r)
    446 		printf("return code = 0x%x\n", r);
    447 }
    448 
    449 void
    450 freecommands(struct command *cmd)
    451 {
    452 	struct command *next;
    453 
    454 	while (cmd) {
    455 		next = cmd->next;
    456 		free(cmd);
    457 		cmd = next;
    458 	}
    459 }
    460