xref: /netbsd-src/external/bsd/libpcap/dist/pcap-usb-linux.c (revision bdc22b2e01993381dcefeff2bc9b56ca75a4235c)
1 /*	$NetBSD: pcap-usb-linux.c,v 1.4 2017/01/24 22:29:28 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.4 2017/01/24 22:29:28 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 #ifdef HAVE_LINUX_USBDEVICE_FS_H
65 /*
66  * We might need <linux/compiler.h> to define __user for
67  * <linux/usbdevice_fs.h>.
68  */
69 #ifdef HAVE_LINUX_COMPILER_H
70 #include <linux/compiler.h>
71 #endif /* HAVE_LINUX_COMPILER_H */
72 #include <linux/usbdevice_fs.h>
73 #endif /* HAVE_LINUX_USBDEVICE_FS_H */
74 
75 #define USB_IFACE "usbmon"
76 #define USB_TEXT_DIR_OLD "/sys/kernel/debug/usbmon"
77 #define USB_TEXT_DIR "/sys/kernel/debug/usb/usbmon"
78 #define SYS_USB_BUS_DIR "/sys/bus/usb/devices"
79 #define PROC_USB_BUS_DIR "/proc/bus/usb"
80 #define USB_LINE_LEN 4096
81 
82 #if __BYTE_ORDER == __LITTLE_ENDIAN
83 #define htols(s) s
84 #define htoll(l) l
85 #define htol64(ll) ll
86 #else
87 #define htols(s) bswap_16(s)
88 #define htoll(l) bswap_32(l)
89 #define htol64(ll) bswap_64(ll)
90 #endif
91 
92 struct mon_bin_stats {
93 	u_int32_t queued;
94 	u_int32_t dropped;
95 };
96 
97 struct mon_bin_get {
98 	pcap_usb_header *hdr;
99 	void *data;
100 	size_t data_len;   /* Length of data (can be zero) */
101 };
102 
103 struct mon_bin_mfetch {
104 	int32_t *offvec;   /* Vector of events fetched */
105 	int32_t nfetch;    /* Number of events to fetch (out: fetched) */
106 	int32_t nflush;    /* Number of events to flush */
107 };
108 
109 #define MON_IOC_MAGIC 0x92
110 
111 #define MON_IOCQ_URB_LEN _IO(MON_IOC_MAGIC, 1)
112 #define MON_IOCX_URB  _IOWR(MON_IOC_MAGIC, 2, struct mon_bin_hdr)
113 #define MON_IOCG_STATS _IOR(MON_IOC_MAGIC, 3, struct mon_bin_stats)
114 #define MON_IOCT_RING_SIZE _IO(MON_IOC_MAGIC, 4)
115 #define MON_IOCQ_RING_SIZE _IO(MON_IOC_MAGIC, 5)
116 #define MON_IOCX_GET   _IOW(MON_IOC_MAGIC, 6, struct mon_bin_get)
117 #define MON_IOCX_MFETCH _IOWR(MON_IOC_MAGIC, 7, struct mon_bin_mfetch)
118 #define MON_IOCH_MFLUSH _IO(MON_IOC_MAGIC, 8)
119 
120 #define MON_BIN_SETUP 	0x1 /* setup hdr is present*/
121 #define MON_BIN_SETUP_ZERO 	0x2 /* setup buffer is not available */
122 #define MON_BIN_DATA_ZERO 	0x4 /* data buffer is not available */
123 #define MON_BIN_ERROR 	0x8
124 
125 /*
126  * Private data for capturing on Linux USB.
127  */
128 struct pcap_usb_linux {
129 	u_char *mmapbuf;	/* memory-mapped region pointer */
130 	size_t mmapbuflen;	/* size of region */
131 	int bus_index;
132 	u_int packets_read;
133 };
134 
135 /* forward declaration */
136 static int usb_activate(pcap_t *);
137 static int usb_stats_linux(pcap_t *, struct pcap_stat *);
138 static int usb_stats_linux_bin(pcap_t *, struct pcap_stat *);
139 static int usb_read_linux(pcap_t *, int , pcap_handler , u_char *);
140 static int usb_read_linux_bin(pcap_t *, int , pcap_handler , u_char *);
141 static int usb_read_linux_mmap(pcap_t *, int , pcap_handler , u_char *);
142 static int usb_inject_linux(pcap_t *, const void *, size_t);
143 static int usb_setdirection_linux(pcap_t *, pcap_direction_t);
144 static void usb_cleanup_linux_mmap(pcap_t *);
145 
146 /* facility to add an USB device to the device list*/
147 static int
148 usb_dev_add(pcap_if_t** alldevsp, int n, char *err_str)
149 {
150 	char dev_name[10];
151 	char dev_descr[30];
152 	pcap_snprintf(dev_name, 10, USB_IFACE"%d", n);
153 	pcap_snprintf(dev_descr, 30, "USB bus number %d", n);
154 
155 	if (pcap_add_if(alldevsp, dev_name, 0,
156 	    dev_descr, err_str) < 0)
157 		return -1;
158 	return 0;
159 }
160 
161 int
162 usb_findalldevs(pcap_if_t **alldevsp, char *err_str)
163 {
164 	int fd;
165 	struct dirent* data;
166 	int ret = 0;
167 	DIR* dir;
168 	int n;
169 	char* name;
170 	size_t len;
171 
172 	/*
173 	 * Do we have a "scan all buses" device?
174 	 * First, try the binary device.
175 	 */
176 	fd = open(LINUX_USB_MON_DEV"0", O_RDONLY, 0);
177 	if (fd >= 0) {
178 		/*
179 		 * Yes.
180 		 */
181 		close(fd);
182 		if (pcap_add_if(alldevsp, "usbmon0", 0, "All USB buses",
183 		    err_str) < 0)
184 			return -1;
185 	} else {
186 		/*
187 		 * No binary device; do we have the text device?
188 		 */
189 		fd = open(USB_TEXT_DIR"/0t", O_RDONLY, 0);
190 		if (fd < 0) {
191 			/*
192 			 * Not at the new location; try the old location.
193 			 */
194 			fd = open(USB_TEXT_DIR_OLD"/0t", O_RDONLY, 0);
195 		}
196 		if (fd >= 0) {
197 			/*
198 			 * We found it.
199 			 */
200 			close(fd);
201 			if (pcap_add_if(alldevsp, "usbmon0", 0, "All USB buses",
202 			    err_str) < 0)
203 				return -1;
204 		}
205 	}
206 
207 	/*
208 	 * Now look for individual USB buses.
209 	 *
210 	 * First, try scanning sysfs USB bus directory.
211 	 */
212 	dir = opendir(SYS_USB_BUS_DIR);
213 	if (dir != NULL) {
214 		while ((ret == 0) && ((data = readdir(dir)) != 0)) {
215 			name = data->d_name;
216 
217 			if (strncmp(name, "usb", 3) != 0)
218 				continue;
219 
220 			if (sscanf(&name[3], "%d", &n) == 0)
221 				continue;
222 
223 			ret = usb_dev_add(alldevsp, n, err_str);
224 		}
225 
226 		closedir(dir);
227 		return ret;
228 	}
229 
230 	/* That didn't work; try scanning procfs USB bus directory. */
231 	dir = opendir(PROC_USB_BUS_DIR);
232 	if (dir != NULL) {
233 		while ((ret == 0) && ((data = readdir(dir)) != 0)) {
234 			name = data->d_name;
235 			len = strlen(name);
236 
237 			/* if this file name does not end with a number it's not of our interest */
238 			if ((len < 1) || !isdigit(name[--len]))
239 				continue;
240 			while (isdigit(name[--len]));
241 			if (sscanf(&name[len+1], "%d", &n) != 1)
242 				continue;
243 
244 			ret = usb_dev_add(alldevsp, n, err_str);
245 		}
246 
247 		closedir(dir);
248 		return ret;
249 	}
250 
251 	/* neither of them worked */
252 	return 0;
253 }
254 
255 static
256 int usb_mmap(pcap_t* handle)
257 {
258 	struct pcap_usb_linux *handlep = handle->priv;
259 	int len = ioctl(handle->fd, MON_IOCQ_RING_SIZE);
260 	if (len < 0)
261 		return 0;
262 
263 	handlep->mmapbuflen = len;
264 	handlep->mmapbuf = mmap(0, handlep->mmapbuflen, PROT_READ,
265 	    MAP_SHARED, handle->fd, 0);
266 	return handlep->mmapbuf != MAP_FAILED;
267 }
268 
269 #ifdef HAVE_LINUX_USBDEVICE_FS_H
270 
271 #define CTRL_TIMEOUT    (5*1000)        /* milliseconds */
272 
273 #define USB_DIR_IN		0x80
274 #define USB_TYPE_STANDARD	0x00
275 #define USB_RECIP_DEVICE	0x00
276 
277 #define USB_REQ_GET_DESCRIPTOR	6
278 
279 #define USB_DT_DEVICE		1
280 
281 /* probe the descriptors of the devices attached to the bus */
282 /* the descriptors will end up in the captured packet stream */
283 /* and be decoded by external apps like wireshark */
284 /* without these identifying probes packet data can't be fully decoded */
285 static void
286 probe_devices(int bus)
287 {
288 	struct usbdevfs_ctrltransfer ctrl;
289 	struct dirent* data;
290 	int ret = 0;
291 	char buf[40];
292 	DIR* dir;
293 
294 	/* scan usb bus directories for device nodes */
295 	pcap_snprintf(buf, sizeof(buf), "/dev/bus/usb/%03d", bus);
296 	dir = opendir(buf);
297 	if (!dir)
298 		return;
299 
300 	while ((ret >= 0) && ((data = readdir(dir)) != 0)) {
301 		int fd;
302 		char* name = data->d_name;
303 
304 		if (name[0] == '.')
305 			continue;
306 
307 		pcap_snprintf(buf, sizeof(buf), "/dev/bus/usb/%03d/%s", bus, data->d_name);
308 
309 		fd = open(buf, O_RDWR);
310 		if (fd == -1)
311 			continue;
312 
313 		/*
314 		 * Sigh.  Different kernels have different member names
315 		 * for this structure.
316 		 */
317 #ifdef HAVE_USBDEVFS_CTRLTRANSFER_BREQUESTTYPE
318 		ctrl.bRequestType = USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE;
319 		ctrl.bRequest = USB_REQ_GET_DESCRIPTOR;
320 		ctrl.wValue = USB_DT_DEVICE << 8;
321 		ctrl.wIndex = 0;
322  		ctrl.wLength = sizeof(buf);
323 #else
324 		ctrl.requesttype = USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE;
325 		ctrl.request = USB_REQ_GET_DESCRIPTOR;
326 		ctrl.value = USB_DT_DEVICE << 8;
327 		ctrl.index = 0;
328  		ctrl.length = sizeof(buf);
329 #endif
330 		ctrl.data = buf;
331 		ctrl.timeout = CTRL_TIMEOUT;
332 
333 		ret = ioctl(fd, USBDEVFS_CONTROL, &ctrl);
334 
335 		close(fd);
336 	}
337 	closedir(dir);
338 }
339 #endif /* HAVE_LINUX_USBDEVICE_FS_H */
340 
341 pcap_t *
342 usb_create(const char *device, char *ebuf, int *is_ours)
343 {
344 	const char *cp;
345 	char *cpend;
346 	long devnum;
347 	pcap_t *p;
348 
349 	/* Does this look like a USB monitoring device? */
350 	cp = strrchr(device, '/');
351 	if (cp == NULL)
352 		cp = device;
353 	/* Does it begin with USB_IFACE? */
354 	if (strncmp(cp, USB_IFACE, sizeof USB_IFACE - 1) != 0) {
355 		/* Nope, doesn't begin with USB_IFACE */
356 		*is_ours = 0;
357 		return NULL;
358 	}
359 	/* Yes - is USB_IFACE followed by a number? */
360 	cp += sizeof USB_IFACE - 1;
361 	devnum = strtol(cp, &cpend, 10);
362 	if (cpend == cp || *cpend != '\0') {
363 		/* Not followed by a number. */
364 		*is_ours = 0;
365 		return NULL;
366 	}
367 	if (devnum < 0) {
368 		/* Followed by a non-valid number. */
369 		*is_ours = 0;
370 		return NULL;
371 	}
372 
373 	/* OK, it's probably ours. */
374 	*is_ours = 1;
375 
376 	p = pcap_create_common(ebuf, sizeof (struct pcap_usb_linux));
377 	if (p == NULL)
378 		return (NULL);
379 
380 	p->activate_op = usb_activate;
381 	return (p);
382 }
383 
384 static int
385 usb_activate(pcap_t* handle)
386 {
387 	struct pcap_usb_linux *handlep = handle->priv;
388 	char 		full_path[USB_LINE_LEN];
389 
390 	/* Initialize some components of the pcap structure. */
391 	handle->bufsize = handle->snapshot;
392 	handle->offset = 0;
393 	handle->linktype = DLT_USB_LINUX;
394 
395 	handle->inject_op = usb_inject_linux;
396 	handle->setfilter_op = install_bpf_program; /* no kernel filtering */
397 	handle->setdirection_op = usb_setdirection_linux;
398 	handle->set_datalink_op = NULL;	/* can't change data link type */
399 	handle->getnonblock_op = pcap_getnonblock_fd;
400 	handle->setnonblock_op = pcap_setnonblock_fd;
401 
402 	/*get usb bus index from device name */
403 	if (sscanf(handle->opt.device, USB_IFACE"%d", &handlep->bus_index) != 1)
404 	{
405 		pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
406 			"Can't get USB bus index from %s", handle->opt.device);
407 		return PCAP_ERROR;
408 	}
409 
410 	/*now select the read method: try to open binary interface */
411 	pcap_snprintf(full_path, USB_LINE_LEN, LINUX_USB_MON_DEV"%d", handlep->bus_index);
412 	handle->fd = open(full_path, O_RDONLY, 0);
413 	if (handle->fd >= 0)
414 	{
415 		if (handle->opt.rfmon) {
416 			/*
417 			 * Monitor mode doesn't apply to USB devices.
418 			 */
419 			close(handle->fd);
420 			return PCAP_ERROR_RFMON_NOTSUP;
421 		}
422 
423 		/* binary api is available, try to use fast mmap access */
424 		if (usb_mmap(handle)) {
425 			handle->linktype = DLT_USB_LINUX_MMAPPED;
426 			handle->stats_op = usb_stats_linux_bin;
427 			handle->read_op = usb_read_linux_mmap;
428 			handle->cleanup_op = usb_cleanup_linux_mmap;
429 #ifdef HAVE_LINUX_USBDEVICE_FS_H
430 			probe_devices(handlep->bus_index);
431 #endif
432 
433 			/*
434 			 * "handle->fd" is a real file, so "select()" and
435 			 * "poll()" work on it.
436 			 */
437 			handle->selectable_fd = handle->fd;
438 			return 0;
439 		}
440 
441 		/* can't mmap, use plain binary interface access */
442 		handle->stats_op = usb_stats_linux_bin;
443 		handle->read_op = usb_read_linux_bin;
444 #ifdef HAVE_LINUX_USBDEVICE_FS_H
445 		probe_devices(handlep->bus_index);
446 #endif
447 	}
448 	else {
449 		/*Binary interface not available, try open text interface */
450 		pcap_snprintf(full_path, USB_LINE_LEN, USB_TEXT_DIR"/%dt", handlep->bus_index);
451 		handle->fd = open(full_path, O_RDONLY, 0);
452 		if (handle->fd < 0)
453 		{
454 			if (errno == ENOENT)
455 			{
456 				/*
457 				 * Not found at the new location; try
458 				 * the old location.
459 				 */
460 				pcap_snprintf(full_path, USB_LINE_LEN, USB_TEXT_DIR_OLD"/%dt", handlep->bus_index);
461 				handle->fd = open(full_path, O_RDONLY, 0);
462 			}
463 			if (handle->fd < 0) {
464 				/* no more fallback, give it up*/
465 				pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
466 					"Can't open USB bus file %s: %s", full_path, strerror(errno));
467 				return PCAP_ERROR;
468 			}
469 		}
470 
471 		if (handle->opt.rfmon) {
472 			/*
473 			 * Monitor mode doesn't apply to USB devices.
474 			 */
475 			close(handle->fd);
476 			return PCAP_ERROR_RFMON_NOTSUP;
477 		}
478 
479 		handle->stats_op = usb_stats_linux;
480 		handle->read_op = usb_read_linux;
481 	}
482 
483 	/*
484 	 * "handle->fd" is a real file, so "select()" and "poll()"
485 	 * work on it.
486 	 */
487 	handle->selectable_fd = handle->fd;
488 
489 	/* for plain binary access and text access we need to allocate the read
490 	 * buffer */
491 	handle->buffer = malloc(handle->bufsize);
492 	if (!handle->buffer) {
493 		pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
494 			 "malloc: %s", pcap_strerror(errno));
495 		close(handle->fd);
496 		return PCAP_ERROR;
497 	}
498 	return 0;
499 }
500 
501 static inline int
502 ascii_to_int(char c)
503 {
504 	return c < 'A' ? c- '0': ((c<'a') ? c - 'A' + 10: c-'a'+10);
505 }
506 
507 /*
508  * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
509  * <linux-kernel-source>/drivers/usb/mon/mon_text.c for urb string
510  * format description
511  */
512 static int
513 usb_read_linux(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
514 {
515 	/* see:
516 	* /usr/src/linux/Documentation/usb/usbmon.txt
517 	* for message format
518 	*/
519 	struct pcap_usb_linux *handlep = handle->priv;
520 	unsigned timestamp;
521 	int tag, cnt, ep_num, dev_addr, dummy, ret, urb_len, data_len;
522 	char etype, pipeid1, pipeid2, status[16], urb_tag, line[USB_LINE_LEN];
523 	char *string = line;
524 	u_char * rawdata = handle->buffer;
525 	struct pcap_pkthdr pkth;
526 	pcap_usb_header* uhdr = (pcap_usb_header*)handle->buffer;
527 	u_char urb_transfer=0;
528 	int incoming=0;
529 
530 	/* ignore interrupt system call errors */
531 	do {
532 		ret = read(handle->fd, line, USB_LINE_LEN - 1);
533 		if (handle->break_loop)
534 		{
535 			handle->break_loop = 0;
536 			return -2;
537 		}
538 	} while ((ret == -1) && (errno == EINTR));
539 	if (ret < 0)
540 	{
541 		if (errno == EAGAIN)
542 			return 0;	/* no data there */
543 
544 		pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
545 		    "Can't read from fd %d: %s", handle->fd, strerror(errno));
546 		return -1;
547 	}
548 
549 	/* read urb header; %n argument may increment return value, but it's
550 	* not mandatory, so does not count on it*/
551 	string[ret] = 0;
552 	ret = sscanf(string, "%x %d %c %c%c:%d:%d %s%n", &tag, &timestamp, &etype,
553 		&pipeid1, &pipeid2, &dev_addr, &ep_num, status,
554 		&cnt);
555 	if (ret < 8)
556 	{
557 		pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
558 		    "Can't parse USB bus message '%s', too few tokens (expected 8 got %d)",
559 		    string, ret);
560 		return -1;
561 	}
562 	uhdr->id = tag;
563 	uhdr->device_address = dev_addr;
564 	uhdr->bus_id = handlep->bus_index;
565 	uhdr->status = 0;
566 	string += cnt;
567 
568 	/* don't use usbmon provided timestamp, since it have low precision*/
569 	if (gettimeofday(&pkth.ts, NULL) < 0)
570 	{
571 		pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
572 			"Can't get timestamp for message '%s' %d:%s",
573 			string, errno, strerror(errno));
574 		return -1;
575 	}
576 	uhdr->ts_sec = pkth.ts.tv_sec;
577 	uhdr->ts_usec = pkth.ts.tv_usec;
578 
579 	/* parse endpoint information */
580 	if (pipeid1 == 'C')
581 		urb_transfer = URB_CONTROL;
582 	else if (pipeid1 == 'Z')
583 		urb_transfer = URB_ISOCHRONOUS;
584 	else if (pipeid1 == 'I')
585 		urb_transfer = URB_INTERRUPT;
586 	else if (pipeid1 == 'B')
587 		urb_transfer = URB_BULK;
588 	if (pipeid2 == 'i') {
589 		ep_num |= URB_TRANSFER_IN;
590 		incoming = 1;
591 	}
592 	if (etype == 'C')
593 		incoming = !incoming;
594 
595 	/* direction check*/
596 	if (incoming)
597 	{
598 		if (handle->direction == PCAP_D_OUT)
599 			return 0;
600 	}
601 	else
602 		if (handle->direction == PCAP_D_IN)
603 			return 0;
604 	uhdr->event_type = etype;
605 	uhdr->transfer_type = urb_transfer;
606 	uhdr->endpoint_number = ep_num;
607 	pkth.caplen = sizeof(pcap_usb_header);
608 	rawdata += sizeof(pcap_usb_header);
609 
610 	/* check if this is a setup packet */
611 	ret = sscanf(status, "%d", &dummy);
612 	if (ret != 1)
613 	{
614 		/* this a setup packet, setup data can be filled with underscore if
615 		* usbmon has not been able to read them, so we must parse this fields as
616 		* strings */
617 		pcap_usb_setup* shdr;
618 		char str1[3], str2[3], str3[5], str4[5], str5[5];
619 		ret = sscanf(string, "%s %s %s %s %s%n", str1, str2, str3, str4,
620 		str5, &cnt);
621 		if (ret < 5)
622 		{
623 			pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
624 				"Can't parse USB bus message '%s', too few tokens (expected 5 got %d)",
625 				string, ret);
626 			return -1;
627 		}
628 		string += cnt;
629 
630 		/* try to convert to corresponding integer */
631 		shdr = &uhdr->setup;
632 		shdr->bmRequestType = strtoul(str1, 0, 16);
633 		shdr->bRequest = strtoul(str2, 0, 16);
634 		shdr->wValue = htols(strtoul(str3, 0, 16));
635 		shdr->wIndex = htols(strtoul(str4, 0, 16));
636 		shdr->wLength = htols(strtoul(str5, 0, 16));
637 
638 		uhdr->setup_flag = 0;
639 	}
640 	else
641 		uhdr->setup_flag = 1;
642 
643 	/* read urb data */
644 	ret = sscanf(string, " %d%n", &urb_len, &cnt);
645 	if (ret < 1)
646 	{
647 		pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
648 		  "Can't parse urb length from '%s'", string);
649 		return -1;
650 	}
651 	string += cnt;
652 
653 	/* urb tag is not present if urb length is 0, so we can stop here
654 	 * text parsing */
655 	pkth.len = urb_len+pkth.caplen;
656 	uhdr->urb_len = urb_len;
657 	uhdr->data_flag = 1;
658 	data_len = 0;
659 	if (uhdr->urb_len == 0)
660 		goto got;
661 
662 	/* check for data presence; data is present if and only if urb tag is '=' */
663 	if (sscanf(string, " %c", &urb_tag) != 1)
664 	{
665 		pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
666 			"Can't parse urb tag from '%s'", string);
667 		return -1;
668 	}
669 
670 	if (urb_tag != '=')
671 		goto got;
672 
673 	/* skip urb tag and following space */
674 	string += 3;
675 
676 	/* if we reach this point we got some urb data*/
677 	uhdr->data_flag = 0;
678 
679 	/* read all urb data; if urb length is greater then the usbmon internal
680 	 * buffer length used by the kernel to spool the URB, we get only
681 	 * a partial information.
682 	 * At least until linux 2.6.17 there is no way to set usbmon intenal buffer
683 	 * length and default value is 130. */
684 	while ((string[0] != 0) && (string[1] != 0) && (pkth.caplen < (bpf_u_int32)handle->snapshot))
685 	{
686 		rawdata[0] = ascii_to_int(string[0]) * 16 + ascii_to_int(string[1]);
687 		rawdata++;
688 		string+=2;
689 		if (string[0] == ' ')
690 			string++;
691 		pkth.caplen++;
692 		data_len++;
693 	}
694 
695 got:
696 	uhdr->data_len = data_len;
697 	if (pkth.caplen > (bpf_u_int32)handle->snapshot)
698 		pkth.caplen = (bpf_u_int32)handle->snapshot;
699 
700 	if (handle->fcode.bf_insns == NULL ||
701 	    bpf_filter(handle->fcode.bf_insns, handle->buffer,
702 	      pkth.len, pkth.caplen)) {
703 		handlep->packets_read++;
704 		callback(user, &pkth, handle->buffer);
705 		return 1;
706 	}
707 	return 0;	/* didn't pass filter */
708 }
709 
710 static int
711 usb_inject_linux(pcap_t *handle, const void *buf, size_t size)
712 {
713 	pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "inject not supported on "
714 		"USB devices");
715 	return (-1);
716 }
717 
718 static int
719 usb_stats_linux(pcap_t *handle, struct pcap_stat *stats)
720 {
721 	struct pcap_usb_linux *handlep = handle->priv;
722 	int dummy, ret, consumed, cnt;
723 	char string[USB_LINE_LEN];
724 	char token[USB_LINE_LEN];
725 	char * ptr = string;
726 	int fd;
727 
728 	pcap_snprintf(string, USB_LINE_LEN, USB_TEXT_DIR"/%ds", handlep->bus_index);
729 	fd = open(string, O_RDONLY, 0);
730 	if (fd < 0)
731 	{
732 		if (errno == ENOENT)
733 		{
734 			/*
735 			 * Not found at the new location; try the old
736 			 * location.
737 			 */
738 			pcap_snprintf(string, USB_LINE_LEN, USB_TEXT_DIR_OLD"/%ds", handlep->bus_index);
739 			fd = open(string, O_RDONLY, 0);
740 		}
741 		if (fd < 0) {
742 			pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
743 				"Can't open USB stats file %s: %s",
744 				string, strerror(errno));
745 			return -1;
746 		}
747 	}
748 
749 	/* read stats line */
750 	do {
751 		ret = read(fd, string, USB_LINE_LEN-1);
752 	} while ((ret == -1) && (errno == EINTR));
753 	close(fd);
754 
755 	if (ret < 0)
756 	{
757 		pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
758 			"Can't read stats from fd %d ", fd);
759 		return -1;
760 	}
761 	string[ret] = 0;
762 
763 	/* extract info on dropped urbs */
764 	for (consumed=0; consumed < ret; ) {
765 		/* from the sscanf man page:
766  		 * The C standard says: "Execution of a %n directive does
767  		 * not increment the assignment count returned at the completion
768 		 * of  execution" but the Corrigendum seems to contradict this.
769 		 * Do not make any assumptions on the effect of %n conversions
770 		 * on the return value and explicitly check for cnt assignmet*/
771 		int ntok;
772 
773 		cnt = -1;
774 		ntok = sscanf(ptr, "%s%n", token, &cnt);
775 		if ((ntok < 1) || (cnt < 0))
776 			break;
777 		consumed += cnt;
778 		ptr += cnt;
779 		if (strcmp(token, "nreaders") == 0)
780 			ret = sscanf(ptr, "%d", &stats->ps_drop);
781 		else
782 			ret = sscanf(ptr, "%d", &dummy);
783 		if (ntok != 1)
784 			break;
785 		consumed += cnt;
786 		ptr += cnt;
787 	}
788 
789 	stats->ps_recv = handlep->packets_read;
790 	stats->ps_ifdrop = 0;
791 	return 0;
792 }
793 
794 static int
795 usb_setdirection_linux(pcap_t *p, pcap_direction_t d)
796 {
797 	p->direction = d;
798 	return 0;
799 }
800 
801 
802 static int
803 usb_stats_linux_bin(pcap_t *handle, struct pcap_stat *stats)
804 {
805 	struct pcap_usb_linux *handlep = handle->priv;
806 	int ret;
807 	struct mon_bin_stats st;
808 	ret = ioctl(handle->fd, MON_IOCG_STATS, &st);
809 	if (ret < 0)
810 	{
811 		pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
812 			"Can't read stats from fd %d:%s ", handle->fd, strerror(errno));
813 		return -1;
814 	}
815 
816 	stats->ps_recv = handlep->packets_read + st.queued;
817 	stats->ps_drop = st.dropped;
818 	stats->ps_ifdrop = 0;
819 	return 0;
820 }
821 
822 /*
823  * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
824  * <linux-kernel-source>/drivers/usb/mon/mon_bin.c binary ABI
825  */
826 static int
827 usb_read_linux_bin(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
828 {
829 	struct pcap_usb_linux *handlep = handle->priv;
830 	struct mon_bin_get info;
831 	int ret;
832 	struct pcap_pkthdr pkth;
833 	u_int clen = handle->snapshot - sizeof(pcap_usb_header);
834 
835 	/* the usb header is going to be part of 'packet' data*/
836 	info.hdr = (pcap_usb_header*) handle->buffer;
837 	info.data = (u_char *)handle->buffer + sizeof(pcap_usb_header);
838 	info.data_len = clen;
839 
840 	/* ignore interrupt system call errors */
841 	do {
842 		ret = ioctl(handle->fd, MON_IOCX_GET, &info);
843 		if (handle->break_loop)
844 		{
845 			handle->break_loop = 0;
846 			return -2;
847 		}
848 	} while ((ret == -1) && (errno == EINTR));
849 	if (ret < 0)
850 	{
851 		if (errno == EAGAIN)
852 			return 0;	/* no data there */
853 
854 		pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
855 		    "Can't read from fd %d: %s", handle->fd, strerror(errno));
856 		return -1;
857 	}
858 
859 	/* we can get less that than really captured from kernel, depending on
860 	 * snaplen, so adjust header accordingly */
861 	if (info.hdr->data_len < clen)
862 		clen = info.hdr->data_len;
863 	info.hdr->data_len = clen;
864 	pkth.caplen = clen + sizeof(pcap_usb_header);
865 	pkth.len = info.hdr->data_len + sizeof(pcap_usb_header);
866 	pkth.ts.tv_sec = info.hdr->ts_sec;
867 	pkth.ts.tv_usec = info.hdr->ts_usec;
868 
869 	if (handle->fcode.bf_insns == NULL ||
870 	    bpf_filter(handle->fcode.bf_insns, handle->buffer,
871 	      pkth.len, pkth.caplen)) {
872 		handlep->packets_read++;
873 		callback(user, &pkth, handle->buffer);
874 		return 1;
875 	}
876 
877 	return 0;	/* didn't pass filter */
878 }
879 
880 /*
881  * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
882  * <linux-kernel-source>/drivers/usb/mon/mon_bin.c binary ABI
883  */
884 #define VEC_SIZE 32
885 static int
886 usb_read_linux_mmap(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
887 {
888 	struct pcap_usb_linux *handlep = handle->priv;
889 	struct mon_bin_mfetch fetch;
890 	int32_t vec[VEC_SIZE];
891 	struct pcap_pkthdr pkth;
892 	pcap_usb_header* hdr;
893 	int nflush = 0;
894 	int packets = 0;
895 	u_int clen, max_clen;
896 
897 	max_clen = handle->snapshot - sizeof(pcap_usb_header);
898 
899 	for (;;) {
900 		int i, ret;
901 		int limit = max_packets - packets;
902 		if (limit <= 0)
903 			limit = VEC_SIZE;
904 		if (limit > VEC_SIZE)
905 			limit = VEC_SIZE;
906 
907 		/* try to fetch as many events as possible*/
908 		fetch.offvec = vec;
909 		fetch.nfetch = limit;
910 		fetch.nflush = nflush;
911 		/* ignore interrupt system call errors */
912 		do {
913 			ret = ioctl(handle->fd, MON_IOCX_MFETCH, &fetch);
914 			if (handle->break_loop)
915 			{
916 				handle->break_loop = 0;
917 				return -2;
918 			}
919 		} while ((ret == -1) && (errno == EINTR));
920 		if (ret < 0)
921 		{
922 			if (errno == EAGAIN)
923 				return 0;	/* no data there */
924 
925 			pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
926 			    "Can't mfetch fd %d: %s", handle->fd, strerror(errno));
927 			return -1;
928 		}
929 
930 		/* keep track of processed events, we will flush them later */
931 		nflush = fetch.nfetch;
932 		for (i=0; i<fetch.nfetch; ++i) {
933 			/* discard filler */
934 			hdr = (pcap_usb_header*) &handlep->mmapbuf[vec[i]];
935 			if (hdr->event_type == '@')
936 				continue;
937 
938 			/* we can get less that than really captured from kernel, depending on
939 	 		* snaplen, so adjust header accordingly */
940 			clen = max_clen;
941 			if (hdr->data_len < clen)
942 				clen = hdr->data_len;
943 
944 			/* get packet info from header*/
945 			pkth.caplen = clen + sizeof(pcap_usb_header_mmapped);
946 			pkth.len = hdr->data_len + sizeof(pcap_usb_header_mmapped);
947 			pkth.ts.tv_sec = hdr->ts_sec;
948 			pkth.ts.tv_usec = hdr->ts_usec;
949 
950 			if (handle->fcode.bf_insns == NULL ||
951 			    bpf_filter(handle->fcode.bf_insns, (u_char*) hdr,
952 			      pkth.len, pkth.caplen)) {
953 				handlep->packets_read++;
954 				callback(user, &pkth, (u_char*) hdr);
955 				packets++;
956 			}
957 		}
958 
959 		/* with max_packets specifying "unlimited" we stop afer the first chunk*/
960 		if (PACKET_COUNT_IS_UNLIMITED(max_packets) || (packets == max_packets))
961 			break;
962 	}
963 
964 	/* flush pending events*/
965 	if (ioctl(handle->fd, MON_IOCH_MFLUSH, nflush) == -1) {
966 		pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
967 		    "Can't mflush fd %d: %s", handle->fd, strerror(errno));
968 		return -1;
969 	}
970 	return packets;
971 }
972 
973 static void
974 usb_cleanup_linux_mmap(pcap_t* handle)
975 {
976 	struct pcap_usb_linux *handlep = handle->priv;
977 
978 	/* if we have a memory-mapped buffer, unmap it */
979 	if (handlep->mmapbuf != NULL) {
980 		munmap(handlep->mmapbuf, handlep->mmapbuflen);
981 		handlep->mmapbuf = NULL;
982 	}
983 	pcap_cleanup_live_common(handle);
984 }
985