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