Home | History | Annotate | Line # | Download | only in usbhidctl
usbhid.c revision 1.31
      1 /*	$NetBSD: usbhid.c,v 1.31 2006/10/22 05:09:14 dsainty Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 2001 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by David Sainty <David.Sainty (at) dtsp.co.nz>
      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: usbhid.c,v 1.31 2006/10/22 05:09:14 dsainty Exp $");
     42 #endif
     43 
     44 #include <sys/types.h>
     45 
     46 #include <dev/usb/usb.h>
     47 #include <dev/usb/usbhid.h>
     48 
     49 #include <ctype.h>
     50 #include <err.h>
     51 #include <errno.h>
     52 #include <fcntl.h>
     53 #include <limits.h>
     54 #include <stdio.h>
     55 #include <stdlib.h>
     56 #include <string.h>
     57 #include <unistd.h>
     58 #include <usbhid.h>
     59 
     60 /*
     61  * Zero if not in a verbose mode.  Greater levels of verbosity
     62  * are indicated by values larger than one.
     63  */
     64 unsigned int verbose;
     65 
     66 /* Parser tokens */
     67 #define DELIM_USAGE '.'
     68 #define DELIM_PAGE ':'
     69 #define DELIM_SET '='
     70 #define DELIM_INSTANCE '#'
     71 
     72 static int reportid;
     73 
     74 struct Susbvar {
     75 	/* Variable name, not NUL terminated */
     76 	char const *variable;
     77 	size_t varlen;
     78 
     79 	char const *value; /* Value to set variable to */
     80 
     81 #define MATCH_ALL		(1 << 0)
     82 #define MATCH_COLLECTIONS	(1 << 1)
     83 #define MATCH_NODATA		(1 << 2)
     84 #define MATCH_CONSTANTS		(1 << 3)
     85 #define MATCH_WASMATCHED	(1 << 4)
     86 #define MATCH_SHOWPAGENAME	(1 << 5)
     87 #define MATCH_SHOWNUMERIC	(1 << 6)
     88 #define MATCH_WRITABLE		(1 << 7)
     89 #define MATCH_SHOWVALUES	(1 << 8)
     90 	unsigned int mflags;
     91 
     92 	/*
     93 	 * An instance number can be used to identify an item by
     94 	 * position as well as by name.  This allows us to manipulate
     95 	 * devices that don't assign unique names to all usage items.
     96 	 */
     97 	int usageinstance;
     98 
     99 	/* Workspace for hidmatch() */
    100 	ssize_t matchindex;
    101 	int matchcount;
    102 
    103 	int (*opfunc)(struct hid_item *item, struct Susbvar *var,
    104 		      u_int32_t const *collist, size_t collen, u_char *buf);
    105 };
    106 
    107 struct Sreport {
    108 	struct usb_ctl_report *buffer;
    109 
    110 	enum {srs_uninit, srs_clean, srs_dirty} status;
    111 	int report_id;
    112 	size_t size;
    113 };
    114 
    115 static struct {
    116 	int uhid_report;
    117 	hid_kind_t hid_kind;
    118 	char const *name;
    119 } const reptoparam[] = {
    120 #define REPORT_INPUT 0
    121 	{ UHID_INPUT_REPORT, hid_input, "input" },
    122 #define REPORT_OUTPUT 1
    123 	{ UHID_OUTPUT_REPORT, hid_output, "output" },
    124 #define REPORT_FEATURE 2
    125 	{ UHID_FEATURE_REPORT, hid_feature, "feature" }
    126 #define REPORT_MAXVAL 2
    127 };
    128 
    129 /*
    130  * Extract 16-bit unsigned usage ID from a numeric string.  Returns -1
    131  * if string failed to parse correctly.
    132  */
    133 static int
    134 strtousage(const char *nptr, size_t nlen)
    135 {
    136 	char *endptr;
    137 	long result;
    138 	char numstr[16];
    139 
    140 	if (nlen >= sizeof(numstr) || !isdigit((unsigned char)*nptr))
    141 		return -1;
    142 
    143 	/*
    144 	 * We use strtol() here, but unfortunately strtol() requires a
    145 	 * NUL terminated string - which we don't have - at least not
    146 	 * officially.
    147 	 */
    148 	memcpy(numstr, nptr, nlen);
    149 	numstr[nlen] = '\0';
    150 
    151 	result = strtol(numstr, &endptr, 0);
    152 
    153 	if (result < 0 || result > 0xffff || endptr != &numstr[nlen])
    154 		return -1;
    155 
    156 	return result;
    157 }
    158 
    159 struct usagedata {
    160 	char const *page_name;
    161 	char const *usage_name;
    162 	size_t page_len;
    163 	size_t usage_len;
    164 	int isfinal;
    165 	u_int32_t usage_id;
    166 };
    167 
    168 /*
    169  * Test a rule against the current usage data.  Returns -1 on no
    170  * match, 0 on partial match and 1 on complete match.
    171  */
    172 static int
    173 hidtestrule(struct Susbvar *var, struct usagedata *cache)
    174 {
    175 	char const *varname;
    176 	ssize_t matchindex, pagesplit;
    177 	size_t strind, varlen;
    178 	int numusage;
    179 	u_int32_t usage_id;
    180 
    181 	matchindex = var->matchindex;
    182 	varname = var->variable;
    183 	varlen = var->varlen;
    184 
    185 	usage_id = cache->usage_id;
    186 
    187 	/*
    188 	 * Parse the current variable name, locating the end of the
    189 	 * current 'usage', and possibly where the usage page name
    190 	 * ends.
    191 	 */
    192 	pagesplit = -1;
    193 	for (strind = matchindex; strind < varlen; strind++) {
    194 		if (varname[strind] == DELIM_USAGE)
    195 			break;
    196 		if (varname[strind] == DELIM_PAGE)
    197 			pagesplit = strind;
    198 	}
    199 
    200 	if (cache->isfinal && strind != varlen)
    201 		/*
    202 		 * Variable name is too long (hit delimiter instead of
    203 		 * end-of-variable).
    204 		 */
    205 		return -1;
    206 
    207 	if (pagesplit >= 0) {
    208 		/*
    209 		 * Page name was specified, determine whether it was
    210 		 * symbolic or numeric.
    211 		 */
    212 		char const *strstart;
    213 		int numpage;
    214 
    215 		strstart = &varname[matchindex];
    216 
    217 		numpage = strtousage(strstart, pagesplit - matchindex);
    218 
    219 		if (numpage >= 0) {
    220 			/* Valid numeric */
    221 
    222 			if (numpage != HID_PAGE(usage_id))
    223 				/* Numeric didn't match page ID */
    224 				return -1;
    225 		} else {
    226 			/* Not a valid numeric */
    227 
    228 			/*
    229 			 * Load and cache the page name if and only if
    230 			 * it hasn't already been loaded (it's a
    231 			 * fairly expensive operation).
    232 			 */
    233 			if (cache->page_name == NULL) {
    234 				cache->page_name = hid_usage_page(HID_PAGE(usage_id));
    235 				cache->page_len = strlen(cache->page_name);
    236 			}
    237 
    238 			/*
    239 			 * Compare specified page name to actual page
    240 			 * name.
    241 			 */
    242 			if (cache->page_len !=
    243 			    (size_t)(pagesplit - matchindex) ||
    244 			    memcmp(cache->page_name,
    245 				   &varname[matchindex],
    246 				   cache->page_len) != 0)
    247 				/* Mismatch, page name wrong */
    248 				return -1;
    249 		}
    250 
    251 		/* Page matches, discard page name */
    252 		matchindex = pagesplit + 1;
    253 	}
    254 
    255 	numusage = strtousage(&varname[matchindex], strind - matchindex);
    256 
    257 	if (numusage >= 0) {
    258 		/* Valid numeric */
    259 
    260 		if (numusage != HID_USAGE(usage_id))
    261 			/* Numeric didn't match usage ID */
    262 			return -1;
    263 	} else {
    264 		/* Not a valid numeric */
    265 
    266 		/* Load and cache the usage name */
    267 		if (cache->usage_name == NULL) {
    268 			cache->usage_name = hid_usage_in_page(usage_id);
    269 			cache->usage_len = strlen(cache->usage_name);
    270 		}
    271 
    272 		/*
    273 		 * Compare specified usage name to actual usage name
    274 		 */
    275 		if (cache->usage_len != (size_t)(strind - matchindex) ||
    276 		    memcmp(cache->usage_name, &varname[matchindex],
    277 			   cache->usage_len) != 0)
    278 			/* Mismatch, usage name wrong */
    279 			return -1;
    280 	}
    281 
    282 	if (cache->isfinal)
    283 		/* Match */
    284 		return 1;
    285 
    286 	/*
    287 	 * Partial match: Move index past this usage string +
    288 	 * delimiter
    289 	 */
    290 	var->matchindex = strind + 1;
    291 
    292 	return 0;
    293 }
    294 
    295 /*
    296  * Clear state in HID variable records used by hidmatch().
    297  */
    298 static void
    299 resethidvars(struct Susbvar *varlist, size_t vlsize)
    300 {
    301 	size_t vlind;
    302 	for (vlind = 0; vlind < vlsize; vlind++)
    303 		varlist[vlind].matchcount = 0;
    304 }
    305 
    306 /*
    307  * hidmatch() determines whether the item specified in 'item', and
    308  * nested within a hierarchy of collections specified in 'collist'
    309  * matches any of the rules in the list 'varlist'.  Returns the
    310  * matching rule on success, or NULL on no match.
    311  */
    312 static struct Susbvar*
    313 hidmatch(u_int32_t const *collist, size_t collen, struct hid_item *item,
    314 	 struct Susbvar *varlist, size_t vlsize)
    315 {
    316 	struct Susbvar *result;
    317 	size_t colind, vlactive, vlind;
    318 	int iscollection;
    319 
    320 	/*
    321 	 * Keep track of how many variables are still "active".  When
    322 	 * the active count reaches zero, don't bother to continue
    323 	 * looking for matches.
    324 	 */
    325 	vlactive = vlsize;
    326 
    327 	iscollection = item->kind == hid_collection ||
    328 		item->kind == hid_endcollection;
    329 
    330 	for (vlind = 0; vlind < vlsize; vlind++) {
    331 		struct Susbvar *var;
    332 
    333 		var = &varlist[vlind];
    334 
    335 		var->matchindex = 0;
    336 
    337 		if (!(var->mflags & MATCH_COLLECTIONS) && iscollection) {
    338 			/* Don't match collections for this variable */
    339 			var->matchindex = -1;
    340 			vlactive--;
    341 		} else if (!iscollection && !(var->mflags & MATCH_CONSTANTS) &&
    342 			   (item->flags & HIO_CONST)) {
    343 			/*
    344 			 * Don't match constants for this variable,
    345 			 * but ignore the constant bit on collections.
    346 			 */
    347 			var->matchindex = -1;
    348 			vlactive--;
    349 		} else if ((var->mflags & MATCH_WRITABLE) &&
    350 			   ((item->kind != hid_output &&
    351 			     item->kind != hid_feature) ||
    352 			    (item->flags & HIO_CONST))) {
    353 			/*
    354 			 * If we are only matching writable items, if
    355 			 * this is not an output or feature kind, or
    356 			 * it is a constant, reject it.
    357 			 */
    358 			var->matchindex = -1;
    359 			vlactive--;
    360 		} else if (var->mflags & MATCH_ALL) {
    361 			/* Match immediately */
    362 			return &varlist[vlind];
    363 		}
    364 	}
    365 
    366 	/*
    367 	 * Loop through each usage in the collection list, including
    368 	 * the 'item' itself on the final iteration.  For each usage,
    369 	 * test which variables named in the rule list are still
    370 	 * applicable - if any.
    371 	 */
    372 	result = NULL;
    373 	for (colind = 0; vlactive > 0 && colind <= collen; colind++) {
    374 		struct usagedata cache;
    375 
    376 		cache.page_len = 0;	/* XXX gcc */
    377 		cache.usage_len = 0;	/* XXX gcc */
    378 
    379 		cache.isfinal = (colind == collen);
    380 		if (cache.isfinal)
    381 			cache.usage_id = item->usage;
    382 		else
    383 			cache.usage_id = collist[colind];
    384 
    385 		cache.usage_name = NULL;
    386 		cache.page_name = NULL;
    387 
    388 		/*
    389 		 * Loop through each rule, testing whether the rule is
    390 		 * still applicable or not.  For each rule,
    391 		 * 'matchindex' retains the current match state as an
    392 		 * index into the variable name string, or -1 if this
    393 		 * rule has been proven not to match.
    394 		 */
    395 		for (vlind = 0; vlind < vlsize; vlind++) {
    396 			struct Susbvar *var;
    397 			int matchres;
    398 
    399 			var = &varlist[vlind];
    400 
    401 			if (var->matchindex < 0)
    402 				/* Mismatch at a previous level */
    403 				continue;
    404 
    405 			matchres = hidtestrule(var, &cache);
    406 
    407 			if (matchres == 0)
    408 				/* Partial match */
    409 				continue;
    410 
    411 			if (matchres > 0) {
    412 				/* Complete match */
    413 				if (var->usageinstance < 0 ||
    414 				    var->matchcount == var->usageinstance)
    415 					result = var;
    416 				var->matchcount++;
    417 			}
    418 
    419 			/*
    420 			 * We either matched completely, or not at
    421 			 * all.  Either way, this variable is no
    422 			 * longer active.
    423 			 */
    424 			var->matchindex = -1;
    425 			vlactive--;
    426 		}
    427 	}
    428 
    429 	return result;
    430 }
    431 
    432 static void
    433 allocreport(struct Sreport *report, report_desc_t rd, int repindex)
    434 {
    435 	int reptsize;
    436 
    437 	reptsize = hid_report_size(rd, reptoparam[repindex].hid_kind, reportid);
    438 	if (reptsize < 0)
    439 		errx(1, "Negative report size");
    440 	report->size = reptsize;
    441 
    442 	if (report->size > 0) {
    443 		/*
    444 		 * Allocate a buffer with enough space for the
    445 		 * report in the variable-sized data field.
    446 		 */
    447 		report->buffer = malloc(sizeof(*report->buffer) -
    448 					sizeof(report->buffer->ucr_data) +
    449 					report->size);
    450 		if (report->buffer == NULL)
    451 			err(1, NULL);
    452 	} else
    453 		report->buffer = NULL;
    454 
    455 	report->status = srs_clean;
    456 }
    457 
    458 static void
    459 freereport(struct Sreport *report)
    460 {
    461 	if (report->buffer != NULL)
    462 		free(report->buffer);
    463 	report->status = srs_uninit;
    464 }
    465 
    466 static void
    467 getreport(struct Sreport *report, int hidfd, report_desc_t rd, int repindex)
    468 {
    469 	if (report->status == srs_uninit) {
    470 		allocreport(report, rd, repindex);
    471 		if (report->size == 0)
    472 			return;
    473 
    474 		report->buffer->ucr_report = reptoparam[repindex].uhid_report;
    475 		if (ioctl(hidfd, USB_GET_REPORT, report->buffer) < 0)
    476 			err(1, "USB_GET_REPORT(%s) [probably not supported by "
    477 			    "device]",
    478 			    reptoparam[repindex].name);
    479 	}
    480 }
    481 
    482 static void
    483 setreport(struct Sreport *report, int hidfd, int repindex)
    484 {
    485 	if (report->status == srs_dirty) {
    486 		report->buffer->ucr_report = reptoparam[repindex].uhid_report;
    487 
    488 		if (ioctl(hidfd, USB_SET_REPORT, report->buffer) < 0)
    489 			err(1, "USB_SET_REPORT(%s)",
    490 			    reptoparam[repindex].name);
    491 
    492 		report->status = srs_clean;
    493 	}
    494 }
    495 
    496 /* ARGSUSED1 */
    497 static int
    498 varop_value(struct hid_item *item, struct Susbvar *var,
    499 	    u_int32_t const *collist, size_t collen, u_char *buf)
    500 {
    501 	printf("%d\n", hid_get_data(buf, item));
    502 	return 0;
    503 }
    504 
    505 /* ARGSUSED1 */
    506 static int
    507 varop_display(struct hid_item *item, struct Susbvar *var,
    508 	      u_int32_t const *collist, size_t collen, u_char *buf)
    509 {
    510 	size_t colitem;
    511 	int val, i;
    512 
    513 	for (i = 0; i < item->report_count; i++) {
    514 		for (colitem = 0; colitem < collen; colitem++) {
    515 			if (var->mflags & MATCH_SHOWPAGENAME)
    516 				printf("%s:",
    517 				    hid_usage_page(HID_PAGE(collist[colitem])));
    518 			printf("%s.", hid_usage_in_page(collist[colitem]));
    519 		}
    520 		if (var->mflags & MATCH_SHOWPAGENAME)
    521 			printf("%s:", hid_usage_page(HID_PAGE(item->usage)));
    522 		val = hid_get_data(buf, item);
    523 		item->pos += item->report_size;
    524 		if (item->usage_minimum != 0 || item->usage_maximum != 0) {
    525 			val += item->usage_minimum;
    526 			printf("%s=1", hid_usage_in_page(val));
    527 		} else {
    528 			printf("%s=%d%s", hid_usage_in_page(item->usage),
    529 			       val, item->flags & HIO_CONST ? " (const)" : "");
    530 		}
    531 		if (item->report_count > 1)
    532 			printf(" [%d]", i);
    533 		printf("\n");
    534 	}
    535 	return 0;
    536 }
    537 
    538 /* ARGSUSED1 */
    539 static int
    540 varop_modify(struct hid_item *item, struct Susbvar *var,
    541 	     u_int32_t const *collist, size_t collen, u_char *buf)
    542 {
    543 	u_int dataval;
    544 
    545 	dataval = (u_int)strtol(var->value, NULL, 10);
    546 
    547 	hid_set_data(buf, item, dataval);
    548 
    549 	if (var->mflags & MATCH_SHOWVALUES)
    550 		/* Display set value */
    551 		varop_display(item, var, collist, collen, buf);
    552 
    553 	return 1;
    554 }
    555 
    556 static void
    557 reportitem(char const *label, struct hid_item const *item, unsigned int mflags)
    558 {
    559 	int isconst = item->flags & HIO_CONST,
    560 	    isvar = item->flags & HIO_VARIABLE;
    561 	printf("%s size=%d count=%d%s%s page=%s", label,
    562 	       item->report_size, item->report_count,
    563 	       isconst ? " Const" : "",
    564 	       !isvar && !isconst ? " Array" : "",
    565 	       hid_usage_page(HID_PAGE(item->usage)));
    566 	if (item->usage_minimum != 0 || item->usage_maximum != 0) {
    567 		printf(" usage=%s..%s", hid_usage_in_page(item->usage_minimum),
    568 		       hid_usage_in_page(item->usage_maximum));
    569 		if (mflags & MATCH_SHOWNUMERIC)
    570 			printf(" (%u:0x%x..%u:0x%x)",
    571 			       HID_PAGE(item->usage_minimum),
    572 			       HID_USAGE(item->usage_minimum),
    573 			       HID_PAGE(item->usage_maximum),
    574 			       HID_USAGE(item->usage_maximum));
    575 	} else {
    576 		printf(" usage=%s", hid_usage_in_page(item->usage));
    577 		if (mflags & MATCH_SHOWNUMERIC)
    578 			printf(" (%u:0x%x)",
    579 			       HID_PAGE(item->usage), HID_USAGE(item->usage));
    580 	}
    581 	printf(", logical range %d..%d",
    582 	       item->logical_minimum, item->logical_maximum);
    583 	if (item->physical_minimum != item->physical_maximum)
    584 		printf(", physical range %d..%d",
    585 		       item->physical_minimum, item->physical_maximum);
    586 	if (item->unit)
    587 		printf(", unit=0x%02x exp=%d", item->unit,
    588 		       item->unit_exponent);
    589 	printf("\n");
    590 }
    591 
    592 /* ARGSUSED1 */
    593 static int
    594 varop_report(struct hid_item *item, struct Susbvar *var,
    595 	     u_int32_t const *collist, size_t collen, u_char *buf)
    596 {
    597 	switch (item->kind) {
    598 	case hid_collection:
    599 		printf("Collection page=%s usage=%s",
    600 		       hid_usage_page(HID_PAGE(item->usage)),
    601 		       hid_usage_in_page(item->usage));
    602 		if (var->mflags & MATCH_SHOWNUMERIC)
    603 			printf(" (%u:0x%x)\n",
    604 			       HID_PAGE(item->usage), HID_USAGE(item->usage));
    605 		else
    606 			printf("\n");
    607 		break;
    608 	case hid_endcollection:
    609 		printf("End collection\n");
    610 		break;
    611 	case hid_input:
    612 		reportitem("Input  ", item, var->mflags);
    613 		break;
    614 	case hid_output:
    615 		reportitem("Output ", item, var->mflags);
    616 		break;
    617 	case hid_feature:
    618 		reportitem("Feature", item, var->mflags);
    619 		break;
    620 	}
    621 
    622 	return 0;
    623 }
    624 
    625 static void
    626 devloop(int hidfd, report_desc_t rd, struct Susbvar *varlist, size_t vlsize)
    627 {
    628 	u_char *dbuf;
    629 	struct hid_data *hdata;
    630 	size_t collind, dlen;
    631 	struct hid_item hitem;
    632 	u_int32_t colls[256];
    633 	struct Sreport inreport;
    634 
    635 	allocreport(&inreport, rd, REPORT_INPUT);
    636 
    637 	if (inreport.size <= 0)
    638 		errx(1, "Input report descriptor invalid length");
    639 
    640 	dlen = inreport.size;
    641 	dbuf = inreport.buffer->ucr_data;
    642 
    643 	for (;;) {
    644 		ssize_t readlen;
    645 
    646 		readlen = read(hidfd, dbuf, dlen);
    647 		if (readlen < 0)
    648 			err(1, "Device read error");
    649 		if (dlen != (size_t)readlen)
    650 			errx(1, "Unexpected response length: %lu != %lu",
    651 			     (unsigned long)readlen, (unsigned long)dlen);
    652 
    653 		collind = 0;
    654 		resethidvars(varlist, vlsize);
    655 
    656 		hdata = hid_start_parse(rd, 1 << hid_input, reportid);
    657 		if (hdata == NULL)
    658 			errx(1, "Failed to start parser");
    659 
    660 		while (hid_get_item(hdata, &hitem)) {
    661 			struct Susbvar *matchvar;
    662 
    663 			switch (hitem.kind) {
    664 			case hid_collection:
    665 				if (collind >= (sizeof(colls) / sizeof(*colls)))
    666 					errx(1, "Excessive nested collections");
    667 				colls[collind++] = hitem.usage;
    668 				break;
    669 			case hid_endcollection:
    670 				if (collind == 0)
    671 					errx(1, "Excessive collection ends");
    672 				collind--;
    673 				break;
    674 			case hid_input:
    675 				break;
    676 			case hid_output:
    677 			case hid_feature:
    678 				errx(1, "Unexpected non-input item returned");
    679 			}
    680 
    681 			if (reportid != -1 && hitem.report_ID != reportid)
    682 				continue;
    683 
    684 			matchvar = hidmatch(colls, collind, &hitem,
    685 					    varlist, vlsize);
    686 
    687 			if (matchvar != NULL)
    688 				matchvar->opfunc(&hitem, matchvar,
    689 						 colls, collind,
    690 						 inreport.buffer->ucr_data);
    691 		}
    692 		hid_end_parse(hdata);
    693 		printf("\n");
    694 	}
    695 	/* NOTREACHED */
    696 }
    697 
    698 static void
    699 devshow(int hidfd, report_desc_t rd, struct Susbvar *varlist, size_t vlsize,
    700 	int kindset)
    701 {
    702 	struct hid_data *hdata;
    703 	size_t collind, repind, vlind;
    704 	struct hid_item hitem;
    705 	u_int32_t colls[256];
    706 	struct Sreport reports[REPORT_MAXVAL + 1];
    707 
    708 
    709 	for (repind = 0; repind < (sizeof(reports) / sizeof(*reports));
    710 	     repind++) {
    711 		reports[repind].status = srs_uninit;
    712 		reports[repind].buffer = NULL;
    713 	}
    714 
    715 	collind = 0;
    716 	resethidvars(varlist, vlsize);
    717 
    718 	hdata = hid_start_parse(rd, kindset, reportid);
    719 	if (hdata == NULL)
    720 		errx(1, "Failed to start parser");
    721 
    722 	while (hid_get_item(hdata, &hitem)) {
    723 		struct Susbvar *matchvar;
    724 		int repindex;
    725 
    726 		if (verbose > 3)
    727 			printf("item: kind=%d repid=%d usage=0x%x\n",
    728 			       hitem.kind, hitem.report_ID, hitem.usage);
    729 		repindex = -1;
    730 		switch (hitem.kind) {
    731 		case hid_collection:
    732 			if (collind >= (sizeof(colls) / sizeof(*colls)))
    733 				errx(1, "Excessive nested collections");
    734 			colls[collind++] = hitem.usage;
    735 			break;
    736 		case hid_endcollection:
    737 			if (collind == 0)
    738 				errx(1, "Excessive collection ends");
    739 			collind--;
    740 			break;
    741 		case hid_input:
    742 			repindex = REPORT_INPUT;
    743 			break;
    744 		case hid_output:
    745 			repindex = REPORT_OUTPUT;
    746 			break;
    747 		case hid_feature:
    748 			repindex = REPORT_FEATURE;
    749 			break;
    750 		}
    751 
    752 		if (reportid != -1 && hitem.report_ID != reportid)
    753 			continue;
    754 
    755 		matchvar = hidmatch(colls, collind, &hitem, varlist, vlsize);
    756 
    757 		if (matchvar != NULL) {
    758 			u_char *bufdata;
    759 			struct Sreport *repptr;
    760 
    761 			matchvar->mflags |= MATCH_WASMATCHED;
    762 
    763 			if (repindex >= 0)
    764 				repptr = &reports[repindex];
    765 			else
    766 				repptr = NULL;
    767 
    768 			if (repptr != NULL &&
    769 			    !(matchvar->mflags & MATCH_NODATA))
    770 				getreport(repptr, hidfd, rd, repindex);
    771 
    772 			bufdata = (repptr == NULL || repptr->buffer == NULL) ?
    773 				NULL : repptr->buffer->ucr_data;
    774 
    775 			if (matchvar->opfunc(&hitem, matchvar, colls, collind,
    776 					     bufdata) && repptr)
    777 				repptr->status = srs_dirty;
    778 		}
    779 	}
    780 	hid_end_parse(hdata);
    781 
    782 	for (repind = 0; repind < (sizeof(reports) / sizeof(*reports));
    783 	     repind++) {
    784 		setreport(&reports[repind], hidfd, repind);
    785 		freereport(&reports[repind]);
    786 	}
    787 
    788 	/* Warn about any items that we couldn't find a match for */
    789 	for (vlind = 0; vlind < vlsize; vlind++) {
    790 		struct Susbvar *var;
    791 
    792 		var = &varlist[vlind];
    793 
    794 		if (var->variable != NULL &&
    795 		    !(var->mflags & MATCH_WASMATCHED))
    796 			warnx("Failed to match: %.*s", (int)var->varlen,
    797 			      var->variable);
    798 	}
    799 }
    800 
    801 static void
    802 usage(void)
    803 {
    804 	const char *progname = getprogname();
    805 
    806 	fprintf(stderr, "usage: %s -f device [-t tablefile] [-l] [-v] -a\n",
    807 	    progname);
    808 	fprintf(stderr, "       %s -f device [-t tablefile] [-v] -r\n",
    809 	    progname);
    810 	fprintf(stderr,
    811 	    "       %s -f device [-t tablefile] [-l] [-n] [-v] name ...\n",
    812 	    progname);
    813 	fprintf(stderr,
    814 	    "       %s -f device [-t tablefile] -w name=value ...\n",
    815 	    progname);
    816 	exit(1);
    817 }
    818 
    819 int
    820 main(int argc, char **argv)
    821 {
    822 	char const *dev;
    823 	char const *table;
    824 	size_t varnum;
    825 	int aflag, lflag, nflag, rflag, wflag;
    826 	int ch, hidfd;
    827 	report_desc_t repdesc;
    828 	char devnamebuf[PATH_MAX];
    829 	struct Susbvar variables[128];
    830 
    831 	wflag = aflag = nflag = verbose = rflag = lflag = 0;
    832 	dev = NULL;
    833 	table = NULL;
    834 	while ((ch = getopt(argc, argv, "?af:lnrt:vw")) != -1) {
    835 		switch (ch) {
    836 		case 'a':
    837 			aflag = 1;
    838 			break;
    839 		case 'f':
    840 			dev = optarg;
    841 			break;
    842 		case 'l':
    843 			lflag = 1;
    844 			break;
    845 		case 'n':
    846 			nflag = 1;
    847 			break;
    848 		case 'r':
    849 			rflag = 1;
    850 			break;
    851 		case 't':
    852 			table = optarg;
    853 			break;
    854 		case 'v':
    855 			verbose++;
    856 			break;
    857 		case 'w':
    858 			wflag = 1;
    859 			break;
    860 		case '?':
    861 		default:
    862 			usage();
    863 			/* NOTREACHED */
    864 		}
    865 	}
    866 	argc -= optind;
    867 	argv += optind;
    868 	if (dev == NULL || (lflag && (wflag || rflag))) {
    869 		/*
    870 		 * No device specified, or attempting to loop and set
    871 		 * or dump report at the same time
    872 		 */
    873 		usage();
    874 		/* NOTREACHED */
    875 	}
    876 
    877 	for (varnum = 0; varnum < (size_t)argc; varnum++) {
    878 		char const *name, *valuesep, *varinst;
    879 		struct Susbvar *svar;
    880 		size_t namelen;
    881 
    882 		svar = &variables[varnum];
    883 		name = argv[varnum];
    884 		valuesep = strchr(name, DELIM_SET);
    885 
    886 		svar->variable = name;
    887 		svar->mflags = 0;
    888 		svar->usageinstance = 0;
    889 
    890 		if (valuesep == NULL) {
    891 			/* Read variable */
    892 			if (wflag)
    893 				errx(1, "Must not specify -w to read variables");
    894 			svar->value = NULL;
    895 			namelen = strlen(name);
    896 
    897 			if (nflag) {
    898 				/* Display value of variable only */
    899 				svar->opfunc = varop_value;
    900 			} else {
    901 				/* Display name and value of variable */
    902 				svar->opfunc = varop_display;
    903 
    904 				if (verbose >= 1)
    905 					/* Show page names in verbose modes */
    906 					svar->mflags |= MATCH_SHOWPAGENAME;
    907 			}
    908 		} else {
    909 			/* Write variable */
    910 			if (!wflag)
    911 				errx(2, "Must specify -w to set variables");
    912 			svar->mflags |= MATCH_WRITABLE;
    913 			if (verbose >= 1)
    914 				/*
    915 				 * Allow displaying of set value in
    916 				 * verbose mode.  This isn't
    917 				 * particularly useful though, so
    918 				 * don't bother documenting it.
    919 				 */
    920 				svar->mflags |= MATCH_SHOWVALUES;
    921 			namelen = valuesep - name;
    922 			svar->value = valuesep + 1;
    923 			svar->opfunc = varop_modify;
    924 		}
    925 
    926 		varinst = memchr(name, DELIM_INSTANCE, namelen);
    927 
    928 		if (varinst != NULL && ++varinst != &name[namelen]) {
    929 			char *endptr;
    930 
    931 			svar->usageinstance = strtol(varinst, &endptr, 0);
    932 
    933 			if (&name[namelen] != (char const*)endptr)
    934 				errx(1, "%s%c%s", "Error parsing item "
    935 				     "instance number after '",
    936 				     DELIM_INSTANCE, "'");
    937 
    938 			namelen = varinst - 1 - name;
    939 		}
    940 
    941 		svar->varlen = namelen;
    942 	}
    943 
    944 	if (aflag || rflag) {
    945 		struct Susbvar *svar;
    946 
    947 		svar = &variables[varnum++];
    948 
    949 		svar->variable = NULL;
    950 		svar->mflags = MATCH_ALL;
    951 
    952 		if (rflag) {
    953 			/*
    954 			 * Dump report descriptor.  Do dump collection
    955 			 * items also, and hint that it won't be
    956 			 * necessary to get the item status.
    957 			 */
    958 			svar->opfunc = varop_report;
    959 			svar->mflags |= MATCH_COLLECTIONS | MATCH_NODATA;
    960 
    961 			switch (verbose) {
    962 			default:
    963 				/* Level 2: Show item numerics and constants */
    964 				svar->mflags |= MATCH_SHOWNUMERIC;
    965 				/* FALLTHROUGH */
    966 			case 1:
    967 				/* Level 1: Just show constants */
    968 				svar->mflags |= MATCH_CONSTANTS;
    969 				/* FALLTHROUGH */
    970 			case 0:
    971 				break;
    972 			}
    973 		} else {
    974 			/* Display name and value of variable */
    975 			svar->opfunc = varop_display;
    976 
    977 			switch (verbose) {
    978 			default:
    979 				/* Level 2: Show constants and page names */
    980 				svar->mflags |= MATCH_CONSTANTS;
    981 				/* FALLTHROUGH */
    982 			case 1:
    983 				/* Level 1: Just show page names */
    984 				svar->mflags |= MATCH_SHOWPAGENAME;
    985 				/* FALLTHROUGH */
    986 			case 0:
    987 				break;
    988 			}
    989 		}
    990 	}
    991 
    992 	if (varnum == 0) {
    993 		/* Nothing to do...  Display usage information. */
    994 		usage();
    995 		/* NOTREACHED */
    996 	}
    997 
    998 	hid_init(table);
    999 
   1000 	if (dev[0] != '/') {
   1001 		snprintf(devnamebuf, sizeof(devnamebuf), "/dev/%s%s",
   1002 			 isdigit((unsigned char)dev[0]) ? "uhid" : "", dev);
   1003 		dev = devnamebuf;
   1004 	}
   1005 
   1006 	hidfd = open(dev, O_RDWR);
   1007 	if (hidfd < 0)
   1008 		err(1, "%s", dev);
   1009 
   1010 	if (ioctl(hidfd, USB_GET_REPORT_ID, &reportid) < 0)
   1011 		reportid = -1;
   1012 	if (verbose > 1)
   1013 		printf("report ID=%d\n", reportid);
   1014 	repdesc = hid_get_report_desc(hidfd);
   1015 	if (repdesc == 0)
   1016 		errx(1, "USB_GET_REPORT_DESC");
   1017 
   1018 	if (lflag) {
   1019 		devloop(hidfd, repdesc, variables, varnum);
   1020 		/* NOTREACHED */
   1021 	}
   1022 
   1023 	if (rflag)
   1024 		/* Report mode header */
   1025 		printf("Report descriptor:\n");
   1026 
   1027 	devshow(hidfd, repdesc, variables, varnum,
   1028 		1 << hid_input |
   1029 		1 << hid_output |
   1030 		1 << hid_feature);
   1031 
   1032 	if (rflag) {
   1033 		/* Report mode trailer */
   1034 		size_t repindex;
   1035 		for (repindex = 0;
   1036 		     repindex < (sizeof(reptoparam) / sizeof(*reptoparam));
   1037 		     repindex++) {
   1038 			int size;
   1039 			size = hid_report_size(repdesc,
   1040 					       reptoparam[repindex].hid_kind,
   1041 					       reportid);
   1042 			printf("Total %7s size %d bytes\n",
   1043 			       reptoparam[repindex].name, size);
   1044 		}
   1045 	}
   1046 
   1047 	hid_dispose_report_desc(repdesc);
   1048 	exit(0);
   1049 	/* NOTREACHED */
   1050 }
   1051