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