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