xref: /freebsd/contrib/libpcap/pcap-usb-linux.c (revision 5861f9665471e98e544f6fa3ce73c4912229ff82)
1 /*
2  * Copyright (c) 2006 Paolo Abeni (Italy)
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  *
9  * 1. Redistributions of source code must retain the above copyright
10  * notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  * notice, this list of conditions and the following disclaimer in the
13  * documentation and/or other materials provided with the distribution.
14  * 3. The name of the author may not be used to endorse or promote
15  * products derived from this software without specific prior written
16  * permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  *
30  * USB sniffing API implementation for Linux platform
31  * By Paolo Abeni <paolo.abeni@email.it>
32  * Modifications: Kris Katterjohn <katterjohn@gmail.com>
33  *
34  */
35 #ifndef lint
36 static const char rcsid[] _U_ =
37     "@(#) $Header: /tcpdump/master/libpcap/pcap-usb-linux.c,v 1.16.2.8 2008-04-14 21:06:29 guy Exp $ (LBL)";
38 #endif
39 
40 #ifdef HAVE_CONFIG_H
41 #include "config.h"
42 #endif
43 
44 #include "pcap-int.h"
45 #include "pcap-usb-linux.h"
46 #include "pcap/usb.h"
47 
48 #ifdef NEED_STRERROR_H
49 #include "strerror.h"
50 #endif
51 
52 #include <ctype.h>
53 #include <errno.h>
54 #include <stdlib.h>
55 #include <unistd.h>
56 #include <fcntl.h>
57 #include <string.h>
58 #include <dirent.h>
59 #include <byteswap.h>
60 #include <netinet/in.h>
61 #include <sys/ioctl.h>
62 #include <sys/mman.h>
63 
64 #define USB_IFACE "usb"
65 #define USB_TEXT_DIR "/sys/kernel/debug/usbmon"
66 #define USB_BUS_DIR "/proc/bus/usb"
67 #define USB_LINE_LEN 4096
68 
69 
70 #define PIPE_IN			0x80
71 #define PIPE_ISOCHRONOUS	0
72 #define PIPE_INTERRUPT		1
73 #define PIPE_CONTROL		2
74 #define PIPE_BULK		3
75 
76 #if __BYTE_ORDER == __LITTLE_ENDIAN
77 #define htols(s) s
78 #define htoll(l) l
79 #define htol64(ll) ll
80 #else
81 #define htols(s) bswap_16(s)
82 #define htoll(l) bswap_32(l)
83 #define htol64(ll) bswap_64(ll)
84 #endif
85 
86 struct mon_bin_stats {
87 	u_int32_t queued;
88 	u_int32_t dropped;
89 };
90 
91 struct mon_bin_get {
92 	pcap_usb_header *hdr;
93 	void *data;
94 	size_t data_len;   /* Length of data (can be zero) */
95 };
96 
97 struct mon_bin_mfetch {
98 	int32_t *offvec;   /* Vector of events fetched */
99 	int32_t nfetch;    /* Number of events to fetch (out: fetched) */
100 	int32_t nflush;    /* Number of events to flush */
101 };
102 
103 #define MON_IOC_MAGIC 0x92
104 
105 #define MON_IOCQ_URB_LEN _IO(MON_IOC_MAGIC, 1)
106 #define MON_IOCX_URB  _IOWR(MON_IOC_MAGIC, 2, struct mon_bin_hdr)
107 #define MON_IOCG_STATS _IOR(MON_IOC_MAGIC, 3, struct mon_bin_stats)
108 #define MON_IOCT_RING_SIZE _IO(MON_IOC_MAGIC, 4)
109 #define MON_IOCQ_RING_SIZE _IO(MON_IOC_MAGIC, 5)
110 #define MON_IOCX_GET   _IOW(MON_IOC_MAGIC, 6, struct mon_bin_get)
111 #define MON_IOCX_MFETCH _IOWR(MON_IOC_MAGIC, 7, struct mon_bin_mfetch)
112 #define MON_IOCH_MFLUSH _IO(MON_IOC_MAGIC, 8)
113 
114 #define MON_BIN_SETUP 	0x1 /* setup hdr is present*/
115 #define MON_BIN_SETUP_ZERO 	0x2 /* setup buffer is not available */
116 #define MON_BIN_DATA_ZERO 	0x4 /* data buffer is not available */
117 #define MON_BIN_ERROR 	0x8
118 
119 /* forward declaration */
120 static int usb_activate(pcap_t *);
121 static int usb_stats_linux(pcap_t *, struct pcap_stat *);
122 static int usb_stats_linux_bin(pcap_t *, struct pcap_stat *);
123 static int usb_read_linux(pcap_t *, int , pcap_handler , u_char *);
124 static int usb_read_linux_bin(pcap_t *, int , pcap_handler , u_char *);
125 static int usb_read_linux_mmap(pcap_t *, int , pcap_handler , u_char *);
126 static int usb_inject_linux(pcap_t *, const void *, size_t);
127 static int usb_setfilter_linux(pcap_t *, struct bpf_program *);
128 static int usb_setdirection_linux(pcap_t *, pcap_direction_t);
129 static void usb_cleanup_linux_mmap(pcap_t *);
130 
131 /* facility to add an USB device to the device list*/
132 static int
133 usb_dev_add(pcap_if_t** alldevsp, int n, char *err_str)
134 {
135 	char dev_name[10];
136 	char dev_descr[30];
137 	snprintf(dev_name, 10, USB_IFACE"%d", n);
138 	snprintf(dev_descr, 30, "USB bus number %d", n);
139 
140 	if (pcap_add_if(alldevsp, dev_name, 0,
141 	    dev_descr, err_str) < 0)
142 		return -1;
143 	return 0;
144 }
145 
146 int
147 usb_platform_finddevs(pcap_if_t **alldevsp, char *err_str)
148 {
149 	struct dirent* data;
150 	int ret = 0;
151 	DIR* dir;
152 
153 	/* scan procfs usb bus directory */
154 	dir = opendir(USB_BUS_DIR);
155 	if (!dir) return 0;
156 	while ((ret == 0) && ((data = readdir(dir)) != 0)) {
157 		int n;
158 		char* name = data->d_name;
159 		int len = strlen(name);
160 
161 		/* if this file name does not end with a number it's not of our interest */
162 		if ((len < 1) || !isdigit(name[--len]))
163 			continue;
164 		while (isdigit(name[--len]));
165 		if (sscanf(&name[len+1], "%d", &n) != 1)
166 			continue;
167 
168 		ret = usb_dev_add(alldevsp, n, err_str);
169 	}
170 
171 	closedir(dir);
172 	return ret;
173 }
174 
175 static
176 int usb_mmap(pcap_t* handle)
177 {
178 	int len = ioctl(handle->fd, MON_IOCQ_RING_SIZE);
179 	if (len < 0)
180 		return 0;
181 
182 	handle->buffer = mmap(0, len, PROT_READ, MAP_SHARED, handle->fd, 0);
183 	return handle->buffer != MAP_FAILED;
184 }
185 
186 pcap_t *
187 usb_create(const char *device, char *ebuf)
188 {
189 	pcap_t *p;
190 
191 	p = pcap_create_common(device, ebuf);
192 	if (p == NULL)
193 		return (NULL);
194 
195 	p->activate_op = usb_activate;
196 	return (p);
197 }
198 
199 static int
200 usb_activate(pcap_t* handle)
201 {
202 	char 		full_path[USB_LINE_LEN];
203 
204 	/* Initialize some components of the pcap structure. */
205 	handle->bufsize = handle->snapshot;
206 	handle->offset = 0;
207 	handle->linktype = DLT_USB_LINUX;
208 
209 	handle->inject_op = usb_inject_linux;
210 	handle->setfilter_op = usb_setfilter_linux;
211 	handle->setdirection_op = usb_setdirection_linux;
212 	handle->set_datalink_op = NULL;	/* can't change data link type */
213 	handle->getnonblock_op = pcap_getnonblock_fd;
214 	handle->setnonblock_op = pcap_setnonblock_fd;
215 
216 	/*get usb bus index from device name */
217 	if (sscanf(handle->opt.source, USB_IFACE"%d", &handle->md.ifindex) != 1)
218 	{
219 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
220 			"Can't get USB bus index from %s", handle->opt.source);
221 		return PCAP_ERROR;
222 	}
223 
224 	/*now select the read method: try to open binary interface */
225 	snprintf(full_path, USB_LINE_LEN, LINUX_USB_MON_DEV"%d", handle->md.ifindex);
226 	handle->fd = open(full_path, O_RDONLY, 0);
227 	if (handle->fd >= 0)
228 	{
229 		if (handle->opt.rfmon) {
230 			/*
231 			 * Monitor mode doesn't apply to USB devices.
232 			 */
233 			return PCAP_ERROR_RFMON_NOTSUP;
234 		}
235 
236 		/* binary api is available, try to use fast mmap access */
237 		if (usb_mmap(handle)) {
238 			handle->stats_op = usb_stats_linux_bin;
239 			handle->read_op = usb_read_linux_mmap;
240 			handle->cleanup_op = usb_cleanup_linux_mmap;
241 
242 			/*
243 			 * "handle->fd" is a real file, so "select()" and
244 			 * "poll()" work on it.
245 			 */
246 			handle->selectable_fd = handle->fd;
247 			return 0;
248 		}
249 
250 		/* can't mmap, use plain binary interface access */
251 		handle->stats_op = usb_stats_linux_bin;
252 		handle->read_op = usb_read_linux_bin;
253 	}
254 	else {
255 		/*Binary interface not available, try open text interface */
256 		snprintf(full_path, USB_LINE_LEN, USB_TEXT_DIR"/%dt", handle->md.ifindex);
257 		handle->fd = open(full_path, O_RDONLY, 0);
258 		if (handle->fd < 0)
259 		{
260 			/* no more fallback, give it up*/
261 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
262 				"Can't open USB bus file %s: %s", full_path, strerror(errno));
263 			return PCAP_ERROR;
264 		}
265 		handle->stats_op = usb_stats_linux;
266 		handle->read_op = usb_read_linux;
267 	}
268 
269 	if (handle->opt.rfmon) {
270 		/*
271 		 * Monitor mode doesn't apply to USB devices.
272 		 */
273 		return PCAP_ERROR_RFMON_NOTSUP;
274 	}
275 
276 	/*
277 	 * "handle->fd" is a real file, so "select()" and "poll()"
278 	 * work on it.
279 	 */
280 	handle->selectable_fd = handle->fd;
281 
282 	/* for plain binary access and text access we need to allocate the read
283 	 * buffer */
284 	handle->buffer = malloc(handle->bufsize);
285 	if (!handle->buffer) {
286 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
287 			 "malloc: %s", pcap_strerror(errno));
288 		return PCAP_ERROR;
289 	}
290 	return 0;
291 }
292 
293 static inline int
294 ascii_to_int(char c)
295 {
296 	return c < 'A' ? c- '0': ((c<'a') ? c - 'A' + 10: c-'a'+10);
297 }
298 
299 /*
300  * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
301  * <linux-kernel-source>/drivers/usb/mon/mon_text.c for urb string
302  * format description
303  */
304 static int
305 usb_read_linux(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
306 {
307 	/* see:
308 	* /usr/src/linux/Documentation/usb/usbmon.txt
309 	* for message format
310 	*/
311 	unsigned timestamp;
312 	int tag, cnt, ep_num, dev_addr, dummy, ret, urb_len, data_len;
313 	char etype, pipeid1, pipeid2, status[16], urb_tag, line[USB_LINE_LEN];
314 	char *string = line;
315 	u_char * rawdata = handle->buffer;
316 	struct pcap_pkthdr pkth;
317 	pcap_usb_header* uhdr = (pcap_usb_header*)handle->buffer;
318 	u_char urb_transfer=0;
319 	int incoming=0;
320 
321 	/* ignore interrupt system call errors */
322 	do {
323 		ret = read(handle->fd, line, USB_LINE_LEN - 1);
324 		if (handle->break_loop)
325 		{
326 			handle->break_loop = 0;
327 			return -2;
328 		}
329 	} while ((ret == -1) && (errno == EINTR));
330 	if (ret < 0)
331 	{
332 		if (errno == EAGAIN)
333 			return 0;	/* no data there */
334 
335 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
336 		    "Can't read from fd %d: %s", handle->fd, strerror(errno));
337 		return -1;
338 	}
339 
340 	/* read urb header; %n argument may increment return value, but it's
341 	* not mandatory, so does not count on it*/
342 	string[ret] = 0;
343 	ret = sscanf(string, "%x %d %c %c%c:%d:%d %s%n", &tag, &timestamp, &etype,
344 		&pipeid1, &pipeid2, &dev_addr, &ep_num, status,
345 		&cnt);
346 	if (ret < 8)
347 	{
348 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
349 		    "Can't parse USB bus message '%s', too few tokens (expected 8 got %d)",
350 		    string, ret);
351 		return -1;
352 	}
353 	uhdr->id = tag;
354 	uhdr->endpoint_number = ep_num;
355 	uhdr->device_address = dev_addr;
356 	uhdr->bus_id = handle->md.ifindex;
357 	uhdr->status = 0;
358 	string += cnt;
359 
360 	/* don't use usbmon provided timestamp, since it have low precision*/
361 	if (gettimeofday(&pkth.ts, NULL) < 0)
362 	{
363 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
364 			"Can't get timestamp for message '%s' %d:%s",
365 			string, errno, strerror(errno));
366 		return -1;
367 	}
368 	uhdr->ts_sec = pkth.ts.tv_sec;
369 	uhdr->ts_usec = pkth.ts.tv_usec;
370 
371 	/* parse endpoint information */
372 	if (pipeid1 == 'C')
373 		urb_transfer = URB_CONTROL;
374 	else if (pipeid1 == 'Z')
375 		urb_transfer = URB_ISOCHRONOUS;
376 	else if (pipeid1 == 'I')
377 		urb_transfer = URB_INTERRUPT;
378 	else if (pipeid1 == 'B')
379 		urb_transfer = URB_BULK;
380 	if (pipeid2 == 'i') {
381 		urb_transfer |= URB_TRANSFER_IN;
382 		incoming = 1;
383 	}
384 	if (etype == 'C')
385 		incoming = !incoming;
386 
387 	/* direction check*/
388 	if (incoming)
389 	{
390 		if (handle->direction == PCAP_D_OUT)
391 			return 0;
392 	}
393 	else
394 		if (handle->direction == PCAP_D_IN)
395 			return 0;
396 	uhdr->event_type = etype;
397 	uhdr->transfer_type = urb_transfer;
398 	pkth.caplen = sizeof(pcap_usb_header);
399 	rawdata += sizeof(pcap_usb_header);
400 
401 	/* check if this is a setup packet */
402 	ret = sscanf(status, "%d", &dummy);
403 	if (ret != 1)
404 	{
405 		/* this a setup packet, setup data can be filled with underscore if
406 		* usbmon has not been able to read them, so we must parse this fields as
407 		* strings */
408 		pcap_usb_setup* shdr;
409 		char str1[3], str2[3], str3[5], str4[5], str5[5];
410 		ret = sscanf(string, "%s %s %s %s %s%n", str1, str2, str3, str4,
411 		str5, &cnt);
412 		if (ret < 5)
413 		{
414 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
415 				"Can't parse USB bus message '%s', too few tokens (expected 5 got %d)",
416 				string, ret);
417 			return -1;
418 		}
419 		string += cnt;
420 
421 		/* try to convert to corresponding integer */
422 		shdr = &uhdr->setup;
423 		shdr->bmRequestType = strtoul(str1, 0, 16);
424 		shdr->bRequest = strtoul(str2, 0, 16);
425 		shdr->wValue = htols(strtoul(str3, 0, 16));
426 		shdr->wIndex = htols(strtoul(str4, 0, 16));
427 		shdr->wLength = htols(strtoul(str5, 0, 16));
428 
429 		uhdr->setup_flag = 0;
430 	}
431 	else
432 		uhdr->setup_flag = 1;
433 
434 	/* read urb data */
435 	ret = sscanf(string, " %d%n", &urb_len, &cnt);
436 	if (ret < 1)
437 	{
438 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
439 		  "Can't parse urb length from '%s'", string);
440 		return -1;
441 	}
442 	string += cnt;
443 
444 	/* urb tag is not present if urb length is 0, so we can stop here
445 	 * text parsing */
446 	pkth.len = urb_len+pkth.caplen;
447 	uhdr->urb_len = urb_len;
448 	uhdr->data_flag = 1;
449 	data_len = 0;
450 	if (uhdr->urb_len == pkth.caplen)
451 		goto got;
452 
453 	/* check for data presence; data is present if and only if urb tag is '=' */
454 	if (sscanf(string, " %c", &urb_tag) != 1)
455 	{
456 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
457 			"Can't parse urb tag from '%s'", string);
458 		return -1;
459 	}
460 
461 	if (urb_tag != '=')
462 		goto got;
463 
464 	/* skip urb tag and following space */
465 	string += 3;
466 
467 	/* if we reach this point we got some urb data*/
468 	uhdr->data_flag = 0;
469 
470 	/* read all urb data; if urb length is greater then the usbmon internal
471 	 * buffer length used by the kernel to spool the URB, we get only
472 	 * a partial information.
473 	 * At least until linux 2.6.17 there is no way to set usbmon intenal buffer
474 	 * length and default value is 130. */
475 	while ((string[0] != 0) && (string[1] != 0) && (pkth.caplen < handle->snapshot))
476 	{
477 		rawdata[0] = ascii_to_int(string[0]) * 16 + ascii_to_int(string[1]);
478 		rawdata++;
479 		string+=2;
480 		if (string[0] == ' ')
481 			string++;
482 		pkth.caplen++;
483 		data_len++;
484 	}
485 
486 got:
487 	uhdr->data_len = data_len;
488 	handle->md.packets_read++;
489 	if (pkth.caplen > handle->snapshot)
490 		pkth.caplen = handle->snapshot;
491 
492 	callback(user, &pkth, handle->buffer);
493 	return 1;
494 }
495 
496 static int
497 usb_inject_linux(pcap_t *handle, const void *buf, size_t size)
498 {
499 	snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "inject not supported on "
500 		"USB devices");
501 	return (-1);
502 }
503 
504 static int
505 usb_stats_linux(pcap_t *handle, struct pcap_stat *stats)
506 {
507 	int dummy, ret, consumed, cnt;
508 	char string[USB_LINE_LEN];
509 	char token[USB_LINE_LEN];
510 	char * ptr = string;
511 	snprintf(string, USB_LINE_LEN, USB_TEXT_DIR"/%ds", handle->md.ifindex);
512 
513 	int fd = open(string, O_RDONLY, 0);
514 	if (fd < 0)
515 	{
516 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
517 			"Can't open USB stats file %s: %s",
518 			string, strerror(errno));
519 		return -1;
520 	}
521 
522 	/* read stats line */
523 	do {
524 		ret = read(fd, string, USB_LINE_LEN-1);
525 	} while ((ret == -1) && (errno == EINTR));
526 	close(fd);
527 
528 	if (ret < 0)
529 	{
530 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
531 			"Can't read stats from fd %d ", fd);
532 		return -1;
533 	}
534 	string[ret] = 0;
535 
536 	/* extract info on dropped urbs */
537 	for (consumed=0; consumed < ret; ) {
538 		/* from the sscanf man page:
539  		 * The C standard says: "Execution of a %n directive does
540  		 * not increment the assignment count returned at the completion
541 		 * of  execution" but the Corrigendum seems to contradict this.
542 		 * Do not make any assumptions on the effect of %n conversions
543 		 * on the return value and explicitly check for cnt assignmet*/
544 		cnt = -1;
545 		int ntok = sscanf(ptr, "%s%n", token, &cnt);
546 		if ((ntok < 1) || (cnt < 0))
547 			break;
548 		consumed += cnt;
549 		ptr += cnt;
550 		if (strcmp(token, "nreaders") == 0)
551 			ret = sscanf(ptr, "%d", &stats->ps_drop);
552 		else
553 			ret = sscanf(ptr, "%d", &dummy);
554 		if (ntok != 1)
555 			break;
556 		consumed += cnt;
557 		ptr += cnt;
558 	}
559 
560 	stats->ps_recv = handle->md.packets_read;
561 	stats->ps_ifdrop = 0;
562 	return 0;
563 }
564 
565 static int
566 usb_setfilter_linux(pcap_t *p, struct bpf_program *fp)
567 {
568 	return 0;
569 }
570 
571 static int
572 usb_setdirection_linux(pcap_t *p, pcap_direction_t d)
573 {
574 	p->direction = d;
575 	return 0;
576 }
577 
578 
579 static int
580 usb_stats_linux_bin(pcap_t *handle, struct pcap_stat *stats)
581 {
582 	int ret;
583 	struct mon_bin_stats st;
584 	ret = ioctl(handle->fd, MON_IOCG_STATS, &st);
585 	if (ret < 0)
586 	{
587 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
588 			"Can't read stats from fd %d:%s ", handle->fd, strerror(errno));
589 		return -1;
590 	}
591 
592 	stats->ps_recv = handle->md.packets_read + st.queued;
593 	stats->ps_ifdrop = st.dropped;
594 	return 0;
595 }
596 
597 /*
598  * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
599  * <linux-kernel-source>/drivers/usb/mon/mon_bin.c binary ABI
600  */
601 static int
602 usb_read_linux_bin(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
603 {
604 	struct mon_bin_get info;
605 	int ret;
606 	struct pcap_pkthdr pkth;
607 	int clen = handle->snapshot - sizeof(pcap_usb_header);
608 
609 	/* the usb header is going to be part of 'packet' data*/
610 	info.hdr = (pcap_usb_header*) handle->buffer;
611 	info.data = handle->buffer + sizeof(pcap_usb_header);
612 	info.data_len = clen;
613 
614 	/* ignore interrupt system call errors */
615 	do {
616 		ret = ioctl(handle->fd, MON_IOCX_GET, &info);
617 		if (handle->break_loop)
618 		{
619 			handle->break_loop = 0;
620 			return -2;
621 		}
622 	} while ((ret == -1) && (errno == EINTR));
623 	if (ret < 0)
624 	{
625 		if (errno == EAGAIN)
626 			return 0;	/* no data there */
627 
628 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
629 		    "Can't read from fd %d: %s", handle->fd, strerror(errno));
630 		return -1;
631 	}
632 
633 	/* we can get less that than really captured from kernel, depending on
634 	 * snaplen, so adjust header accordingly */
635 	if (info.hdr->data_len < clen)
636 		clen = info.hdr->data_len;
637 	info.hdr->data_len = clen;
638 	pkth.caplen = clen + sizeof(pcap_usb_header);
639 	pkth.len = info.hdr->urb_len + sizeof(pcap_usb_header);
640 	pkth.ts.tv_sec = info.hdr->ts_sec;
641 	pkth.ts.tv_usec = info.hdr->ts_usec;
642 
643 	handle->md.packets_read++;
644 	callback(user, &pkth, handle->buffer);
645 	return 1;
646 }
647 
648 /*
649  * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
650  * <linux-kernel-source>/drivers/usb/mon/mon_bin.c binary ABI
651  */
652 #define VEC_SIZE 32
653 static int
654 usb_read_linux_mmap(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
655 {
656 	struct mon_bin_mfetch fetch;
657 	int32_t vec[VEC_SIZE];
658 	struct pcap_pkthdr pkth;
659 	pcap_usb_header* hdr;
660 	int nflush = 0;
661 	int packets = 0;
662 
663 	for (;;) {
664 		int i, ret;
665 		int limit = max_packets - packets;
666 		if (limit <= 0)
667 			limit = VEC_SIZE;
668 		if (limit > VEC_SIZE)
669 			limit = VEC_SIZE;
670 
671 		/* try to fetch as many events as possible*/
672 		fetch.offvec = vec;
673 		fetch.nfetch = limit;
674 		fetch.nflush = nflush;
675 		/* ignore interrupt system call errors */
676 		do {
677 			ret = ioctl(handle->fd, MON_IOCX_MFETCH, &fetch);
678 			if (handle->break_loop)
679 			{
680 				handle->break_loop = 0;
681 				return -2;
682 			}
683 		} while ((ret == -1) && (errno == EINTR));
684 		if (ret < 0)
685 		{
686 			if (errno == EAGAIN)
687 				return 0;	/* no data there */
688 
689 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
690 			    "Can't mfetch fd %d: %s", handle->fd, strerror(errno));
691 			return -1;
692 		}
693 
694 		/* keep track of processed events, we will flush them later */
695 		nflush = fetch.nfetch;
696 		for (i=0; i<fetch.nfetch; ++i) {
697 			/* discard filler */
698 			hdr = (pcap_usb_header*) &handle->buffer[vec[i]];
699 			if (hdr->event_type == '@')
700 				continue;
701 
702 			/* get packet info from header*/
703 			pkth.caplen = hdr->data_len + sizeof(pcap_usb_header);
704 			pkth.len = hdr->urb_len + sizeof(pcap_usb_header);
705 			pkth.ts.tv_sec = hdr->ts_sec;
706 			pkth.ts.tv_usec = hdr->ts_usec;
707 
708 			handle->md.packets_read++;
709 			callback(user, &pkth, (u_char*) hdr);
710 			packets++;
711 		}
712 
713 		/* with max_packets <= 0 we stop afer the first chunk*/
714 		if ((max_packets <= 0) || (packets == max_packets))
715 			break;
716 	}
717 
718 	/* flush pending events*/
719 	ioctl(handle->fd, MON_IOCH_MFLUSH, nflush);
720 	return packets;
721 }
722 
723 static void
724 usb_cleanup_linux_mmap(pcap_t* handle)
725 {
726 	/* buffer must not be freed because it's memory mapped */
727 	/* XXX - does it need to be unmapped? */
728 	handle->buffer = NULL;
729 	pcap_cleanup_live_common(handle);
730 }
731