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