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