usbdump.c revision 233039
1215651Sweongyo/*-
2215651Sweongyo * Copyright (c) 2010 Weongyo Jeong <weongyo@freebsd.org>
3215651Sweongyo * All rights reserved.
4215651Sweongyo *
5215651Sweongyo * Redistribution and use in source and binary forms, with or without
6215651Sweongyo * modification, are permitted provided that the following conditions
7215651Sweongyo * are met:
8215651Sweongyo * 1. Redistributions of source code must retain the above copyright
9215651Sweongyo *    notice, this list of conditions and the following disclaimer,
10215651Sweongyo *    without modification.
11215651Sweongyo * 2. Redistributions in binary form must reproduce at minimum a disclaimer
12215651Sweongyo *    similar to the "NO WARRANTY" disclaimer below ("Disclaimer") and any
13215651Sweongyo *    redistribution must be conditioned upon including a substantially
14215651Sweongyo *    similar Disclaimer requirement for further binary redistribution.
15215651Sweongyo *
16215651Sweongyo * NO WARRANTY
17215651Sweongyo * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18215651Sweongyo * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19215651Sweongyo * LIMITED TO, THE IMPLIED WARRANTIES OF NONINFRINGEMENT, MERCHANTIBILITY
20215651Sweongyo * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
21215651Sweongyo * THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY,
22215651Sweongyo * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23215651Sweongyo * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24215651Sweongyo * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
25215651Sweongyo * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26215651Sweongyo * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
27215651Sweongyo * THE POSSIBILITY OF SUCH DAMAGES.
28215651Sweongyo *
29215651Sweongyo * $FreeBSD: head/usr.sbin/usbdump/usbdump.c 233039 2012-03-16 17:30:22Z hselasky $
30215651Sweongyo */
31215651Sweongyo
32215651Sweongyo#include <sys/param.h>
33215651Sweongyo#include <sys/endian.h>
34215651Sweongyo#include <sys/ioctl.h>
35215803Sweongyo#include <sys/socket.h>
36215651Sweongyo#include <sys/stat.h>
37215651Sweongyo#include <sys/utsname.h>
38231835Shselasky#include <sys/queue.h>
39215803Sweongyo#include <net/if.h>
40215803Sweongyo#include <net/bpf.h>
41215651Sweongyo#include <dev/usb/usb.h>
42215651Sweongyo#include <dev/usb/usb_pf.h>
43215651Sweongyo#include <dev/usb/usbdi.h>
44215651Sweongyo#include <errno.h>
45215651Sweongyo#include <fcntl.h>
46215651Sweongyo#include <limits.h>
47215651Sweongyo#include <stdio.h>
48215651Sweongyo#include <stdlib.h>
49231835Shselasky#include <stdint.h>
50215651Sweongyo#include <string.h>
51215651Sweongyo#include <time.h>
52215651Sweongyo#include <unistd.h>
53221604Shselasky#include <sysexits.h>
54221604Shselasky#include <err.h>
55215651Sweongyo
56231835Shselasky#define	BPF_STORE_JUMP(x,_c,_k,_jt,_jf) do {	\
57231835Shselasky  (x).code = (_c);				\
58231835Shselasky  (x).k = (_k);					\
59231835Shselasky  (x).jt = (_jt);				\
60231835Shselasky  (x).jf = (_jf);				\
61231835Shselasky} while (0)
62231835Shselasky
63231835Shselasky#define	BPF_STORE_STMT(x,_c,_k) do {		\
64231835Shselasky  (x).code = (_c);				\
65231835Shselasky  (x).k = (_k);					\
66231835Shselasky  (x).jt = 0;					\
67231835Shselasky  (x).jf = 0;					\
68231835Shselasky} while (0)
69231835Shselasky
70231835Shselaskystruct usb_filt {
71231835Shselasky	STAILQ_ENTRY(usb_filt) entry;
72231835Shselasky	int unit;
73231835Shselasky	int endpoint;
74231835Shselasky};
75231835Shselasky
76215651Sweongyostruct usbcap {
77215651Sweongyo	int		fd;		/* fd for /dev/usbpf */
78220301Shselasky	uint32_t	bufsize;
79220301Shselasky	uint8_t		*buffer;
80215651Sweongyo
81215651Sweongyo	/* for -w option */
82215651Sweongyo	int		wfd;
83215651Sweongyo	/* for -r option */
84215651Sweongyo	int		rfd;
85215651Sweongyo};
86215651Sweongyo
87215651Sweongyostruct usbcap_filehdr {
88220301Shselasky	uint32_t	magic;
89215651Sweongyo#define	USBCAP_FILEHDR_MAGIC	0x9a90000e
90220301Shselasky	uint8_t   	major;
91220301Shselasky	uint8_t		minor;
92220301Shselasky	uint8_t		reserved[26];
93215651Sweongyo} __packed;
94215651Sweongyo
95233037Shselasky#define	HEADER_ALIGN(x,a) (((x) + (a) - 1) & ~((a) - 1))
96233037Shselasky
97233037Shselaskystruct header_32 {
98233039Shselasky	/* capture timestamp */
99233037Shselasky	uint32_t ts_sec;
100233037Shselasky	uint32_t ts_usec;
101233039Shselasky	/* data length and alignment information */
102233037Shselasky	uint32_t caplen;
103233037Shselasky	uint32_t datalen;
104233039Shselasky	uint8_t hdrlen;
105233039Shselasky	uint8_t align;
106233037Shselasky} __packed;
107233037Shselasky
108215651Sweongyostatic int doexit = 0;
109215651Sweongyostatic int pkt_captured = 0;
110215651Sweongyostatic int verbose = 0;
111233039Shselaskystatic int uf_minor;
112218010Shselaskystatic const char *i_arg = "usbus0";
113215651Sweongyostatic const char *r_arg = NULL;
114215651Sweongyostatic const char *w_arg = NULL;
115215651Sweongyostatic const char *errstr_table[USB_ERR_MAX] = {
116220301Shselasky	[USB_ERR_NORMAL_COMPLETION]	= "0",
117215651Sweongyo	[USB_ERR_PENDING_REQUESTS]	= "PENDING_REQUESTS",
118215651Sweongyo	[USB_ERR_NOT_STARTED]		= "NOT_STARTED",
119215651Sweongyo	[USB_ERR_INVAL]			= "INVAL",
120215651Sweongyo	[USB_ERR_NOMEM]			= "NOMEM",
121215651Sweongyo	[USB_ERR_CANCELLED]		= "CANCELLED",
122215651Sweongyo	[USB_ERR_BAD_ADDRESS]		= "BAD_ADDRESS",
123215651Sweongyo	[USB_ERR_BAD_BUFSIZE]		= "BAD_BUFSIZE",
124215651Sweongyo	[USB_ERR_BAD_FLAG]		= "BAD_FLAG",
125215651Sweongyo	[USB_ERR_NO_CALLBACK]		= "NO_CALLBACK",
126215651Sweongyo	[USB_ERR_IN_USE]		= "IN_USE",
127215651Sweongyo	[USB_ERR_NO_ADDR]		= "NO_ADDR",
128215651Sweongyo	[USB_ERR_NO_PIPE]		= "NO_PIPE",
129215651Sweongyo	[USB_ERR_ZERO_NFRAMES]		= "ZERO_NFRAMES",
130215651Sweongyo	[USB_ERR_ZERO_MAXP]		= "ZERO_MAXP",
131215651Sweongyo	[USB_ERR_SET_ADDR_FAILED]	= "SET_ADDR_FAILED",
132215651Sweongyo	[USB_ERR_NO_POWER]		= "NO_POWER",
133215651Sweongyo	[USB_ERR_TOO_DEEP]		= "TOO_DEEP",
134215651Sweongyo	[USB_ERR_IOERROR]		= "IOERROR",
135215651Sweongyo	[USB_ERR_NOT_CONFIGURED]	= "NOT_CONFIGURED",
136215651Sweongyo	[USB_ERR_TIMEOUT]		= "TIMEOUT",
137215651Sweongyo	[USB_ERR_SHORT_XFER]		= "SHORT_XFER",
138215651Sweongyo	[USB_ERR_STALLED]		= "STALLED",
139215651Sweongyo	[USB_ERR_INTERRUPTED]		= "INTERRUPTED",
140215651Sweongyo	[USB_ERR_DMA_LOAD_FAILED]	= "DMA_LOAD_FAILED",
141215651Sweongyo	[USB_ERR_BAD_CONTEXT]		= "BAD_CONTEXT",
142215651Sweongyo	[USB_ERR_NO_ROOT_HUB]		= "NO_ROOT_HUB",
143215651Sweongyo	[USB_ERR_NO_INTR_THREAD]	= "NO_INTR_THREAD",
144215651Sweongyo	[USB_ERR_NOT_LOCKED]		= "NOT_LOCKED",
145215651Sweongyo};
146215651Sweongyo
147220301Shselaskystatic const char *xfertype_table[4] = {
148215651Sweongyo	[UE_CONTROL]			= "CTRL",
149215651Sweongyo	[UE_ISOCHRONOUS]		= "ISOC",
150215651Sweongyo	[UE_BULK]			= "BULK",
151215651Sweongyo	[UE_INTERRUPT]			= "INTR"
152215651Sweongyo};
153215651Sweongyo
154220301Shselaskystatic const char *speed_table[USB_SPEED_MAX] = {
155220301Shselasky	[USB_SPEED_FULL] = "FULL",
156220301Shselasky	[USB_SPEED_HIGH] = "HIGH",
157220301Shselasky	[USB_SPEED_LOW] = "LOW",
158220301Shselasky	[USB_SPEED_VARIABLE] = "VARI",
159220301Shselasky	[USB_SPEED_SUPER] = "SUPER",
160220301Shselasky};
161220301Shselasky
162231835Shselaskystatic STAILQ_HEAD(,usb_filt) usb_filt_head =
163231835Shselasky    STAILQ_HEAD_INITIALIZER(usb_filt_head);
164231835Shselasky
165215651Sweongyostatic void
166231835Shselaskyadd_filter(int usb_filt_unit, int usb_filt_ep)
167231835Shselasky{
168231835Shselasky	struct usb_filt *puf;
169231835Shselasky
170231835Shselasky	puf = malloc(sizeof(struct usb_filt));
171231835Shselasky	if (puf == NULL)
172231835Shselasky		errx(EX_SOFTWARE, "Out of memory.");
173231835Shselasky
174231835Shselasky	puf->unit = usb_filt_unit;
175231835Shselasky	puf->endpoint = usb_filt_ep;
176231835Shselasky
177231835Shselasky	STAILQ_INSERT_TAIL(&usb_filt_head, puf, entry);
178231835Shselasky}
179231835Shselasky
180231835Shselaskystatic void
181231835Shselaskymake_filter(struct bpf_program *pprog, int snapshot)
182231835Shselasky{
183231835Shselasky	struct usb_filt *puf;
184231835Shselasky	struct bpf_insn *dynamic_insn;
185231835Shselasky	int len;
186231835Shselasky
187231835Shselasky	len = 0;
188231835Shselasky
189231835Shselasky	STAILQ_FOREACH(puf, &usb_filt_head, entry)
190231835Shselasky		len++;
191231835Shselasky
192231835Shselasky	dynamic_insn = malloc(((len * 5) + 1) * sizeof(struct bpf_insn));
193231835Shselasky
194231835Shselasky	if (dynamic_insn == NULL)
195231835Shselasky		errx(EX_SOFTWARE, "Out of memory.");
196231835Shselasky
197231835Shselasky	len++;
198231835Shselasky
199231835Shselasky	if (len == 1) {
200231835Shselasky		/* accept all packets */
201231835Shselasky
202231835Shselasky		BPF_STORE_STMT(dynamic_insn[0], BPF_RET | BPF_K, snapshot);
203231835Shselasky
204231835Shselasky		goto done;
205231835Shselasky	}
206231835Shselasky
207231835Shselasky	len = 0;
208231835Shselasky
209231835Shselasky	STAILQ_FOREACH(puf, &usb_filt_head, entry) {
210231835Shselasky		const int addr_off = (uintptr_t)&((struct usbpf_pkthdr *)0)->up_address;
211231835Shselasky		const int addr_ep = (uintptr_t)&((struct usbpf_pkthdr *)0)->up_endpoint;
212231835Shselasky
213231835Shselasky		if (puf->unit != -1) {
214231835Shselasky			if (puf->endpoint != -1) {
215231835Shselasky				BPF_STORE_STMT(dynamic_insn[len],
216231835Shselasky				    BPF_LD | BPF_B | BPF_ABS, addr_off);
217231835Shselasky				len++;
218231835Shselasky				BPF_STORE_JUMP(dynamic_insn[len],
219231835Shselasky				    BPF_JMP | BPF_JEQ | BPF_K, (uint8_t)puf->unit, 0, 3);
220231835Shselasky				len++;
221231835Shselasky				BPF_STORE_STMT(dynamic_insn[len],
222231835Shselasky				    BPF_LD | BPF_W | BPF_ABS, addr_ep);
223231835Shselasky				len++;
224231835Shselasky				BPF_STORE_JUMP(dynamic_insn[len],
225231835Shselasky				    BPF_JMP | BPF_JEQ | BPF_K, htobe32(puf->endpoint), 0, 1);
226231835Shselasky				len++;
227231835Shselasky			} else {
228231835Shselasky				BPF_STORE_STMT(dynamic_insn[len],
229231835Shselasky				    BPF_LD | BPF_B | BPF_ABS, addr_off);
230231835Shselasky				len++;
231231835Shselasky				BPF_STORE_JUMP(dynamic_insn[len],
232231835Shselasky				    BPF_JMP | BPF_JEQ | BPF_K, (uint8_t)puf->unit, 0, 1);
233231835Shselasky				len++;
234231835Shselasky			}
235231835Shselasky		} else {
236231835Shselasky			if (puf->endpoint != -1) {
237231835Shselasky				BPF_STORE_STMT(dynamic_insn[len],
238231835Shselasky				    BPF_LD | BPF_W | BPF_ABS, addr_ep);
239231835Shselasky				len++;
240231835Shselasky				BPF_STORE_JUMP(dynamic_insn[len],
241231835Shselasky				    BPF_JMP | BPF_JEQ | BPF_K, htobe32(puf->endpoint), 0, 1);
242231835Shselasky				len++;
243231835Shselasky			}
244231835Shselasky		}
245231835Shselasky		BPF_STORE_STMT(dynamic_insn[len],
246231835Shselasky		    BPF_RET | BPF_K, snapshot);
247231835Shselasky		len++;
248231835Shselasky	}
249231835Shselasky
250231835Shselasky	BPF_STORE_STMT(dynamic_insn[len], BPF_RET | BPF_K, 0);
251231835Shselasky	len++;
252231835Shselasky
253231835Shselaskydone:
254231835Shselasky	pprog->bf_len = len;
255231835Shselasky	pprog->bf_insns = dynamic_insn;
256231835Shselasky}
257231835Shselasky
258231835Shselaskystatic void
259231835Shselaskyfree_filter(struct bpf_program *pprog)
260231835Shselasky{
261231835Shselasky	struct usb_filt *puf;
262231835Shselasky
263231835Shselasky	while ((puf = STAILQ_FIRST(&usb_filt_head)) != NULL) {
264231835Shselasky		STAILQ_REMOVE_HEAD(&usb_filt_head, entry);
265231835Shselasky		free(puf);
266231835Shselasky	}
267231835Shselasky	free(pprog->bf_insns);
268231835Shselasky}
269231835Shselasky
270231835Shselaskystatic void
271215651Sweongyohandle_sigint(int sig)
272215651Sweongyo{
273215651Sweongyo
274215651Sweongyo	(void)sig;
275215651Sweongyo	doexit = 1;
276215651Sweongyo}
277215651Sweongyo
278220301Shselasky#define	FLAGS(x, name)	\
279220301Shselasky	(((x) & USBPF_FLAG_##name) ? #name "|" : "")
280220301Shselasky
281220301Shselasky#define	STATUS(x, name) \
282220301Shselasky	(((x) & USBPF_STATUS_##name) ? #name "|" : "")
283220301Shselasky
284220301Shselaskystatic const char *
285220301Shselaskyusb_errstr(uint32_t error)
286220301Shselasky{
287220301Shselasky	if (error >= USB_ERR_MAX || errstr_table[error] == NULL)
288220301Shselasky		return ("UNKNOWN");
289220301Shselasky	else
290220301Shselasky		return (errstr_table[error]);
291220301Shselasky}
292220301Shselasky
293220301Shselaskystatic const char *
294220301Shselaskyusb_speedstr(uint8_t speed)
295220301Shselasky{
296220301Shselasky	if (speed >= USB_SPEED_MAX  || speed_table[speed] == NULL)
297220301Shselasky		return ("UNKNOWN");
298220301Shselasky	else
299220301Shselasky		return (speed_table[speed]);
300220301Shselasky}
301220301Shselasky
302215651Sweongyostatic void
303220301Shselaskyprint_flags(uint32_t flags)
304215651Sweongyo{
305220301Shselasky	printf(" flags %#x <%s%s%s%s%s%s%s%s%s0>\n",
306220301Shselasky	    flags,
307220301Shselasky	    FLAGS(flags, FORCE_SHORT_XFER),
308220301Shselasky	    FLAGS(flags, SHORT_XFER_OK),
309220301Shselasky	    FLAGS(flags, SHORT_FRAMES_OK),
310220301Shselasky	    FLAGS(flags, PIPE_BOF),
311220301Shselasky	    FLAGS(flags, PROXY_BUFFER),
312220301Shselasky	    FLAGS(flags, EXT_BUFFER),
313220301Shselasky	    FLAGS(flags, MANUAL_STATUS),
314220301Shselasky	    FLAGS(flags, NO_PIPE_OK),
315220301Shselasky	    FLAGS(flags, STALL_PIPE));
316215651Sweongyo}
317215651Sweongyo
318215651Sweongyostatic void
319220301Shselaskyprint_status(uint32_t status)
320215651Sweongyo{
321220301Shselasky	printf(" status %#x <%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s0>\n",
322220301Shselasky	    status,
323220301Shselasky	    STATUS(status, OPEN),
324220301Shselasky	    STATUS(status, TRANSFERRING),
325220301Shselasky	    STATUS(status, DID_DMA_DELAY),
326220301Shselasky	    STATUS(status, DID_CLOSE),
327220301Shselasky	    STATUS(status, DRAINING),
328220301Shselasky	    STATUS(status, STARTED),
329220301Shselasky	    STATUS(status, BW_RECLAIMED),
330220301Shselasky	    STATUS(status, CONTROL_XFR),
331220301Shselasky	    STATUS(status, CONTROL_HDR),
332220301Shselasky	    STATUS(status, CONTROL_ACT),
333220301Shselasky	    STATUS(status, CONTROL_STALL),
334220301Shselasky	    STATUS(status, SHORT_FRAMES_OK),
335220301Shselasky	    STATUS(status, SHORT_XFER_OK),
336220301Shselasky	    STATUS(status, BDMA_ENABLE),
337220301Shselasky	    STATUS(status, BDMA_NO_POST_SYNC),
338220301Shselasky	    STATUS(status, BDMA_SETUP),
339220301Shselasky	    STATUS(status, ISOCHRONOUS_XFR),
340220301Shselasky	    STATUS(status, CURR_DMA_SET),
341220301Shselasky	    STATUS(status, CAN_CANCEL_IMMED),
342220301Shselasky	    STATUS(status, DOING_CALLBACK));
343220301Shselasky}
344215651Sweongyo
345220301Shselasky/*
346220301Shselasky * Dump a byte into hex format.
347220301Shselasky */
348220301Shselaskystatic void
349220301Shselaskyhexbyte(char *buf, uint8_t temp)
350220301Shselasky{
351220301Shselasky	uint8_t lo;
352220301Shselasky	uint8_t hi;
353220301Shselasky
354220301Shselasky	lo = temp & 0xF;
355220301Shselasky	hi = temp >> 4;
356220301Shselasky
357220301Shselasky	if (hi < 10)
358220301Shselasky		buf[0] = '0' + hi;
359220301Shselasky	else
360220301Shselasky		buf[0] = 'A' + hi - 10;
361220301Shselasky
362220301Shselasky	if (lo < 10)
363220301Shselasky		buf[1] = '0' + lo;
364220301Shselasky	else
365220301Shselasky		buf[1] = 'A' + lo - 10;
366215651Sweongyo}
367215651Sweongyo
368215651Sweongyo/*
369215651Sweongyo * Display a region in traditional hexdump format.
370215651Sweongyo */
371215651Sweongyostatic void
372220301Shselaskyhexdump(const uint8_t *region, uint32_t len)
373215651Sweongyo{
374220301Shselasky	const uint8_t *line;
375220301Shselasky	char linebuf[128];
376220301Shselasky	int i;
377218010Shselasky	int x;
378218010Shselasky	int c;
379215651Sweongyo
380215651Sweongyo	for (line = region; line < (region + len); line += 16) {
381220301Shselasky
382220301Shselasky		i = 0;
383220301Shselasky
384220301Shselasky		linebuf[i] = ' ';
385220301Shselasky		hexbyte(linebuf + i + 1, ((line - region) >> 8) & 0xFF);
386220301Shselasky		hexbyte(linebuf + i + 3, (line - region) & 0xFF);
387220301Shselasky		linebuf[i + 5] = ' ';
388220301Shselasky		linebuf[i + 6] = ' ';
389220301Shselasky		i += 7;
390220301Shselasky
391215651Sweongyo		for (x = 0; x < 16; x++) {
392220301Shselasky		  if ((line + x) < (region + len)) {
393220301Shselasky			hexbyte(linebuf + i,
394220301Shselasky			    *(const u_int8_t *)(line + x));
395220301Shselasky		  } else {
396220301Shselasky			  linebuf[i] = '-';
397220301Shselasky			  linebuf[i + 1] = '-';
398220301Shselasky			}
399220301Shselasky			linebuf[i + 2] = ' ';
400220301Shselasky			if (x == 7) {
401220301Shselasky			  linebuf[i + 3] = ' ';
402220301Shselasky			  i += 4;
403220301Shselasky			} else {
404220301Shselasky			  i += 3;
405220301Shselasky			}
406215651Sweongyo		}
407220301Shselasky		linebuf[i] = ' ';
408220301Shselasky		linebuf[i + 1] = '|';
409220301Shselasky		i += 2;
410215651Sweongyo		for (x = 0; x < 16; x++) {
411215651Sweongyo			if ((line + x) < (region + len)) {
412215651Sweongyo				c = *(const u_int8_t *)(line + x);
413215651Sweongyo				/* !isprint(c) */
414215651Sweongyo				if ((c < ' ') || (c > '~'))
415215651Sweongyo					c = '.';
416220301Shselasky				linebuf[i] = c;
417220301Shselasky			} else {
418220301Shselasky				linebuf[i] = ' ';
419220301Shselasky			}
420220301Shselasky			i++;
421215651Sweongyo		}
422220301Shselasky		linebuf[i] = '|';
423220301Shselasky		linebuf[i + 1] = 0;
424220301Shselasky		i += 2;
425220301Shselasky		puts(linebuf);
426215651Sweongyo	}
427215651Sweongyo}
428215651Sweongyo
429215651Sweongyostatic void
430233037Shselaskyprint_apacket(const struct header_32 *hdr, const uint8_t *ptr, int ptr_len)
431215651Sweongyo{
432215651Sweongyo	struct tm *tm;
433220301Shselasky	struct usbpf_pkthdr up_temp;
434220301Shselasky	struct usbpf_pkthdr *up;
435215651Sweongyo	struct timeval tv;
436215651Sweongyo	size_t len;
437220301Shselasky	uint32_t x;
438215651Sweongyo	char buf[64];
439215651Sweongyo
440220301Shselasky	ptr += USBPF_HDR_LEN;
441220301Shselasky	ptr_len -= USBPF_HDR_LEN;
442220301Shselasky	if (ptr_len < 0)
443220301Shselasky		return;
444220301Shselasky
445220301Shselasky	/* make sure we don't change the source buffer */
446220301Shselasky	memcpy(&up_temp, ptr - USBPF_HDR_LEN, sizeof(up_temp));
447220301Shselasky	up = &up_temp;
448220301Shselasky
449220301Shselasky	/*
450220301Shselasky	 * A packet from the kernel is based on little endian byte
451220301Shselasky	 * order.
452220301Shselasky	 */
453220301Shselasky	up->up_totlen = le32toh(up->up_totlen);
454215651Sweongyo	up->up_busunit = le32toh(up->up_busunit);
455220301Shselasky	up->up_address = le32toh(up->up_address);
456215651Sweongyo	up->up_flags = le32toh(up->up_flags);
457215651Sweongyo	up->up_status = le32toh(up->up_status);
458215651Sweongyo	up->up_error = le32toh(up->up_error);
459215651Sweongyo	up->up_interval = le32toh(up->up_interval);
460220301Shselasky	up->up_frames = le32toh(up->up_frames);
461220301Shselasky	up->up_packet_size = le32toh(up->up_packet_size);
462220301Shselasky	up->up_packet_count = le32toh(up->up_packet_count);
463220301Shselasky	up->up_endpoint = le32toh(up->up_endpoint);
464215651Sweongyo
465233037Shselasky	tv.tv_sec = hdr->ts_sec;
466233037Shselasky	tv.tv_usec = hdr->ts_usec;
467215651Sweongyo	tm = localtime(&tv.tv_sec);
468215651Sweongyo
469215651Sweongyo	len = strftime(buf, sizeof(buf), "%H:%M:%S", tm);
470220301Shselasky
471220314Sthompsa	printf("%.*s.%06ld usbus%d.%d %s-%s-EP=%08x,SPD=%s,NFR=%d,SLEN=%d,IVAL=%d%s%s\n",
472220301Shselasky	    (int)len, buf, tv.tv_usec,
473220301Shselasky	    (int)up->up_busunit, (int)up->up_address,
474220301Shselasky	    (up->up_type == USBPF_XFERTAP_SUBMIT) ? "SUBM" : "DONE",
475215651Sweongyo	    xfertype_table[up->up_xfertype],
476220301Shselasky	    (unsigned int)up->up_endpoint,
477220301Shselasky	    usb_speedstr(up->up_speed),
478220301Shselasky	    (int)up->up_frames,
479220301Shselasky	    (int)(up->up_totlen - USBPF_HDR_LEN -
480220301Shselasky	    (USBPF_FRAME_HDR_LEN * up->up_frames)),
481220301Shselasky	    (int)up->up_interval,
482220301Shselasky	    (up->up_type == USBPF_XFERTAP_DONE) ? ",ERR=" : "",
483220301Shselasky	    (up->up_type == USBPF_XFERTAP_DONE) ?
484220301Shselasky	    usb_errstr(up->up_error) : "");
485215651Sweongyo
486215651Sweongyo	if (verbose >= 1) {
487220301Shselasky		for (x = 0; x != up->up_frames; x++) {
488220301Shselasky			const struct usbpf_framehdr *uf;
489220301Shselasky			uint32_t framelen;
490220301Shselasky			uint32_t flags;
491220301Shselasky
492220301Shselasky			uf = (const struct usbpf_framehdr *)ptr;
493220301Shselasky			ptr += USBPF_FRAME_HDR_LEN;
494220301Shselasky			ptr_len -= USBPF_FRAME_HDR_LEN;
495220301Shselasky			if (ptr_len < 0)
496220301Shselasky				return;
497220301Shselasky
498220301Shselasky			framelen = le32toh(uf->length);
499220301Shselasky			flags = le32toh(uf->flags);
500220301Shselasky
501220301Shselasky			printf(" frame[%u] %s %d bytes\n",
502220301Shselasky			    (unsigned int)x,
503220301Shselasky			    (flags & USBPF_FRAMEFLAG_READ) ? "READ" : "WRITE",
504220301Shselasky			    (int)framelen);
505220301Shselasky
506220301Shselasky			if (flags & USBPF_FRAMEFLAG_DATA_FOLLOWS) {
507220301Shselasky
508220301Shselasky				int tot_frame_len;
509220301Shselasky
510220301Shselasky				tot_frame_len = USBPF_FRAME_ALIGN(framelen);
511220301Shselasky
512220301Shselasky				ptr_len -= tot_frame_len;
513220301Shselasky
514220301Shselasky				if (tot_frame_len < 0 ||
515220301Shselasky				    (int)framelen < 0 || (int)ptr_len < 0)
516220301Shselasky					break;
517220301Shselasky
518220301Shselasky				hexdump(ptr, framelen);
519220301Shselasky
520220301Shselasky				ptr += tot_frame_len;
521220301Shselasky			}
522215651Sweongyo		}
523215651Sweongyo	}
524220301Shselasky	if (verbose >= 2)
525215651Sweongyo		print_flags(up->up_flags);
526220301Shselasky	if (verbose >= 3)
527215651Sweongyo		print_status(up->up_status);
528215651Sweongyo}
529215651Sweongyo
530215651Sweongyostatic void
531233039Shselaskyfix_packets(uint8_t *data, const int datalen)
532215651Sweongyo{
533233037Shselasky	struct header_32 temp;
534220301Shselasky	uint8_t *ptr;
535220301Shselasky	uint8_t *next;
536233039Shselasky	uint32_t hdrlen;
537233039Shselasky	uint32_t caplen;
538215651Sweongyo
539215651Sweongyo	for (ptr = data; ptr < (data + datalen); ptr = next) {
540215651Sweongyo
541233039Shselasky		const struct bpf_hdr *hdr;
542233037Shselasky
543233039Shselasky		hdr = (const struct bpf_hdr *)ptr;
544233037Shselasky
545233039Shselasky		temp.ts_sec = htole32(hdr->bh_tstamp.tv_sec);
546233039Shselasky		temp.ts_usec = htole32(hdr->bh_tstamp.tv_usec);
547233039Shselasky		temp.caplen = htole32(hdr->bh_caplen);
548233039Shselasky		temp.datalen = htole32(hdr->bh_datalen);
549233039Shselasky		temp.hdrlen = hdr->bh_hdrlen;
550233039Shselasky		temp.align = BPF_WORDALIGN(1);
551233037Shselasky
552233039Shselasky		hdrlen = hdr->bh_hdrlen;
553233039Shselasky		caplen = hdr->bh_caplen;
554233037Shselasky
555233039Shselasky		if ((hdrlen >= sizeof(temp)) && (hdrlen <= 255) &&
556233039Shselasky		    ((ptr + hdrlen) <= (data + datalen))) {
557233039Shselasky			memcpy(ptr, &temp, sizeof(temp));
558233039Shselasky			memset(ptr + sizeof(temp), 0, hdrlen - sizeof(temp));
559233039Shselasky		} else {
560233039Shselasky			err(EXIT_FAILURE, "Invalid header length %d", hdrlen);
561233039Shselasky		}
562233037Shselasky
563233039Shselasky		next = ptr + BPF_WORDALIGN(hdrlen + caplen);
564233037Shselasky
565233039Shselasky		if (next <= ptr)
566233039Shselasky			err(EXIT_FAILURE, "Invalid length");
567233039Shselasky	}
568233039Shselasky}
569233037Shselasky
570233039Shselaskystatic void
571233039Shselaskyprint_packets(uint8_t *data, const int datalen)
572233039Shselasky{
573233039Shselasky	struct header_32 temp;
574233039Shselasky	uint8_t *ptr;
575233039Shselasky	uint8_t *next;
576233037Shselasky
577233039Shselasky	for (ptr = data; ptr < (data + datalen); ptr = next) {
578233037Shselasky
579233039Shselasky		const struct header_32 *hdr32;
580233037Shselasky
581233039Shselasky		hdr32 = (const struct header_32 *)ptr;
582233039Shselasky
583233039Shselasky		temp.ts_sec = le32toh(hdr32->ts_sec);
584233039Shselasky		temp.ts_usec = le32toh(hdr32->ts_usec);
585233039Shselasky		temp.caplen = le32toh(hdr32->caplen);
586233039Shselasky		temp.datalen = le32toh(hdr32->datalen);
587233039Shselasky		temp.hdrlen = hdr32->hdrlen;
588233039Shselasky		temp.align = hdr32->align;
589233039Shselasky
590233039Shselasky		next = ptr + HEADER_ALIGN(temp.hdrlen + temp.caplen, temp.align);
591233039Shselasky
592233037Shselasky		if (next <= ptr)
593233039Shselasky			err(EXIT_FAILURE, "Invalid length");
594233037Shselasky
595233039Shselasky		if (w_arg == NULL || r_arg != NULL) {
596233037Shselasky			print_apacket(&temp, ptr +
597233037Shselasky			    temp.hdrlen, temp.caplen);
598220301Shselasky		}
599215651Sweongyo		pkt_captured++;
600215651Sweongyo	}
601215651Sweongyo}
602215651Sweongyo
603215651Sweongyostatic void
604220301Shselaskywrite_packets(struct usbcap *p, const uint8_t *data, const int datalen)
605215651Sweongyo{
606220301Shselasky	int len = htole32(datalen);
607220301Shselasky	int ret;
608215651Sweongyo
609215651Sweongyo	ret = write(p->wfd, &len, sizeof(int));
610221604Shselasky	if (ret != sizeof(int)) {
611221604Shselasky		err(EXIT_FAILURE, "Could not write length "
612221604Shselasky		    "field of USB data payload");
613221604Shselasky	}
614215651Sweongyo	ret = write(p->wfd, data, datalen);
615221604Shselasky	if (ret != datalen) {
616221604Shselasky		err(EXIT_FAILURE, "Could not write "
617221604Shselasky		    "complete USB data payload");
618221604Shselasky	}
619215651Sweongyo}
620215651Sweongyo
621215651Sweongyostatic void
622215651Sweongyoread_file(struct usbcap *p)
623215651Sweongyo{
624220301Shselasky	int datalen;
625220301Shselasky	int ret;
626220301Shselasky	uint8_t *data;
627215651Sweongyo
628215651Sweongyo	while ((ret = read(p->rfd, &datalen, sizeof(int))) == sizeof(int)) {
629215651Sweongyo		datalen = le32toh(datalen);
630215651Sweongyo		data = malloc(datalen);
631221604Shselasky		if (data == NULL)
632221604Shselasky			errx(EX_SOFTWARE, "Out of memory.");
633215651Sweongyo		ret = read(p->rfd, data, datalen);
634221604Shselasky		if (ret != datalen) {
635221604Shselasky			err(EXIT_FAILURE, "Could not read complete "
636221604Shselasky			    "USB data payload");
637221604Shselasky		}
638233039Shselasky		if (uf_minor == 2)
639233039Shselasky			fix_packets(data, datalen);
640233039Shselasky
641215651Sweongyo		print_packets(data, datalen);
642215651Sweongyo		free(data);
643215651Sweongyo	}
644215651Sweongyo}
645215651Sweongyo
646215651Sweongyostatic void
647215651Sweongyodo_loop(struct usbcap *p)
648215651Sweongyo{
649215651Sweongyo	int cc;
650215651Sweongyo
651215651Sweongyo	while (doexit == 0) {
652220301Shselasky		cc = read(p->fd, (uint8_t *)p->buffer, p->bufsize);
653215651Sweongyo		if (cc < 0) {
654215651Sweongyo			switch (errno) {
655215651Sweongyo			case EINTR:
656215651Sweongyo				break;
657215651Sweongyo			default:
658215651Sweongyo				fprintf(stderr, "read: %s\n", strerror(errno));
659215651Sweongyo				return;
660215651Sweongyo			}
661215651Sweongyo			continue;
662215651Sweongyo		}
663215651Sweongyo		if (cc == 0)
664215651Sweongyo			continue;
665233039Shselasky
666233039Shselasky		fix_packets(p->buffer, cc);
667233039Shselasky
668215651Sweongyo		if (w_arg != NULL)
669215651Sweongyo			write_packets(p, p->buffer, cc);
670215651Sweongyo		print_packets(p->buffer, cc);
671215651Sweongyo	}
672215651Sweongyo}
673215651Sweongyo
674215651Sweongyostatic void
675215651Sweongyoinit_rfile(struct usbcap *p)
676215651Sweongyo{
677215651Sweongyo	struct usbcap_filehdr uf;
678215651Sweongyo	int ret;
679215651Sweongyo
680215651Sweongyo	p->rfd = open(r_arg, O_RDONLY);
681215651Sweongyo	if (p->rfd < 0) {
682221604Shselasky		err(EXIT_FAILURE, "Could not open "
683221604Shselasky		    "'%s' for read", r_arg);
684215651Sweongyo	}
685215651Sweongyo	ret = read(p->rfd, &uf, sizeof(uf));
686221604Shselasky	if (ret != sizeof(uf)) {
687221604Shselasky		err(EXIT_FAILURE, "Could not read USB capture "
688221604Shselasky		    "file header");
689221604Shselasky	}
690221604Shselasky	if (le32toh(uf.magic) != USBCAP_FILEHDR_MAGIC) {
691221604Shselasky		errx(EX_SOFTWARE, "Invalid magic field(0x%08x) "
692221604Shselasky		    "in USB capture file header.",
693221604Shselasky		    (unsigned int)le32toh(uf.magic));
694221604Shselasky	}
695221604Shselasky	if (uf.major != 0) {
696221604Shselasky		errx(EX_SOFTWARE, "Invalid major version(%d) "
697221604Shselasky		    "field in USB capture file header.", (int)uf.major);
698221604Shselasky	}
699233039Shselasky
700233039Shselasky	uf_minor = uf.minor;
701233039Shselasky
702233039Shselasky	if (uf.minor != 3 && uf.minor != 2) {
703221604Shselasky		errx(EX_SOFTWARE, "Invalid minor version(%d) "
704221604Shselasky		    "field in USB capture file header.", (int)uf.minor);
705221604Shselasky	}
706215651Sweongyo}
707215651Sweongyo
708215651Sweongyostatic void
709215651Sweongyoinit_wfile(struct usbcap *p)
710215651Sweongyo{
711215651Sweongyo	struct usbcap_filehdr uf;
712215651Sweongyo	int ret;
713215651Sweongyo
714215651Sweongyo	p->wfd = open(w_arg, O_CREAT | O_TRUNC | O_WRONLY, S_IRUSR | S_IWUSR);
715215651Sweongyo	if (p->wfd < 0) {
716221604Shselasky		err(EXIT_FAILURE, "Could not open "
717233039Shselasky		    "'%s' for write", w_arg);
718215651Sweongyo	}
719221604Shselasky	memset(&uf, 0, sizeof(uf));
720215651Sweongyo	uf.magic = htole32(USBCAP_FILEHDR_MAGIC);
721215651Sweongyo	uf.major = 0;
722233039Shselasky	uf.minor = 3;
723215651Sweongyo	ret = write(p->wfd, (const void *)&uf, sizeof(uf));
724221604Shselasky	if (ret != sizeof(uf)) {
725221604Shselasky		err(EXIT_FAILURE, "Could not write "
726221604Shselasky		    "USB capture header");
727221604Shselasky	}
728215651Sweongyo}
729215651Sweongyo
730215651Sweongyostatic void
731215651Sweongyousage(void)
732215651Sweongyo{
733215651Sweongyo
734215651Sweongyo#define FMT "    %-14s %s\n"
735215651Sweongyo	fprintf(stderr, "usage: usbdump [options]\n");
736221604Shselasky	fprintf(stderr, FMT, "-i <usbusX>", "Listen on USB bus interface");
737231835Shselasky	fprintf(stderr, FMT, "-f <unit[.endpoint]>", "Specify a device and endpoint filter");
738221604Shselasky	fprintf(stderr, FMT, "-r <file>", "Read the raw packets from file");
739221604Shselasky	fprintf(stderr, FMT, "-s <snaplen>", "Snapshot bytes from each packet");
740221604Shselasky	fprintf(stderr, FMT, "-v", "Increase the verbose level");
741221604Shselasky	fprintf(stderr, FMT, "-w <file>", "Write the raw packets to file");
742215651Sweongyo#undef FMT
743221604Shselasky	exit(EX_USAGE);
744215651Sweongyo}
745215651Sweongyo
746215651Sweongyoint
747215651Sweongyomain(int argc, char *argv[])
748215651Sweongyo{
749215651Sweongyo	struct timeval tv;
750215803Sweongyo	struct bpf_program total_prog;
751215803Sweongyo	struct bpf_stat us;
752215803Sweongyo	struct bpf_version bv;
753215651Sweongyo	struct usbcap uc, *p = &uc;
754215803Sweongyo	struct ifreq ifr;
755215651Sweongyo	long snapshot = 192;
756220301Shselasky	uint32_t v;
757231835Shselasky	int fd;
758231835Shselasky	int o;
759231835Shselasky	int filt_unit;
760231835Shselasky	int filt_ep;
761215651Sweongyo	const char *optstring;
762231835Shselasky	char *pp;
763215651Sweongyo
764221604Shselasky	memset(&uc, 0, sizeof(struct usbcap));
765215651Sweongyo
766231835Shselasky	optstring = "i:r:s:vw:f:";
767215651Sweongyo	while ((o = getopt(argc, argv, optstring)) != -1) {
768215651Sweongyo		switch (o) {
769215651Sweongyo		case 'i':
770215651Sweongyo			i_arg = optarg;
771215651Sweongyo			break;
772215651Sweongyo		case 'r':
773215651Sweongyo			r_arg = optarg;
774215651Sweongyo			init_rfile(p);
775215651Sweongyo			break;
776215651Sweongyo		case 's':
777231835Shselasky			snapshot = strtol(optarg, &pp, 10);
778215651Sweongyo			errno = 0;
779231835Shselasky			if (pp != NULL && *pp != 0)
780231835Shselasky				usage();
781215651Sweongyo			if (snapshot == 0 && errno == EINVAL)
782215651Sweongyo				usage();
783215651Sweongyo			/* snapeshot == 0 is special */
784215651Sweongyo			if (snapshot == 0)
785215651Sweongyo				snapshot = -1;
786215651Sweongyo			break;
787215651Sweongyo		case 'v':
788215651Sweongyo			verbose++;
789215651Sweongyo			break;
790215651Sweongyo		case 'w':
791215651Sweongyo			w_arg = optarg;
792215651Sweongyo			init_wfile(p);
793215651Sweongyo			break;
794231835Shselasky		case 'f':
795231835Shselasky			filt_unit = strtol(optarg, &pp, 10);
796231835Shselasky			filt_ep = -1;
797231835Shselasky			if (pp != NULL) {
798231835Shselasky				if (*pp == '.') {
799231835Shselasky					filt_ep = strtol(pp + 1, &pp, 10);
800231835Shselasky					if (pp != NULL && *pp != 0)
801231835Shselasky						usage();
802231835Shselasky				} else if (*pp != 0) {
803231835Shselasky					usage();
804231835Shselasky				}
805231835Shselasky			}
806231835Shselasky			add_filter(filt_unit, filt_ep);
807231835Shselasky			break;
808215651Sweongyo		default:
809215651Sweongyo			usage();
810215651Sweongyo			/* NOTREACHED */
811215651Sweongyo		}
812215651Sweongyo	}
813215651Sweongyo
814215651Sweongyo	if (r_arg != NULL) {
815215651Sweongyo		read_file(p);
816215651Sweongyo		exit(EXIT_SUCCESS);
817215651Sweongyo	}
818215651Sweongyo
819215803Sweongyo	p->fd = fd = open("/dev/bpf", O_RDONLY);
820221604Shselasky	if (p->fd < 0)
821221604Shselasky		err(EXIT_FAILURE, "Could not open BPF device");
822215651Sweongyo
823221604Shselasky	if (ioctl(fd, BIOCVERSION, (caddr_t)&bv) < 0)
824221604Shselasky		err(EXIT_FAILURE, "BIOCVERSION ioctl failed");
825221604Shselasky
826215803Sweongyo	if (bv.bv_major != BPF_MAJOR_VERSION ||
827221604Shselasky	    bv.bv_minor < BPF_MINOR_VERSION)
828221604Shselasky		errx(EXIT_FAILURE, "Kernel BPF filter out of date");
829215651Sweongyo
830220301Shselasky	/* USB transfers can be greater than 64KByte */
831220301Shselasky	v = 1U << 16;
832220301Shselasky
833220301Shselasky	/* clear ifr structure */
834220301Shselasky	memset(&ifr, 0, sizeof(ifr));
835220301Shselasky
836220301Shselasky	for ( ; v >= USBPF_HDR_LEN; v >>= 1) {
837215803Sweongyo		(void)ioctl(fd, BIOCSBLEN, (caddr_t)&v);
838215803Sweongyo		(void)strncpy(ifr.ifr_name, i_arg, sizeof(ifr.ifr_name));
839215803Sweongyo		if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) >= 0)
840215651Sweongyo			break;
841215651Sweongyo	}
842221604Shselasky	if (v == 0)
843221604Shselasky		errx(EXIT_FAILURE, "No buffer size worked.");
844215651Sweongyo
845221604Shselasky	if (ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0)
846221604Shselasky		err(EXIT_FAILURE, "BIOCGBLEN ioctl failed");
847215651Sweongyo
848215651Sweongyo	p->bufsize = v;
849220301Shselasky	p->buffer = (uint8_t *)malloc(p->bufsize);
850221604Shselasky	if (p->buffer == NULL)
851221604Shselasky		errx(EX_SOFTWARE, "Out of memory.");
852215651Sweongyo
853231835Shselasky	make_filter(&total_prog, snapshot);
854215651Sweongyo
855221604Shselasky	if (ioctl(p->fd, BIOCSETF, (caddr_t)&total_prog) < 0)
856221604Shselasky		err(EXIT_FAILURE, "BIOCSETF ioctl failed");
857215651Sweongyo
858231835Shselasky	free_filter(&total_prog);
859231835Shselasky
860215651Sweongyo	/* 1 second read timeout */
861215651Sweongyo	tv.tv_sec = 1;
862215651Sweongyo	tv.tv_usec = 0;
863221604Shselasky	if (ioctl(p->fd, BIOCSRTIMEOUT, (caddr_t)&tv) < 0)
864221604Shselasky		err(EXIT_FAILURE, "BIOCSRTIMEOUT ioctl failed");
865215651Sweongyo
866215651Sweongyo	(void)signal(SIGINT, handle_sigint);
867215651Sweongyo
868215651Sweongyo	do_loop(p);
869215651Sweongyo
870221604Shselasky	if (ioctl(fd, BIOCGSTATS, (caddr_t)&us) < 0)
871221604Shselasky		err(EXIT_FAILURE, "BIOCGSTATS ioctl failed");
872215651Sweongyo
873215651Sweongyo	/* XXX what's difference between pkt_captured and us.us_recv? */
874215651Sweongyo	printf("\n");
875215651Sweongyo	printf("%d packets captured\n", pkt_captured);
876215803Sweongyo	printf("%d packets received by filter\n", us.bs_recv);
877215803Sweongyo	printf("%d packets dropped by kernel\n", us.bs_drop);
878215651Sweongyo
879215651Sweongyo	if (p->fd > 0)
880215651Sweongyo		close(p->fd);
881215651Sweongyo	if (p->rfd > 0)
882215651Sweongyo		close(p->rfd);
883215651Sweongyo	if (p->wfd > 0)
884215651Sweongyo		close(p->wfd);
885215651Sweongyo
886215651Sweongyo	return (EXIT_SUCCESS);
887215651Sweongyo}
888