]> CyberLeo.Net >> Repos - FreeBSD/releng/10.2.git/blob - usr.sbin/usbdump/usbdump.c
- Copy stable/10@285827 to releng/10.2 in preparation for 10.2-RC1
[FreeBSD/releng/10.2.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 <sys/queue.h>
39 #include <net/if.h>
40 #include <net/bpf.h>
41 #include <dev/usb/usb.h>
42 #include <dev/usb/usb_pf.h>
43 #include <dev/usb/usbdi.h>
44 #include <errno.h>
45 #include <fcntl.h>
46 #include <limits.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <stdint.h>
50 #include <string.h>
51 #include <time.h>
52 #include <unistd.h>
53 #include <sysexits.h>
54 #include <err.h>
55
56 #define BPF_STORE_JUMP(x,_c,_k,_jt,_jf) do {    \
57   (x).code = (_c);                              \
58   (x).k = (_k);                                 \
59   (x).jt = (_jt);                               \
60   (x).jf = (_jf);                               \
61 } while (0)
62
63 #define BPF_STORE_STMT(x,_c,_k) do {            \
64   (x).code = (_c);                              \
65   (x).k = (_k);                                 \
66   (x).jt = 0;                                   \
67   (x).jf = 0;                                   \
68 } while (0)
69
70 struct usb_filt {
71         STAILQ_ENTRY(usb_filt) entry;
72         int unit;
73         int endpoint;
74 };
75
76 struct usbcap {
77         int             fd;             /* fd for /dev/usbpf */
78         uint32_t        bufsize;
79         uint8_t         *buffer;
80
81         /* for -w option */
82         int             wfd;
83         /* for -r option */
84         int             rfd;
85         /* for -b option */
86         int             bfd;
87 };
88
89 struct usbcap_filehdr {
90         uint32_t        magic;
91 #define USBCAP_FILEHDR_MAGIC    0x9a90000e
92         uint8_t         major;
93         uint8_t         minor;
94         uint8_t         reserved[26];
95 } __packed;
96
97 #define HEADER_ALIGN(x,a) (((x) + (a) - 1) & ~((a) - 1))
98
99 struct header_32 {
100         /* capture timestamp */
101         uint32_t ts_sec;
102         uint32_t ts_usec;
103         /* data length and alignment information */
104         uint32_t caplen;
105         uint32_t datalen;
106         uint8_t hdrlen;
107         uint8_t align;
108 } __packed;
109
110 static int doexit = 0;
111 static int pkt_captured = 0;
112 static int verbose = 0;
113 static int uf_minor;
114 static const char *i_arg = "usbus0";
115 static const char *r_arg = NULL;
116 static const char *w_arg = NULL;
117 static const char *b_arg = NULL;
118 static struct usbcap uc;
119 static const char *errstr_table[USB_ERR_MAX] = {
120         [USB_ERR_NORMAL_COMPLETION]     = "0",
121         [USB_ERR_PENDING_REQUESTS]      = "PENDING_REQUESTS",
122         [USB_ERR_NOT_STARTED]           = "NOT_STARTED",
123         [USB_ERR_INVAL]                 = "INVAL",
124         [USB_ERR_NOMEM]                 = "NOMEM",
125         [USB_ERR_CANCELLED]             = "CANCELLED",
126         [USB_ERR_BAD_ADDRESS]           = "BAD_ADDRESS",
127         [USB_ERR_BAD_BUFSIZE]           = "BAD_BUFSIZE",
128         [USB_ERR_BAD_FLAG]              = "BAD_FLAG",
129         [USB_ERR_NO_CALLBACK]           = "NO_CALLBACK",
130         [USB_ERR_IN_USE]                = "IN_USE",
131         [USB_ERR_NO_ADDR]               = "NO_ADDR",
132         [USB_ERR_NO_PIPE]               = "NO_PIPE",
133         [USB_ERR_ZERO_NFRAMES]          = "ZERO_NFRAMES",
134         [USB_ERR_ZERO_MAXP]             = "ZERO_MAXP",
135         [USB_ERR_SET_ADDR_FAILED]       = "SET_ADDR_FAILED",
136         [USB_ERR_NO_POWER]              = "NO_POWER",
137         [USB_ERR_TOO_DEEP]              = "TOO_DEEP",
138         [USB_ERR_IOERROR]               = "IOERROR",
139         [USB_ERR_NOT_CONFIGURED]        = "NOT_CONFIGURED",
140         [USB_ERR_TIMEOUT]               = "TIMEOUT",
141         [USB_ERR_SHORT_XFER]            = "SHORT_XFER",
142         [USB_ERR_STALLED]               = "STALLED",
143         [USB_ERR_INTERRUPTED]           = "INTERRUPTED",
144         [USB_ERR_DMA_LOAD_FAILED]       = "DMA_LOAD_FAILED",
145         [USB_ERR_BAD_CONTEXT]           = "BAD_CONTEXT",
146         [USB_ERR_NO_ROOT_HUB]           = "NO_ROOT_HUB",
147         [USB_ERR_NO_INTR_THREAD]        = "NO_INTR_THREAD",
148         [USB_ERR_NOT_LOCKED]            = "NOT_LOCKED",
149 };
150
151 static const char *xfertype_table[4] = {
152         [UE_CONTROL]                    = "CTRL",
153         [UE_ISOCHRONOUS]                = "ISOC",
154         [UE_BULK]                       = "BULK",
155         [UE_INTERRUPT]                  = "INTR"
156 };
157
158 static const char *speed_table[USB_SPEED_MAX] = {
159         [USB_SPEED_FULL] = "FULL",
160         [USB_SPEED_HIGH] = "HIGH",
161         [USB_SPEED_LOW] = "LOW",
162         [USB_SPEED_VARIABLE] = "VARI",
163         [USB_SPEED_SUPER] = "SUPER",
164 };
165
166 static STAILQ_HEAD(,usb_filt) usb_filt_head =
167     STAILQ_HEAD_INITIALIZER(usb_filt_head);
168
169 static void
170 add_filter(int usb_filt_unit, int usb_filt_ep)
171 {
172         struct usb_filt *puf;
173
174         puf = malloc(sizeof(struct usb_filt));
175         if (puf == NULL)
176                 errx(EX_SOFTWARE, "Out of memory.");
177
178         puf->unit = usb_filt_unit;
179         puf->endpoint = usb_filt_ep;
180
181         STAILQ_INSERT_TAIL(&usb_filt_head, puf, entry);
182 }
183
184 static void
185 make_filter(struct bpf_program *pprog, int snapshot)
186 {
187         struct usb_filt *puf;
188         struct bpf_insn *dynamic_insn;
189         int len;
190
191         len = 0;
192
193         STAILQ_FOREACH(puf, &usb_filt_head, entry)
194                 len++;
195
196         dynamic_insn = malloc(((len * 5) + 1) * sizeof(struct bpf_insn));
197
198         if (dynamic_insn == NULL)
199                 errx(EX_SOFTWARE, "Out of memory.");
200
201         len++;
202
203         if (len == 1) {
204                 /* accept all packets */
205
206                 BPF_STORE_STMT(dynamic_insn[0], BPF_RET | BPF_K, snapshot);
207
208                 goto done;
209         }
210
211         len = 0;
212
213         STAILQ_FOREACH(puf, &usb_filt_head, entry) {
214                 const int addr_off = (uintptr_t)&((struct usbpf_pkthdr *)0)->up_address;
215                 const int addr_ep = (uintptr_t)&((struct usbpf_pkthdr *)0)->up_endpoint;
216                 
217                 if (puf->unit != -1) {
218                         if (puf->endpoint != -1) {
219                                 BPF_STORE_STMT(dynamic_insn[len],
220                                     BPF_LD | BPF_B | BPF_ABS, addr_off);
221                                 len++;
222                                 BPF_STORE_JUMP(dynamic_insn[len],
223                                     BPF_JMP | BPF_JEQ | BPF_K, (uint8_t)puf->unit, 0, 3);
224                                 len++;
225                                 BPF_STORE_STMT(dynamic_insn[len],
226                                     BPF_LD | BPF_W | BPF_ABS, addr_ep);
227                                 len++;
228                                 BPF_STORE_JUMP(dynamic_insn[len],
229                                     BPF_JMP | BPF_JEQ | BPF_K, htobe32(puf->endpoint), 0, 1);
230                                 len++;
231                         } else {
232                                 BPF_STORE_STMT(dynamic_insn[len],
233                                     BPF_LD | BPF_B | BPF_ABS, addr_off);
234                                 len++;
235                                 BPF_STORE_JUMP(dynamic_insn[len],
236                                     BPF_JMP | BPF_JEQ | BPF_K, (uint8_t)puf->unit, 0, 1);
237                                 len++;
238                         }
239                 } else {
240                         if (puf->endpoint != -1) {
241                                 BPF_STORE_STMT(dynamic_insn[len],
242                                     BPF_LD | BPF_W | BPF_ABS, addr_ep);
243                                 len++;
244                                 BPF_STORE_JUMP(dynamic_insn[len],
245                                     BPF_JMP | BPF_JEQ | BPF_K, htobe32(puf->endpoint), 0, 1);
246                                 len++;
247                         }
248                 }
249                 BPF_STORE_STMT(dynamic_insn[len],
250                     BPF_RET | BPF_K, snapshot);
251                 len++;
252         }
253
254         BPF_STORE_STMT(dynamic_insn[len], BPF_RET | BPF_K, 0);
255         len++;
256
257 done:
258         pprog->bf_len = len;
259         pprog->bf_insns = dynamic_insn;
260 }
261
262 static int
263 match_filter(int unit, int endpoint)
264 {
265         struct usb_filt *puf;
266
267         if (STAILQ_FIRST(&usb_filt_head) == NULL)
268                 return (1);
269
270         STAILQ_FOREACH(puf, &usb_filt_head, entry) {
271                 if ((puf->unit == -1 || puf->unit == unit) &&
272                     (puf->endpoint == -1 || puf->endpoint == endpoint))
273                         return (1);
274         }
275         return (0);
276 }
277
278 static void
279 free_filter(struct bpf_program *pprog)
280 {
281         struct usb_filt *puf;
282
283         while ((puf = STAILQ_FIRST(&usb_filt_head)) != NULL) {
284                 STAILQ_REMOVE_HEAD(&usb_filt_head, entry);
285                 free(puf);
286         }
287         free(pprog->bf_insns);
288 }
289
290 static void
291 handle_sigint(int sig)
292 {
293
294         (void)sig;
295         doexit = 1;
296 }
297
298 #define FLAGS(x, name)  \
299         (((x) & USBPF_FLAG_##name) ? #name "|" : "")
300
301 #define STATUS(x, name) \
302         (((x) & USBPF_STATUS_##name) ? #name "|" : "")
303
304 static const char *
305 usb_errstr(uint32_t error)
306 {
307         if (error >= USB_ERR_MAX || errstr_table[error] == NULL)
308                 return ("UNKNOWN");
309         else
310                 return (errstr_table[error]);
311 }
312
313 static const char *
314 usb_speedstr(uint8_t speed)
315 {
316         if (speed >= USB_SPEED_MAX  || speed_table[speed] == NULL)
317                 return ("UNKNOWN");
318         else
319                 return (speed_table[speed]);
320 }
321
322 static void
323 print_flags(uint32_t flags)
324 {
325         printf(" flags %#x <%s%s%s%s%s%s%s%s%s0>\n",
326             flags,
327             FLAGS(flags, FORCE_SHORT_XFER),
328             FLAGS(flags, SHORT_XFER_OK),
329             FLAGS(flags, SHORT_FRAMES_OK),
330             FLAGS(flags, PIPE_BOF),
331             FLAGS(flags, PROXY_BUFFER),
332             FLAGS(flags, EXT_BUFFER),
333             FLAGS(flags, MANUAL_STATUS),
334             FLAGS(flags, NO_PIPE_OK),
335             FLAGS(flags, STALL_PIPE));
336 }
337
338 static void
339 print_status(uint32_t status)
340 {
341         printf(" status %#x <%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s0>\n",
342             status, 
343             STATUS(status, OPEN),
344             STATUS(status, TRANSFERRING),
345             STATUS(status, DID_DMA_DELAY),
346             STATUS(status, DID_CLOSE),
347             STATUS(status, DRAINING),
348             STATUS(status, STARTED),
349             STATUS(status, BW_RECLAIMED),
350             STATUS(status, CONTROL_XFR),
351             STATUS(status, CONTROL_HDR),
352             STATUS(status, CONTROL_ACT),
353             STATUS(status, CONTROL_STALL),
354             STATUS(status, SHORT_FRAMES_OK),
355             STATUS(status, SHORT_XFER_OK),
356             STATUS(status, BDMA_ENABLE),
357             STATUS(status, BDMA_NO_POST_SYNC),
358             STATUS(status, BDMA_SETUP),
359             STATUS(status, ISOCHRONOUS_XFR),
360             STATUS(status, CURR_DMA_SET),
361             STATUS(status, CAN_CANCEL_IMMED),
362             STATUS(status, DOING_CALLBACK));
363 }
364
365 /*
366  * Dump a byte into hex format.
367  */
368 static void
369 hexbyte(char *buf, uint8_t temp)
370 {
371         uint8_t lo;
372         uint8_t hi;
373
374         lo = temp & 0xF;
375         hi = temp >> 4;
376
377         if (hi < 10)
378                 buf[0] = '0' + hi;
379         else
380                 buf[0] = 'A' + hi - 10;
381
382         if (lo < 10)
383                 buf[1] = '0' + lo;
384         else
385                 buf[1] = 'A' + lo - 10;
386 }
387
388 /*
389  * Display a region in traditional hexdump format.
390  */
391 static void
392 hexdump(const uint8_t *region, uint32_t len)
393 {
394         const uint8_t *line;
395         char linebuf[128];
396         int i;
397         int x;
398         int c;
399
400         for (line = region; line < (region + len); line += 16) {
401
402                 i = 0;
403
404                 linebuf[i] = ' ';
405                 hexbyte(linebuf + i + 1, ((line - region) >> 8) & 0xFF);
406                 hexbyte(linebuf + i + 3, (line - region) & 0xFF);
407                 linebuf[i + 5] = ' ';
408                 linebuf[i + 6] = ' ';
409                 i += 7;
410
411                 for (x = 0; x < 16; x++) {
412                   if ((line + x) < (region + len)) {
413                         hexbyte(linebuf + i,
414                             *(const u_int8_t *)(line + x));
415                   } else {
416                           linebuf[i] = '-';
417                           linebuf[i + 1] = '-';
418                         }
419                         linebuf[i + 2] = ' ';
420                         if (x == 7) {
421                           linebuf[i + 3] = ' ';
422                           i += 4;
423                         } else {
424                           i += 3;
425                         }
426                 }
427                 linebuf[i] = ' ';
428                 linebuf[i + 1] = '|';
429                 i += 2;
430                 for (x = 0; x < 16; x++) {
431                         if ((line + x) < (region + len)) {
432                                 c = *(const u_int8_t *)(line + x);
433                                 /* !isprint(c) */
434                                 if ((c < ' ') || (c > '~'))
435                                         c = '.';
436                                 linebuf[i] = c;
437                         } else {
438                                 linebuf[i] = ' ';
439                         }
440                         i++;
441                 }
442                 linebuf[i] = '|';
443                 linebuf[i + 1] = 0;
444                 i += 2;
445                 puts(linebuf);
446         }
447 }
448
449 static void
450 print_apacket(const struct header_32 *hdr, const uint8_t *ptr, int ptr_len)
451 {
452         struct tm *tm;
453         struct usbpf_pkthdr up_temp;
454         struct usbpf_pkthdr *up;
455         struct timeval tv;
456         size_t len;
457         uint32_t x;
458         char buf[64];
459
460         ptr += USBPF_HDR_LEN;
461         ptr_len -= USBPF_HDR_LEN;
462         if (ptr_len < 0)
463                 return;
464
465         /* make sure we don't change the source buffer */
466         memcpy(&up_temp, ptr - USBPF_HDR_LEN, sizeof(up_temp));
467         up = &up_temp;
468
469         /*
470          * A packet from the kernel is based on little endian byte
471          * order.
472          */
473         up->up_totlen = le32toh(up->up_totlen);
474         up->up_busunit = le32toh(up->up_busunit);
475         up->up_flags = le32toh(up->up_flags);
476         up->up_status = le32toh(up->up_status);
477         up->up_error = le32toh(up->up_error);
478         up->up_interval = le32toh(up->up_interval);
479         up->up_frames = le32toh(up->up_frames);
480         up->up_packet_size = le32toh(up->up_packet_size);
481         up->up_packet_count = le32toh(up->up_packet_count);
482         up->up_endpoint = le32toh(up->up_endpoint);
483
484         if (!match_filter(up->up_address, up->up_endpoint))
485                 return;
486
487         tv.tv_sec = hdr->ts_sec;
488         tv.tv_usec = hdr->ts_usec;
489         tm = localtime(&tv.tv_sec);
490
491         len = strftime(buf, sizeof(buf), "%H:%M:%S", tm);
492
493         if (verbose >= 0) {
494                 printf("%.*s.%06ld usbus%d.%d %s-%s-EP=%08x,SPD=%s,NFR=%d,SLEN=%d,IVAL=%d%s%s\n",
495                     (int)len, buf, tv.tv_usec,
496                     (int)up->up_busunit, (int)up->up_address,
497                     (up->up_type == USBPF_XFERTAP_SUBMIT) ? "SUBM" : "DONE",
498                     xfertype_table[up->up_xfertype],
499                     (unsigned int)up->up_endpoint,
500                     usb_speedstr(up->up_speed),
501                     (int)up->up_frames,
502                     (int)(up->up_totlen - USBPF_HDR_LEN -
503                     (USBPF_FRAME_HDR_LEN * up->up_frames)),
504                     (int)up->up_interval,
505                     (up->up_type == USBPF_XFERTAP_DONE) ? ",ERR=" : "",
506                     (up->up_type == USBPF_XFERTAP_DONE) ?
507                     usb_errstr(up->up_error) : "");
508         }
509
510         if (verbose >= 1 || b_arg != NULL) {
511                 for (x = 0; x != up->up_frames; x++) {
512                         const struct usbpf_framehdr *uf;
513                         uint32_t framelen;
514                         uint32_t flags;
515
516                         uf = (const struct usbpf_framehdr *)ptr;
517                         ptr += USBPF_FRAME_HDR_LEN;
518                         ptr_len -= USBPF_FRAME_HDR_LEN;
519                         if (ptr_len < 0)
520                                 return;
521
522                         framelen = le32toh(uf->length);
523                         flags = le32toh(uf->flags);
524
525                         if (verbose >= 1) {
526                                 printf(" frame[%u] %s %d bytes\n",
527                                     (unsigned int)x,
528                                     (flags & USBPF_FRAMEFLAG_READ) ? "READ" : "WRITE",
529                                     (int)framelen);
530                         }
531
532                         if (flags & USBPF_FRAMEFLAG_DATA_FOLLOWS) {
533
534                                 int tot_frame_len;
535
536                                 tot_frame_len = USBPF_FRAME_ALIGN(framelen);
537
538                                 ptr_len -= tot_frame_len;
539
540                                 if (tot_frame_len < 0 ||
541                                     (int)framelen < 0 || (int)ptr_len < 0)
542                                         break;
543
544                                 if (b_arg != NULL) {
545                                         struct usbcap *p = &uc;
546                                         int ret;
547                                         ret = write(p->bfd, ptr, framelen);
548                                         if (ret != (int)framelen)
549                                                 err(EXIT_FAILURE, "Could not write binary data");
550                                 }
551                                 if (verbose >= 1)
552                                         hexdump(ptr, framelen);
553
554                                 ptr += tot_frame_len;
555                         }
556                 }
557         }
558         if (verbose >= 2)
559                 print_flags(up->up_flags);
560         if (verbose >= 3)
561                 print_status(up->up_status);
562 }
563
564 static void
565 fix_packets(uint8_t *data, const int datalen)
566 {
567         struct header_32 temp;
568         uint8_t *ptr;
569         uint8_t *next;
570         uint32_t hdrlen;
571         uint32_t caplen;
572
573         for (ptr = data; ptr < (data + datalen); ptr = next) {
574
575                 const struct bpf_hdr *hdr;
576
577                 hdr = (const struct bpf_hdr *)ptr;
578
579                 temp.ts_sec = htole32(hdr->bh_tstamp.tv_sec);
580                 temp.ts_usec = htole32(hdr->bh_tstamp.tv_usec);
581                 temp.caplen = htole32(hdr->bh_caplen);
582                 temp.datalen = htole32(hdr->bh_datalen);
583                 temp.hdrlen = hdr->bh_hdrlen;
584                 temp.align = BPF_WORDALIGN(1);
585
586                 hdrlen = hdr->bh_hdrlen;
587                 caplen = hdr->bh_caplen;
588
589                 if ((hdrlen >= sizeof(temp)) && (hdrlen <= 255) &&
590                     ((ptr + hdrlen) <= (data + datalen))) {
591                         memcpy(ptr, &temp, sizeof(temp));
592                         memset(ptr + sizeof(temp), 0, hdrlen - sizeof(temp));
593                 } else {
594                         err(EXIT_FAILURE, "Invalid header length %d", hdrlen);
595                 }
596
597                 next = ptr + BPF_WORDALIGN(hdrlen + caplen);
598
599                 if (next <= ptr)
600                         err(EXIT_FAILURE, "Invalid length");
601         }
602 }
603
604 static void
605 print_packets(uint8_t *data, const int datalen)
606 {
607         struct header_32 temp;
608         uint8_t *ptr;
609         uint8_t *next;
610
611         for (ptr = data; ptr < (data + datalen); ptr = next) {
612
613                 const struct header_32 *hdr32;
614
615                 hdr32 = (const struct header_32 *)ptr;
616
617                 temp.ts_sec = le32toh(hdr32->ts_sec);
618                 temp.ts_usec = le32toh(hdr32->ts_usec);
619                 temp.caplen = le32toh(hdr32->caplen);
620                 temp.datalen = le32toh(hdr32->datalen);
621                 temp.hdrlen = hdr32->hdrlen;
622                 temp.align = hdr32->align;
623
624                 next = ptr + HEADER_ALIGN(temp.hdrlen + temp.caplen, temp.align);
625
626                 if (next <= ptr)
627                         err(EXIT_FAILURE, "Invalid length");
628
629                 if (verbose >= 0 || r_arg != NULL || b_arg != NULL) {
630                         print_apacket(&temp, ptr +
631                             temp.hdrlen, temp.caplen);
632                 }
633                 pkt_captured++;
634         }
635 }
636
637 static void
638 write_packets(struct usbcap *p, const uint8_t *data, const int datalen)
639 {
640         int len = htole32(datalen);
641         int ret;
642
643         ret = write(p->wfd, &len, sizeof(int));
644         if (ret != sizeof(int)) {
645                 err(EXIT_FAILURE, "Could not write length "
646                     "field of USB data payload");
647         }
648         ret = write(p->wfd, data, datalen);
649         if (ret != datalen) {
650                 err(EXIT_FAILURE, "Could not write "
651                     "complete USB data payload");
652         }
653 }
654
655 static void
656 read_file(struct usbcap *p)
657 {
658         int datalen;
659         int ret;
660         uint8_t *data;
661
662         while ((ret = read(p->rfd, &datalen, sizeof(int))) == sizeof(int)) {
663                 datalen = le32toh(datalen);
664                 data = malloc(datalen);
665                 if (data == NULL)
666                         errx(EX_SOFTWARE, "Out of memory.");
667                 ret = read(p->rfd, data, datalen);
668                 if (ret != datalen) {
669                         err(EXIT_FAILURE, "Could not read complete "
670                             "USB data payload");
671                 }
672                 if (uf_minor == 2)
673                         fix_packets(data, datalen);
674
675                 print_packets(data, datalen);
676                 free(data);
677         }
678 }
679
680 static void
681 do_loop(struct usbcap *p)
682 {
683         int cc;
684
685         while (doexit == 0) {
686                 cc = read(p->fd, (uint8_t *)p->buffer, p->bufsize);
687                 if (cc < 0) {
688                         switch (errno) {
689                         case EINTR:
690                                 break;
691                         default:
692                                 fprintf(stderr, "read: %s\n", strerror(errno));
693                                 return;
694                         }
695                         continue;
696                 }
697                 if (cc == 0)
698                         continue;
699
700                 fix_packets(p->buffer, cc);
701
702                 if (w_arg != NULL)
703                         write_packets(p, p->buffer, cc);
704                 print_packets(p->buffer, cc);
705         }
706 }
707
708 static void
709 init_rfile(struct usbcap *p)
710 {
711         struct usbcap_filehdr uf;
712         int ret;
713
714         p->rfd = open(r_arg, O_RDONLY);
715         if (p->rfd < 0) {
716                 err(EXIT_FAILURE, "Could not open "
717                     "'%s' for read", r_arg);
718         }
719         ret = read(p->rfd, &uf, sizeof(uf));
720         if (ret != sizeof(uf)) {
721                 err(EXIT_FAILURE, "Could not read USB capture "
722                     "file header");
723         }
724         if (le32toh(uf.magic) != USBCAP_FILEHDR_MAGIC) {
725                 errx(EX_SOFTWARE, "Invalid magic field(0x%08x) "
726                     "in USB capture file header.",
727                     (unsigned int)le32toh(uf.magic));
728         }
729         if (uf.major != 0) {
730                 errx(EX_SOFTWARE, "Invalid major version(%d) "
731                     "field in USB capture file header.", (int)uf.major);
732         }
733
734         uf_minor = uf.minor;
735
736         if (uf.minor != 3 && uf.minor != 2) {
737                 errx(EX_SOFTWARE, "Invalid minor version(%d) "
738                     "field in USB capture file header.", (int)uf.minor);
739         }
740 }
741
742 static void
743 init_wfile(struct usbcap *p)
744 {
745         struct usbcap_filehdr uf;
746         int ret;
747
748         p->wfd = open(w_arg, O_CREAT | O_TRUNC | O_WRONLY, S_IRUSR | S_IWUSR);
749         if (p->wfd < 0) {
750                 err(EXIT_FAILURE, "Could not open "
751                     "'%s' for write", w_arg);
752         }
753         memset(&uf, 0, sizeof(uf));
754         uf.magic = htole32(USBCAP_FILEHDR_MAGIC);
755         uf.major = 0;
756         uf.minor = 3;
757         ret = write(p->wfd, (const void *)&uf, sizeof(uf));
758         if (ret != sizeof(uf)) {
759                 err(EXIT_FAILURE, "Could not write "
760                     "USB capture header");
761         }
762 }
763
764 static void
765 usage(void)
766 {
767
768 #define FMT "    %-14s %s\n"
769         fprintf(stderr, "usage: usbdump [options]\n");
770         fprintf(stderr, FMT, "-i <usbusX>", "Listen on USB bus interface");
771         fprintf(stderr, FMT, "-f <unit[.endpoint]>", "Specify a device and endpoint filter");
772         fprintf(stderr, FMT, "-r <file>", "Read the raw packets from file");
773         fprintf(stderr, FMT, "-s <snaplen>", "Snapshot bytes from each packet");
774         fprintf(stderr, FMT, "-v", "Increase the verbose level");
775         fprintf(stderr, FMT, "-b <file>", "Save raw version of all recorded data to file");
776         fprintf(stderr, FMT, "-w <file>", "Write the raw packets to file");
777         fprintf(stderr, FMT, "-h", "Display summary of command line options");
778 #undef FMT
779         exit(EX_USAGE);
780 }
781
782 int
783 main(int argc, char *argv[])
784 {
785         struct timeval tv;
786         struct bpf_program total_prog;
787         struct bpf_stat us;
788         struct bpf_version bv;
789         struct usbcap *p = &uc;
790         struct ifreq ifr;
791         long snapshot = 192;
792         uint32_t v;
793         int fd;
794         int o;
795         int filt_unit;
796         int filt_ep;
797         int s;
798         int ifindex;
799         const char *optstring;
800         char *pp;
801
802         optstring = "b:hi:r:s:vw:f:";
803         while ((o = getopt(argc, argv, optstring)) != -1) {
804                 switch (o) {
805                 case 'i':
806                         i_arg = optarg;
807                         break;
808                 case 'r':
809                         r_arg = optarg;
810                         init_rfile(p);
811                         break;
812                 case 's':
813                         snapshot = strtol(optarg, &pp, 10);
814                         errno = 0;
815                         if (pp != NULL && *pp != 0)
816                                 usage();
817                         if (snapshot == 0 && errno == EINVAL)
818                                 usage();
819                         /* snapeshot == 0 is special */
820                         if (snapshot == 0)
821                                 snapshot = -1;
822                         break;
823                 case 'b':
824                         b_arg = optarg;
825                         break;
826                 case 'v':
827                         verbose++;
828                         break;
829                 case 'w':
830                         w_arg = optarg;
831                         init_wfile(p);
832                         break;
833                 case 'f':
834                         filt_unit = strtol(optarg, &pp, 10);
835                         filt_ep = -1;
836                         if (pp != NULL) {
837                                 if (*pp == '.') {
838                                         filt_ep = strtol(pp + 1, &pp, 10);
839                                         if (pp != NULL && *pp != 0)
840                                                 usage();
841                                 } else if (*pp != 0) {
842                                         usage();
843                                 }
844                         }
845                         add_filter(filt_unit, filt_ep);
846                         break;
847                 default:
848                         usage();
849                         /* NOTREACHED */
850                 }
851         }
852
853         if (b_arg != NULL) {
854                 p->bfd = open(b_arg, O_CREAT | O_TRUNC |
855                     O_WRONLY, S_IRUSR | S_IWUSR);
856                 if (p->bfd < 0) {
857                         err(EXIT_FAILURE, "Could not open "
858                             "'%s' for write", b_arg);
859                 }
860         }
861
862         /*
863          * Require more verbosity to print anything when -w or -b is
864          * specified on the command line:
865          */
866         if (w_arg != NULL || b_arg != NULL)
867                 verbose--;
868
869         if (r_arg != NULL) {
870                 read_file(p);
871                 exit(EXIT_SUCCESS);
872         }
873
874         p->fd = fd = open("/dev/bpf", O_RDONLY);
875         if (p->fd < 0)
876                 err(EXIT_FAILURE, "Could not open BPF device");
877
878         if (ioctl(fd, BIOCVERSION, (caddr_t)&bv) < 0)
879                 err(EXIT_FAILURE, "BIOCVERSION ioctl failed");
880
881         if (bv.bv_major != BPF_MAJOR_VERSION ||
882             bv.bv_minor < BPF_MINOR_VERSION)
883                 errx(EXIT_FAILURE, "Kernel BPF filter out of date");
884
885         /* USB transfers can be greater than 64KByte */
886         v = 1U << 16;
887
888         /* clear ifr structure */
889         memset(&ifr, 0, sizeof(ifr));
890
891         /* Try to create usbusN interface if it is not available. */
892         s = socket(AF_LOCAL, SOCK_DGRAM, 0);
893         if (s < 0)
894                 errx(EXIT_FAILURE, "Could not open a socket");
895         ifindex = if_nametoindex(i_arg);
896         if (ifindex == 0) {
897                 (void)strlcpy(ifr.ifr_name, i_arg, sizeof(ifr.ifr_name));
898                 if (ioctl(s, SIOCIFCREATE2, &ifr) < 0)
899                         errx(EXIT_FAILURE, "Invalid bus interface: %s", i_arg);
900         }
901
902         for ( ; v >= USBPF_HDR_LEN; v >>= 1) {
903                 (void)ioctl(fd, BIOCSBLEN, (caddr_t)&v);
904                 (void)strlcpy(ifr.ifr_name, i_arg, sizeof(ifr.ifr_name));
905                 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) >= 0)
906                         break;
907         }
908         if (v == 0)
909                 errx(EXIT_FAILURE, "No buffer size worked.");
910
911         if (ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0)
912                 err(EXIT_FAILURE, "BIOCGBLEN ioctl failed");
913
914         p->bufsize = v;
915         p->buffer = (uint8_t *)malloc(p->bufsize);
916         if (p->buffer == NULL)
917                 errx(EX_SOFTWARE, "Out of memory.");
918
919         make_filter(&total_prog, snapshot);
920
921         if (ioctl(p->fd, BIOCSETF, (caddr_t)&total_prog) < 0)
922                 err(EXIT_FAILURE, "BIOCSETF ioctl failed");
923
924         free_filter(&total_prog);
925
926         /* 1 second read timeout */
927         tv.tv_sec = 1;
928         tv.tv_usec = 0;
929         if (ioctl(p->fd, BIOCSRTIMEOUT, (caddr_t)&tv) < 0)
930                 err(EXIT_FAILURE, "BIOCSRTIMEOUT ioctl failed");
931
932         (void)signal(SIGINT, handle_sigint);
933
934         do_loop(p);
935
936         if (ioctl(fd, BIOCGSTATS, (caddr_t)&us) < 0)
937                 err(EXIT_FAILURE, "BIOCGSTATS ioctl failed");
938
939         /* XXX what's difference between pkt_captured and us.us_recv? */
940         printf("\n");
941         printf("%d packets captured\n", pkt_captured);
942         printf("%d packets received by filter\n", us.bs_recv);
943         printf("%d packets dropped by kernel\n", us.bs_drop);
944
945         /*
946          * Destroy the usbusN interface only if it was created by
947          * usbdump(8).  Ignore when it was already destroyed.
948          */
949         if (ifindex == 0 && if_nametoindex(i_arg) > 0) {
950                 (void)strlcpy(ifr.ifr_name, i_arg, sizeof(ifr.ifr_name));
951                 if (ioctl(s, SIOCIFDESTROY, &ifr) < 0)
952                         warn("SIOCIFDESTROY ioctl failed");
953         }
954         close(s);
955
956         if (p->fd > 0)
957                 close(p->fd);
958         if (p->rfd > 0)
959                 close(p->rfd);
960         if (p->wfd > 0)
961                 close(p->wfd);
962         if (p->bfd > 0)
963                 close(p->bfd);
964
965         return (EXIT_SUCCESS);
966 }