xref: /netbsd-src/external/bsd/libpcap/dist/pcap-usb-linux.c (revision f3cfa6f6ce31685c6c4a758bc430e69eb99f50a4)
1 /*	$NetBSD: pcap-usb-linux.c,v 1.5 2018/09/03 15:26:43 christos Exp $	*/
2 
3 /*
4  * Copyright (c) 2006 Paolo Abeni (Italy)
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  * notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  * notice, this list of conditions and the following disclaimer in the
15  * documentation and/or other materials provided with the distribution.
16  * 3. The name of the author may not be used to endorse or promote
17  * products derived from this software without specific prior written
18  * permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  *
32  * USB sniffing API implementation for Linux platform
33  * By Paolo Abeni <paolo.abeni@email.it>
34  * Modifications: Kris Katterjohn <katterjohn@gmail.com>
35  *
36  */
37 
38 #include <sys/cdefs.h>
39 __RCSID("$NetBSD: pcap-usb-linux.c,v 1.5 2018/09/03 15:26:43 christos Exp $");
40 
41 #ifdef HAVE_CONFIG_H
42 #include <config.h>
43 #endif
44 
45 #include "pcap-int.h"
46 #include "pcap-usb-linux.h"
47 #include "pcap/usb.h"
48 
49 #ifdef NEED_STRERROR_H
50 #include "strerror.h"
51 #endif
52 
53 #include <ctype.h>
54 #include <errno.h>
55 #include <stdlib.h>
56 #include <unistd.h>
57 #include <fcntl.h>
58 #include <string.h>
59 #include <dirent.h>
60 #include <byteswap.h>
61 #include <netinet/in.h>
62 #include <sys/ioctl.h>
63 #include <sys/mman.h>
64 #include <sys/utsname.h>
65 #ifdef HAVE_LINUX_USBDEVICE_FS_H
66 /*
67  * We might need <linux/compiler.h> to define __user for
68  * <linux/usbdevice_fs.h>.
69  */
70 #ifdef HAVE_LINUX_COMPILER_H
71 #include <linux/compiler.h>
72 #endif /* HAVE_LINUX_COMPILER_H */
73 #include <linux/usbdevice_fs.h>
74 #endif /* HAVE_LINUX_USBDEVICE_FS_H */
75 
76 #define USB_IFACE "usbmon"
77 #define USB_TEXT_DIR_OLD "/sys/kernel/debug/usbmon"
78 #define USB_TEXT_DIR "/sys/kernel/debug/usb/usbmon"
79 #define SYS_USB_BUS_DIR "/sys/bus/usb/devices"
80 #define PROC_USB_BUS_DIR "/proc/bus/usb"
81 #define USB_LINE_LEN 4096
82 
83 #if __BYTE_ORDER == __LITTLE_ENDIAN
84 #define htols(s) s
85 #define htoll(l) l
86 #define htol64(ll) ll
87 #else
88 #define htols(s) bswap_16(s)
89 #define htoll(l) bswap_32(l)
90 #define htol64(ll) bswap_64(ll)
91 #endif
92 
93 struct mon_bin_stats {
94 	uint32_t queued;
95 	uint32_t dropped;
96 };
97 
98 struct mon_bin_get {
99 	pcap_usb_header *hdr;
100 	void *data;
101 	size_t data_len;   /* Length of data (can be zero) */
102 };
103 
104 struct mon_bin_mfetch {
105 	int32_t *offvec;   /* Vector of events fetched */
106 	int32_t nfetch;    /* Number of events to fetch (out: fetched) */
107 	int32_t nflush;    /* Number of events to flush */
108 };
109 
110 #define MON_IOC_MAGIC 0x92
111 
112 #define MON_IOCQ_URB_LEN _IO(MON_IOC_MAGIC, 1)
113 #define MON_IOCX_URB  _IOWR(MON_IOC_MAGIC, 2, struct mon_bin_hdr)
114 #define MON_IOCG_STATS _IOR(MON_IOC_MAGIC, 3, struct mon_bin_stats)
115 #define MON_IOCT_RING_SIZE _IO(MON_IOC_MAGIC, 4)
116 #define MON_IOCQ_RING_SIZE _IO(MON_IOC_MAGIC, 5)
117 #define MON_IOCX_GET   _IOW(MON_IOC_MAGIC, 6, struct mon_bin_get)
118 #define MON_IOCX_MFETCH _IOWR(MON_IOC_MAGIC, 7, struct mon_bin_mfetch)
119 #define MON_IOCH_MFLUSH _IO(MON_IOC_MAGIC, 8)
120 
121 #define MON_BIN_SETUP 	0x1 /* setup hdr is present*/
122 #define MON_BIN_SETUP_ZERO 	0x2 /* setup buffer is not available */
123 #define MON_BIN_DATA_ZERO 	0x4 /* data buffer is not available */
124 #define MON_BIN_ERROR 	0x8
125 
126 /*
127  * Private data for capturing on Linux USB.
128  */
129 struct pcap_usb_linux {
130 	u_char *mmapbuf;	/* memory-mapped region pointer */
131 	size_t mmapbuflen;	/* size of region */
132 	int bus_index;
133 	u_int packets_read;
134 };
135 
136 /* forward declaration */
137 static int usb_activate(pcap_t *);
138 static int usb_stats_linux(pcap_t *, struct pcap_stat *);
139 static int usb_stats_linux_bin(pcap_t *, struct pcap_stat *);
140 static int usb_read_linux(pcap_t *, int , pcap_handler , u_char *);
141 static int usb_read_linux_bin(pcap_t *, int , pcap_handler , u_char *);
142 static int usb_read_linux_mmap(pcap_t *, int , pcap_handler , u_char *);
143 static int usb_inject_linux(pcap_t *, const void *, size_t);
144 static int usb_setdirection_linux(pcap_t *, pcap_direction_t);
145 static void usb_cleanup_linux_mmap(pcap_t *);
146 
147 static int
148 have_binary_usbmon(void)
149 {
150 	struct utsname utsname;
151 	char *version_component, *endp;
152 	int major, minor, subminor;
153 
154 	if (uname(&utsname) == 0) {
155 		/*
156 		 * 2.6.21 is the first release with the binary-mode
157 		 * USB monitoring.
158 		 */
159 		version_component = utsname.release;
160 		major = strtol(version_component, &endp, 10);
161 		if (endp != version_component && *endp == '.') {
162 			/*
163 			 * OK, that was a valid major version.
164 			 * Is it 3 or greater?  If so, we have binary
165 			 * mode support.
166 			 */
167 			if (major >= 3)
168 				return 1;
169 
170 			/*
171 			 * Is it 1 or less?  If so, we don't have binary
172 			 * mode support.  (In fact, we don't have any
173 			 * USB monitoring....)
174 			 */
175 			if (major <= 1)
176 				return 0;
177 		}
178 
179 		/*
180 		 * OK, this is a 2.x kernel.
181 		 * What's the minor version?
182 		 */
183 		version_component = endp + 1;
184 		minor = strtol(version_component, &endp, 10);
185 		if (endp != version_component &&
186 		    (*endp == '.' || *endp == '\0')) {
187 			/*
188 			 * OK, that was a valid minor version.
189 			 * Is is 2.6 or later?  (There shouldn't be a
190 			 * "later", as 2.6.x went to 3.x, but we'll
191 			 * check anyway.)
192 			 */
193 			if (minor < 6) {
194 				/*
195 				 * No, so no binary support (did 2.4 have
196 				 * any USB monitoring at all?)
197 				 */
198 				return 0;
199 			}
200 
201 			/*
202 			 * OK, this is a 2.6.x kernel.
203 			 * What's the subminor version?
204 			 */
205 			version_component = endp + 1;
206 			subminor = strtol(version_component, &endp, 10);
207 			if (endp != version_component &&
208 			    (*endp == '.' || *endp == '\0')) {
209 				/*
210 				 * OK, that was a valid subminor version.
211 				 * Is it 21 or greater?
212 				 */
213 				if (subminor >= 21) {
214 					/*
215 					 * Yes - we have binary mode
216 					 * support.
217 					 */
218 					return 1;
219 				}
220 			}
221 		}
222 	}
223 
224 	/*
225 	 * Either uname() failed, in which case we just say "no binary
226 	 * mode support", or we don't have binary mode support.
227 	 */
228 	return 0;
229 }
230 
231 /* facility to add an USB device to the device list*/
232 static int
233 usb_dev_add(pcap_if_list_t *devlistp, int n, char *err_str)
234 {
235 	char dev_name[10];
236 	char dev_descr[30];
237 	pcap_snprintf(dev_name, 10, USB_IFACE"%d", n);
238 	/*
239 	 * XXX - is there any notion of "up" and "running"?
240 	 */
241 	if (n == 0) {
242 		/*
243 		 * As this refers to all buses, there's no notion of
244 		 * "connected" vs. "disconnected", as that's a property
245 		 * that would apply to a particular USB interface.
246 		 */
247 		if (add_dev(devlistp, dev_name,
248 		    PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE,
249 		    "All USB buses", err_str) == NULL)
250 			return -1;
251 	} else {
252 		/*
253 		 * XXX - is there a way to determine whether anything's
254 		 * plugged into this bus interface or not, and set
255 		 * PCAP_IF_CONNECTION_STATUS_CONNECTED or
256 		 * PCAP_IF_CONNECTION_STATUS_DISCONNECTED?
257 		 */
258 		pcap_snprintf(dev_descr, 30, "USB bus number %d", n);
259 		if (add_dev(devlistp, dev_name, 0, dev_descr, err_str) == NULL)
260 			return -1;
261 	}
262 
263 	return 0;
264 }
265 
266 int
267 usb_findalldevs(pcap_if_list_t *devlistp, char *err_str)
268 {
269 	char usb_mon_dir[PATH_MAX];
270 	char *usb_mon_prefix;
271 	size_t usb_mon_prefix_len;
272 	struct dirent* data;
273 	int ret = 0;
274 	DIR* dir;
275 	int n;
276 	char* name;
277 	size_t len;
278 
279 	if (have_binary_usbmon()) {
280 		/*
281 		 * We have binary-mode support.
282 		 * What do the device names look like?
283 		 * Split LINUX_USB_MON_DEV into a directory that we'll
284 		 * scan and a file name prefix that we'll check for.
285 		 */
286 		strlcpy(usb_mon_dir, LINUX_USB_MON_DEV, sizeof usb_mon_dir);
287 		usb_mon_prefix = strrchr(usb_mon_dir, '/');
288 		if (usb_mon_prefix == NULL) {
289 			/*
290 			 * This "shouldn't happen".  Just give up if it
291 			 * does.
292 			 */
293 			return 0;
294 		}
295 		*usb_mon_prefix++ = '\0';
296 		usb_mon_prefix_len = strlen(usb_mon_prefix);
297 
298 		/*
299 		 * Open the directory and scan it.
300 		 */
301 		dir = opendir(usb_mon_dir);
302 		if (dir != NULL) {
303 			while ((ret == 0) && ((data = readdir(dir)) != 0)) {
304 				name = data->d_name;
305 
306 				/*
307 				 * Is this a usbmon device?
308 				 */
309 				if (strncmp(name, usb_mon_prefix, usb_mon_prefix_len) != 0)
310 					continue;	/* no */
311 
312 				/*
313 				 * What's the device number?
314 				 */
315 				if (sscanf(&name[usb_mon_prefix_len], "%d", &n) == 0)
316 					continue;	/* failed */
317 
318 				ret = usb_dev_add(devlistp, n, err_str);
319 			}
320 
321 			closedir(dir);
322 		}
323 		return 0;
324 	} else {
325 		/*
326 		 * We have only text mode support.
327 		 * We don't look for the text devices because we can't
328 		 * look for them without root privileges, and we don't
329 		 * want to require root privileges to enumerate devices
330 		 * (we want to let the user to try a device and get
331 		 * an error, rather than seeing no devices and asking
332 		 * "why am I not seeing devices" and forcing a long
333 		 * process of poking to figure out whether it's "no
334 		 * privileges" or "your kernel is too old" or "the
335 		 * usbmon module isn't loaded" or...).
336 		 *
337 		 * Instead, we look to see what buses we have.
338 		 * If the kernel is so old that it doesn't have
339 		 * binary-mode support, it's also so old that
340 		 * it doesn't have a "scan all buses" device.
341 		 *
342 		 * First, try scanning sysfs USB bus directory.
343 		 */
344 		dir = opendir(SYS_USB_BUS_DIR);
345 		if (dir != NULL) {
346 			while ((ret == 0) && ((data = readdir(dir)) != 0)) {
347 				name = data->d_name;
348 
349 				if (strncmp(name, "usb", 3) != 0)
350 					continue;
351 
352 				if (sscanf(&name[3], "%d", &n) == 0)
353 					continue;
354 
355 				ret = usb_dev_add(devlistp, n, err_str);
356 			}
357 
358 			closedir(dir);
359 			return 0;
360 		}
361 
362 		/* That didn't work; try scanning procfs USB bus directory. */
363 		dir = opendir(PROC_USB_BUS_DIR);
364 		if (dir != NULL) {
365 			while ((ret == 0) && ((data = readdir(dir)) != 0)) {
366 				name = data->d_name;
367 				len = strlen(name);
368 
369 				/* if this file name does not end with a number it's not of our interest */
370 				if ((len < 1) || !isdigit(name[--len]))
371 					continue;
372 				while (isdigit(name[--len]));
373 				if (sscanf(&name[len+1], "%d", &n) != 1)
374 					continue;
375 
376 				ret = usb_dev_add(devlistp, n, err_str);
377 			}
378 
379 			closedir(dir);
380 			return ret;
381 		}
382 
383 		/* neither of them worked */
384 		return 0;
385 	}
386 }
387 
388 static
389 int usb_mmap(pcap_t* handle)
390 {
391 	struct pcap_usb_linux *handlep = handle->priv;
392 	int len = ioctl(handle->fd, MON_IOCQ_RING_SIZE);
393 	if (len < 0)
394 		return 0;
395 
396 	handlep->mmapbuflen = len;
397 	handlep->mmapbuf = mmap(0, handlep->mmapbuflen, PROT_READ,
398 	    MAP_SHARED, handle->fd, 0);
399 	return handlep->mmapbuf != MAP_FAILED;
400 }
401 
402 #ifdef HAVE_LINUX_USBDEVICE_FS_H
403 
404 #define CTRL_TIMEOUT    (5*1000)        /* milliseconds */
405 
406 #define USB_DIR_IN		0x80
407 #define USB_TYPE_STANDARD	0x00
408 #define USB_RECIP_DEVICE	0x00
409 
410 #define USB_REQ_GET_DESCRIPTOR	6
411 
412 #define USB_DT_DEVICE		1
413 
414 /* probe the descriptors of the devices attached to the bus */
415 /* the descriptors will end up in the captured packet stream */
416 /* and be decoded by external apps like wireshark */
417 /* without these identifying probes packet data can't be fully decoded */
418 static void
419 probe_devices(int bus)
420 {
421 	struct usbdevfs_ctrltransfer ctrl;
422 	struct dirent* data;
423 	int ret = 0;
424 	char buf[sizeof("/dev/bus/usb/000/") + NAME_MAX];
425 	DIR* dir;
426 
427 	/* scan usb bus directories for device nodes */
428 	pcap_snprintf(buf, sizeof(buf), "/dev/bus/usb/%03d", bus);
429 	dir = opendir(buf);
430 	if (!dir)
431 		return;
432 
433 	while ((ret >= 0) && ((data = readdir(dir)) != 0)) {
434 		int fd;
435 		char* name = data->d_name;
436 
437 		if (name[0] == '.')
438 			continue;
439 
440 		pcap_snprintf(buf, sizeof(buf), "/dev/bus/usb/%03d/%s", bus, data->d_name);
441 
442 		fd = open(buf, O_RDWR);
443 		if (fd == -1)
444 			continue;
445 
446 		/*
447 		 * Sigh.  Different kernels have different member names
448 		 * for this structure.
449 		 */
450 #ifdef HAVE_STRUCT_USBDEVFS_CTRLTRANSFER_BREQUESTTYPE
451 		ctrl.bRequestType = USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE;
452 		ctrl.bRequest = USB_REQ_GET_DESCRIPTOR;
453 		ctrl.wValue = USB_DT_DEVICE << 8;
454 		ctrl.wIndex = 0;
455  		ctrl.wLength = sizeof(buf);
456 #else
457 		ctrl.requesttype = USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE;
458 		ctrl.request = USB_REQ_GET_DESCRIPTOR;
459 		ctrl.value = USB_DT_DEVICE << 8;
460 		ctrl.index = 0;
461  		ctrl.length = sizeof(buf);
462 #endif
463 		ctrl.data = buf;
464 		ctrl.timeout = CTRL_TIMEOUT;
465 
466 		ret = ioctl(fd, USBDEVFS_CONTROL, &ctrl);
467 
468 		close(fd);
469 	}
470 	closedir(dir);
471 }
472 #endif /* HAVE_LINUX_USBDEVICE_FS_H */
473 
474 pcap_t *
475 usb_create(const char *device, char *ebuf, int *is_ours)
476 {
477 	const char *cp;
478 	char *cpend;
479 	long devnum;
480 	pcap_t *p;
481 
482 	/* Does this look like a USB monitoring device? */
483 	cp = strrchr(device, '/');
484 	if (cp == NULL)
485 		cp = device;
486 	/* Does it begin with USB_IFACE? */
487 	if (strncmp(cp, USB_IFACE, sizeof USB_IFACE - 1) != 0) {
488 		/* Nope, doesn't begin with USB_IFACE */
489 		*is_ours = 0;
490 		return NULL;
491 	}
492 	/* Yes - is USB_IFACE followed by a number? */
493 	cp += sizeof USB_IFACE - 1;
494 	devnum = strtol(cp, &cpend, 10);
495 	if (cpend == cp || *cpend != '\0') {
496 		/* Not followed by a number. */
497 		*is_ours = 0;
498 		return NULL;
499 	}
500 	if (devnum < 0) {
501 		/* Followed by a non-valid number. */
502 		*is_ours = 0;
503 		return NULL;
504 	}
505 
506 	/* OK, it's probably ours. */
507 	*is_ours = 1;
508 
509 	p = pcap_create_common(ebuf, sizeof (struct pcap_usb_linux));
510 	if (p == NULL)
511 		return (NULL);
512 
513 	p->activate_op = usb_activate;
514 	return (p);
515 }
516 
517 static int
518 usb_activate(pcap_t* handle)
519 {
520 	struct pcap_usb_linux *handlep = handle->priv;
521 	char 		full_path[USB_LINE_LEN];
522 
523 	/*
524 	 * Turn a negative snapshot value (invalid), a snapshot value of
525 	 * 0 (unspecified), or a value bigger than the normal maximum
526 	 * value, into the maximum allowed value.
527 	 *
528 	 * If some application really *needs* a bigger snapshot
529 	 * length, we should just increase MAXIMUM_SNAPLEN.
530 	 */
531 	if (handle->snapshot <= 0 || handle->snapshot > MAXIMUM_SNAPLEN)
532 		handle->snapshot = MAXIMUM_SNAPLEN;
533 
534 	/* Initialize some components of the pcap structure. */
535 	handle->bufsize = handle->snapshot;
536 	handle->offset = 0;
537 	handle->linktype = DLT_USB_LINUX;
538 
539 	handle->inject_op = usb_inject_linux;
540 	handle->setfilter_op = install_bpf_program; /* no kernel filtering */
541 	handle->setdirection_op = usb_setdirection_linux;
542 	handle->set_datalink_op = NULL;	/* can't change data link type */
543 	handle->getnonblock_op = pcap_getnonblock_fd;
544 	handle->setnonblock_op = pcap_setnonblock_fd;
545 
546 	/*get usb bus index from device name */
547 	if (sscanf(handle->opt.device, USB_IFACE"%d", &handlep->bus_index) != 1)
548 	{
549 		pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
550 			"Can't get USB bus index from %s", handle->opt.device);
551 		return PCAP_ERROR;
552 	}
553 
554 	if (have_binary_usbmon())
555 	{
556 		/*
557 		 * We have binary-mode support.
558 		 * Try to open the binary interface.
559 		 */
560 		pcap_snprintf(full_path, USB_LINE_LEN, LINUX_USB_MON_DEV"%d", handlep->bus_index);
561 		handle->fd = open(full_path, O_RDONLY, 0);
562 		if (handle->fd < 0)
563 		{
564 			/*
565 			 * The attempt failed; why?
566 			 */
567 			switch (errno) {
568 
569 			case ENOENT:
570 				/*
571 				 * The device doesn't exist.
572 				 * That could either mean that there's
573 				 * no support for monitoring USB buses
574 				 * (which probably means "the usbmon
575 				 * module isn't loaded") or that there
576 				 * is but that *particular* device
577 				 * doesn't exist (no "scan all buses"
578 				 * device if the bus index is 0, no
579 				 * such bus if the bus index isn't 0).
580 				 */
581 				return PCAP_ERROR_NO_SUCH_DEVICE;
582 
583 			case EACCES:
584 				/*
585 				 * We didn't have permission to open it.
586 				 */
587 				return PCAP_ERROR_PERM_DENIED;
588 
589 			default:
590 				/*
591 				 * Something went wrong.
592 				 */
593 				pcap_fmt_errmsg_for_errno(handle->errbuf,
594 				    PCAP_ERRBUF_SIZE, errno,
595 				    "Can't open USB bus file %s", full_path);
596 				return PCAP_ERROR;
597 			}
598 		}
599 
600 		if (handle->opt.rfmon)
601 		{
602 			/*
603 			 * Monitor mode doesn't apply to USB devices.
604 			 */
605 			close(handle->fd);
606 			return PCAP_ERROR_RFMON_NOTSUP;
607 		}
608 
609 		/* try to use fast mmap access */
610 		if (usb_mmap(handle))
611 		{
612 			handle->linktype = DLT_USB_LINUX_MMAPPED;
613 			handle->stats_op = usb_stats_linux_bin;
614 			handle->read_op = usb_read_linux_mmap;
615 			handle->cleanup_op = usb_cleanup_linux_mmap;
616 #ifdef HAVE_LINUX_USBDEVICE_FS_H
617 			probe_devices(handlep->bus_index);
618 #endif
619 
620 			/*
621 			 * "handle->fd" is a real file, so
622 			 * "select()" and "poll()" work on it.
623 			 */
624 			handle->selectable_fd = handle->fd;
625 			return 0;
626 		}
627 
628 		/* can't mmap, use plain binary interface access */
629 		handle->stats_op = usb_stats_linux_bin;
630 		handle->read_op = usb_read_linux_bin;
631 #ifdef HAVE_LINUX_USBDEVICE_FS_H
632 		probe_devices(handlep->bus_index);
633 #endif
634 	}
635 	else {
636 		/*
637 		 * We don't have binary mode support.
638 		 * Try opening the text-mode device.
639 		 */
640 		pcap_snprintf(full_path, USB_LINE_LEN, USB_TEXT_DIR"/%dt", handlep->bus_index);
641 		handle->fd = open(full_path, O_RDONLY, 0);
642 		if (handle->fd < 0)
643 		{
644 			if (errno == ENOENT)
645 			{
646 				/*
647 				 * Not found at the new location; try
648 				 * the old location.
649 				 */
650 				pcap_snprintf(full_path, USB_LINE_LEN, USB_TEXT_DIR_OLD"/%dt", handlep->bus_index);
651 				handle->fd = open(full_path, O_RDONLY, 0);
652 			}
653 			if (handle->fd < 0) {
654 				/*
655 				 * Is the problem that we didn't have
656 				 * sufficient permission to open it?
657 				 */
658 				if (errno == EACCES) {
659 					/*
660 					 * Yes - return that error.
661 					 */
662 					return PCAP_ERROR_PERM_DENIED;
663 				}
664 
665 				/*
666 				 * No - was the problem something other
667 				 * than "it doesn't exist"?
668 				 */
669 				if (errno != ENOENT) {
670 					/*
671 					 * Yes - return *that* error.
672 					 */
673 					pcap_fmt_errmsg_for_errno(handle->errbuf,
674 					    PCAP_ERRBUF_SIZE, errno,
675 					    "Can't open USB bus file %s",
676 					    full_path);
677 					return PCAP_ERROR;
678 				}
679 
680 				/*
681 				 * No.  Report that as "no such device".
682 				 * (That could mean "no such USB bus"
683 				 * or "monitoring not supported".)
684 				 */
685 				return PCAP_ERROR_NO_SUCH_DEVICE;
686 			}
687 		}
688 
689 		if (handle->opt.rfmon)
690 		{
691 			/*
692 			 * Monitor mode doesn't apply to USB devices.
693 			 */
694 			close(handle->fd);
695 			return PCAP_ERROR_RFMON_NOTSUP;
696 		}
697 
698 		handle->stats_op = usb_stats_linux;
699 		handle->read_op = usb_read_linux;
700 	}
701 
702 	/*
703 	 * "handle->fd" is a real file, so "select()" and "poll()"
704 	 * work on it.
705 	 */
706 	handle->selectable_fd = handle->fd;
707 
708 	/* for plain binary access and text access we need to allocate the read
709 	 * buffer */
710 	handle->buffer = malloc(handle->bufsize);
711 	if (!handle->buffer) {
712 		pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
713 		    errno, "malloc");
714 		close(handle->fd);
715 		return PCAP_ERROR;
716 	}
717 	return 0;
718 }
719 
720 static inline int
721 ascii_to_int(char c)
722 {
723 	return c < 'A' ? c- '0': ((c<'a') ? c - 'A' + 10: c-'a'+10);
724 }
725 
726 /*
727  * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
728  * <linux-kernel-source>/drivers/usb/mon/mon_text.c for urb string
729  * format description
730  */
731 static int
732 usb_read_linux(pcap_t *handle, int max_packets _U_, pcap_handler callback, u_char *user)
733 {
734 	/* see:
735 	* /usr/src/linux/Documentation/usb/usbmon.txt
736 	* for message format
737 	*/
738 	struct pcap_usb_linux *handlep = handle->priv;
739 	unsigned timestamp;
740 	int tag, cnt, ep_num, dev_addr, dummy, ret, urb_len, data_len;
741 	char etype, pipeid1, pipeid2, status[16], urb_tag, line[USB_LINE_LEN];
742 	char *string = line;
743 	u_char * rawdata = handle->buffer;
744 	struct pcap_pkthdr pkth;
745 	pcap_usb_header* uhdr = (pcap_usb_header*)handle->buffer;
746 	u_char urb_transfer=0;
747 	int incoming=0;
748 
749 	/* ignore interrupt system call errors */
750 	do {
751 		ret = read(handle->fd, line, USB_LINE_LEN - 1);
752 		if (handle->break_loop)
753 		{
754 			handle->break_loop = 0;
755 			return -2;
756 		}
757 	} while ((ret == -1) && (errno == EINTR));
758 	if (ret < 0)
759 	{
760 		if (errno == EAGAIN)
761 			return 0;	/* no data there */
762 
763 		pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
764 		    errno, "Can't read from fd %d", handle->fd);
765 		return -1;
766 	}
767 
768 	/* read urb header; %n argument may increment return value, but it's
769 	* not mandatory, so does not count on it*/
770 	string[ret] = 0;
771 	ret = sscanf(string, "%x %d %c %c%c:%d:%d %s%n", &tag, &timestamp, &etype,
772 		&pipeid1, &pipeid2, &dev_addr, &ep_num, status,
773 		&cnt);
774 	if (ret < 8)
775 	{
776 		pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
777 		    "Can't parse USB bus message '%s', too few tokens (expected 8 got %d)",
778 		    string, ret);
779 		return -1;
780 	}
781 	uhdr->id = tag;
782 	uhdr->device_address = dev_addr;
783 	uhdr->bus_id = handlep->bus_index;
784 	uhdr->status = 0;
785 	string += cnt;
786 
787 	/* don't use usbmon provided timestamp, since it have low precision*/
788 	if (gettimeofday(&pkth.ts, NULL) < 0)
789 	{
790 		pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
791 		    errno, "Can't get timestamp for message '%s'", string);
792 		return -1;
793 	}
794 	uhdr->ts_sec = pkth.ts.tv_sec;
795 	uhdr->ts_usec = pkth.ts.tv_usec;
796 
797 	/* parse endpoint information */
798 	if (pipeid1 == 'C')
799 		urb_transfer = URB_CONTROL;
800 	else if (pipeid1 == 'Z')
801 		urb_transfer = URB_ISOCHRONOUS;
802 	else if (pipeid1 == 'I')
803 		urb_transfer = URB_INTERRUPT;
804 	else if (pipeid1 == 'B')
805 		urb_transfer = URB_BULK;
806 	if (pipeid2 == 'i') {
807 		ep_num |= URB_TRANSFER_IN;
808 		incoming = 1;
809 	}
810 	if (etype == 'C')
811 		incoming = !incoming;
812 
813 	/* direction check*/
814 	if (incoming)
815 	{
816 		if (handle->direction == PCAP_D_OUT)
817 			return 0;
818 	}
819 	else
820 		if (handle->direction == PCAP_D_IN)
821 			return 0;
822 	uhdr->event_type = etype;
823 	uhdr->transfer_type = urb_transfer;
824 	uhdr->endpoint_number = ep_num;
825 	pkth.caplen = sizeof(pcap_usb_header);
826 	rawdata += sizeof(pcap_usb_header);
827 
828 	/* check if this is a setup packet */
829 	ret = sscanf(status, "%d", &dummy);
830 	if (ret != 1)
831 	{
832 		/* this a setup packet, setup data can be filled with underscore if
833 		* usbmon has not been able to read them, so we must parse this fields as
834 		* strings */
835 		pcap_usb_setup* shdr;
836 		char str1[3], str2[3], str3[5], str4[5], str5[5];
837 		ret = sscanf(string, "%s %s %s %s %s%n", str1, str2, str3, str4,
838 		str5, &cnt);
839 		if (ret < 5)
840 		{
841 			pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
842 				"Can't parse USB bus message '%s', too few tokens (expected 5 got %d)",
843 				string, ret);
844 			return -1;
845 		}
846 		string += cnt;
847 
848 		/* try to convert to corresponding integer */
849 		shdr = &uhdr->setup;
850 		shdr->bmRequestType = strtoul(str1, 0, 16);
851 		shdr->bRequest = strtoul(str2, 0, 16);
852 		shdr->wValue = htols(strtoul(str3, 0, 16));
853 		shdr->wIndex = htols(strtoul(str4, 0, 16));
854 		shdr->wLength = htols(strtoul(str5, 0, 16));
855 
856 		uhdr->setup_flag = 0;
857 	}
858 	else
859 		uhdr->setup_flag = 1;
860 
861 	/* read urb data */
862 	ret = sscanf(string, " %d%n", &urb_len, &cnt);
863 	if (ret < 1)
864 	{
865 		pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
866 		  "Can't parse urb length from '%s'", string);
867 		return -1;
868 	}
869 	string += cnt;
870 
871 	/* urb tag is not present if urb length is 0, so we can stop here
872 	 * text parsing */
873 	pkth.len = urb_len+pkth.caplen;
874 	uhdr->urb_len = urb_len;
875 	uhdr->data_flag = 1;
876 	data_len = 0;
877 	if (uhdr->urb_len == 0)
878 		goto got;
879 
880 	/* check for data presence; data is present if and only if urb tag is '=' */
881 	if (sscanf(string, " %c", &urb_tag) != 1)
882 	{
883 		pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
884 			"Can't parse urb tag from '%s'", string);
885 		return -1;
886 	}
887 
888 	if (urb_tag != '=')
889 		goto got;
890 
891 	/* skip urb tag and following space */
892 	string += 3;
893 
894 	/* if we reach this point we got some urb data*/
895 	uhdr->data_flag = 0;
896 
897 	/* read all urb data; if urb length is greater then the usbmon internal
898 	 * buffer length used by the kernel to spool the URB, we get only
899 	 * a partial information.
900 	 * At least until linux 2.6.17 there is no way to set usbmon intenal buffer
901 	 * length and default value is 130. */
902 	while ((string[0] != 0) && (string[1] != 0) && (pkth.caplen < (bpf_u_int32)handle->snapshot))
903 	{
904 		rawdata[0] = ascii_to_int(string[0]) * 16 + ascii_to_int(string[1]);
905 		rawdata++;
906 		string+=2;
907 		if (string[0] == ' ')
908 			string++;
909 		pkth.caplen++;
910 		data_len++;
911 	}
912 
913 got:
914 	uhdr->data_len = data_len;
915 	if (pkth.caplen > (bpf_u_int32)handle->snapshot)
916 		pkth.caplen = (bpf_u_int32)handle->snapshot;
917 
918 	if (handle->fcode.bf_insns == NULL ||
919 	    bpf_filter(handle->fcode.bf_insns, handle->buffer,
920 	      pkth.len, pkth.caplen)) {
921 		handlep->packets_read++;
922 		callback(user, &pkth, handle->buffer);
923 		return 1;
924 	}
925 	return 0;	/* didn't pass filter */
926 }
927 
928 static int
929 usb_inject_linux(pcap_t *handle, const void *buf _U_, size_t size _U_)
930 {
931 	pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "inject not supported on "
932 		"USB devices");
933 	return (-1);
934 }
935 
936 static int
937 usb_stats_linux(pcap_t *handle, struct pcap_stat *stats)
938 {
939 	struct pcap_usb_linux *handlep = handle->priv;
940 	int dummy, ret, consumed, cnt;
941 	char string[USB_LINE_LEN];
942 	char token[USB_LINE_LEN];
943 	char * ptr = string;
944 	int fd;
945 
946 	pcap_snprintf(string, USB_LINE_LEN, USB_TEXT_DIR"/%ds", handlep->bus_index);
947 	fd = open(string, O_RDONLY, 0);
948 	if (fd < 0)
949 	{
950 		if (errno == ENOENT)
951 		{
952 			/*
953 			 * Not found at the new location; try the old
954 			 * location.
955 			 */
956 			pcap_snprintf(string, USB_LINE_LEN, USB_TEXT_DIR_OLD"/%ds", handlep->bus_index);
957 			fd = open(string, O_RDONLY, 0);
958 		}
959 		if (fd < 0) {
960 			pcap_fmt_errmsg_for_errno(handle->errbuf,
961 			    PCAP_ERRBUF_SIZE, errno,
962 			    "Can't open USB stats file %s", string);
963 			return -1;
964 		}
965 	}
966 
967 	/* read stats line */
968 	do {
969 		ret = read(fd, string, USB_LINE_LEN-1);
970 	} while ((ret == -1) && (errno == EINTR));
971 	close(fd);
972 
973 	if (ret < 0)
974 	{
975 		pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
976 			"Can't read stats from fd %d ", fd);
977 		return -1;
978 	}
979 	string[ret] = 0;
980 
981 	/* extract info on dropped urbs */
982 	for (consumed=0; consumed < ret; ) {
983 		/* from the sscanf man page:
984  		 * The C standard says: "Execution of a %n directive does
985  		 * not increment the assignment count returned at the completion
986 		 * of  execution" but the Corrigendum seems to contradict this.
987 		 * Do not make any assumptions on the effect of %n conversions
988 		 * on the return value and explicitly check for cnt assignmet*/
989 		int ntok;
990 
991 		cnt = -1;
992 		ntok = sscanf(ptr, "%s%n", token, &cnt);
993 		if ((ntok < 1) || (cnt < 0))
994 			break;
995 		consumed += cnt;
996 		ptr += cnt;
997 		if (strcmp(token, "nreaders") == 0)
998 			ret = sscanf(ptr, "%d", &stats->ps_drop);
999 		else
1000 			ret = sscanf(ptr, "%d", &dummy);
1001 		if (ntok != 1)
1002 			break;
1003 		consumed += cnt;
1004 		ptr += cnt;
1005 	}
1006 
1007 	stats->ps_recv = handlep->packets_read;
1008 	stats->ps_ifdrop = 0;
1009 	return 0;
1010 }
1011 
1012 static int
1013 usb_setdirection_linux(pcap_t *p, pcap_direction_t d)
1014 {
1015 	p->direction = d;
1016 	return 0;
1017 }
1018 
1019 
1020 static int
1021 usb_stats_linux_bin(pcap_t *handle, struct pcap_stat *stats)
1022 {
1023 	struct pcap_usb_linux *handlep = handle->priv;
1024 	int ret;
1025 	struct mon_bin_stats st;
1026 	ret = ioctl(handle->fd, MON_IOCG_STATS, &st);
1027 	if (ret < 0)
1028 	{
1029 		pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
1030 		    errno, "Can't read stats from fd %d", handle->fd);
1031 		return -1;
1032 	}
1033 
1034 	stats->ps_recv = handlep->packets_read + st.queued;
1035 	stats->ps_drop = st.dropped;
1036 	stats->ps_ifdrop = 0;
1037 	return 0;
1038 }
1039 
1040 /*
1041  * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
1042  * <linux-kernel-source>/drivers/usb/mon/mon_bin.c binary ABI
1043  */
1044 static int
1045 usb_read_linux_bin(pcap_t *handle, int max_packets _U_, pcap_handler callback, u_char *user)
1046 {
1047 	struct pcap_usb_linux *handlep = handle->priv;
1048 	struct mon_bin_get info;
1049 	int ret;
1050 	struct pcap_pkthdr pkth;
1051 	u_int clen = handle->snapshot - sizeof(pcap_usb_header);
1052 
1053 	/* the usb header is going to be part of 'packet' data*/
1054 	info.hdr = (pcap_usb_header*) handle->buffer;
1055 	info.data = (u_char *)handle->buffer + sizeof(pcap_usb_header);
1056 	info.data_len = clen;
1057 
1058 	/* ignore interrupt system call errors */
1059 	do {
1060 		ret = ioctl(handle->fd, MON_IOCX_GET, &info);
1061 		if (handle->break_loop)
1062 		{
1063 			handle->break_loop = 0;
1064 			return -2;
1065 		}
1066 	} while ((ret == -1) && (errno == EINTR));
1067 	if (ret < 0)
1068 	{
1069 		if (errno == EAGAIN)
1070 			return 0;	/* no data there */
1071 
1072 		pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
1073 		    errno, "Can't read from fd %d", handle->fd);
1074 		return -1;
1075 	}
1076 
1077 	/* we can get less that than really captured from kernel, depending on
1078 	 * snaplen, so adjust header accordingly */
1079 	if (info.hdr->data_len < clen)
1080 		clen = info.hdr->data_len;
1081 	info.hdr->data_len = clen;
1082 	pkth.caplen = clen + sizeof(pcap_usb_header);
1083 	pkth.len = info.hdr->data_len + sizeof(pcap_usb_header);
1084 	pkth.ts.tv_sec = info.hdr->ts_sec;
1085 	pkth.ts.tv_usec = info.hdr->ts_usec;
1086 
1087 	if (handle->fcode.bf_insns == NULL ||
1088 	    bpf_filter(handle->fcode.bf_insns, handle->buffer,
1089 	      pkth.len, pkth.caplen)) {
1090 		handlep->packets_read++;
1091 		callback(user, &pkth, handle->buffer);
1092 		return 1;
1093 	}
1094 
1095 	return 0;	/* didn't pass filter */
1096 }
1097 
1098 /*
1099  * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
1100  * <linux-kernel-source>/drivers/usb/mon/mon_bin.c binary ABI
1101  */
1102 #define VEC_SIZE 32
1103 static int
1104 usb_read_linux_mmap(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
1105 {
1106 	struct pcap_usb_linux *handlep = handle->priv;
1107 	struct mon_bin_mfetch fetch;
1108 	int32_t vec[VEC_SIZE];
1109 	struct pcap_pkthdr pkth;
1110 	pcap_usb_header* hdr;
1111 	int nflush = 0;
1112 	int packets = 0;
1113 	u_int clen, max_clen;
1114 
1115 	max_clen = handle->snapshot - sizeof(pcap_usb_header);
1116 
1117 	for (;;) {
1118 		int i, ret;
1119 		int limit = max_packets - packets;
1120 		if (limit <= 0)
1121 			limit = VEC_SIZE;
1122 		if (limit > VEC_SIZE)
1123 			limit = VEC_SIZE;
1124 
1125 		/* try to fetch as many events as possible*/
1126 		fetch.offvec = vec;
1127 		fetch.nfetch = limit;
1128 		fetch.nflush = nflush;
1129 		/* ignore interrupt system call errors */
1130 		do {
1131 			ret = ioctl(handle->fd, MON_IOCX_MFETCH, &fetch);
1132 			if (handle->break_loop)
1133 			{
1134 				handle->break_loop = 0;
1135 				return -2;
1136 			}
1137 		} while ((ret == -1) && (errno == EINTR));
1138 		if (ret < 0)
1139 		{
1140 			if (errno == EAGAIN)
1141 				return 0;	/* no data there */
1142 
1143 			pcap_fmt_errmsg_for_errno(handle->errbuf,
1144 			    PCAP_ERRBUF_SIZE, errno, "Can't mfetch fd %d",
1145 			    handle->fd);
1146 			return -1;
1147 		}
1148 
1149 		/* keep track of processed events, we will flush them later */
1150 		nflush = fetch.nfetch;
1151 		for (i=0; i<fetch.nfetch; ++i) {
1152 			/* discard filler */
1153 			hdr = (pcap_usb_header*) &handlep->mmapbuf[vec[i]];
1154 			if (hdr->event_type == '@')
1155 				continue;
1156 
1157 			/* we can get less that than really captured from kernel, depending on
1158 	 		* snaplen, so adjust header accordingly */
1159 			clen = max_clen;
1160 			if (hdr->data_len < clen)
1161 				clen = hdr->data_len;
1162 
1163 			/* get packet info from header*/
1164 			pkth.caplen = clen + sizeof(pcap_usb_header_mmapped);
1165 			pkth.len = hdr->data_len + sizeof(pcap_usb_header_mmapped);
1166 			pkth.ts.tv_sec = hdr->ts_sec;
1167 			pkth.ts.tv_usec = hdr->ts_usec;
1168 
1169 			if (handle->fcode.bf_insns == NULL ||
1170 			    bpf_filter(handle->fcode.bf_insns, (u_char*) hdr,
1171 			      pkth.len, pkth.caplen)) {
1172 				handlep->packets_read++;
1173 				callback(user, &pkth, (u_char*) hdr);
1174 				packets++;
1175 			}
1176 		}
1177 
1178 		/* with max_packets specifying "unlimited" we stop afer the first chunk*/
1179 		if (PACKET_COUNT_IS_UNLIMITED(max_packets) || (packets == max_packets))
1180 			break;
1181 	}
1182 
1183 	/* flush pending events*/
1184 	if (ioctl(handle->fd, MON_IOCH_MFLUSH, nflush) == -1) {
1185 		pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
1186 		    errno, "Can't mflush fd %d", handle->fd);
1187 		return -1;
1188 	}
1189 	return packets;
1190 }
1191 
1192 static void
1193 usb_cleanup_linux_mmap(pcap_t* handle)
1194 {
1195 	struct pcap_usb_linux *handlep = handle->priv;
1196 
1197 	/* if we have a memory-mapped buffer, unmap it */
1198 	if (handlep->mmapbuf != NULL) {
1199 		munmap(handlep->mmapbuf, handlep->mmapbuflen);
1200 		handlep->mmapbuf = NULL;
1201 	}
1202 	pcap_cleanup_live_common(handle);
1203 }
1204