]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - usr.sbin/usbdump/usbdump.c
MFC r233037 and r233039:
[FreeBSD/stable/8.git] / usr.sbin / usbdump / usbdump.c
1 /*-
2  * Copyright (c) 2010 Weongyo Jeong <weongyo@freebsd.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer,
10  *    without modification.
11  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
12  *    similar to the "NO WARRANTY" disclaimer below ("Disclaimer") and any
13  *    redistribution must be conditioned upon including a substantially
14  *    similar Disclaimer requirement for further binary redistribution.
15  *
16  * NO WARRANTY
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19  * LIMITED TO, THE IMPLIED WARRANTIES OF NONINFRINGEMENT, MERCHANTIBILITY
20  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
21  * THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY,
22  * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
25  * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
27  * THE POSSIBILITY OF SUCH DAMAGES.
28  *
29  * $FreeBSD$
30  */
31
32 #include <sys/param.h>
33 #include <sys/endian.h>
34 #include <sys/ioctl.h>
35 #include <sys/socket.h>
36 #include <sys/stat.h>
37 #include <sys/utsname.h>
38 #include <net/if.h>
39 #include <net/bpf.h>
40 #include <dev/usb/usb.h>
41 #include <dev/usb/usb_pf.h>
42 #include <dev/usb/usbdi.h>
43 #include <errno.h>
44 #include <fcntl.h>
45 #include <limits.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <time.h>
50 #include <unistd.h>
51 #include <sysexits.h>
52 #include <err.h>
53
54 struct usbcap {
55         int             fd;             /* fd for /dev/usbpf */
56         uint32_t        bufsize;
57         uint8_t         *buffer;
58
59         /* for -w option */
60         int             wfd;
61         /* for -r option */
62         int             rfd;
63 };
64
65 struct usbcap_filehdr {
66         uint32_t        magic;
67 #define USBCAP_FILEHDR_MAGIC    0x9a90000e
68         uint8_t         major;
69         uint8_t         minor;
70         uint8_t         reserved[26];
71 } __packed;
72
73 #define HEADER_ALIGN(x,a) (((x) + (a) - 1) & ~((a) - 1))
74
75 struct header_32 {
76         /* capture timestamp */
77         uint32_t ts_sec;
78         uint32_t ts_usec;
79         /* data length and alignment information */
80         uint32_t caplen;
81         uint32_t datalen;
82         uint8_t hdrlen;
83         uint8_t align;
84 } __packed;
85
86 static int doexit = 0;
87 static int pkt_captured = 0;
88 static int verbose = 0;
89 static int uf_minor;
90 static const char *i_arg = "usbus0";
91 static const char *r_arg = NULL;
92 static const char *w_arg = NULL;
93 static const char *errstr_table[USB_ERR_MAX] = {
94         [USB_ERR_NORMAL_COMPLETION]     = "0",
95         [USB_ERR_PENDING_REQUESTS]      = "PENDING_REQUESTS",
96         [USB_ERR_NOT_STARTED]           = "NOT_STARTED",
97         [USB_ERR_INVAL]                 = "INVAL",
98         [USB_ERR_NOMEM]                 = "NOMEM",
99         [USB_ERR_CANCELLED]             = "CANCELLED",
100         [USB_ERR_BAD_ADDRESS]           = "BAD_ADDRESS",
101         [USB_ERR_BAD_BUFSIZE]           = "BAD_BUFSIZE",
102         [USB_ERR_BAD_FLAG]              = "BAD_FLAG",
103         [USB_ERR_NO_CALLBACK]           = "NO_CALLBACK",
104         [USB_ERR_IN_USE]                = "IN_USE",
105         [USB_ERR_NO_ADDR]               = "NO_ADDR",
106         [USB_ERR_NO_PIPE]               = "NO_PIPE",
107         [USB_ERR_ZERO_NFRAMES]          = "ZERO_NFRAMES",
108         [USB_ERR_ZERO_MAXP]             = "ZERO_MAXP",
109         [USB_ERR_SET_ADDR_FAILED]       = "SET_ADDR_FAILED",
110         [USB_ERR_NO_POWER]              = "NO_POWER",
111         [USB_ERR_TOO_DEEP]              = "TOO_DEEP",
112         [USB_ERR_IOERROR]               = "IOERROR",
113         [USB_ERR_NOT_CONFIGURED]        = "NOT_CONFIGURED",
114         [USB_ERR_TIMEOUT]               = "TIMEOUT",
115         [USB_ERR_SHORT_XFER]            = "SHORT_XFER",
116         [USB_ERR_STALLED]               = "STALLED",
117         [USB_ERR_INTERRUPTED]           = "INTERRUPTED",
118         [USB_ERR_DMA_LOAD_FAILED]       = "DMA_LOAD_FAILED",
119         [USB_ERR_BAD_CONTEXT]           = "BAD_CONTEXT",
120         [USB_ERR_NO_ROOT_HUB]           = "NO_ROOT_HUB",
121         [USB_ERR_NO_INTR_THREAD]        = "NO_INTR_THREAD",
122         [USB_ERR_NOT_LOCKED]            = "NOT_LOCKED",
123 };
124
125 static const char *xfertype_table[4] = {
126         [UE_CONTROL]                    = "CTRL",
127         [UE_ISOCHRONOUS]                = "ISOC",
128         [UE_BULK]                       = "BULK",
129         [UE_INTERRUPT]                  = "INTR"
130 };
131
132 static const char *speed_table[USB_SPEED_MAX] = {
133         [USB_SPEED_FULL] = "FULL",
134         [USB_SPEED_HIGH] = "HIGH",
135         [USB_SPEED_LOW] = "LOW",
136         [USB_SPEED_VARIABLE] = "VARI",
137         [USB_SPEED_SUPER] = "SUPER",
138 };
139
140 static void
141 handle_sigint(int sig)
142 {
143
144         (void)sig;
145         doexit = 1;
146 }
147
148 #define FLAGS(x, name)  \
149         (((x) & USBPF_FLAG_##name) ? #name "|" : "")
150
151 #define STATUS(x, name) \
152         (((x) & USBPF_STATUS_##name) ? #name "|" : "")
153
154 static const char *
155 usb_errstr(uint32_t error)
156 {
157         if (error >= USB_ERR_MAX || errstr_table[error] == NULL)
158                 return ("UNKNOWN");
159         else
160                 return (errstr_table[error]);
161 }
162
163 static const char *
164 usb_speedstr(uint8_t speed)
165 {
166         if (speed >= USB_SPEED_MAX  || speed_table[speed] == NULL)
167                 return ("UNKNOWN");
168         else
169                 return (speed_table[speed]);
170 }
171
172 static void
173 print_flags(uint32_t flags)
174 {
175         printf(" flags %#x <%s%s%s%s%s%s%s%s%s0>\n",
176             flags,
177             FLAGS(flags, FORCE_SHORT_XFER),
178             FLAGS(flags, SHORT_XFER_OK),
179             FLAGS(flags, SHORT_FRAMES_OK),
180             FLAGS(flags, PIPE_BOF),
181             FLAGS(flags, PROXY_BUFFER),
182             FLAGS(flags, EXT_BUFFER),
183             FLAGS(flags, MANUAL_STATUS),
184             FLAGS(flags, NO_PIPE_OK),
185             FLAGS(flags, STALL_PIPE));
186 }
187
188 static void
189 print_status(uint32_t status)
190 {
191         printf(" status %#x <%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s0>\n",
192             status, 
193             STATUS(status, OPEN),
194             STATUS(status, TRANSFERRING),
195             STATUS(status, DID_DMA_DELAY),
196             STATUS(status, DID_CLOSE),
197             STATUS(status, DRAINING),
198             STATUS(status, STARTED),
199             STATUS(status, BW_RECLAIMED),
200             STATUS(status, CONTROL_XFR),
201             STATUS(status, CONTROL_HDR),
202             STATUS(status, CONTROL_ACT),
203             STATUS(status, CONTROL_STALL),
204             STATUS(status, SHORT_FRAMES_OK),
205             STATUS(status, SHORT_XFER_OK),
206             STATUS(status, BDMA_ENABLE),
207             STATUS(status, BDMA_NO_POST_SYNC),
208             STATUS(status, BDMA_SETUP),
209             STATUS(status, ISOCHRONOUS_XFR),
210             STATUS(status, CURR_DMA_SET),
211             STATUS(status, CAN_CANCEL_IMMED),
212             STATUS(status, DOING_CALLBACK));
213 }
214
215 /*
216  * Dump a byte into hex format.
217  */
218 static void
219 hexbyte(char *buf, uint8_t temp)
220 {
221         uint8_t lo;
222         uint8_t hi;
223
224         lo = temp & 0xF;
225         hi = temp >> 4;
226
227         if (hi < 10)
228                 buf[0] = '0' + hi;
229         else
230                 buf[0] = 'A' + hi - 10;
231
232         if (lo < 10)
233                 buf[1] = '0' + lo;
234         else
235                 buf[1] = 'A' + lo - 10;
236 }
237
238 /*
239  * Display a region in traditional hexdump format.
240  */
241 static void
242 hexdump(const uint8_t *region, uint32_t len)
243 {
244         const uint8_t *line;
245         char linebuf[128];
246         int i;
247         int x;
248         int c;
249
250         for (line = region; line < (region + len); line += 16) {
251
252                 i = 0;
253
254                 linebuf[i] = ' ';
255                 hexbyte(linebuf + i + 1, ((line - region) >> 8) & 0xFF);
256                 hexbyte(linebuf + i + 3, (line - region) & 0xFF);
257                 linebuf[i + 5] = ' ';
258                 linebuf[i + 6] = ' ';
259                 i += 7;
260
261                 for (x = 0; x < 16; x++) {
262                   if ((line + x) < (region + len)) {
263                         hexbyte(linebuf + i,
264                             *(const u_int8_t *)(line + x));
265                   } else {
266                           linebuf[i] = '-';
267                           linebuf[i + 1] = '-';
268                         }
269                         linebuf[i + 2] = ' ';
270                         if (x == 7) {
271                           linebuf[i + 3] = ' ';
272                           i += 4;
273                         } else {
274                           i += 3;
275                         }
276                 }
277                 linebuf[i] = ' ';
278                 linebuf[i + 1] = '|';
279                 i += 2;
280                 for (x = 0; x < 16; x++) {
281                         if ((line + x) < (region + len)) {
282                                 c = *(const u_int8_t *)(line + x);
283                                 /* !isprint(c) */
284                                 if ((c < ' ') || (c > '~'))
285                                         c = '.';
286                                 linebuf[i] = c;
287                         } else {
288                                 linebuf[i] = ' ';
289                         }
290                         i++;
291                 }
292                 linebuf[i] = '|';
293                 linebuf[i + 1] = 0;
294                 i += 2;
295                 puts(linebuf);
296         }
297 }
298
299 static void
300 print_apacket(const struct header_32 *hdr, const uint8_t *ptr, int ptr_len)
301 {
302         struct tm *tm;
303         struct usbpf_pkthdr up_temp;
304         struct usbpf_pkthdr *up;
305         struct timeval tv;
306         size_t len;
307         uint32_t x;
308         char buf[64];
309
310         ptr += USBPF_HDR_LEN;
311         ptr_len -= USBPF_HDR_LEN;
312         if (ptr_len < 0)
313                 return;
314
315         /* make sure we don't change the source buffer */
316         memcpy(&up_temp, ptr - USBPF_HDR_LEN, sizeof(up_temp));
317         up = &up_temp;
318
319         /*
320          * A packet from the kernel is based on little endian byte
321          * order.
322          */
323         up->up_totlen = le32toh(up->up_totlen);
324         up->up_busunit = le32toh(up->up_busunit);
325         up->up_address = le32toh(up->up_address);
326         up->up_flags = le32toh(up->up_flags);
327         up->up_status = le32toh(up->up_status);
328         up->up_error = le32toh(up->up_error);
329         up->up_interval = le32toh(up->up_interval);
330         up->up_frames = le32toh(up->up_frames);
331         up->up_packet_size = le32toh(up->up_packet_size);
332         up->up_packet_count = le32toh(up->up_packet_count);
333         up->up_endpoint = le32toh(up->up_endpoint);
334
335         tv.tv_sec = hdr->ts_sec;
336         tv.tv_usec = hdr->ts_usec;
337         tm = localtime(&tv.tv_sec);
338
339         len = strftime(buf, sizeof(buf), "%H:%M:%S", tm);
340
341         printf("%.*s.%06ld usbus%d.%d %s-%s-EP=%08x,SPD=%s,NFR=%d,SLEN=%d,IVAL=%d%s%s\n",
342             (int)len, buf, tv.tv_usec,
343             (int)up->up_busunit, (int)up->up_address,
344             (up->up_type == USBPF_XFERTAP_SUBMIT) ? "SUBM" : "DONE",
345             xfertype_table[up->up_xfertype],
346             (unsigned int)up->up_endpoint,
347             usb_speedstr(up->up_speed),
348             (int)up->up_frames,
349             (int)(up->up_totlen - USBPF_HDR_LEN -
350             (USBPF_FRAME_HDR_LEN * up->up_frames)),
351             (int)up->up_interval,
352             (up->up_type == USBPF_XFERTAP_DONE) ? ",ERR=" : "",
353             (up->up_type == USBPF_XFERTAP_DONE) ?
354             usb_errstr(up->up_error) : "");
355
356         if (verbose >= 1) {
357                 for (x = 0; x != up->up_frames; x++) {
358                         const struct usbpf_framehdr *uf;
359                         uint32_t framelen;
360                         uint32_t flags;
361
362                         uf = (const struct usbpf_framehdr *)ptr;
363                         ptr += USBPF_FRAME_HDR_LEN;
364                         ptr_len -= USBPF_FRAME_HDR_LEN;
365                         if (ptr_len < 0)
366                                 return;
367
368                         framelen = le32toh(uf->length);
369                         flags = le32toh(uf->flags);
370
371                         printf(" frame[%u] %s %d bytes\n",
372                             (unsigned int)x,
373                             (flags & USBPF_FRAMEFLAG_READ) ? "READ" : "WRITE",
374                             (int)framelen);
375
376                         if (flags & USBPF_FRAMEFLAG_DATA_FOLLOWS) {
377
378                                 int tot_frame_len;
379
380                                 tot_frame_len = USBPF_FRAME_ALIGN(framelen);
381
382                                 ptr_len -= tot_frame_len;
383
384                                 if (tot_frame_len < 0 ||
385                                     (int)framelen < 0 || (int)ptr_len < 0)
386                                         break;
387
388                                 hexdump(ptr, framelen);
389
390                                 ptr += tot_frame_len;
391                         }
392                 }
393         }
394         if (verbose >= 2)
395                 print_flags(up->up_flags);
396         if (verbose >= 3)
397                 print_status(up->up_status);
398 }
399
400 static void
401 fix_packets(uint8_t *data, const int datalen)
402 {
403         struct header_32 temp;
404         uint8_t *ptr;
405         uint8_t *next;
406         uint32_t hdrlen;
407         uint32_t caplen;
408
409         for (ptr = data; ptr < (data + datalen); ptr = next) {
410
411                 const struct bpf_hdr *hdr;
412
413                 hdr = (const struct bpf_hdr *)ptr;
414
415                 temp.ts_sec = htole32(hdr->bh_tstamp.tv_sec);
416                 temp.ts_usec = htole32(hdr->bh_tstamp.tv_usec);
417                 temp.caplen = htole32(hdr->bh_caplen);
418                 temp.datalen = htole32(hdr->bh_datalen);
419                 temp.hdrlen = hdr->bh_hdrlen;
420                 temp.align = BPF_WORDALIGN(1);
421
422                 hdrlen = hdr->bh_hdrlen;
423                 caplen = hdr->bh_caplen;
424
425                 if ((hdrlen >= sizeof(temp)) && (hdrlen <= 255) &&
426                     ((ptr + hdrlen) <= (data + datalen))) {
427                         memcpy(ptr, &temp, sizeof(temp));
428                         memset(ptr + sizeof(temp), 0, hdrlen - sizeof(temp));
429                 } else {
430                         err(EXIT_FAILURE, "Invalid header length %d", hdrlen);
431                 }
432
433                 next = ptr + BPF_WORDALIGN(hdrlen + caplen);
434
435                 if (next <= ptr)
436                         err(EXIT_FAILURE, "Invalid length");
437         }
438 }
439
440 static void
441 print_packets(uint8_t *data, const int datalen)
442 {
443         struct header_32 temp;
444         uint8_t *ptr;
445         uint8_t *next;
446
447         for (ptr = data; ptr < (data + datalen); ptr = next) {
448
449                 const struct header_32 *hdr32;
450
451                 hdr32 = (const struct header_32 *)ptr;
452
453                 temp.ts_sec = le32toh(hdr32->ts_sec);
454                 temp.ts_usec = le32toh(hdr32->ts_usec);
455                 temp.caplen = le32toh(hdr32->caplen);
456                 temp.datalen = le32toh(hdr32->datalen);
457                 temp.hdrlen = hdr32->hdrlen;
458                 temp.align = hdr32->align;
459
460                 next = ptr + HEADER_ALIGN(temp.hdrlen + temp.caplen, temp.align);
461
462                 if (next <= ptr)
463                         err(EXIT_FAILURE, "Invalid length");
464
465                 if (w_arg == NULL || r_arg != NULL) {
466                         print_apacket(&temp, ptr +
467                             temp.hdrlen, temp.caplen);
468                 }
469                 pkt_captured++;
470         }
471 }
472
473 static void
474 write_packets(struct usbcap *p, const uint8_t *data, const int datalen)
475 {
476         int len = htole32(datalen);
477         int ret;
478
479         ret = write(p->wfd, &len, sizeof(int));
480         if (ret != sizeof(int)) {
481                 err(EXIT_FAILURE, "Could not write length "
482                     "field of USB data payload");
483         }
484         ret = write(p->wfd, data, datalen);
485         if (ret != datalen) {
486                 err(EXIT_FAILURE, "Could not write "
487                     "complete USB data payload");
488         }
489 }
490
491 static void
492 read_file(struct usbcap *p)
493 {
494         int datalen;
495         int ret;
496         uint8_t *data;
497
498         while ((ret = read(p->rfd, &datalen, sizeof(int))) == sizeof(int)) {
499                 datalen = le32toh(datalen);
500                 data = malloc(datalen);
501                 if (data == NULL)
502                         errx(EX_SOFTWARE, "Out of memory.");
503                 ret = read(p->rfd, data, datalen);
504                 if (ret != datalen) {
505                         err(EXIT_FAILURE, "Could not read complete "
506                             "USB data payload");
507                 }
508                 if (uf_minor == 2)
509                         fix_packets(data, datalen);
510
511                 print_packets(data, datalen);
512                 free(data);
513         }
514 }
515
516 static void
517 do_loop(struct usbcap *p)
518 {
519         int cc;
520
521         while (doexit == 0) {
522                 cc = read(p->fd, (uint8_t *)p->buffer, p->bufsize);
523                 if (cc < 0) {
524                         switch (errno) {
525                         case EINTR:
526                                 break;
527                         default:
528                                 fprintf(stderr, "read: %s\n", strerror(errno));
529                                 return;
530                         }
531                         continue;
532                 }
533                 if (cc == 0)
534                         continue;
535
536                 fix_packets(p->buffer, cc);
537
538                 if (w_arg != NULL)
539                         write_packets(p, p->buffer, cc);
540                 print_packets(p->buffer, cc);
541         }
542 }
543
544 static void
545 init_rfile(struct usbcap *p)
546 {
547         struct usbcap_filehdr uf;
548         int ret;
549
550         p->rfd = open(r_arg, O_RDONLY);
551         if (p->rfd < 0) {
552                 err(EXIT_FAILURE, "Could not open "
553                     "'%s' for read", r_arg);
554         }
555         ret = read(p->rfd, &uf, sizeof(uf));
556         if (ret != sizeof(uf)) {
557                 err(EXIT_FAILURE, "Could not read USB capture "
558                     "file header");
559         }
560         if (le32toh(uf.magic) != USBCAP_FILEHDR_MAGIC) {
561                 errx(EX_SOFTWARE, "Invalid magic field(0x%08x) "
562                     "in USB capture file header.",
563                     (unsigned int)le32toh(uf.magic));
564         }
565         if (uf.major != 0) {
566                 errx(EX_SOFTWARE, "Invalid major version(%d) "
567                     "field in USB capture file header.", (int)uf.major);
568         }
569
570         uf_minor = uf.minor;
571
572         if (uf.minor != 3 && uf.minor != 2) {
573                 errx(EX_SOFTWARE, "Invalid minor version(%d) "
574                     "field in USB capture file header.", (int)uf.minor);
575         }
576 }
577
578 static void
579 init_wfile(struct usbcap *p)
580 {
581         struct usbcap_filehdr uf;
582         int ret;
583
584         p->wfd = open(w_arg, O_CREAT | O_TRUNC | O_WRONLY, S_IRUSR | S_IWUSR);
585         if (p->wfd < 0) {
586                 err(EXIT_FAILURE, "Could not open "
587                     "'%s' for write", w_arg);
588         }
589         memset(&uf, 0, sizeof(uf));
590         uf.magic = htole32(USBCAP_FILEHDR_MAGIC);
591         uf.major = 0;
592         uf.minor = 3;
593         ret = write(p->wfd, (const void *)&uf, sizeof(uf));
594         if (ret != sizeof(uf)) {
595                 err(EXIT_FAILURE, "Could not write "
596                     "USB capture header");
597         }
598 }
599
600 static void
601 usage(void)
602 {
603
604 #define FMT "    %-14s %s\n"
605         fprintf(stderr, "usage: usbdump [options]\n");
606         fprintf(stderr, FMT, "-i <usbusX>", "Listen on USB bus interface");
607         fprintf(stderr, FMT, "-r <file>", "Read the raw packets from file");
608         fprintf(stderr, FMT, "-s <snaplen>", "Snapshot bytes from each packet");
609         fprintf(stderr, FMT, "-v", "Increase the verbose level");
610         fprintf(stderr, FMT, "-w <file>", "Write the raw packets to file");
611 #undef FMT
612         exit(EX_USAGE);
613 }
614
615 int
616 main(int argc, char *argv[])
617 {
618         struct timeval tv;
619         struct bpf_insn total_insn;
620         struct bpf_program total_prog;
621         struct bpf_stat us;
622         struct bpf_version bv;
623         struct usbcap uc, *p = &uc;
624         struct ifreq ifr;
625         long snapshot = 192;
626         uint32_t v;
627         int fd, o;
628         const char *optstring;
629
630         memset(&uc, 0, sizeof(struct usbcap));
631
632         optstring = "i:r:s:vw:";
633         while ((o = getopt(argc, argv, optstring)) != -1) {
634                 switch (o) {
635                 case 'i':
636                         i_arg = optarg;
637                         break;
638                 case 'r':
639                         r_arg = optarg;
640                         init_rfile(p);
641                         break;
642                 case 's':
643                         snapshot = strtol(optarg, NULL, 10);
644                         errno = 0;
645                         if (snapshot == 0 && errno == EINVAL)
646                                 usage();
647                         /* snapeshot == 0 is special */
648                         if (snapshot == 0)
649                                 snapshot = -1;
650                         break;
651                 case 'v':
652                         verbose++;
653                         break;
654                 case 'w':
655                         w_arg = optarg;
656                         init_wfile(p);
657                         break;
658                 default:
659                         usage();
660                         /* NOTREACHED */
661                 }
662         }
663
664         if (r_arg != NULL) {
665                 read_file(p);
666                 exit(EXIT_SUCCESS);
667         }
668
669         p->fd = fd = open("/dev/bpf", O_RDONLY);
670         if (p->fd < 0)
671                 err(EXIT_FAILURE, "Could not open BPF device");
672
673         if (ioctl(fd, BIOCVERSION, (caddr_t)&bv) < 0)
674                 err(EXIT_FAILURE, "BIOCVERSION ioctl failed");
675
676         if (bv.bv_major != BPF_MAJOR_VERSION ||
677             bv.bv_minor < BPF_MINOR_VERSION)
678                 errx(EXIT_FAILURE, "Kernel BPF filter out of date");
679
680         /* USB transfers can be greater than 64KByte */
681         v = 1U << 16;
682
683         /* clear ifr structure */
684         memset(&ifr, 0, sizeof(ifr));
685
686         for ( ; v >= USBPF_HDR_LEN; v >>= 1) {
687                 (void)ioctl(fd, BIOCSBLEN, (caddr_t)&v);
688                 (void)strncpy(ifr.ifr_name, i_arg, sizeof(ifr.ifr_name));
689                 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) >= 0)
690                         break;
691         }
692         if (v == 0)
693                 errx(EXIT_FAILURE, "No buffer size worked.");
694
695         if (ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0)
696                 err(EXIT_FAILURE, "BIOCGBLEN ioctl failed");
697
698         p->bufsize = v;
699         p->buffer = (uint8_t *)malloc(p->bufsize);
700         if (p->buffer == NULL)
701                 errx(EX_SOFTWARE, "Out of memory.");
702
703         /* XXX no read filter rules yet so at this moment accept everything */
704         total_insn.code = (u_short)(BPF_RET | BPF_K);
705         total_insn.jt = 0;
706         total_insn.jf = 0;
707         total_insn.k = snapshot;
708
709         total_prog.bf_len = 1;
710         total_prog.bf_insns = &total_insn;
711         if (ioctl(p->fd, BIOCSETF, (caddr_t)&total_prog) < 0)
712                 err(EXIT_FAILURE, "BIOCSETF ioctl failed");
713
714         /* 1 second read timeout */
715         tv.tv_sec = 1;
716         tv.tv_usec = 0;
717         if (ioctl(p->fd, BIOCSRTIMEOUT, (caddr_t)&tv) < 0)
718                 err(EXIT_FAILURE, "BIOCSRTIMEOUT ioctl failed");
719
720         (void)signal(SIGINT, handle_sigint);
721
722         do_loop(p);
723
724         if (ioctl(fd, BIOCGSTATS, (caddr_t)&us) < 0)
725                 err(EXIT_FAILURE, "BIOCGSTATS ioctl failed");
726
727         /* XXX what's difference between pkt_captured and us.us_recv? */
728         printf("\n");
729         printf("%d packets captured\n", pkt_captured);
730         printf("%d packets received by filter\n", us.bs_recv);
731         printf("%d packets dropped by kernel\n", us.bs_drop);
732
733         if (p->fd > 0)
734                 close(p->fd);
735         if (p->rfd > 0)
736                 close(p->rfd);
737         if (p->wfd > 0)
738                 close(p->wfd);
739
740         return (EXIT_SUCCESS);
741 }