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