2 * Copyright (c) 2010 Weongyo Jeong <weongyo@freebsd.org>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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.
32 #include <sys/param.h>
33 #include <sys/endian.h>
34 #include <sys/ioctl.h>
35 #include <sys/socket.h>
37 #include <sys/utsname.h>
40 #include <dev/usb/usb.h>
41 #include <dev/usb/usb_pf.h>
42 #include <dev/usb/usbdi.h>
55 int fd; /* fd for /dev/usbpf */
65 struct usbcap_filehdr {
67 #define USBCAP_FILEHDR_MAGIC 0x9a90000e
73 #define HEADER_ALIGN(x,a) (((x) + (a) - 1) & ~((a) - 1))
76 /* capture timestamp */
79 /* data length and alignment information */
86 static int doexit = 0;
87 static int pkt_captured = 0;
88 static int verbose = 0;
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",
125 static const char *xfertype_table[4] = {
126 [UE_CONTROL] = "CTRL",
127 [UE_ISOCHRONOUS] = "ISOC",
129 [UE_INTERRUPT] = "INTR"
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",
141 handle_sigint(int sig)
148 #define FLAGS(x, name) \
149 (((x) & USBPF_FLAG_##name) ? #name "|" : "")
151 #define STATUS(x, name) \
152 (((x) & USBPF_STATUS_##name) ? #name "|" : "")
155 usb_errstr(uint32_t error)
157 if (error >= USB_ERR_MAX || errstr_table[error] == NULL)
160 return (errstr_table[error]);
164 usb_speedstr(uint8_t speed)
166 if (speed >= USB_SPEED_MAX || speed_table[speed] == NULL)
169 return (speed_table[speed]);
173 print_flags(uint32_t flags)
175 printf(" flags %#x <%s%s%s%s%s%s%s%s%s0>\n",
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));
189 print_status(uint32_t status)
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",
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));
216 * Dump a byte into hex format.
219 hexbyte(char *buf, uint8_t temp)
230 buf[0] = 'A' + hi - 10;
235 buf[1] = 'A' + lo - 10;
239 * Display a region in traditional hexdump format.
242 hexdump(const uint8_t *region, uint32_t len)
250 for (line = region; line < (region + len); line += 16) {
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] = ' ';
261 for (x = 0; x < 16; x++) {
262 if ((line + x) < (region + len)) {
264 *(const u_int8_t *)(line + x));
267 linebuf[i + 1] = '-';
269 linebuf[i + 2] = ' ';
271 linebuf[i + 3] = ' ';
278 linebuf[i + 1] = '|';
280 for (x = 0; x < 16; x++) {
281 if ((line + x) < (region + len)) {
282 c = *(const u_int8_t *)(line + x);
284 if ((c < ' ') || (c > '~'))
300 print_apacket(const struct header_32 *hdr, const uint8_t *ptr, int ptr_len)
303 struct usbpf_pkthdr up_temp;
304 struct usbpf_pkthdr *up;
310 ptr += USBPF_HDR_LEN;
311 ptr_len -= USBPF_HDR_LEN;
315 /* make sure we don't change the source buffer */
316 memcpy(&up_temp, ptr - USBPF_HDR_LEN, sizeof(up_temp));
320 * A packet from the kernel is based on little endian byte
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);
335 tv.tv_sec = hdr->ts_sec;
336 tv.tv_usec = hdr->ts_usec;
337 tm = localtime(&tv.tv_sec);
339 len = strftime(buf, sizeof(buf), "%H:%M:%S", tm);
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),
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) : "");
357 for (x = 0; x != up->up_frames; x++) {
358 const struct usbpf_framehdr *uf;
362 uf = (const struct usbpf_framehdr *)ptr;
363 ptr += USBPF_FRAME_HDR_LEN;
364 ptr_len -= USBPF_FRAME_HDR_LEN;
368 framelen = le32toh(uf->length);
369 flags = le32toh(uf->flags);
371 printf(" frame[%u] %s %d bytes\n",
373 (flags & USBPF_FRAMEFLAG_READ) ? "READ" : "WRITE",
376 if (flags & USBPF_FRAMEFLAG_DATA_FOLLOWS) {
380 tot_frame_len = USBPF_FRAME_ALIGN(framelen);
382 ptr_len -= tot_frame_len;
384 if (tot_frame_len < 0 ||
385 (int)framelen < 0 || (int)ptr_len < 0)
388 hexdump(ptr, framelen);
390 ptr += tot_frame_len;
395 print_flags(up->up_flags);
397 print_status(up->up_status);
401 fix_packets(uint8_t *data, const int datalen)
403 struct header_32 temp;
409 for (ptr = data; ptr < (data + datalen); ptr = next) {
411 const struct bpf_hdr *hdr;
413 hdr = (const struct bpf_hdr *)ptr;
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);
422 hdrlen = hdr->bh_hdrlen;
423 caplen = hdr->bh_caplen;
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));
430 err(EXIT_FAILURE, "Invalid header length %d", hdrlen);
433 next = ptr + BPF_WORDALIGN(hdrlen + caplen);
436 err(EXIT_FAILURE, "Invalid length");
441 print_packets(uint8_t *data, const int datalen)
443 struct header_32 temp;
447 for (ptr = data; ptr < (data + datalen); ptr = next) {
449 const struct header_32 *hdr32;
451 hdr32 = (const struct header_32 *)ptr;
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;
460 next = ptr + HEADER_ALIGN(temp.hdrlen + temp.caplen, temp.align);
463 err(EXIT_FAILURE, "Invalid length");
465 if (w_arg == NULL || r_arg != NULL) {
466 print_apacket(&temp, ptr +
467 temp.hdrlen, temp.caplen);
474 write_packets(struct usbcap *p, const uint8_t *data, const int datalen)
476 int len = htole32(datalen);
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");
484 ret = write(p->wfd, data, datalen);
485 if (ret != datalen) {
486 err(EXIT_FAILURE, "Could not write "
487 "complete USB data payload");
492 read_file(struct usbcap *p)
498 while ((ret = read(p->rfd, &datalen, sizeof(int))) == sizeof(int)) {
499 datalen = le32toh(datalen);
500 data = malloc(datalen);
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 "
509 fix_packets(data, datalen);
511 print_packets(data, datalen);
517 do_loop(struct usbcap *p)
521 while (doexit == 0) {
522 cc = read(p->fd, (uint8_t *)p->buffer, p->bufsize);
528 fprintf(stderr, "read: %s\n", strerror(errno));
536 fix_packets(p->buffer, cc);
539 write_packets(p, p->buffer, cc);
540 print_packets(p->buffer, cc);
545 init_rfile(struct usbcap *p)
547 struct usbcap_filehdr uf;
550 p->rfd = open(r_arg, O_RDONLY);
552 err(EXIT_FAILURE, "Could not open "
553 "'%s' for read", r_arg);
555 ret = read(p->rfd, &uf, sizeof(uf));
556 if (ret != sizeof(uf)) {
557 err(EXIT_FAILURE, "Could not read USB capture "
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));
566 errx(EX_SOFTWARE, "Invalid major version(%d) "
567 "field in USB capture file header.", (int)uf.major);
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);
579 init_wfile(struct usbcap *p)
581 struct usbcap_filehdr uf;
584 p->wfd = open(w_arg, O_CREAT | O_TRUNC | O_WRONLY, S_IRUSR | S_IWUSR);
586 err(EXIT_FAILURE, "Could not open "
587 "'%s' for write", w_arg);
589 memset(&uf, 0, sizeof(uf));
590 uf.magic = htole32(USBCAP_FILEHDR_MAGIC);
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");
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");
616 main(int argc, char *argv[])
619 struct bpf_insn total_insn;
620 struct bpf_program total_prog;
622 struct bpf_version bv;
623 struct usbcap uc, *p = &uc;
628 const char *optstring;
630 memset(&uc, 0, sizeof(struct usbcap));
632 optstring = "i:r:s:vw:";
633 while ((o = getopt(argc, argv, optstring)) != -1) {
643 snapshot = strtol(optarg, NULL, 10);
645 if (snapshot == 0 && errno == EINVAL)
647 /* snapeshot == 0 is special */
669 p->fd = fd = open("/dev/bpf", O_RDONLY);
671 err(EXIT_FAILURE, "Could not open BPF device");
673 if (ioctl(fd, BIOCVERSION, (caddr_t)&bv) < 0)
674 err(EXIT_FAILURE, "BIOCVERSION ioctl failed");
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");
680 /* USB transfers can be greater than 64KByte */
683 /* clear ifr structure */
684 memset(&ifr, 0, sizeof(ifr));
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)
693 errx(EXIT_FAILURE, "No buffer size worked.");
695 if (ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0)
696 err(EXIT_FAILURE, "BIOCGBLEN ioctl failed");
699 p->buffer = (uint8_t *)malloc(p->bufsize);
700 if (p->buffer == NULL)
701 errx(EX_SOFTWARE, "Out of memory.");
703 /* XXX no read filter rules yet so at this moment accept everything */
704 total_insn.code = (u_short)(BPF_RET | BPF_K);
707 total_insn.k = snapshot;
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");
714 /* 1 second read timeout */
717 if (ioctl(p->fd, BIOCSRTIMEOUT, (caddr_t)&tv) < 0)
718 err(EXIT_FAILURE, "BIOCSRTIMEOUT ioctl failed");
720 (void)signal(SIGINT, handle_sigint);
724 if (ioctl(fd, BIOCGSTATS, (caddr_t)&us) < 0)
725 err(EXIT_FAILURE, "BIOCGSTATS ioctl failed");
727 /* XXX what's difference between pkt_captured and us.us_recv? */
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);
740 return (EXIT_SUCCESS);