xref: /netbsd-src/external/bsd/libpcap/dist/pcap-usb-linux.c (revision b7b7574d3bf8eeb51a1fa3977b59142ec6434a55)
1 /*	$NetBSD: pcap-usb-linux.c,v 1.1.1.4 2013/12/31 16:57:24 christos Exp $	*/
2 
3 /*
4  * Copyright (c) 2006 Paolo Abeni (Italy)
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  * notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  * notice, this list of conditions and the following disclaimer in the
15  * documentation and/or other materials provided with the distribution.
16  * 3. The name of the author may not be used to endorse or promote
17  * products derived from this software without specific prior written
18  * permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  *
32  * USB sniffing API implementation for Linux platform
33  * By Paolo Abeni <paolo.abeni@email.it>
34  * Modifications: Kris Katterjohn <katterjohn@gmail.com>
35  *
36  */
37 #ifndef lint
38 static const char rcsid[] _U_ =
39     "@(#) Header: /tcpdump/master/libpcap/pcap-usb-linux.c,v 1.33 2008-12-23 21:38:50 guy Exp  (LBL)";
40 #endif
41 
42 #ifdef HAVE_CONFIG_H
43 #include "config.h"
44 #endif
45 
46 #include "pcap-int.h"
47 #include "pcap-usb-linux.h"
48 #include "pcap/usb.h"
49 
50 #ifdef NEED_STRERROR_H
51 #include "strerror.h"
52 #endif
53 
54 #include <ctype.h>
55 #include <errno.h>
56 #include <stdlib.h>
57 #include <unistd.h>
58 #include <fcntl.h>
59 #include <string.h>
60 #include <dirent.h>
61 #include <byteswap.h>
62 #include <netinet/in.h>
63 #include <sys/ioctl.h>
64 #include <sys/mman.h>
65 #ifdef HAVE_LINUX_USBDEVICE_FS_H
66 /*
67  * We might need <linux/compiler.h> to define __user for
68  * <linux/usbdevice_fs.h>.
69  */
70 #ifdef HAVE_LINUX_COMPILER_H
71 #include <linux/compiler.h>
72 #endif /* HAVE_LINUX_COMPILER_H */
73 #include <linux/usbdevice_fs.h>
74 #endif /* HAVE_LINUX_USBDEVICE_FS_H */
75 
76 #define USB_IFACE "usbmon"
77 #define USB_TEXT_DIR_OLD "/sys/kernel/debug/usbmon"
78 #define USB_TEXT_DIR "/sys/kernel/debug/usb/usbmon"
79 #define SYS_USB_BUS_DIR "/sys/bus/usb/devices"
80 #define PROC_USB_BUS_DIR "/proc/bus/usb"
81 #define USB_LINE_LEN 4096
82 
83 #if __BYTE_ORDER == __LITTLE_ENDIAN
84 #define htols(s) s
85 #define htoll(l) l
86 #define htol64(ll) ll
87 #else
88 #define htols(s) bswap_16(s)
89 #define htoll(l) bswap_32(l)
90 #define htol64(ll) bswap_64(ll)
91 #endif
92 
93 struct mon_bin_stats {
94 	u_int32_t queued;
95 	u_int32_t dropped;
96 };
97 
98 struct mon_bin_get {
99 	pcap_usb_header *hdr;
100 	void *data;
101 	size_t data_len;   /* Length of data (can be zero) */
102 };
103 
104 struct mon_bin_mfetch {
105 	int32_t *offvec;   /* Vector of events fetched */
106 	int32_t nfetch;    /* Number of events to fetch (out: fetched) */
107 	int32_t nflush;    /* Number of events to flush */
108 };
109 
110 #define MON_IOC_MAGIC 0x92
111 
112 #define MON_IOCQ_URB_LEN _IO(MON_IOC_MAGIC, 1)
113 #define MON_IOCX_URB  _IOWR(MON_IOC_MAGIC, 2, struct mon_bin_hdr)
114 #define MON_IOCG_STATS _IOR(MON_IOC_MAGIC, 3, struct mon_bin_stats)
115 #define MON_IOCT_RING_SIZE _IO(MON_IOC_MAGIC, 4)
116 #define MON_IOCQ_RING_SIZE _IO(MON_IOC_MAGIC, 5)
117 #define MON_IOCX_GET   _IOW(MON_IOC_MAGIC, 6, struct mon_bin_get)
118 #define MON_IOCX_MFETCH _IOWR(MON_IOC_MAGIC, 7, struct mon_bin_mfetch)
119 #define MON_IOCH_MFLUSH _IO(MON_IOC_MAGIC, 8)
120 
121 #define MON_BIN_SETUP 	0x1 /* setup hdr is present*/
122 #define MON_BIN_SETUP_ZERO 	0x2 /* setup buffer is not available */
123 #define MON_BIN_DATA_ZERO 	0x4 /* data buffer is not available */
124 #define MON_BIN_ERROR 	0x8
125 
126 /*
127  * Private data for capturing on Linux USB.
128  */
129 struct pcap_usb_linux {
130 	u_char *mmapbuf;	/* memory-mapped region pointer */
131 	size_t mmapbuflen;	/* size of region */
132 	int bus_index;
133 	u_int packets_read;
134 };
135 
136 /* forward declaration */
137 static int usb_activate(pcap_t *);
138 static int usb_stats_linux(pcap_t *, struct pcap_stat *);
139 static int usb_stats_linux_bin(pcap_t *, struct pcap_stat *);
140 static int usb_read_linux(pcap_t *, int , pcap_handler , u_char *);
141 static int usb_read_linux_bin(pcap_t *, int , pcap_handler , u_char *);
142 static int usb_read_linux_mmap(pcap_t *, int , pcap_handler , u_char *);
143 static int usb_inject_linux(pcap_t *, const void *, size_t);
144 static int usb_setdirection_linux(pcap_t *, pcap_direction_t);
145 static void usb_cleanup_linux_mmap(pcap_t *);
146 
147 /* facility to add an USB device to the device list*/
148 static int
149 usb_dev_add(pcap_if_t** alldevsp, int n, char *err_str)
150 {
151 	char dev_name[10];
152 	char dev_descr[30];
153 	snprintf(dev_name, 10, USB_IFACE"%d", n);
154 	snprintf(dev_descr, 30, "USB bus number %d", n);
155 
156 	if (pcap_add_if(alldevsp, dev_name, 0,
157 	    dev_descr, err_str) < 0)
158 		return -1;
159 	return 0;
160 }
161 
162 int
163 usb_findalldevs(pcap_if_t **alldevsp, char *err_str)
164 {
165 	struct dirent* data;
166 	int ret = 0;
167 	DIR* dir;
168 	int n;
169 	char* name;
170 	size_t len;
171 
172 	/* try scanning sysfs usb bus directory */
173 	dir = opendir(SYS_USB_BUS_DIR);
174 	if (dir != NULL) {
175 		while ((ret == 0) && ((data = readdir(dir)) != 0)) {
176 			name = data->d_name;
177 
178 			if (strncmp(name, "usb", 3) != 0)
179 				continue;
180 
181 			if (sscanf(&name[3], "%d", &n) == 0)
182 				continue;
183 
184 			ret = usb_dev_add(alldevsp, n, err_str);
185 		}
186 
187 		closedir(dir);
188 		return ret;
189 	}
190 
191 	/* that didn't work; try scanning procfs usb bus directory */
192 	dir = opendir(PROC_USB_BUS_DIR);
193 	if (dir != NULL) {
194 		while ((ret == 0) && ((data = readdir(dir)) != 0)) {
195 			name = data->d_name;
196 			len = strlen(name);
197 
198 			/* if this file name does not end with a number it's not of our interest */
199 			if ((len < 1) || !isdigit(name[--len]))
200 				continue;
201 			while (isdigit(name[--len]));
202 			if (sscanf(&name[len+1], "%d", &n) != 1)
203 				continue;
204 
205 			ret = usb_dev_add(alldevsp, n, err_str);
206 		}
207 
208 		closedir(dir);
209 		return ret;
210 	}
211 
212 	/* neither of them worked */
213 	return 0;
214 }
215 
216 static
217 int usb_mmap(pcap_t* handle)
218 {
219 	struct pcap_usb_linux *handlep = handle->priv;
220 	int len = ioctl(handle->fd, MON_IOCQ_RING_SIZE);
221 	if (len < 0)
222 		return 0;
223 
224 	handlep->mmapbuflen = len;
225 	handlep->mmapbuf = mmap(0, handlep->mmapbuflen, PROT_READ,
226 	    MAP_SHARED, handle->fd, 0);
227 	return handlep->mmapbuf != MAP_FAILED;
228 }
229 
230 #define CTRL_TIMEOUT    (5*1000)        /* milliseconds */
231 
232 #define USB_DIR_IN		0x80
233 #define USB_TYPE_STANDARD	0x00
234 #define USB_RECIP_DEVICE	0x00
235 
236 #define USB_REQ_GET_DESCRIPTOR	6
237 
238 #define USB_DT_DEVICE		1
239 
240 /* probe the descriptors of the devices attached to the bus */
241 /* the descriptors will end up in the captured packet stream */
242 /* and be decoded by external apps like wireshark */
243 /* without these identifying probes packet data can't be fully decoded */
244 static void
245 probe_devices(int bus)
246 {
247 	struct usbdevfs_ctrltransfer ctrl;
248 	struct dirent* data;
249 	int ret = 0;
250 	char buf[40];
251 	DIR* dir;
252 
253 	/* scan usb bus directories for device nodes */
254 	snprintf(buf, sizeof(buf), "/dev/bus/usb/%03d", bus);
255 	dir = opendir(buf);
256 	if (!dir)
257 		return;
258 
259 	while ((ret >= 0) && ((data = readdir(dir)) != 0)) {
260 		int fd;
261 		char* name = data->d_name;
262 
263 		if (name[0] == '.')
264 			continue;
265 
266 		snprintf(buf, sizeof(buf), "/dev/bus/usb/%03d/%s", bus, data->d_name);
267 
268 		fd = open(buf, O_RDWR);
269 		if (fd == -1)
270 			continue;
271 
272 		/*
273 		 * Sigh.  Different kernels have different member names
274 		 * for this structure.
275 		 */
276 #ifdef HAVE_USBDEVFS_CTRLTRANSFER_BREQUESTTYPE
277 		ctrl.bRequestType = USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE;
278 		ctrl.bRequest = USB_REQ_GET_DESCRIPTOR;
279 		ctrl.wValue = USB_DT_DEVICE << 8;
280 		ctrl.wIndex = 0;
281  		ctrl.wLength = sizeof(buf);
282 #else
283 		ctrl.requesttype = USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE;
284 		ctrl.request = USB_REQ_GET_DESCRIPTOR;
285 		ctrl.value = USB_DT_DEVICE << 8;
286 		ctrl.index = 0;
287  		ctrl.length = sizeof(buf);
288 #endif
289 		ctrl.data = buf;
290 		ctrl.timeout = CTRL_TIMEOUT;
291 
292 		ret = ioctl(fd, USBDEVFS_CONTROL, &ctrl);
293 
294 		close(fd);
295 	}
296 	closedir(dir);
297 }
298 
299 pcap_t *
300 usb_create(const char *device, char *ebuf, int *is_ours)
301 {
302 	const char *cp;
303 	char *cpend;
304 	long devnum;
305 	pcap_t *p;
306 
307 	/* Does this look like a USB monitoring device? */
308 	cp = strrchr(device, '/');
309 	if (cp == NULL)
310 		cp = device;
311 	/* Does it begin with USB_IFACE? */
312 	if (strncmp(cp, USB_IFACE, sizeof USB_IFACE - 1) != 0) {
313 		/* Nope, doesn't begin with USB_IFACE */
314 		*is_ours = 0;
315 		return NULL;
316 	}
317 	/* Yes - is USB_IFACE followed by a number? */
318 	cp += sizeof USB_IFACE - 1;
319 	devnum = strtol(cp, &cpend, 10);
320 	if (cpend == cp || *cpend != '\0') {
321 		/* Not followed by a number. */
322 		*is_ours = 0;
323 		return NULL;
324 	}
325 	if (devnum < 0) {
326 		/* Followed by a non-valid number. */
327 		*is_ours = 0;
328 		return NULL;
329 	}
330 
331 	/* OK, it's probably ours. */
332 	*is_ours = 1;
333 
334 	p = pcap_create_common(device, ebuf, sizeof (struct pcap_usb_linux));
335 	if (p == NULL)
336 		return (NULL);
337 
338 	p->activate_op = usb_activate;
339 	return (p);
340 }
341 
342 static int
343 usb_activate(pcap_t* handle)
344 {
345 	struct pcap_usb_linux *handlep = handle->priv;
346 	char 		full_path[USB_LINE_LEN];
347 
348 	/* Initialize some components of the pcap structure. */
349 	handle->bufsize = handle->snapshot;
350 	handle->offset = 0;
351 	handle->linktype = DLT_USB_LINUX;
352 
353 	handle->inject_op = usb_inject_linux;
354 	handle->setfilter_op = install_bpf_program; /* no kernel filtering */
355 	handle->setdirection_op = usb_setdirection_linux;
356 	handle->set_datalink_op = NULL;	/* can't change data link type */
357 	handle->getnonblock_op = pcap_getnonblock_fd;
358 	handle->setnonblock_op = pcap_setnonblock_fd;
359 
360 	/*get usb bus index from device name */
361 	if (sscanf(handle->opt.source, USB_IFACE"%d", &handlep->bus_index) != 1)
362 	{
363 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
364 			"Can't get USB bus index from %s", handle->opt.source);
365 		return PCAP_ERROR;
366 	}
367 
368 	/*now select the read method: try to open binary interface */
369 	snprintf(full_path, USB_LINE_LEN, LINUX_USB_MON_DEV"%d", handlep->bus_index);
370 	handle->fd = open(full_path, O_RDONLY, 0);
371 	if (handle->fd >= 0)
372 	{
373 		if (handle->opt.rfmon) {
374 			/*
375 			 * Monitor mode doesn't apply to USB devices.
376 			 */
377 			close(handle->fd);
378 			return PCAP_ERROR_RFMON_NOTSUP;
379 		}
380 
381 		/* binary api is available, try to use fast mmap access */
382 		if (usb_mmap(handle)) {
383 			handle->linktype = DLT_USB_LINUX_MMAPPED;
384 			handle->stats_op = usb_stats_linux_bin;
385 			handle->read_op = usb_read_linux_mmap;
386 			handle->cleanup_op = usb_cleanup_linux_mmap;
387 			probe_devices(handlep->bus_index);
388 
389 			/*
390 			 * "handle->fd" is a real file, so "select()" and
391 			 * "poll()" work on it.
392 			 */
393 			handle->selectable_fd = handle->fd;
394 			return 0;
395 		}
396 
397 		/* can't mmap, use plain binary interface access */
398 		handle->stats_op = usb_stats_linux_bin;
399 		handle->read_op = usb_read_linux_bin;
400 		probe_devices(handlep->bus_index);
401 	}
402 	else {
403 		/*Binary interface not available, try open text interface */
404 		snprintf(full_path, USB_LINE_LEN, USB_TEXT_DIR"/%dt", handlep->bus_index);
405 		handle->fd = open(full_path, O_RDONLY, 0);
406 		if (handle->fd < 0)
407 		{
408 			if (errno == ENOENT)
409 			{
410 				/*
411 				 * Not found at the new location; try
412 				 * the old location.
413 				 */
414 				snprintf(full_path, USB_LINE_LEN, USB_TEXT_DIR_OLD"/%dt", handlep->bus_index);
415 				handle->fd = open(full_path, O_RDONLY, 0);
416 			}
417 			if (handle->fd < 0) {
418 				/* no more fallback, give it up*/
419 				snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
420 					"Can't open USB bus file %s: %s", full_path, strerror(errno));
421 				return PCAP_ERROR;
422 			}
423 		}
424 
425 		if (handle->opt.rfmon) {
426 			/*
427 			 * Monitor mode doesn't apply to USB devices.
428 			 */
429 			close(handle->fd);
430 			return PCAP_ERROR_RFMON_NOTSUP;
431 		}
432 
433 		handle->stats_op = usb_stats_linux;
434 		handle->read_op = usb_read_linux;
435 	}
436 
437 	/*
438 	 * "handle->fd" is a real file, so "select()" and "poll()"
439 	 * work on it.
440 	 */
441 	handle->selectable_fd = handle->fd;
442 
443 	/* for plain binary access and text access we need to allocate the read
444 	 * buffer */
445 	handle->buffer = malloc(handle->bufsize);
446 	if (!handle->buffer) {
447 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
448 			 "malloc: %s", pcap_strerror(errno));
449 		close(handle->fd);
450 		return PCAP_ERROR;
451 	}
452 	return 0;
453 }
454 
455 static inline int
456 ascii_to_int(char c)
457 {
458 	return c < 'A' ? c- '0': ((c<'a') ? c - 'A' + 10: c-'a'+10);
459 }
460 
461 /*
462  * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
463  * <linux-kernel-source>/drivers/usb/mon/mon_text.c for urb string
464  * format description
465  */
466 static int
467 usb_read_linux(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
468 {
469 	/* see:
470 	* /usr/src/linux/Documentation/usb/usbmon.txt
471 	* for message format
472 	*/
473 	struct pcap_usb_linux *handlep = handle->priv;
474 	unsigned timestamp;
475 	int tag, cnt, ep_num, dev_addr, dummy, ret, urb_len, data_len;
476 	char etype, pipeid1, pipeid2, status[16], urb_tag, line[USB_LINE_LEN];
477 	char *string = line;
478 	u_char * rawdata = handle->buffer;
479 	struct pcap_pkthdr pkth;
480 	pcap_usb_header* uhdr = (pcap_usb_header*)handle->buffer;
481 	u_char urb_transfer=0;
482 	int incoming=0;
483 
484 	/* ignore interrupt system call errors */
485 	do {
486 		ret = read(handle->fd, line, USB_LINE_LEN - 1);
487 		if (handle->break_loop)
488 		{
489 			handle->break_loop = 0;
490 			return -2;
491 		}
492 	} while ((ret == -1) && (errno == EINTR));
493 	if (ret < 0)
494 	{
495 		if (errno == EAGAIN)
496 			return 0;	/* no data there */
497 
498 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
499 		    "Can't read from fd %d: %s", handle->fd, strerror(errno));
500 		return -1;
501 	}
502 
503 	/* read urb header; %n argument may increment return value, but it's
504 	* not mandatory, so does not count on it*/
505 	string[ret] = 0;
506 	ret = sscanf(string, "%x %d %c %c%c:%d:%d %s%n", &tag, &timestamp, &etype,
507 		&pipeid1, &pipeid2, &dev_addr, &ep_num, status,
508 		&cnt);
509 	if (ret < 8)
510 	{
511 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
512 		    "Can't parse USB bus message '%s', too few tokens (expected 8 got %d)",
513 		    string, ret);
514 		return -1;
515 	}
516 	uhdr->id = tag;
517 	uhdr->device_address = dev_addr;
518 	uhdr->bus_id = handlep->bus_index;
519 	uhdr->status = 0;
520 	string += cnt;
521 
522 	/* don't use usbmon provided timestamp, since it have low precision*/
523 	if (gettimeofday(&pkth.ts, NULL) < 0)
524 	{
525 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
526 			"Can't get timestamp for message '%s' %d:%s",
527 			string, errno, strerror(errno));
528 		return -1;
529 	}
530 	uhdr->ts_sec = pkth.ts.tv_sec;
531 	uhdr->ts_usec = pkth.ts.tv_usec;
532 
533 	/* parse endpoint information */
534 	if (pipeid1 == 'C')
535 		urb_transfer = URB_CONTROL;
536 	else if (pipeid1 == 'Z')
537 		urb_transfer = URB_ISOCHRONOUS;
538 	else if (pipeid1 == 'I')
539 		urb_transfer = URB_INTERRUPT;
540 	else if (pipeid1 == 'B')
541 		urb_transfer = URB_BULK;
542 	if (pipeid2 == 'i') {
543 		ep_num |= URB_TRANSFER_IN;
544 		incoming = 1;
545 	}
546 	if (etype == 'C')
547 		incoming = !incoming;
548 
549 	/* direction check*/
550 	if (incoming)
551 	{
552 		if (handle->direction == PCAP_D_OUT)
553 			return 0;
554 	}
555 	else
556 		if (handle->direction == PCAP_D_IN)
557 			return 0;
558 	uhdr->event_type = etype;
559 	uhdr->transfer_type = urb_transfer;
560 	uhdr->endpoint_number = ep_num;
561 	pkth.caplen = sizeof(pcap_usb_header);
562 	rawdata += sizeof(pcap_usb_header);
563 
564 	/* check if this is a setup packet */
565 	ret = sscanf(status, "%d", &dummy);
566 	if (ret != 1)
567 	{
568 		/* this a setup packet, setup data can be filled with underscore if
569 		* usbmon has not been able to read them, so we must parse this fields as
570 		* strings */
571 		pcap_usb_setup* shdr;
572 		char str1[3], str2[3], str3[5], str4[5], str5[5];
573 		ret = sscanf(string, "%s %s %s %s %s%n", str1, str2, str3, str4,
574 		str5, &cnt);
575 		if (ret < 5)
576 		{
577 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
578 				"Can't parse USB bus message '%s', too few tokens (expected 5 got %d)",
579 				string, ret);
580 			return -1;
581 		}
582 		string += cnt;
583 
584 		/* try to convert to corresponding integer */
585 		shdr = &uhdr->setup;
586 		shdr->bmRequestType = strtoul(str1, 0, 16);
587 		shdr->bRequest = strtoul(str2, 0, 16);
588 		shdr->wValue = htols(strtoul(str3, 0, 16));
589 		shdr->wIndex = htols(strtoul(str4, 0, 16));
590 		shdr->wLength = htols(strtoul(str5, 0, 16));
591 
592 		uhdr->setup_flag = 0;
593 	}
594 	else
595 		uhdr->setup_flag = 1;
596 
597 	/* read urb data */
598 	ret = sscanf(string, " %d%n", &urb_len, &cnt);
599 	if (ret < 1)
600 	{
601 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
602 		  "Can't parse urb length from '%s'", string);
603 		return -1;
604 	}
605 	string += cnt;
606 
607 	/* urb tag is not present if urb length is 0, so we can stop here
608 	 * text parsing */
609 	pkth.len = urb_len+pkth.caplen;
610 	uhdr->urb_len = urb_len;
611 	uhdr->data_flag = 1;
612 	data_len = 0;
613 	if (uhdr->urb_len == 0)
614 		goto got;
615 
616 	/* check for data presence; data is present if and only if urb tag is '=' */
617 	if (sscanf(string, " %c", &urb_tag) != 1)
618 	{
619 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
620 			"Can't parse urb tag from '%s'", string);
621 		return -1;
622 	}
623 
624 	if (urb_tag != '=')
625 		goto got;
626 
627 	/* skip urb tag and following space */
628 	string += 3;
629 
630 	/* if we reach this point we got some urb data*/
631 	uhdr->data_flag = 0;
632 
633 	/* read all urb data; if urb length is greater then the usbmon internal
634 	 * buffer length used by the kernel to spool the URB, we get only
635 	 * a partial information.
636 	 * At least until linux 2.6.17 there is no way to set usbmon intenal buffer
637 	 * length and default value is 130. */
638 	while ((string[0] != 0) && (string[1] != 0) && (pkth.caplen < handle->snapshot))
639 	{
640 		rawdata[0] = ascii_to_int(string[0]) * 16 + ascii_to_int(string[1]);
641 		rawdata++;
642 		string+=2;
643 		if (string[0] == ' ')
644 			string++;
645 		pkth.caplen++;
646 		data_len++;
647 	}
648 
649 got:
650 	uhdr->data_len = data_len;
651 	if (pkth.caplen > handle->snapshot)
652 		pkth.caplen = handle->snapshot;
653 
654 	if (handle->fcode.bf_insns == NULL ||
655 	    bpf_filter(handle->fcode.bf_insns, handle->buffer,
656 	      pkth.len, pkth.caplen)) {
657 		handlep->packets_read++;
658 		callback(user, &pkth, handle->buffer);
659 		return 1;
660 	}
661 	return 0;	/* didn't pass filter */
662 }
663 
664 static int
665 usb_inject_linux(pcap_t *handle, const void *buf, size_t size)
666 {
667 	snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "inject not supported on "
668 		"USB devices");
669 	return (-1);
670 }
671 
672 static int
673 usb_stats_linux(pcap_t *handle, struct pcap_stat *stats)
674 {
675 	struct pcap_usb_linux *handlep = handle->priv;
676 	int dummy, ret, consumed, cnt;
677 	char string[USB_LINE_LEN];
678 	char token[USB_LINE_LEN];
679 	char * ptr = string;
680 	int fd;
681 
682 	snprintf(string, USB_LINE_LEN, USB_TEXT_DIR"/%ds", handlep->bus_index);
683 	fd = open(string, O_RDONLY, 0);
684 	if (fd < 0)
685 	{
686 		if (errno == ENOENT)
687 		{
688 			/*
689 			 * Not found at the new location; try the old
690 			 * location.
691 			 */
692 			snprintf(string, USB_LINE_LEN, USB_TEXT_DIR_OLD"/%ds", handlep->bus_index);
693 			fd = open(string, O_RDONLY, 0);
694 		}
695 		if (fd < 0) {
696 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
697 				"Can't open USB stats file %s: %s",
698 				string, strerror(errno));
699 			return -1;
700 		}
701 	}
702 
703 	/* read stats line */
704 	do {
705 		ret = read(fd, string, USB_LINE_LEN-1);
706 	} while ((ret == -1) && (errno == EINTR));
707 	close(fd);
708 
709 	if (ret < 0)
710 	{
711 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
712 			"Can't read stats from fd %d ", fd);
713 		return -1;
714 	}
715 	string[ret] = 0;
716 
717 	/* extract info on dropped urbs */
718 	for (consumed=0; consumed < ret; ) {
719 		/* from the sscanf man page:
720  		 * The C standard says: "Execution of a %n directive does
721  		 * not increment the assignment count returned at the completion
722 		 * of  execution" but the Corrigendum seems to contradict this.
723 		 * Do not make any assumptions on the effect of %n conversions
724 		 * on the return value and explicitly check for cnt assignmet*/
725 		int ntok;
726 
727 		cnt = -1;
728 		ntok = sscanf(ptr, "%s%n", token, &cnt);
729 		if ((ntok < 1) || (cnt < 0))
730 			break;
731 		consumed += cnt;
732 		ptr += cnt;
733 		if (strcmp(token, "nreaders") == 0)
734 			ret = sscanf(ptr, "%d", &stats->ps_drop);
735 		else
736 			ret = sscanf(ptr, "%d", &dummy);
737 		if (ntok != 1)
738 			break;
739 		consumed += cnt;
740 		ptr += cnt;
741 	}
742 
743 	stats->ps_recv = handlep->packets_read;
744 	stats->ps_ifdrop = 0;
745 	return 0;
746 }
747 
748 static int
749 usb_setdirection_linux(pcap_t *p, pcap_direction_t d)
750 {
751 	p->direction = d;
752 	return 0;
753 }
754 
755 
756 static int
757 usb_stats_linux_bin(pcap_t *handle, struct pcap_stat *stats)
758 {
759 	struct pcap_usb_linux *handlep = handle->priv;
760 	int ret;
761 	struct mon_bin_stats st;
762 	ret = ioctl(handle->fd, MON_IOCG_STATS, &st);
763 	if (ret < 0)
764 	{
765 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
766 			"Can't read stats from fd %d:%s ", handle->fd, strerror(errno));
767 		return -1;
768 	}
769 
770 	stats->ps_recv = handlep->packets_read + st.queued;
771 	stats->ps_drop = st.dropped;
772 	stats->ps_ifdrop = 0;
773 	return 0;
774 }
775 
776 /*
777  * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
778  * <linux-kernel-source>/drivers/usb/mon/mon_bin.c binary ABI
779  */
780 static int
781 usb_read_linux_bin(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
782 {
783 	struct pcap_usb_linux *handlep = handle->priv;
784 	struct mon_bin_get info;
785 	int ret;
786 	struct pcap_pkthdr pkth;
787 	int clen = handle->snapshot - sizeof(pcap_usb_header);
788 
789 	/* the usb header is going to be part of 'packet' data*/
790 	info.hdr = (pcap_usb_header*) handle->buffer;
791 	info.data = handle->buffer + sizeof(pcap_usb_header);
792 	info.data_len = clen;
793 
794 	/* ignore interrupt system call errors */
795 	do {
796 		ret = ioctl(handle->fd, MON_IOCX_GET, &info);
797 		if (handle->break_loop)
798 		{
799 			handle->break_loop = 0;
800 			return -2;
801 		}
802 	} while ((ret == -1) && (errno == EINTR));
803 	if (ret < 0)
804 	{
805 		if (errno == EAGAIN)
806 			return 0;	/* no data there */
807 
808 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
809 		    "Can't read from fd %d: %s", handle->fd, strerror(errno));
810 		return -1;
811 	}
812 
813 	/* we can get less that than really captured from kernel, depending on
814 	 * snaplen, so adjust header accordingly */
815 	if (info.hdr->data_len < clen)
816 		clen = info.hdr->data_len;
817 	info.hdr->data_len = clen;
818 	pkth.caplen = clen + sizeof(pcap_usb_header);
819 	pkth.len = info.hdr->data_len + sizeof(pcap_usb_header);
820 	pkth.ts.tv_sec = info.hdr->ts_sec;
821 	pkth.ts.tv_usec = info.hdr->ts_usec;
822 
823 	if (handle->fcode.bf_insns == NULL ||
824 	    bpf_filter(handle->fcode.bf_insns, handle->buffer,
825 	      pkth.len, pkth.caplen)) {
826 		handlep->packets_read++;
827 		callback(user, &pkth, handle->buffer);
828 		return 1;
829 	}
830 
831 	return 0;	/* didn't pass filter */
832 }
833 
834 /*
835  * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
836  * <linux-kernel-source>/drivers/usb/mon/mon_bin.c binary ABI
837  */
838 #define VEC_SIZE 32
839 static int
840 usb_read_linux_mmap(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
841 {
842 	struct pcap_usb_linux *handlep = handle->priv;
843 	struct mon_bin_mfetch fetch;
844 	int32_t vec[VEC_SIZE];
845 	struct pcap_pkthdr pkth;
846 	pcap_usb_header* hdr;
847 	int nflush = 0;
848 	int packets = 0;
849 	int clen, max_clen;
850 
851 	max_clen = handle->snapshot - sizeof(pcap_usb_header);
852 
853 	for (;;) {
854 		int i, ret;
855 		int limit = max_packets - packets;
856 		if (limit <= 0)
857 			limit = VEC_SIZE;
858 		if (limit > VEC_SIZE)
859 			limit = VEC_SIZE;
860 
861 		/* try to fetch as many events as possible*/
862 		fetch.offvec = vec;
863 		fetch.nfetch = limit;
864 		fetch.nflush = nflush;
865 		/* ignore interrupt system call errors */
866 		do {
867 			ret = ioctl(handle->fd, MON_IOCX_MFETCH, &fetch);
868 			if (handle->break_loop)
869 			{
870 				handle->break_loop = 0;
871 				return -2;
872 			}
873 		} while ((ret == -1) && (errno == EINTR));
874 		if (ret < 0)
875 		{
876 			if (errno == EAGAIN)
877 				return 0;	/* no data there */
878 
879 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
880 			    "Can't mfetch fd %d: %s", handle->fd, strerror(errno));
881 			return -1;
882 		}
883 
884 		/* keep track of processed events, we will flush them later */
885 		nflush = fetch.nfetch;
886 		for (i=0; i<fetch.nfetch; ++i) {
887 			/* discard filler */
888 			hdr = (pcap_usb_header*) &handlep->mmapbuf[vec[i]];
889 			if (hdr->event_type == '@')
890 				continue;
891 
892 			/* we can get less that than really captured from kernel, depending on
893 	 		* snaplen, so adjust header accordingly */
894 			clen = max_clen;
895 			if (hdr->data_len < clen)
896 				clen = hdr->data_len;
897 
898 			/* get packet info from header*/
899 			pkth.caplen = clen + sizeof(pcap_usb_header_mmapped);
900 			pkth.len = hdr->data_len + sizeof(pcap_usb_header_mmapped);
901 			pkth.ts.tv_sec = hdr->ts_sec;
902 			pkth.ts.tv_usec = hdr->ts_usec;
903 
904 			if (handle->fcode.bf_insns == NULL ||
905 			    bpf_filter(handle->fcode.bf_insns, (u_char*) hdr,
906 			      pkth.len, pkth.caplen)) {
907 				handlep->packets_read++;
908 				callback(user, &pkth, (u_char*) hdr);
909 				packets++;
910 			}
911 		}
912 
913 		/* with max_packets <= 0 we stop afer the first chunk*/
914 		if ((max_packets <= 0) || (packets == max_packets))
915 			break;
916 	}
917 
918 	/* flush pending events*/
919 	ioctl(handle->fd, MON_IOCH_MFLUSH, nflush);
920 	return packets;
921 }
922 
923 static void
924 usb_cleanup_linux_mmap(pcap_t* handle)
925 {
926 	struct pcap_usb_linux *handlep = handle->priv;
927 
928 	/* if we have a memory-mapped buffer, unmap it */
929 	if (handlep->mmapbuf != NULL) {
930 		munmap(handlep->mmapbuf, handlep->mmapbuflen);
931 		handlep->mmapbuf = NULL;
932 	}
933 	pcap_cleanup_live_common(handle);
934 }
935