xref: /freebsd/contrib/libpcap/pcap-usb-linux.c (revision 22d7dd834bc5cd189810e414701e3ad1e98102e4)
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 
36 #ifdef HAVE_CONFIG_H
37 #include <config.h>
38 #endif
39 
40 #include "pcap-int.h"
41 #include "pcap-usb-linux.h"
42 #include "pcap-usb-linux-common.h"
43 #include "pcap/usb.h"
44 
45 #include "extract.h"
46 
47 #ifdef NEED_STRERROR_H
48 #include "strerror.h"
49 #endif
50 
51 #include <errno.h>
52 #include <stdlib.h>
53 #include <unistd.h>
54 #include <fcntl.h>
55 #include <limits.h>
56 #include <string.h>
57 #include <dirent.h>
58 #include <byteswap.h>
59 #include <netinet/in.h>
60 #include <sys/ioctl.h>
61 #include <sys/mman.h>
62 #include <sys/utsname.h>
63 #ifdef HAVE_LINUX_USBDEVICE_FS_H
64 /*
65  * We might need <linux/compiler.h> to define __user for
66  * <linux/usbdevice_fs.h>.
67  */
68 #ifdef HAVE_LINUX_COMPILER_H
69 #include <linux/compiler.h>
70 #endif /* HAVE_LINUX_COMPILER_H */
71 #include <linux/usbdevice_fs.h>
72 #endif /* HAVE_LINUX_USBDEVICE_FS_H */
73 
74 #include "diag-control.h"
75 
76 #define USB_IFACE "usbmon"
77 
78 #define USBMON_DEV_PREFIX "usbmon"
79 #define USBMON_DEV_PREFIX_LEN	(sizeof USBMON_DEV_PREFIX - 1)
80 #define USB_LINE_LEN 4096
81 
82 #if __BYTE_ORDER == __LITTLE_ENDIAN
83 #define htols(s) s
84 #define htoll(l) l
85 #define htol64(ll) ll
86 #else
87 #define htols(s) bswap_16(s)
88 #define htoll(l) bswap_32(l)
89 #define htol64(ll) bswap_64(ll)
90 #endif
91 
92 struct mon_bin_stats {
93 	uint32_t queued;
94 	uint32_t dropped;
95 };
96 
97 struct mon_bin_get {
98 	pcap_usb_header *hdr;
99 	void *data;
100 	size_t data_len;   /* Length of data (can be zero) */
101 };
102 
103 struct mon_bin_mfetch {
104 	int32_t *offvec;   /* Vector of events fetched */
105 	int32_t nfetch;    /* Number of events to fetch (out: fetched) */
106 	int32_t nflush;    /* Number of events to flush */
107 };
108 
109 #define MON_IOC_MAGIC 0x92
110 
111 #define MON_IOCQ_URB_LEN _IO(MON_IOC_MAGIC, 1)
112 #define MON_IOCX_URB  _IOWR(MON_IOC_MAGIC, 2, struct mon_bin_hdr)
113 #define MON_IOCG_STATS _IOR(MON_IOC_MAGIC, 3, struct mon_bin_stats)
114 #define MON_IOCT_RING_SIZE _IO(MON_IOC_MAGIC, 4)
115 #define MON_IOCQ_RING_SIZE _IO(MON_IOC_MAGIC, 5)
116 #define MON_IOCX_GET   _IOW(MON_IOC_MAGIC, 6, struct mon_bin_get)
117 #define MON_IOCX_MFETCH _IOWR(MON_IOC_MAGIC, 7, struct mon_bin_mfetch)
118 #define MON_IOCH_MFLUSH _IO(MON_IOC_MAGIC, 8)
119 
120 #define MON_BIN_SETUP	0x1 /* setup hdr is present*/
121 #define MON_BIN_SETUP_ZERO	0x2 /* setup buffer is not available */
122 #define MON_BIN_DATA_ZERO	0x4 /* data buffer is not available */
123 #define MON_BIN_ERROR	0x8
124 
125 /*
126  * Private data for capturing on Linux USB.
127  */
128 struct pcap_usb_linux {
129 	u_char *mmapbuf;	/* memory-mapped region pointer */
130 	size_t mmapbuflen;	/* size of region */
131 	int bus_index;
132 	u_int packets_read;
133 };
134 
135 /* forward declaration */
136 static int usb_activate(pcap_t *);
137 static int usb_stats_linux_bin(pcap_t *, struct pcap_stat *);
138 static int usb_read_linux_bin(pcap_t *, int , pcap_handler , u_char *);
139 static int usb_read_linux_mmap(pcap_t *, int , pcap_handler , u_char *);
140 static int usb_inject_linux(pcap_t *, const void *, int);
141 static int usb_setdirection_linux(pcap_t *, pcap_direction_t);
142 static void usb_cleanup_linux_mmap(pcap_t *);
143 
144 /* facility to add an USB device to the device list*/
145 static int
146 usb_dev_add(pcap_if_list_t *devlistp, int n, char *err_str)
147 {
148 	char dev_name[10];
149 	char dev_descr[30];
150 	snprintf(dev_name, 10, USB_IFACE"%d", n);
151 	/*
152 	 * XXX - is there any notion of "up" and "running"?
153 	 */
154 	if (n == 0) {
155 		/*
156 		 * As this refers to all buses, there's no notion of
157 		 * "connected" vs. "disconnected", as that's a property
158 		 * that would apply to a particular USB interface.
159 		 */
160 		if (add_dev(devlistp, dev_name,
161 		    PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE,
162 		    "Raw USB traffic, all USB buses", err_str) == NULL)
163 			return -1;
164 	} else {
165 		/*
166 		 * XXX - is there a way to determine whether anything's
167 		 * plugged into this bus interface or not, and set
168 		 * PCAP_IF_CONNECTION_STATUS_CONNECTED or
169 		 * PCAP_IF_CONNECTION_STATUS_DISCONNECTED?
170 		 */
171 		snprintf(dev_descr, 30, "Raw USB traffic, bus number %d", n);
172 		if (add_dev(devlistp, dev_name, 0, dev_descr, err_str) == NULL)
173 			return -1;
174 	}
175 
176 	return 0;
177 }
178 
179 int
180 usb_findalldevs(pcap_if_list_t *devlistp, char *err_str)
181 {
182 	struct dirent* data;
183 	int ret = 0;
184 	DIR* dir;
185 	int n;
186 	char* name;
187 
188 	/*
189 	 * We require 2.6.27 or later kernels, so we have binary-mode support.
190 	 * The devices are of the form /dev/usbmon{N}.
191 	 * Open /dev and scan it.
192 	 */
193 	dir = opendir("/dev");
194 	if (dir != NULL) {
195 		while ((ret == 0) && ((data = readdir(dir)) != 0)) {
196 			name = data->d_name;
197 
198 			/*
199 			 * Is this a usbmon device?
200 			 */
201 			if (strncmp(name, USBMON_DEV_PREFIX,
202 			    USBMON_DEV_PREFIX_LEN) != 0)
203 				continue;	/* no */
204 
205 			/*
206 			 * What's the device number?
207 			 */
208 			if (sscanf(&name[USBMON_DEV_PREFIX_LEN], "%d", &n) == 0)
209 				continue;	/* failed */
210 
211 			ret = usb_dev_add(devlistp, n, err_str);
212 		}
213 
214 		closedir(dir);
215 	}
216 	return 0;
217 }
218 
219 /*
220  * Matches what's in mon_bin.c in the Linux kernel.
221  */
222 #define MIN_RING_SIZE	(8*1024)
223 #define MAX_RING_SIZE	(1200*1024)
224 
225 static int
226 usb_set_ring_size(pcap_t* handle, int header_size)
227 {
228 	/*
229 	 * A packet from binary usbmon has:
230 	 *
231 	 *  1) a fixed-length header, of size header_size;
232 	 *  2) descriptors, for isochronous transfers;
233 	 *  3) the payload.
234 	 *
235 	 * The kernel buffer has a size, defaulting to 300KB, with a
236 	 * minimum of 8KB and a maximum of 1200KB.  The size is set with
237 	 * the MON_IOCT_RING_SIZE ioctl; the size passed in is rounded up
238 	 * to a page size.
239 	 *
240 	 * No more than {buffer size}/5 bytes worth of payload is saved.
241 	 * Therefore, if we subtract the fixed-length size from the
242 	 * snapshot length, we have the biggest payload we want (we
243 	 * don't worry about the descriptors - if we have descriptors,
244 	 * we'll just discard the last bit of the payload to get it
245 	 * to fit).  We multiply that result by 5 and set the buffer
246 	 * size to that value.
247 	 */
248 	int ring_size;
249 
250 	if (handle->snapshot < header_size)
251 		handle->snapshot = header_size;
252 	/* The maximum snapshot size is small enough that this won't overflow */
253 	ring_size = (handle->snapshot - header_size) * 5;
254 
255 	/*
256 	 * Will this get an error?
257 	 * (There's no wqy to query the minimum or maximum, so we just
258 	 * copy the value from the kernel source.  We don't round it
259 	 * up to a multiple of the page size.)
260 	 */
261 	if (ring_size > MAX_RING_SIZE) {
262 		/*
263 		 * Yes.  Lower the ring size to the maximum, and set the
264 		 * snapshot length to the value that would give us a
265 		 * maximum-size ring.
266 		 */
267 		ring_size = MAX_RING_SIZE;
268 		handle->snapshot = header_size + (MAX_RING_SIZE/5);
269 	} else if (ring_size < MIN_RING_SIZE) {
270 		/*
271 		 * Yes.  Raise the ring size to the minimum, but leave
272 		 * the snapshot length unchanged, so we show the
273 		 * callback no more data than specified by the
274 		 * snapshot length.
275 		 */
276 		ring_size = MIN_RING_SIZE;
277 	}
278 
279 	if (ioctl(handle->fd, MON_IOCT_RING_SIZE, ring_size) == -1) {
280 		pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
281 		    errno, "Can't set ring size from fd %d", handle->fd);
282 		return -1;
283 	}
284 	return ring_size;
285 }
286 
287 static
288 int usb_mmap(pcap_t* handle)
289 {
290 	struct pcap_usb_linux *handlep = handle->priv;
291 	int len;
292 
293 	/*
294 	 * Attempt to set the ring size as appropriate for the snapshot
295 	 * length, reducing the snapshot length if that'd make the ring
296 	 * bigger than the kernel supports.
297 	 */
298 	len = usb_set_ring_size(handle, (int)sizeof(pcap_usb_header_mmapped));
299 	if (len == -1) {
300 		/* Failed.  Fall back on non-memory-mapped access. */
301 		return 0;
302 	}
303 
304 	handlep->mmapbuflen = len;
305 	handlep->mmapbuf = mmap(0, handlep->mmapbuflen, PROT_READ,
306 	    MAP_SHARED, handle->fd, 0);
307 	if (handlep->mmapbuf == MAP_FAILED) {
308 		/*
309 		 * Failed.  We don't treat that as a fatal error, we
310 		 * just try to fall back on non-memory-mapped access.
311 		 */
312 		return 0;
313 	}
314 	return 1;
315 }
316 
317 #ifdef HAVE_LINUX_USBDEVICE_FS_H
318 
319 #define CTRL_TIMEOUT    (5*1000)        /* milliseconds */
320 
321 #define USB_DIR_IN		0x80
322 #define USB_TYPE_STANDARD	0x00
323 #define USB_RECIP_DEVICE	0x00
324 
325 #define USB_REQ_GET_DESCRIPTOR	6
326 
327 #define USB_DT_DEVICE		1
328 #define USB_DT_CONFIG		2
329 
330 #define USB_DEVICE_DESCRIPTOR_SIZE	18
331 #define USB_CONFIG_DESCRIPTOR_SIZE	9
332 
333 /* probe the descriptors of the devices attached to the bus */
334 /* the descriptors will end up in the captured packet stream */
335 /* and be decoded by external apps like wireshark */
336 /* without these identifying probes packet data can't be fully decoded */
337 static void
338 probe_devices(int bus)
339 {
340 	struct usbdevfs_ctrltransfer ctrl;
341 	struct dirent* data;
342 	int ret = 0;
343 	char busdevpath[sizeof("/dev/bus/usb/000/") + NAME_MAX];
344 	DIR* dir;
345 	uint8_t descriptor[USB_DEVICE_DESCRIPTOR_SIZE];
346 	uint8_t configdesc[USB_CONFIG_DESCRIPTOR_SIZE];
347 
348 	/* scan usb bus directories for device nodes */
349 	snprintf(busdevpath, sizeof(busdevpath), "/dev/bus/usb/%03d", bus);
350 	dir = opendir(busdevpath);
351 	if (!dir)
352 		return;
353 
354 	while ((ret >= 0) && ((data = readdir(dir)) != 0)) {
355 		int fd;
356 		char* name = data->d_name;
357 
358 		if (name[0] == '.')
359 			continue;
360 
361 		snprintf(busdevpath, sizeof(busdevpath), "/dev/bus/usb/%03d/%s", bus, data->d_name);
362 
363 		fd = open(busdevpath, O_RDWR);
364 		if (fd == -1)
365 			continue;
366 
367 		/*
368 		 * Sigh.  Different kernels have different member names
369 		 * for this structure.
370 		 */
371 #ifdef HAVE_STRUCT_USBDEVFS_CTRLTRANSFER_BREQUESTTYPE
372 		ctrl.bRequestType = USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE;
373 		ctrl.bRequest = USB_REQ_GET_DESCRIPTOR;
374 		ctrl.wValue = USB_DT_DEVICE << 8;
375 		ctrl.wIndex = 0;
376 		ctrl.wLength = sizeof(descriptor);
377 #else
378 		ctrl.requesttype = USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE;
379 		ctrl.request = USB_REQ_GET_DESCRIPTOR;
380 		ctrl.value = USB_DT_DEVICE << 8;
381 		ctrl.index = 0;
382 		ctrl.length = sizeof(descriptor);
383 #endif
384 		ctrl.data = descriptor;
385 		ctrl.timeout = CTRL_TIMEOUT;
386 
387 		ret = ioctl(fd, USBDEVFS_CONTROL, &ctrl);
388 
389 		/* Request CONFIGURATION descriptor alone to know wTotalLength */
390 #ifdef HAVE_STRUCT_USBDEVFS_CTRLTRANSFER_BREQUESTTYPE
391 		ctrl.wValue = USB_DT_CONFIG << 8;
392 		ctrl.wLength = sizeof(configdesc);
393 #else
394 		ctrl.value = USB_DT_CONFIG << 8;
395 		ctrl.length = sizeof(configdesc);
396 #endif
397 		ctrl.data = configdesc;
398 		ret = ioctl(fd, USBDEVFS_CONTROL, &ctrl);
399 		if (ret >= 0) {
400 			uint16_t wtotallength;
401 			wtotallength = EXTRACT_LE_U_2(&configdesc[2]);
402 #ifdef HAVE_STRUCT_USBDEVFS_CTRLTRANSFER_BREQUESTTYPE
403 			ctrl.wLength = wtotallength;
404 #else
405 			ctrl.length = wtotallength;
406 #endif
407 			ctrl.data = malloc(wtotallength);
408 			if (ctrl.data) {
409 				ret = ioctl(fd, USBDEVFS_CONTROL, &ctrl);
410 				free(ctrl.data);
411 			}
412 		}
413 		close(fd);
414 	}
415 	closedir(dir);
416 }
417 #endif /* HAVE_LINUX_USBDEVICE_FS_H */
418 
419 pcap_t *
420 usb_create(const char *device, char *ebuf, int *is_ours)
421 {
422 	const char *cp;
423 	char *cpend;
424 	long devnum;
425 	pcap_t *p;
426 
427 	/* Does this look like a USB monitoring device? */
428 	cp = strrchr(device, '/');
429 	if (cp == NULL)
430 		cp = device;
431 	/* Does it begin with USB_IFACE? */
432 	if (strncmp(cp, USB_IFACE, sizeof USB_IFACE - 1) != 0) {
433 		/* Nope, doesn't begin with USB_IFACE */
434 		*is_ours = 0;
435 		return NULL;
436 	}
437 	/* Yes - is USB_IFACE followed by a number? */
438 	cp += sizeof USB_IFACE - 1;
439 	devnum = strtol(cp, &cpend, 10);
440 	if (cpend == cp || *cpend != '\0') {
441 		/* Not followed by a number. */
442 		*is_ours = 0;
443 		return NULL;
444 	}
445 	if (devnum < 0) {
446 		/* Followed by a non-valid number. */
447 		*is_ours = 0;
448 		return NULL;
449 	}
450 
451 	/* OK, it's probably ours. */
452 	*is_ours = 1;
453 
454 	p = PCAP_CREATE_COMMON(ebuf, struct pcap_usb_linux);
455 	if (p == NULL)
456 		return (NULL);
457 
458 	p->activate_op = usb_activate;
459 	return (p);
460 }
461 
462 static int
463 usb_activate(pcap_t* handle)
464 {
465 	struct pcap_usb_linux *handlep = handle->priv;
466 	char		full_path[USB_LINE_LEN];
467 
468 	/*
469 	 * Turn a negative snapshot value (invalid), a snapshot value of
470 	 * 0 (unspecified), or a value bigger than the normal maximum
471 	 * value, into the maximum allowed value.
472 	 *
473 	 * If some application really *needs* a bigger snapshot
474 	 * length, we should just increase MAXIMUM_SNAPLEN.
475 	 */
476 	if (handle->snapshot <= 0 || handle->snapshot > MAXIMUM_SNAPLEN)
477 		handle->snapshot = MAXIMUM_SNAPLEN;
478 
479 	/* Initialize some components of the pcap structure. */
480 	handle->bufsize = handle->snapshot;
481 	handle->offset = 0;
482 	handle->linktype = DLT_USB_LINUX;
483 
484 	handle->inject_op = usb_inject_linux;
485 	handle->setfilter_op = install_bpf_program; /* no kernel filtering */
486 	handle->setdirection_op = usb_setdirection_linux;
487 	handle->set_datalink_op = NULL;	/* can't change data link type */
488 	handle->getnonblock_op = pcap_getnonblock_fd;
489 	handle->setnonblock_op = pcap_setnonblock_fd;
490 
491 	/*get usb bus index from device name */
492 	if (sscanf(handle->opt.device, USB_IFACE"%d", &handlep->bus_index) != 1)
493 	{
494 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
495 			"Can't get USB bus index from %s", handle->opt.device);
496 		return PCAP_ERROR;
497 	}
498 
499 	/*
500 	 * We require 2.6.27 or later kernels, so we have binary-mode support.
501 	 * Try to open the binary interface.
502 	 */
503 	snprintf(full_path, USB_LINE_LEN, "/dev/"USBMON_DEV_PREFIX"%d",
504 	    handlep->bus_index);
505 	handle->fd = open(full_path, O_RDONLY, 0);
506 	if (handle->fd < 0)
507 	{
508 		/*
509 		 * The attempt failed; why?
510 		 */
511 		switch (errno) {
512 
513 		case ENOENT:
514 			/*
515 			 * The device doesn't exist.
516 			 * That could either mean that there's
517 			 * no support for monitoring USB buses
518 			 * (which probably means "the usbmon
519 			 * module isn't loaded") or that there
520 			 * is but that *particular* device
521 			 * doesn't exist (no "scan all buses"
522 			 * device if the bus index is 0, no
523 			 * such bus if the bus index isn't 0).
524 			 *
525 			 * For now, don't provide an error message;
526 			 * if we can determine what the particular
527 			 * problem is, we should report that.
528 			 */
529 			handle->errbuf[0] = '\0';
530 			return PCAP_ERROR_NO_SUCH_DEVICE;
531 
532 		case EACCES:
533 			/*
534 			 * We didn't have permission to open it.
535 			 */
536 DIAG_OFF_FORMAT_TRUNCATION
537 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
538 			    "Attempt to open %s failed with EACCES - root privileges may be required",
539 			    full_path);
540 DIAG_ON_FORMAT_TRUNCATION
541 			return PCAP_ERROR_PERM_DENIED;
542 
543 		default:
544 			/*
545 			 * Something went wrong.
546 			 */
547 			pcap_fmt_errmsg_for_errno(handle->errbuf,
548 			    PCAP_ERRBUF_SIZE, errno,
549 			    "Can't open USB bus file %s", full_path);
550 			return PCAP_ERROR;
551 		}
552 	}
553 
554 	if (handle->opt.rfmon)
555 	{
556 		/*
557 		 * Monitor mode doesn't apply to USB devices.
558 		 */
559 		close(handle->fd);
560 		return PCAP_ERROR_RFMON_NOTSUP;
561 	}
562 
563 	/* try to use fast mmap access */
564 	if (usb_mmap(handle))
565 	{
566 		/* We succeeded. */
567 		handle->linktype = DLT_USB_LINUX_MMAPPED;
568 		handle->stats_op = usb_stats_linux_bin;
569 		handle->read_op = usb_read_linux_mmap;
570 		handle->cleanup_op = usb_cleanup_linux_mmap;
571 #ifdef HAVE_LINUX_USBDEVICE_FS_H
572 		probe_devices(handlep->bus_index);
573 #endif
574 
575 		/*
576 		 * "handle->fd" is a real file, so
577 		 * "select()" and "poll()" work on it.
578 		 */
579 		handle->selectable_fd = handle->fd;
580 		return 0;
581 	}
582 
583 	/*
584 	 * We failed; try plain binary interface access.
585 	 *
586 	 * Attempt to set the ring size as appropriate for
587 	 * the snapshot length, reducing the snapshot length
588 	 * if that'd make the ring bigger than the kernel
589 	 * supports.
590 	 */
591 	if (usb_set_ring_size(handle, (int)sizeof(pcap_usb_header)) == -1) {
592 		/* Failed. */
593 		close(handle->fd);
594 		return PCAP_ERROR;
595 	}
596 	handle->stats_op = usb_stats_linux_bin;
597 	handle->read_op = usb_read_linux_bin;
598 #ifdef HAVE_LINUX_USBDEVICE_FS_H
599 	probe_devices(handlep->bus_index);
600 #endif
601 
602 	/*
603 	 * "handle->fd" is a real file, so "select()" and "poll()"
604 	 * work on it.
605 	 */
606 	handle->selectable_fd = handle->fd;
607 
608 	/* for plain binary access and text access we need to allocate the read
609 	 * buffer */
610 	handle->buffer = malloc(handle->bufsize);
611 	if (!handle->buffer) {
612 		pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
613 		    errno, "malloc");
614 		close(handle->fd);
615 		return PCAP_ERROR;
616 	}
617 	return 0;
618 }
619 
620 static int
621 usb_inject_linux(pcap_t *handle, const void *buf _U_, int size _U_)
622 {
623 	snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
624 	    "Packet injection is not supported on USB devices");
625 	return (-1);
626 }
627 
628 static int
629 usb_setdirection_linux(pcap_t *p, pcap_direction_t d)
630 {
631 	/*
632 	 * It's guaranteed, at this point, that d is a valid
633 	 * direction value.
634 	 */
635 	p->direction = d;
636 	return 0;
637 }
638 
639 static int
640 usb_stats_linux_bin(pcap_t *handle, struct pcap_stat *stats)
641 {
642 	struct pcap_usb_linux *handlep = handle->priv;
643 	int ret;
644 	struct mon_bin_stats st;
645 	ret = ioctl(handle->fd, MON_IOCG_STATS, &st);
646 	if (ret < 0)
647 	{
648 		pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
649 		    errno, "Can't read stats from fd %d", handle->fd);
650 		return -1;
651 	}
652 
653 	stats->ps_recv = handlep->packets_read + st.queued;
654 	stats->ps_drop = st.dropped;
655 	stats->ps_ifdrop = 0;
656 	return 0;
657 }
658 
659 /*
660  * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
661  * <linux-kernel-source>/drivers/usb/mon/mon_bin.c binary ABI
662  */
663 static int
664 usb_read_linux_bin(pcap_t *handle, int max_packets _U_, pcap_handler callback, u_char *user)
665 {
666 	struct pcap_usb_linux *handlep = handle->priv;
667 	struct mon_bin_get info;
668 	int ret;
669 	struct pcap_pkthdr pkth;
670 	u_int clen = handle->snapshot - sizeof(pcap_usb_header);
671 
672 	/* the usb header is going to be part of 'packet' data*/
673 	info.hdr = (pcap_usb_header*) handle->buffer;
674 	info.data = (u_char *)handle->buffer + sizeof(pcap_usb_header);
675 	info.data_len = clen;
676 
677 	/* ignore interrupt system call errors */
678 	do {
679 		ret = ioctl(handle->fd, MON_IOCX_GET, &info);
680 		if (handle->break_loop)
681 		{
682 			handle->break_loop = 0;
683 			return -2;
684 		}
685 	} while ((ret == -1) && (errno == EINTR));
686 	if (ret < 0)
687 	{
688 		if (errno == EAGAIN)
689 			return 0;	/* no data there */
690 
691 		pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
692 		    errno, "Can't read from fd %d", handle->fd);
693 		return -1;
694 	}
695 
696 	/*
697 	 * info.hdr->data_len is the number of bytes of isochronous
698 	 * descriptors (if any) plus the number of bytes of data
699 	 * provided.  There are no isochronous descriptors here,
700 	 * because we're using the old 48-byte header.
701 	 *
702 	 * If info.hdr->data_flag is non-zero, there's no URB data;
703 	 * info.hdr->urb_len is the size of the buffer into which
704 	 * data is to be placed; it does not represent the amount
705 	 * of data transferred.  If info.hdr->data_flag is zero,
706 	 * there is URB data, and info.hdr->urb_len is the number
707 	 * of bytes transmitted or received; it doesn't include
708 	 * isochronous descriptors.
709 	 *
710 	 * The kernel may give us more data than the snaplen; if it did,
711 	 * reduce the data length so that the total number of bytes we
712 	 * tell our client we have is not greater than the snaplen.
713 	 */
714 	if (info.hdr->data_len < clen)
715 		clen = info.hdr->data_len;
716 	info.hdr->data_len = clen;
717 	pkth.caplen = sizeof(pcap_usb_header) + clen;
718 	if (info.hdr->data_flag) {
719 		/*
720 		 * No data; just base the on-the-wire length on
721 		 * info.hdr->data_len (so that it's >= the captured
722 		 * length).
723 		 */
724 		pkth.len = sizeof(pcap_usb_header) + info.hdr->data_len;
725 	} else {
726 		/*
727 		 * We got data; base the on-the-wire length on
728 		 * info.hdr->urb_len, so that it includes data
729 		 * discarded by the USB monitor device due to
730 		 * its buffer being too small.
731 		 */
732 		pkth.len = sizeof(pcap_usb_header) + info.hdr->urb_len;
733 	}
734 	pkth.ts.tv_sec = (time_t)info.hdr->ts_sec;
735 	pkth.ts.tv_usec = info.hdr->ts_usec;
736 
737 	if (handle->fcode.bf_insns == NULL ||
738 	    pcap_filter(handle->fcode.bf_insns, handle->buffer,
739 	      pkth.len, pkth.caplen)) {
740 		handlep->packets_read++;
741 		callback(user, &pkth, handle->buffer);
742 		return 1;
743 	}
744 
745 	return 0;	/* didn't pass filter */
746 }
747 
748 /*
749  * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
750  * <linux-kernel-source>/drivers/usb/mon/mon_bin.c binary ABI
751  */
752 #define VEC_SIZE 32
753 static int
754 usb_read_linux_mmap(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
755 {
756 	struct pcap_usb_linux *handlep = handle->priv;
757 	struct mon_bin_mfetch fetch;
758 	int32_t vec[VEC_SIZE];
759 	struct pcap_pkthdr pkth;
760 	u_char *bp;
761 	pcap_usb_header_mmapped* hdr;
762 	int nflush = 0;
763 	int packets = 0;
764 	u_int clen, max_clen;
765 
766 	max_clen = handle->snapshot - sizeof(pcap_usb_header_mmapped);
767 
768 	for (;;) {
769 		int i, ret;
770 		int limit;
771 
772 		if (PACKET_COUNT_IS_UNLIMITED(max_packets)) {
773 			/*
774 			 * There's no limit on the number of packets
775 			 * to process, so try to fetch VEC_SIZE packets.
776 			 */
777 			limit = VEC_SIZE;
778 		} else {
779 			/*
780 			 * Try to fetch as many packets as we have left
781 			 * to process, or VEC_SIZE packets, whichever
782 			 * is less.
783 			 *
784 			 * At this point, max_packets > 0 (otherwise,
785 			 * PACKET_COUNT_IS_UNLIMITED(max_packets)
786 			 * would be true) and max_packets > packets
787 			 * (packet starts out as 0, and the test
788 			 * at the bottom of the loop exits if
789 			 * max_packets <= packets), so limit is
790 			 * guaranteed to be > 0.
791 			 */
792 			limit = max_packets - packets;
793 			if (limit > VEC_SIZE)
794 				limit = VEC_SIZE;
795 		}
796 
797 		/*
798 		 * Try to fetch as many events as possible, up to
799 		 * the limit, and flush the events we've processed
800 		 * earlier (nflush) - MON_IOCX_MFETCH does both
801 		 * (presumably to reduce the number of system
802 		 * calls in loops like this).
803 		 */
804 		fetch.offvec = vec;
805 		fetch.nfetch = limit;
806 		fetch.nflush = nflush;
807 		/* ignore interrupt system call errors */
808 		do {
809 			ret = ioctl(handle->fd, MON_IOCX_MFETCH, &fetch);
810 			if (handle->break_loop)
811 			{
812 				handle->break_loop = 0;
813 				return -2;
814 			}
815 		} while ((ret == -1) && (errno == EINTR));
816 		if (ret < 0)
817 		{
818 			if (errno == EAGAIN)
819 				return 0;	/* no data there */
820 
821 			pcap_fmt_errmsg_for_errno(handle->errbuf,
822 			    PCAP_ERRBUF_SIZE, errno, "Can't mfetch fd %d",
823 			    handle->fd);
824 			return -1;
825 		}
826 
827 		/* keep track of processed events, we will flush them later */
828 		nflush = fetch.nfetch;
829 		for (i=0; i<fetch.nfetch; ++i) {
830 			/*
831 			 * XXX - we can't check break_loop here, as
832 			 * we read the indices of packets into a
833 			 * local variable, so if we're later called
834 			 * to fetch more packets, those packets will
835 			 * not be seen - and won't be flushed, either.
836 			 *
837 			 * Instead, we would have to keep the array
838 			 * of indices in our private data, along
839 			 * with the count of packets to flush - or
840 			 * would have to flush the already-processed
841 			 * packets if we break out of the loop here.
842 			 */
843 
844 			/* Get a pointer to this packet's buffer */
845 			bp = &handlep->mmapbuf[vec[i]];
846 
847 			/* That begins with a metadata header */
848 			hdr = (pcap_usb_header_mmapped*) bp;
849 
850 			/* discard filler */
851 			if (hdr->event_type == '@')
852 				continue;
853 
854 			/*
855 			 * hdr->data_len is the number of bytes of
856 			 * isochronous descriptors (if any) plus the
857 			 * number of bytes of data provided.
858 			 *
859 			 * If hdr->data_flag is non-zero, there's no
860 			 * URB data; hdr->urb_len is the size of the
861 			 * buffer into which data is to be placed; it does
862 			 * not represent the amount of data transferred.
863 			 * If hdr->data_flag is zero, there is URB data,
864 			 * and hdr->urb_len is the number of bytes
865 			 * transmitted or received; it doesn't include
866 			 * isochronous descriptors.
867 			 *
868 			 * The kernel may give us more data than the
869 			 * snaplen; if it did, reduce the data length
870 			 * so that the total number of bytes we
871 			 * tell our client we have is not greater than
872 			 * the snaplen.
873 			 */
874 			clen = max_clen;
875 			if (hdr->data_len < clen)
876 				clen = hdr->data_len;
877 			pkth.caplen = sizeof(pcap_usb_header_mmapped) + clen;
878 			if (hdr->data_flag) {
879 				/*
880 				 * No data; just base the on-the-wire length
881 				 * on hdr->data_len (so that it's >= the
882 				 * captured length).
883 				 */
884 				pkth.len = sizeof(pcap_usb_header_mmapped) +
885 				    hdr->data_len;
886 			} else {
887 				/*
888 				 * We got data; base the on-the-wire length
889 				 * on hdr->urb_len, so that it includes
890 				 * data discarded by the USB monitor device
891 				 * due to its buffer being too small.
892 				 */
893 				pkth.len = sizeof(pcap_usb_header_mmapped) +
894 				    (hdr->ndesc * sizeof (usb_isodesc)) + hdr->urb_len;
895 
896 				/*
897 				 * Now clean it up if it's a completion
898 				 * event for an incoming isochronous
899 				 * transfer.
900 				 */
901 				fix_linux_usb_mmapped_length(&pkth, bp);
902 			}
903 			pkth.ts.tv_sec = (time_t)hdr->ts_sec;
904 			pkth.ts.tv_usec = hdr->ts_usec;
905 
906 			if (handle->fcode.bf_insns == NULL ||
907 			    pcap_filter(handle->fcode.bf_insns, (u_char*) hdr,
908 			      pkth.len, pkth.caplen)) {
909 				handlep->packets_read++;
910 				callback(user, &pkth, (u_char*) hdr);
911 				packets++;
912 			}
913 		}
914 
915 		/*
916 		 * If max_packets specifiesg "unlimited", we stop after
917 		 * the first chunk.
918 		 */
919 		if (PACKET_COUNT_IS_UNLIMITED(max_packets) ||
920 		    (packets >= max_packets))
921 			break;
922 	}
923 
924 	/* flush pending events*/
925 	if (ioctl(handle->fd, MON_IOCH_MFLUSH, nflush) == -1) {
926 		pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
927 		    errno, "Can't mflush fd %d", handle->fd);
928 		return -1;
929 	}
930 	return packets;
931 }
932 
933 static void
934 usb_cleanup_linux_mmap(pcap_t* handle)
935 {
936 	struct pcap_usb_linux *handlep = handle->priv;
937 
938 	/* if we have a memory-mapped buffer, unmap it */
939 	if (handlep->mmapbuf != NULL) {
940 		munmap(handlep->mmapbuf, handlep->mmapbuflen);
941 		handlep->mmapbuf = NULL;
942 	}
943 	pcap_cleanup_live_common(handle);
944 }
945