1335640Shselasky/*
2335640Shselasky * Copyright (c) 2006 Paolo Abeni (Italy)
3335640Shselasky * All rights reserved.
4335640Shselasky *
5335640Shselasky * Redistribution and use in source and binary forms, with or without
6335640Shselasky * modification, are permitted provided that the following conditions
7335640Shselasky * are met:
8335640Shselasky *
9335640Shselasky * 1. Redistributions of source code must retain the above copyright
10335640Shselasky * notice, this list of conditions and the following disclaimer.
11335640Shselasky * 2. Redistributions in binary form must reproduce the above copyright
12335640Shselasky * notice, this list of conditions and the following disclaimer in the
13335640Shselasky * documentation and/or other materials provided with the distribution.
14335640Shselasky * 3. The name of the author may not be used to endorse or promote
15335640Shselasky * products derived from this software without specific prior written
16335640Shselasky * permission.
17335640Shselasky *
18335640Shselasky * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19335640Shselasky * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20335640Shselasky * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21335640Shselasky * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22335640Shselasky * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23335640Shselasky * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24335640Shselasky * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25335640Shselasky * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26335640Shselasky * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27335640Shselasky * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28335640Shselasky * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29335640Shselasky *
30335640Shselasky * USB sniffing API implementation for Linux platform
31335640Shselasky * By Paolo Abeni <paolo.abeni@email.it>
32335640Shselasky * Modifications: Kris Katterjohn <katterjohn@gmail.com>
33335640Shselasky *
34335640Shselasky */
35335640Shselasky
36335640Shselasky#ifdef HAVE_CONFIG_H
37335640Shselasky#include <config.h>
38335640Shselasky#endif
39335640Shselasky
40335640Shselasky#include "pcap-int.h"
41335640Shselasky#include "pcap-usb-linux.h"
42335640Shselasky#include "pcap/usb.h"
43335640Shselasky
44335640Shselasky#ifdef NEED_STRERROR_H
45335640Shselasky#include "strerror.h"
46335640Shselasky#endif
47335640Shselasky
48335640Shselasky#include <ctype.h>
49335640Shselasky#include <errno.h>
50335640Shselasky#include <stdlib.h>
51335640Shselasky#include <unistd.h>
52335640Shselasky#include <fcntl.h>
53356341Scy#include <limits.h>
54335640Shselasky#include <string.h>
55335640Shselasky#include <dirent.h>
56335640Shselasky#include <byteswap.h>
57335640Shselasky#include <netinet/in.h>
58335640Shselasky#include <sys/ioctl.h>
59335640Shselasky#include <sys/mman.h>
60335640Shselasky#include <sys/utsname.h>
61335640Shselasky#ifdef HAVE_LINUX_USBDEVICE_FS_H
62335640Shselasky/*
63335640Shselasky * We might need <linux/compiler.h> to define __user for
64335640Shselasky * <linux/usbdevice_fs.h>.
65335640Shselasky */
66335640Shselasky#ifdef HAVE_LINUX_COMPILER_H
67335640Shselasky#include <linux/compiler.h>
68335640Shselasky#endif /* HAVE_LINUX_COMPILER_H */
69335640Shselasky#include <linux/usbdevice_fs.h>
70335640Shselasky#endif /* HAVE_LINUX_USBDEVICE_FS_H */
71335640Shselasky
72335640Shselasky#define USB_IFACE "usbmon"
73335640Shselasky#define USB_TEXT_DIR_OLD "/sys/kernel/debug/usbmon"
74335640Shselasky#define USB_TEXT_DIR "/sys/kernel/debug/usb/usbmon"
75335640Shselasky#define SYS_USB_BUS_DIR "/sys/bus/usb/devices"
76335640Shselasky#define PROC_USB_BUS_DIR "/proc/bus/usb"
77335640Shselasky#define USB_LINE_LEN 4096
78335640Shselasky
79335640Shselasky#if __BYTE_ORDER == __LITTLE_ENDIAN
80335640Shselasky#define htols(s) s
81335640Shselasky#define htoll(l) l
82335640Shselasky#define htol64(ll) ll
83335640Shselasky#else
84335640Shselasky#define htols(s) bswap_16(s)
85335640Shselasky#define htoll(l) bswap_32(l)
86335640Shselasky#define htol64(ll) bswap_64(ll)
87335640Shselasky#endif
88335640Shselasky
89335640Shselaskystruct mon_bin_stats {
90335640Shselasky	uint32_t queued;
91335640Shselasky	uint32_t dropped;
92335640Shselasky};
93335640Shselasky
94335640Shselaskystruct mon_bin_get {
95335640Shselasky	pcap_usb_header *hdr;
96335640Shselasky	void *data;
97335640Shselasky	size_t data_len;   /* Length of data (can be zero) */
98335640Shselasky};
99335640Shselasky
100335640Shselaskystruct mon_bin_mfetch {
101335640Shselasky	int32_t *offvec;   /* Vector of events fetched */
102335640Shselasky	int32_t nfetch;    /* Number of events to fetch (out: fetched) */
103335640Shselasky	int32_t nflush;    /* Number of events to flush */
104335640Shselasky};
105335640Shselasky
106335640Shselasky#define MON_IOC_MAGIC 0x92
107335640Shselasky
108335640Shselasky#define MON_IOCQ_URB_LEN _IO(MON_IOC_MAGIC, 1)
109335640Shselasky#define MON_IOCX_URB  _IOWR(MON_IOC_MAGIC, 2, struct mon_bin_hdr)
110335640Shselasky#define MON_IOCG_STATS _IOR(MON_IOC_MAGIC, 3, struct mon_bin_stats)
111335640Shselasky#define MON_IOCT_RING_SIZE _IO(MON_IOC_MAGIC, 4)
112335640Shselasky#define MON_IOCQ_RING_SIZE _IO(MON_IOC_MAGIC, 5)
113335640Shselasky#define MON_IOCX_GET   _IOW(MON_IOC_MAGIC, 6, struct mon_bin_get)
114335640Shselasky#define MON_IOCX_MFETCH _IOWR(MON_IOC_MAGIC, 7, struct mon_bin_mfetch)
115335640Shselasky#define MON_IOCH_MFLUSH _IO(MON_IOC_MAGIC, 8)
116335640Shselasky
117335640Shselasky#define MON_BIN_SETUP 	0x1 /* setup hdr is present*/
118335640Shselasky#define MON_BIN_SETUP_ZERO 	0x2 /* setup buffer is not available */
119335640Shselasky#define MON_BIN_DATA_ZERO 	0x4 /* data buffer is not available */
120335640Shselasky#define MON_BIN_ERROR 	0x8
121335640Shselasky
122335640Shselasky/*
123335640Shselasky * Private data for capturing on Linux USB.
124335640Shselasky */
125335640Shselaskystruct pcap_usb_linux {
126335640Shselasky	u_char *mmapbuf;	/* memory-mapped region pointer */
127335640Shselasky	size_t mmapbuflen;	/* size of region */
128335640Shselasky	int bus_index;
129335640Shselasky	u_int packets_read;
130335640Shselasky};
131335640Shselasky
132335640Shselasky/* forward declaration */
133335640Shselaskystatic int usb_activate(pcap_t *);
134335640Shselaskystatic int usb_stats_linux(pcap_t *, struct pcap_stat *);
135335640Shselaskystatic int usb_stats_linux_bin(pcap_t *, struct pcap_stat *);
136335640Shselaskystatic int usb_read_linux(pcap_t *, int , pcap_handler , u_char *);
137335640Shselaskystatic int usb_read_linux_bin(pcap_t *, int , pcap_handler , u_char *);
138335640Shselaskystatic int usb_read_linux_mmap(pcap_t *, int , pcap_handler , u_char *);
139335640Shselaskystatic int usb_inject_linux(pcap_t *, const void *, size_t);
140335640Shselaskystatic int usb_setdirection_linux(pcap_t *, pcap_direction_t);
141335640Shselaskystatic void usb_cleanup_linux_mmap(pcap_t *);
142335640Shselasky
143335640Shselaskystatic int
144335640Shselaskyhave_binary_usbmon(void)
145335640Shselasky{
146335640Shselasky	struct utsname utsname;
147335640Shselasky	char *version_component, *endp;
148335640Shselasky	int major, minor, subminor;
149335640Shselasky
150335640Shselasky	if (uname(&utsname) == 0) {
151335640Shselasky		/*
152335640Shselasky		 * 2.6.21 is the first release with the binary-mode
153335640Shselasky		 * USB monitoring.
154335640Shselasky		 */
155335640Shselasky		version_component = utsname.release;
156335640Shselasky		major = strtol(version_component, &endp, 10);
157335640Shselasky		if (endp != version_component && *endp == '.') {
158335640Shselasky			/*
159335640Shselasky			 * OK, that was a valid major version.
160335640Shselasky			 * Is it 3 or greater?  If so, we have binary
161335640Shselasky			 * mode support.
162335640Shselasky			 */
163335640Shselasky			if (major >= 3)
164335640Shselasky				return 1;
165335640Shselasky
166335640Shselasky			/*
167335640Shselasky			 * Is it 1 or less?  If so, we don't have binary
168335640Shselasky			 * mode support.  (In fact, we don't have any
169335640Shselasky			 * USB monitoring....)
170335640Shselasky			 */
171335640Shselasky			if (major <= 1)
172335640Shselasky				return 0;
173335640Shselasky		}
174335640Shselasky
175335640Shselasky		/*
176335640Shselasky		 * OK, this is a 2.x kernel.
177335640Shselasky		 * What's the minor version?
178335640Shselasky		 */
179335640Shselasky		version_component = endp + 1;
180335640Shselasky		minor = strtol(version_component, &endp, 10);
181335640Shselasky		if (endp != version_component &&
182335640Shselasky		    (*endp == '.' || *endp == '\0')) {
183335640Shselasky			/*
184335640Shselasky			 * OK, that was a valid minor version.
185335640Shselasky			 * Is is 2.6 or later?  (There shouldn't be a
186335640Shselasky			 * "later", as 2.6.x went to 3.x, but we'll
187335640Shselasky			 * check anyway.)
188335640Shselasky			 */
189335640Shselasky			if (minor < 6) {
190335640Shselasky				/*
191335640Shselasky				 * No, so no binary support (did 2.4 have
192335640Shselasky				 * any USB monitoring at all?)
193335640Shselasky				 */
194335640Shselasky				return 0;
195335640Shselasky			}
196335640Shselasky
197335640Shselasky			/*
198335640Shselasky			 * OK, this is a 2.6.x kernel.
199335640Shselasky			 * What's the subminor version?
200335640Shselasky			 */
201335640Shselasky			version_component = endp + 1;
202335640Shselasky			subminor = strtol(version_component, &endp, 10);
203335640Shselasky			if (endp != version_component &&
204335640Shselasky			    (*endp == '.' || *endp == '\0')) {
205335640Shselasky				/*
206335640Shselasky				 * OK, that was a valid subminor version.
207335640Shselasky				 * Is it 21 or greater?
208335640Shselasky				 */
209335640Shselasky				if (subminor >= 21) {
210335640Shselasky					/*
211335640Shselasky					 * Yes - we have binary mode
212335640Shselasky					 * support.
213335640Shselasky					 */
214335640Shselasky					return 1;
215335640Shselasky				}
216335640Shselasky			}
217335640Shselasky		}
218335640Shselasky	}
219335640Shselasky
220335640Shselasky	/*
221335640Shselasky	 * Either uname() failed, in which case we just say "no binary
222335640Shselasky	 * mode support", or we don't have binary mode support.
223335640Shselasky	 */
224335640Shselasky	return 0;
225335640Shselasky}
226335640Shselasky
227335640Shselasky/* facility to add an USB device to the device list*/
228335640Shselaskystatic int
229335640Shselaskyusb_dev_add(pcap_if_list_t *devlistp, int n, char *err_str)
230335640Shselasky{
231335640Shselasky	char dev_name[10];
232335640Shselasky	char dev_descr[30];
233335640Shselasky	pcap_snprintf(dev_name, 10, USB_IFACE"%d", n);
234335640Shselasky	/*
235335640Shselasky	 * XXX - is there any notion of "up" and "running"?
236335640Shselasky	 */
237335640Shselasky	if (n == 0) {
238335640Shselasky		/*
239335640Shselasky		 * As this refers to all buses, there's no notion of
240335640Shselasky		 * "connected" vs. "disconnected", as that's a property
241335640Shselasky		 * that would apply to a particular USB interface.
242335640Shselasky		 */
243335640Shselasky		if (add_dev(devlistp, dev_name,
244335640Shselasky		    PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE,
245356341Scy		    "Raw USB traffic, all USB buses", err_str) == NULL)
246335640Shselasky			return -1;
247335640Shselasky	} else {
248335640Shselasky		/*
249335640Shselasky		 * XXX - is there a way to determine whether anything's
250335640Shselasky		 * plugged into this bus interface or not, and set
251335640Shselasky		 * PCAP_IF_CONNECTION_STATUS_CONNECTED or
252335640Shselasky		 * PCAP_IF_CONNECTION_STATUS_DISCONNECTED?
253335640Shselasky		 */
254356341Scy		pcap_snprintf(dev_descr, 30, "Raw USB traffic, bus number %d", n);
255335640Shselasky		if (add_dev(devlistp, dev_name, 0, dev_descr, err_str) == NULL)
256335640Shselasky			return -1;
257335640Shselasky	}
258335640Shselasky
259335640Shselasky	return 0;
260335640Shselasky}
261335640Shselasky
262335640Shselaskyint
263335640Shselaskyusb_findalldevs(pcap_if_list_t *devlistp, char *err_str)
264335640Shselasky{
265335640Shselasky	char usb_mon_dir[PATH_MAX];
266335640Shselasky	char *usb_mon_prefix;
267335640Shselasky	size_t usb_mon_prefix_len;
268335640Shselasky	struct dirent* data;
269335640Shselasky	int ret = 0;
270335640Shselasky	DIR* dir;
271335640Shselasky	int n;
272335640Shselasky	char* name;
273335640Shselasky	size_t len;
274335640Shselasky
275335640Shselasky	if (have_binary_usbmon()) {
276335640Shselasky		/*
277335640Shselasky		 * We have binary-mode support.
278335640Shselasky		 * What do the device names look like?
279335640Shselasky		 * Split LINUX_USB_MON_DEV into a directory that we'll
280335640Shselasky		 * scan and a file name prefix that we'll check for.
281335640Shselasky		 */
282356341Scy		pcap_strlcpy(usb_mon_dir, LINUX_USB_MON_DEV, sizeof usb_mon_dir);
283335640Shselasky		usb_mon_prefix = strrchr(usb_mon_dir, '/');
284335640Shselasky		if (usb_mon_prefix == NULL) {
285335640Shselasky			/*
286335640Shselasky			 * This "shouldn't happen".  Just give up if it
287335640Shselasky			 * does.
288335640Shselasky			 */
289335640Shselasky			return 0;
290335640Shselasky		}
291335640Shselasky		*usb_mon_prefix++ = '\0';
292335640Shselasky		usb_mon_prefix_len = strlen(usb_mon_prefix);
293335640Shselasky
294335640Shselasky		/*
295335640Shselasky		 * Open the directory and scan it.
296335640Shselasky		 */
297335640Shselasky		dir = opendir(usb_mon_dir);
298335640Shselasky		if (dir != NULL) {
299335640Shselasky			while ((ret == 0) && ((data = readdir(dir)) != 0)) {
300335640Shselasky				name = data->d_name;
301335640Shselasky
302335640Shselasky				/*
303335640Shselasky				 * Is this a usbmon device?
304335640Shselasky				 */
305335640Shselasky				if (strncmp(name, usb_mon_prefix, usb_mon_prefix_len) != 0)
306335640Shselasky					continue;	/* no */
307335640Shselasky
308335640Shselasky				/*
309335640Shselasky				 * What's the device number?
310335640Shselasky				 */
311335640Shselasky				if (sscanf(&name[usb_mon_prefix_len], "%d", &n) == 0)
312335640Shselasky					continue;	/* failed */
313335640Shselasky
314335640Shselasky				ret = usb_dev_add(devlistp, n, err_str);
315335640Shselasky			}
316335640Shselasky
317335640Shselasky			closedir(dir);
318335640Shselasky		}
319335640Shselasky		return 0;
320335640Shselasky	} else {
321335640Shselasky		/*
322335640Shselasky		 * We have only text mode support.
323335640Shselasky		 * We don't look for the text devices because we can't
324335640Shselasky		 * look for them without root privileges, and we don't
325335640Shselasky		 * want to require root privileges to enumerate devices
326335640Shselasky		 * (we want to let the user to try a device and get
327335640Shselasky		 * an error, rather than seeing no devices and asking
328335640Shselasky		 * "why am I not seeing devices" and forcing a long
329335640Shselasky		 * process of poking to figure out whether it's "no
330335640Shselasky		 * privileges" or "your kernel is too old" or "the
331335640Shselasky		 * usbmon module isn't loaded" or...).
332335640Shselasky		 *
333335640Shselasky		 * Instead, we look to see what buses we have.
334335640Shselasky		 * If the kernel is so old that it doesn't have
335335640Shselasky		 * binary-mode support, it's also so old that
336335640Shselasky		 * it doesn't have a "scan all buses" device.
337335640Shselasky		 *
338335640Shselasky		 * First, try scanning sysfs USB bus directory.
339335640Shselasky		 */
340335640Shselasky		dir = opendir(SYS_USB_BUS_DIR);
341335640Shselasky		if (dir != NULL) {
342335640Shselasky			while ((ret == 0) && ((data = readdir(dir)) != 0)) {
343335640Shselasky				name = data->d_name;
344335640Shselasky
345335640Shselasky				if (strncmp(name, "usb", 3) != 0)
346335640Shselasky					continue;
347335640Shselasky
348335640Shselasky				if (sscanf(&name[3], "%d", &n) == 0)
349335640Shselasky					continue;
350335640Shselasky
351335640Shselasky				ret = usb_dev_add(devlistp, n, err_str);
352335640Shselasky			}
353335640Shselasky
354335640Shselasky			closedir(dir);
355335640Shselasky			return 0;
356335640Shselasky		}
357335640Shselasky
358335640Shselasky		/* That didn't work; try scanning procfs USB bus directory. */
359335640Shselasky		dir = opendir(PROC_USB_BUS_DIR);
360335640Shselasky		if (dir != NULL) {
361335640Shselasky			while ((ret == 0) && ((data = readdir(dir)) != 0)) {
362335640Shselasky				name = data->d_name;
363335640Shselasky				len = strlen(name);
364335640Shselasky
365335640Shselasky				/* if this file name does not end with a number it's not of our interest */
366335640Shselasky				if ((len < 1) || !isdigit(name[--len]))
367335640Shselasky					continue;
368335640Shselasky				while (isdigit(name[--len]));
369335640Shselasky				if (sscanf(&name[len+1], "%d", &n) != 1)
370335640Shselasky					continue;
371335640Shselasky
372335640Shselasky				ret = usb_dev_add(devlistp, n, err_str);
373335640Shselasky			}
374335640Shselasky
375335640Shselasky			closedir(dir);
376335640Shselasky			return ret;
377335640Shselasky		}
378335640Shselasky
379335640Shselasky		/* neither of them worked */
380335640Shselasky		return 0;
381335640Shselasky	}
382335640Shselasky}
383335640Shselasky
384356341Scy/*
385356341Scy * Matches what's in mon_bin.c in the Linux kernel.
386356341Scy */
387356341Scy#define MIN_RING_SIZE	(8*1024)
388356341Scy#define MAX_RING_SIZE	(1200*1024)
389356341Scy
390356341Scystatic int
391356341Scyusb_set_ring_size(pcap_t* handle, int header_size)
392356341Scy{
393356341Scy	/*
394356341Scy	 * A packet from binary usbmon has:
395356341Scy	 *
396356341Scy	 *  1) a fixed-length header, of size header_size;
397356341Scy	 *  2) descriptors, for isochronous transfers;
398356341Scy	 *  3) the payload.
399356341Scy	 *
400356341Scy	 * The kernel buffer has a size, defaulting to 300KB, with a
401356341Scy	 * minimum of 8KB and a maximum of 1200KB.  The size is set with
402356341Scy	 * the MON_IOCT_RING_SIZE ioctl; the size passed in is rounded up
403356341Scy	 * to a page size.
404356341Scy	 *
405356341Scy	 * No more than {buffer size}/5 bytes worth of payload is saved.
406356341Scy	 * Therefore, if we subtract the fixed-length size from the
407356341Scy	 * snapshot length, we have the biggest payload we want (we
408356341Scy	 * don't worry about the descriptors - if we have descriptors,
409356341Scy	 * we'll just discard the last bit of the payload to get it
410356341Scy	 * to fit).  We multiply that result by 5 and set the buffer
411356341Scy	 * size to that value.
412356341Scy	 */
413356341Scy	int ring_size;
414356341Scy
415356341Scy	if (handle->snapshot < header_size)
416356341Scy		handle->snapshot = header_size;
417356341Scy	/* The maximum snapshot size is small enough that this won't overflow */
418356341Scy	ring_size = (handle->snapshot - header_size) * 5;
419356341Scy
420356341Scy	/*
421356341Scy	 * Will this get an error?
422356341Scy	 * (There's no wqy to query the minimum or maximum, so we just
423356341Scy	 * copy the value from the kernel source.  We don't round it
424356341Scy	 * up to a multiple of the page size.)
425356341Scy	 */
426356341Scy	if (ring_size > MAX_RING_SIZE) {
427356341Scy		/*
428356341Scy		 * Yes.  Lower the ring size to the maximum, and set the
429356341Scy		 * snapshot length to the value that would give us a
430356341Scy		 * maximum-size ring.
431356341Scy		 */
432356341Scy		ring_size = MAX_RING_SIZE;
433356341Scy		handle->snapshot = header_size + (MAX_RING_SIZE/5);
434356341Scy	} else if (ring_size < MIN_RING_SIZE) {
435356341Scy		/*
436356341Scy		 * Yes.  Raise the ring size to the minimum, but leave
437356341Scy		 * the snapshot length unchanged, so we show the
438356341Scy		 * callback no more data than specified by the
439356341Scy		 * snapshot length.
440356341Scy		 */
441356341Scy		ring_size = MIN_RING_SIZE;
442356341Scy	}
443356341Scy
444356341Scy	if (ioctl(handle->fd, MON_IOCT_RING_SIZE, ring_size) == -1) {
445356341Scy		pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
446356341Scy		    errno, "Can't set ring size from fd %d", handle->fd);
447356341Scy		return -1;
448356341Scy	}
449356341Scy	return ring_size;
450356341Scy}
451356341Scy
452335640Shselaskystatic
453335640Shselaskyint usb_mmap(pcap_t* handle)
454335640Shselasky{
455335640Shselasky	struct pcap_usb_linux *handlep = handle->priv;
456356341Scy	int len;
457356341Scy
458356341Scy	/*
459356341Scy	 * Attempt to set the ring size as appropriate for the snapshot
460356341Scy	 * length, reducing the snapshot length if that'd make the ring
461356341Scy	 * bigger than the kernel supports.
462356341Scy	 */
463356341Scy	len = usb_set_ring_size(handle, (int)sizeof(pcap_usb_header_mmapped));
464356341Scy	if (len == -1) {
465356341Scy		/* Failed.  Fall back on non-memory-mapped access. */
466335640Shselasky		return 0;
467356341Scy	}
468335640Shselasky
469335640Shselasky	handlep->mmapbuflen = len;
470335640Shselasky	handlep->mmapbuf = mmap(0, handlep->mmapbuflen, PROT_READ,
471335640Shselasky	    MAP_SHARED, handle->fd, 0);
472356341Scy	if (handlep->mmapbuf == MAP_FAILED) {
473356341Scy		/*
474356341Scy		 * Failed.  We don't treat that as a fatal error, we
475356341Scy		 * just try to fall back on non-memory-mapped access.
476356341Scy		 */
477356341Scy		return 0;
478356341Scy	}
479356341Scy	return 1;
480335640Shselasky}
481335640Shselasky
482335640Shselasky#ifdef HAVE_LINUX_USBDEVICE_FS_H
483335640Shselasky
484335640Shselasky#define CTRL_TIMEOUT    (5*1000)        /* milliseconds */
485335640Shselasky
486335640Shselasky#define USB_DIR_IN		0x80
487335640Shselasky#define USB_TYPE_STANDARD	0x00
488335640Shselasky#define USB_RECIP_DEVICE	0x00
489335640Shselasky
490335640Shselasky#define USB_REQ_GET_DESCRIPTOR	6
491335640Shselasky
492335640Shselasky#define USB_DT_DEVICE		1
493335640Shselasky
494335640Shselasky/* probe the descriptors of the devices attached to the bus */
495335640Shselasky/* the descriptors will end up in the captured packet stream */
496335640Shselasky/* and be decoded by external apps like wireshark */
497335640Shselasky/* without these identifying probes packet data can't be fully decoded */
498335640Shselaskystatic void
499335640Shselaskyprobe_devices(int bus)
500335640Shselasky{
501335640Shselasky	struct usbdevfs_ctrltransfer ctrl;
502335640Shselasky	struct dirent* data;
503335640Shselasky	int ret = 0;
504335640Shselasky	char buf[sizeof("/dev/bus/usb/000/") + NAME_MAX];
505335640Shselasky	DIR* dir;
506335640Shselasky
507335640Shselasky	/* scan usb bus directories for device nodes */
508335640Shselasky	pcap_snprintf(buf, sizeof(buf), "/dev/bus/usb/%03d", bus);
509335640Shselasky	dir = opendir(buf);
510335640Shselasky	if (!dir)
511335640Shselasky		return;
512335640Shselasky
513335640Shselasky	while ((ret >= 0) && ((data = readdir(dir)) != 0)) {
514335640Shselasky		int fd;
515335640Shselasky		char* name = data->d_name;
516335640Shselasky
517335640Shselasky		if (name[0] == '.')
518335640Shselasky			continue;
519335640Shselasky
520335640Shselasky		pcap_snprintf(buf, sizeof(buf), "/dev/bus/usb/%03d/%s", bus, data->d_name);
521335640Shselasky
522335640Shselasky		fd = open(buf, O_RDWR);
523335640Shselasky		if (fd == -1)
524335640Shselasky			continue;
525335640Shselasky
526335640Shselasky		/*
527335640Shselasky		 * Sigh.  Different kernels have different member names
528335640Shselasky		 * for this structure.
529335640Shselasky		 */
530335640Shselasky#ifdef HAVE_STRUCT_USBDEVFS_CTRLTRANSFER_BREQUESTTYPE
531335640Shselasky		ctrl.bRequestType = USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE;
532335640Shselasky		ctrl.bRequest = USB_REQ_GET_DESCRIPTOR;
533335640Shselasky		ctrl.wValue = USB_DT_DEVICE << 8;
534335640Shselasky		ctrl.wIndex = 0;
535335640Shselasky 		ctrl.wLength = sizeof(buf);
536335640Shselasky#else
537335640Shselasky		ctrl.requesttype = USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE;
538335640Shselasky		ctrl.request = USB_REQ_GET_DESCRIPTOR;
539335640Shselasky		ctrl.value = USB_DT_DEVICE << 8;
540335640Shselasky		ctrl.index = 0;
541335640Shselasky 		ctrl.length = sizeof(buf);
542335640Shselasky#endif
543335640Shselasky		ctrl.data = buf;
544335640Shselasky		ctrl.timeout = CTRL_TIMEOUT;
545335640Shselasky
546335640Shselasky		ret = ioctl(fd, USBDEVFS_CONTROL, &ctrl);
547335640Shselasky
548335640Shselasky		close(fd);
549335640Shselasky	}
550335640Shselasky	closedir(dir);
551335640Shselasky}
552335640Shselasky#endif /* HAVE_LINUX_USBDEVICE_FS_H */
553335640Shselasky
554335640Shselaskypcap_t *
555335640Shselaskyusb_create(const char *device, char *ebuf, int *is_ours)
556335640Shselasky{
557335640Shselasky	const char *cp;
558335640Shselasky	char *cpend;
559335640Shselasky	long devnum;
560335640Shselasky	pcap_t *p;
561335640Shselasky
562335640Shselasky	/* Does this look like a USB monitoring device? */
563335640Shselasky	cp = strrchr(device, '/');
564335640Shselasky	if (cp == NULL)
565335640Shselasky		cp = device;
566335640Shselasky	/* Does it begin with USB_IFACE? */
567335640Shselasky	if (strncmp(cp, USB_IFACE, sizeof USB_IFACE - 1) != 0) {
568335640Shselasky		/* Nope, doesn't begin with USB_IFACE */
569335640Shselasky		*is_ours = 0;
570335640Shselasky		return NULL;
571335640Shselasky	}
572335640Shselasky	/* Yes - is USB_IFACE followed by a number? */
573335640Shselasky	cp += sizeof USB_IFACE - 1;
574335640Shselasky	devnum = strtol(cp, &cpend, 10);
575335640Shselasky	if (cpend == cp || *cpend != '\0') {
576335640Shselasky		/* Not followed by a number. */
577335640Shselasky		*is_ours = 0;
578335640Shselasky		return NULL;
579335640Shselasky	}
580335640Shselasky	if (devnum < 0) {
581335640Shselasky		/* Followed by a non-valid number. */
582335640Shselasky		*is_ours = 0;
583335640Shselasky		return NULL;
584335640Shselasky	}
585335640Shselasky
586335640Shselasky	/* OK, it's probably ours. */
587335640Shselasky	*is_ours = 1;
588335640Shselasky
589335640Shselasky	p = pcap_create_common(ebuf, sizeof (struct pcap_usb_linux));
590335640Shselasky	if (p == NULL)
591335640Shselasky		return (NULL);
592335640Shselasky
593335640Shselasky	p->activate_op = usb_activate;
594335640Shselasky	return (p);
595335640Shselasky}
596335640Shselasky
597335640Shselaskystatic int
598335640Shselaskyusb_activate(pcap_t* handle)
599335640Shselasky{
600335640Shselasky	struct pcap_usb_linux *handlep = handle->priv;
601335640Shselasky	char 		full_path[USB_LINE_LEN];
602356341Scy	int		ret;
603335640Shselasky
604335640Shselasky	/*
605335640Shselasky	 * Turn a negative snapshot value (invalid), a snapshot value of
606335640Shselasky	 * 0 (unspecified), or a value bigger than the normal maximum
607335640Shselasky	 * value, into the maximum allowed value.
608335640Shselasky	 *
609335640Shselasky	 * If some application really *needs* a bigger snapshot
610335640Shselasky	 * length, we should just increase MAXIMUM_SNAPLEN.
611335640Shselasky	 */
612335640Shselasky	if (handle->snapshot <= 0 || handle->snapshot > MAXIMUM_SNAPLEN)
613335640Shselasky		handle->snapshot = MAXIMUM_SNAPLEN;
614335640Shselasky
615335640Shselasky	/* Initialize some components of the pcap structure. */
616335640Shselasky	handle->bufsize = handle->snapshot;
617335640Shselasky	handle->offset = 0;
618335640Shselasky	handle->linktype = DLT_USB_LINUX;
619335640Shselasky
620335640Shselasky	handle->inject_op = usb_inject_linux;
621335640Shselasky	handle->setfilter_op = install_bpf_program; /* no kernel filtering */
622335640Shselasky	handle->setdirection_op = usb_setdirection_linux;
623335640Shselasky	handle->set_datalink_op = NULL;	/* can't change data link type */
624335640Shselasky	handle->getnonblock_op = pcap_getnonblock_fd;
625335640Shselasky	handle->setnonblock_op = pcap_setnonblock_fd;
626335640Shselasky
627335640Shselasky	/*get usb bus index from device name */
628335640Shselasky	if (sscanf(handle->opt.device, USB_IFACE"%d", &handlep->bus_index) != 1)
629335640Shselasky	{
630335640Shselasky		pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
631335640Shselasky			"Can't get USB bus index from %s", handle->opt.device);
632335640Shselasky		return PCAP_ERROR;
633335640Shselasky	}
634335640Shselasky
635335640Shselasky	if (have_binary_usbmon())
636335640Shselasky	{
637335640Shselasky		/*
638335640Shselasky		 * We have binary-mode support.
639335640Shselasky		 * Try to open the binary interface.
640335640Shselasky		 */
641335640Shselasky		pcap_snprintf(full_path, USB_LINE_LEN, LINUX_USB_MON_DEV"%d", handlep->bus_index);
642335640Shselasky		handle->fd = open(full_path, O_RDONLY, 0);
643335640Shselasky		if (handle->fd < 0)
644335640Shselasky		{
645335640Shselasky			/*
646335640Shselasky			 * The attempt failed; why?
647335640Shselasky			 */
648335640Shselasky			switch (errno) {
649335640Shselasky
650335640Shselasky			case ENOENT:
651335640Shselasky				/*
652335640Shselasky				 * The device doesn't exist.
653335640Shselasky				 * That could either mean that there's
654335640Shselasky				 * no support for monitoring USB buses
655335640Shselasky				 * (which probably means "the usbmon
656335640Shselasky				 * module isn't loaded") or that there
657335640Shselasky				 * is but that *particular* device
658335640Shselasky				 * doesn't exist (no "scan all buses"
659335640Shselasky				 * device if the bus index is 0, no
660335640Shselasky				 * such bus if the bus index isn't 0).
661335640Shselasky				 */
662335640Shselasky				return PCAP_ERROR_NO_SUCH_DEVICE;
663335640Shselasky
664335640Shselasky			case EACCES:
665335640Shselasky				/*
666335640Shselasky				 * We didn't have permission to open it.
667335640Shselasky				 */
668335640Shselasky				return PCAP_ERROR_PERM_DENIED;
669335640Shselasky
670335640Shselasky			default:
671335640Shselasky				/*
672335640Shselasky				 * Something went wrong.
673335640Shselasky				 */
674335640Shselasky				pcap_fmt_errmsg_for_errno(handle->errbuf,
675335640Shselasky				    PCAP_ERRBUF_SIZE, errno,
676335640Shselasky				    "Can't open USB bus file %s", full_path);
677335640Shselasky				return PCAP_ERROR;
678335640Shselasky			}
679335640Shselasky		}
680335640Shselasky
681335640Shselasky		if (handle->opt.rfmon)
682335640Shselasky		{
683335640Shselasky			/*
684335640Shselasky			 * Monitor mode doesn't apply to USB devices.
685335640Shselasky			 */
686335640Shselasky			close(handle->fd);
687335640Shselasky			return PCAP_ERROR_RFMON_NOTSUP;
688335640Shselasky		}
689335640Shselasky
690335640Shselasky		/* try to use fast mmap access */
691335640Shselasky		if (usb_mmap(handle))
692335640Shselasky		{
693356341Scy			/* We succeeded. */
694335640Shselasky			handle->linktype = DLT_USB_LINUX_MMAPPED;
695335640Shselasky			handle->stats_op = usb_stats_linux_bin;
696335640Shselasky			handle->read_op = usb_read_linux_mmap;
697335640Shselasky			handle->cleanup_op = usb_cleanup_linux_mmap;
698335640Shselasky#ifdef HAVE_LINUX_USBDEVICE_FS_H
699335640Shselasky			probe_devices(handlep->bus_index);
700335640Shselasky#endif
701335640Shselasky
702335640Shselasky			/*
703335640Shselasky			 * "handle->fd" is a real file, so
704335640Shselasky			 * "select()" and "poll()" work on it.
705335640Shselasky			 */
706335640Shselasky			handle->selectable_fd = handle->fd;
707335640Shselasky			return 0;
708335640Shselasky		}
709335640Shselasky
710356341Scy		/*
711356341Scy		 * We failed; try plain binary interface access.
712356341Scy		 *
713356341Scy		 * Attempt to set the ring size as appropriate for
714356341Scy		 * the snapshot length, reducing the snapshot length
715356341Scy		 * if that'd make the ring bigger than the kernel
716356341Scy		 * supports.
717356341Scy		 */
718356341Scy		if (usb_set_ring_size(handle, (int)sizeof(pcap_usb_header)) == -1) {
719356341Scy			/* Failed. */
720356341Scy			close(handle->fd);
721356341Scy			return PCAP_ERROR;
722356341Scy		}
723335640Shselasky		handle->stats_op = usb_stats_linux_bin;
724335640Shselasky		handle->read_op = usb_read_linux_bin;
725335640Shselasky#ifdef HAVE_LINUX_USBDEVICE_FS_H
726335640Shselasky		probe_devices(handlep->bus_index);
727335640Shselasky#endif
728335640Shselasky	}
729335640Shselasky	else {
730335640Shselasky		/*
731335640Shselasky		 * We don't have binary mode support.
732335640Shselasky		 * Try opening the text-mode device.
733335640Shselasky		 */
734335640Shselasky		pcap_snprintf(full_path, USB_LINE_LEN, USB_TEXT_DIR"/%dt", handlep->bus_index);
735335640Shselasky		handle->fd = open(full_path, O_RDONLY, 0);
736335640Shselasky		if (handle->fd < 0)
737335640Shselasky		{
738335640Shselasky			if (errno == ENOENT)
739335640Shselasky			{
740335640Shselasky				/*
741335640Shselasky				 * Not found at the new location; try
742335640Shselasky				 * the old location.
743335640Shselasky				 */
744335640Shselasky				pcap_snprintf(full_path, USB_LINE_LEN, USB_TEXT_DIR_OLD"/%dt", handlep->bus_index);
745335640Shselasky				handle->fd = open(full_path, O_RDONLY, 0);
746335640Shselasky			}
747335640Shselasky			if (handle->fd < 0) {
748356341Scy				if (errno == ENOENT)
749356341Scy				{
750335640Shselasky					/*
751356341Scy					 * The problem is that the file
752356341Scy					 * doesn't exist.  Report that as
753356341Scy					 * "no such device".  (That could
754356341Scy					 * mean "no such USB bus" or
755356341Scy					 * "monitoring not supported".)
756335640Shselasky					 */
757356341Scy					ret = PCAP_ERROR_NO_SUCH_DEVICE;
758335640Shselasky				}
759356341Scy				else if (errno == EACCES)
760356341Scy				{
761335640Shselasky					/*
762356341Scy					 * The problem is that we don't
763356341Scy					 * have sufficient permission to
764356341Scy					 * open the file.  Report that.
765335640Shselasky					 */
766356341Scy					ret = PCAP_ERROR_PERM_DENIED;
767335640Shselasky				}
768356341Scy				else
769356341Scy				{
770356341Scy					/*
771356341Scy					 * Some other error.
772356341Scy					 */
773356341Scy					ret = PCAP_ERROR;
774356341Scy				}
775356341Scy				pcap_fmt_errmsg_for_errno(handle->errbuf,
776356341Scy				    PCAP_ERRBUF_SIZE, errno,
777356341Scy				    "Can't open USB bus file %s",
778356341Scy				    full_path);
779356341Scy				return ret;
780335640Shselasky			}
781335640Shselasky		}
782335640Shselasky
783335640Shselasky		if (handle->opt.rfmon)
784335640Shselasky		{
785335640Shselasky			/*
786335640Shselasky			 * Monitor mode doesn't apply to USB devices.
787335640Shselasky			 */
788335640Shselasky			close(handle->fd);
789335640Shselasky			return PCAP_ERROR_RFMON_NOTSUP;
790335640Shselasky		}
791335640Shselasky
792335640Shselasky		handle->stats_op = usb_stats_linux;
793335640Shselasky		handle->read_op = usb_read_linux;
794335640Shselasky	}
795335640Shselasky
796335640Shselasky	/*
797335640Shselasky	 * "handle->fd" is a real file, so "select()" and "poll()"
798335640Shselasky	 * work on it.
799335640Shselasky	 */
800335640Shselasky	handle->selectable_fd = handle->fd;
801335640Shselasky
802335640Shselasky	/* for plain binary access and text access we need to allocate the read
803335640Shselasky	 * buffer */
804335640Shselasky	handle->buffer = malloc(handle->bufsize);
805335640Shselasky	if (!handle->buffer) {
806335640Shselasky		pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
807335640Shselasky		    errno, "malloc");
808335640Shselasky		close(handle->fd);
809335640Shselasky		return PCAP_ERROR;
810335640Shselasky	}
811335640Shselasky	return 0;
812335640Shselasky}
813335640Shselasky
814335640Shselaskystatic inline int
815335640Shselaskyascii_to_int(char c)
816335640Shselasky{
817335640Shselasky	return c < 'A' ? c- '0': ((c<'a') ? c - 'A' + 10: c-'a'+10);
818335640Shselasky}
819335640Shselasky
820335640Shselasky/*
821335640Shselasky * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
822335640Shselasky * <linux-kernel-source>/drivers/usb/mon/mon_text.c for urb string
823335640Shselasky * format description
824335640Shselasky */
825335640Shselaskystatic int
826335640Shselaskyusb_read_linux(pcap_t *handle, int max_packets _U_, pcap_handler callback, u_char *user)
827335640Shselasky{
828335640Shselasky	/* see:
829335640Shselasky	* /usr/src/linux/Documentation/usb/usbmon.txt
830335640Shselasky	* for message format
831335640Shselasky	*/
832335640Shselasky	struct pcap_usb_linux *handlep = handle->priv;
833335640Shselasky	unsigned timestamp;
834335640Shselasky	int tag, cnt, ep_num, dev_addr, dummy, ret, urb_len, data_len;
835335640Shselasky	char etype, pipeid1, pipeid2, status[16], urb_tag, line[USB_LINE_LEN];
836335640Shselasky	char *string = line;
837335640Shselasky	u_char * rawdata = handle->buffer;
838335640Shselasky	struct pcap_pkthdr pkth;
839335640Shselasky	pcap_usb_header* uhdr = (pcap_usb_header*)handle->buffer;
840335640Shselasky	u_char urb_transfer=0;
841335640Shselasky	int incoming=0;
842335640Shselasky
843335640Shselasky	/* ignore interrupt system call errors */
844335640Shselasky	do {
845335640Shselasky		ret = read(handle->fd, line, USB_LINE_LEN - 1);
846335640Shselasky		if (handle->break_loop)
847335640Shselasky		{
848335640Shselasky			handle->break_loop = 0;
849335640Shselasky			return -2;
850335640Shselasky		}
851335640Shselasky	} while ((ret == -1) && (errno == EINTR));
852335640Shselasky	if (ret < 0)
853335640Shselasky	{
854335640Shselasky		if (errno == EAGAIN)
855335640Shselasky			return 0;	/* no data there */
856335640Shselasky
857335640Shselasky		pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
858335640Shselasky		    errno, "Can't read from fd %d", handle->fd);
859335640Shselasky		return -1;
860335640Shselasky	}
861335640Shselasky
862335640Shselasky	/* read urb header; %n argument may increment return value, but it's
863335640Shselasky	* not mandatory, so does not count on it*/
864335640Shselasky	string[ret] = 0;
865335640Shselasky	ret = sscanf(string, "%x %d %c %c%c:%d:%d %s%n", &tag, &timestamp, &etype,
866335640Shselasky		&pipeid1, &pipeid2, &dev_addr, &ep_num, status,
867335640Shselasky		&cnt);
868335640Shselasky	if (ret < 8)
869335640Shselasky	{
870335640Shselasky		pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
871335640Shselasky		    "Can't parse USB bus message '%s', too few tokens (expected 8 got %d)",
872335640Shselasky		    string, ret);
873335640Shselasky		return -1;
874335640Shselasky	}
875335640Shselasky	uhdr->id = tag;
876335640Shselasky	uhdr->device_address = dev_addr;
877335640Shselasky	uhdr->bus_id = handlep->bus_index;
878335640Shselasky	uhdr->status = 0;
879335640Shselasky	string += cnt;
880335640Shselasky
881335640Shselasky	/* don't use usbmon provided timestamp, since it have low precision*/
882335640Shselasky	if (gettimeofday(&pkth.ts, NULL) < 0)
883335640Shselasky	{
884335640Shselasky		pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
885335640Shselasky		    errno, "Can't get timestamp for message '%s'", string);
886335640Shselasky		return -1;
887335640Shselasky	}
888335640Shselasky	uhdr->ts_sec = pkth.ts.tv_sec;
889335640Shselasky	uhdr->ts_usec = pkth.ts.tv_usec;
890335640Shselasky
891335640Shselasky	/* parse endpoint information */
892335640Shselasky	if (pipeid1 == 'C')
893335640Shselasky		urb_transfer = URB_CONTROL;
894335640Shselasky	else if (pipeid1 == 'Z')
895335640Shselasky		urb_transfer = URB_ISOCHRONOUS;
896335640Shselasky	else if (pipeid1 == 'I')
897335640Shselasky		urb_transfer = URB_INTERRUPT;
898335640Shselasky	else if (pipeid1 == 'B')
899335640Shselasky		urb_transfer = URB_BULK;
900335640Shselasky	if (pipeid2 == 'i') {
901335640Shselasky		ep_num |= URB_TRANSFER_IN;
902335640Shselasky		incoming = 1;
903335640Shselasky	}
904335640Shselasky	if (etype == 'C')
905335640Shselasky		incoming = !incoming;
906335640Shselasky
907335640Shselasky	/* direction check*/
908335640Shselasky	if (incoming)
909335640Shselasky	{
910335640Shselasky		if (handle->direction == PCAP_D_OUT)
911335640Shselasky			return 0;
912335640Shselasky	}
913335640Shselasky	else
914335640Shselasky		if (handle->direction == PCAP_D_IN)
915335640Shselasky			return 0;
916335640Shselasky	uhdr->event_type = etype;
917335640Shselasky	uhdr->transfer_type = urb_transfer;
918335640Shselasky	uhdr->endpoint_number = ep_num;
919335640Shselasky	pkth.caplen = sizeof(pcap_usb_header);
920335640Shselasky	rawdata += sizeof(pcap_usb_header);
921335640Shselasky
922335640Shselasky	/* check if this is a setup packet */
923335640Shselasky	ret = sscanf(status, "%d", &dummy);
924335640Shselasky	if (ret != 1)
925335640Shselasky	{
926335640Shselasky		/* this a setup packet, setup data can be filled with underscore if
927335640Shselasky		* usbmon has not been able to read them, so we must parse this fields as
928335640Shselasky		* strings */
929335640Shselasky		pcap_usb_setup* shdr;
930335640Shselasky		char str1[3], str2[3], str3[5], str4[5], str5[5];
931335640Shselasky		ret = sscanf(string, "%s %s %s %s %s%n", str1, str2, str3, str4,
932335640Shselasky		str5, &cnt);
933335640Shselasky		if (ret < 5)
934335640Shselasky		{
935335640Shselasky			pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
936335640Shselasky				"Can't parse USB bus message '%s', too few tokens (expected 5 got %d)",
937335640Shselasky				string, ret);
938335640Shselasky			return -1;
939335640Shselasky		}
940335640Shselasky		string += cnt;
941335640Shselasky
942335640Shselasky		/* try to convert to corresponding integer */
943335640Shselasky		shdr = &uhdr->setup;
944335640Shselasky		shdr->bmRequestType = strtoul(str1, 0, 16);
945335640Shselasky		shdr->bRequest = strtoul(str2, 0, 16);
946335640Shselasky		shdr->wValue = htols(strtoul(str3, 0, 16));
947335640Shselasky		shdr->wIndex = htols(strtoul(str4, 0, 16));
948335640Shselasky		shdr->wLength = htols(strtoul(str5, 0, 16));
949335640Shselasky
950335640Shselasky		uhdr->setup_flag = 0;
951335640Shselasky	}
952335640Shselasky	else
953335640Shselasky		uhdr->setup_flag = 1;
954335640Shselasky
955335640Shselasky	/* read urb data */
956335640Shselasky	ret = sscanf(string, " %d%n", &urb_len, &cnt);
957335640Shselasky	if (ret < 1)
958335640Shselasky	{
959335640Shselasky		pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
960335640Shselasky		  "Can't parse urb length from '%s'", string);
961335640Shselasky		return -1;
962335640Shselasky	}
963335640Shselasky	string += cnt;
964335640Shselasky
965335640Shselasky	/* urb tag is not present if urb length is 0, so we can stop here
966335640Shselasky	 * text parsing */
967335640Shselasky	pkth.len = urb_len+pkth.caplen;
968335640Shselasky	uhdr->urb_len = urb_len;
969335640Shselasky	uhdr->data_flag = 1;
970335640Shselasky	data_len = 0;
971335640Shselasky	if (uhdr->urb_len == 0)
972335640Shselasky		goto got;
973335640Shselasky
974335640Shselasky	/* check for data presence; data is present if and only if urb tag is '=' */
975335640Shselasky	if (sscanf(string, " %c", &urb_tag) != 1)
976335640Shselasky	{
977335640Shselasky		pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
978335640Shselasky			"Can't parse urb tag from '%s'", string);
979335640Shselasky		return -1;
980335640Shselasky	}
981335640Shselasky
982335640Shselasky	if (urb_tag != '=')
983335640Shselasky		goto got;
984335640Shselasky
985335640Shselasky	/* skip urb tag and following space */
986335640Shselasky	string += 3;
987335640Shselasky
988335640Shselasky	/* if we reach this point we got some urb data*/
989335640Shselasky	uhdr->data_flag = 0;
990335640Shselasky
991335640Shselasky	/* read all urb data; if urb length is greater then the usbmon internal
992335640Shselasky	 * buffer length used by the kernel to spool the URB, we get only
993335640Shselasky	 * a partial information.
994335640Shselasky	 * At least until linux 2.6.17 there is no way to set usbmon intenal buffer
995335640Shselasky	 * length and default value is 130. */
996335640Shselasky	while ((string[0] != 0) && (string[1] != 0) && (pkth.caplen < (bpf_u_int32)handle->snapshot))
997335640Shselasky	{
998335640Shselasky		rawdata[0] = ascii_to_int(string[0]) * 16 + ascii_to_int(string[1]);
999335640Shselasky		rawdata++;
1000335640Shselasky		string+=2;
1001335640Shselasky		if (string[0] == ' ')
1002335640Shselasky			string++;
1003335640Shselasky		pkth.caplen++;
1004335640Shselasky		data_len++;
1005335640Shselasky	}
1006335640Shselasky
1007335640Shselaskygot:
1008335640Shselasky	uhdr->data_len = data_len;
1009335640Shselasky	if (pkth.caplen > (bpf_u_int32)handle->snapshot)
1010335640Shselasky		pkth.caplen = (bpf_u_int32)handle->snapshot;
1011335640Shselasky
1012335640Shselasky	if (handle->fcode.bf_insns == NULL ||
1013335640Shselasky	    bpf_filter(handle->fcode.bf_insns, handle->buffer,
1014335640Shselasky	      pkth.len, pkth.caplen)) {
1015335640Shselasky		handlep->packets_read++;
1016335640Shselasky		callback(user, &pkth, handle->buffer);
1017335640Shselasky		return 1;
1018335640Shselasky	}
1019335640Shselasky	return 0;	/* didn't pass filter */
1020335640Shselasky}
1021335640Shselasky
1022335640Shselaskystatic int
1023335640Shselaskyusb_inject_linux(pcap_t *handle, const void *buf _U_, size_t size _U_)
1024335640Shselasky{
1025356341Scy	pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1026356341Scy	    "Packet injection is not supported on USB devices");
1027335640Shselasky	return (-1);
1028335640Shselasky}
1029335640Shselasky
1030335640Shselaskystatic int
1031335640Shselaskyusb_stats_linux(pcap_t *handle, struct pcap_stat *stats)
1032335640Shselasky{
1033335640Shselasky	struct pcap_usb_linux *handlep = handle->priv;
1034335640Shselasky	int dummy, ret, consumed, cnt;
1035335640Shselasky	char string[USB_LINE_LEN];
1036335640Shselasky	char token[USB_LINE_LEN];
1037335640Shselasky	char * ptr = string;
1038335640Shselasky	int fd;
1039335640Shselasky
1040335640Shselasky	pcap_snprintf(string, USB_LINE_LEN, USB_TEXT_DIR"/%ds", handlep->bus_index);
1041335640Shselasky	fd = open(string, O_RDONLY, 0);
1042335640Shselasky	if (fd < 0)
1043335640Shselasky	{
1044335640Shselasky		if (errno == ENOENT)
1045335640Shselasky		{
1046335640Shselasky			/*
1047335640Shselasky			 * Not found at the new location; try the old
1048335640Shselasky			 * location.
1049335640Shselasky			 */
1050335640Shselasky			pcap_snprintf(string, USB_LINE_LEN, USB_TEXT_DIR_OLD"/%ds", handlep->bus_index);
1051335640Shselasky			fd = open(string, O_RDONLY, 0);
1052335640Shselasky		}
1053335640Shselasky		if (fd < 0) {
1054335640Shselasky			pcap_fmt_errmsg_for_errno(handle->errbuf,
1055335640Shselasky			    PCAP_ERRBUF_SIZE, errno,
1056335640Shselasky			    "Can't open USB stats file %s", string);
1057335640Shselasky			return -1;
1058335640Shselasky		}
1059335640Shselasky	}
1060335640Shselasky
1061335640Shselasky	/* read stats line */
1062335640Shselasky	do {
1063335640Shselasky		ret = read(fd, string, USB_LINE_LEN-1);
1064335640Shselasky	} while ((ret == -1) && (errno == EINTR));
1065335640Shselasky	close(fd);
1066335640Shselasky
1067335640Shselasky	if (ret < 0)
1068335640Shselasky	{
1069335640Shselasky		pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1070335640Shselasky			"Can't read stats from fd %d ", fd);
1071335640Shselasky		return -1;
1072335640Shselasky	}
1073335640Shselasky	string[ret] = 0;
1074335640Shselasky
1075356341Scy	stats->ps_recv = handlep->packets_read;
1076356341Scy	stats->ps_drop = 0;	/* unless we find text_lost */
1077356341Scy	stats->ps_ifdrop = 0;
1078356341Scy
1079335640Shselasky	/* extract info on dropped urbs */
1080335640Shselasky	for (consumed=0; consumed < ret; ) {
1081335640Shselasky		/* from the sscanf man page:
1082335640Shselasky 		 * The C standard says: "Execution of a %n directive does
1083335640Shselasky 		 * not increment the assignment count returned at the completion
1084335640Shselasky		 * of  execution" but the Corrigendum seems to contradict this.
1085335640Shselasky		 * Do not make any assumptions on the effect of %n conversions
1086335640Shselasky		 * on the return value and explicitly check for cnt assignmet*/
1087335640Shselasky		int ntok;
1088335640Shselasky
1089335640Shselasky		cnt = -1;
1090335640Shselasky		ntok = sscanf(ptr, "%s%n", token, &cnt);
1091335640Shselasky		if ((ntok < 1) || (cnt < 0))
1092335640Shselasky			break;
1093335640Shselasky		consumed += cnt;
1094335640Shselasky		ptr += cnt;
1095356341Scy		if (strcmp(token, "text_lost") == 0)
1096356341Scy			ntok = sscanf(ptr, "%d%n", &stats->ps_drop, &cnt);
1097335640Shselasky		else
1098356341Scy			ntok = sscanf(ptr, "%d%n", &dummy, &cnt);
1099356341Scy		if ((ntok != 1) || (cnt < 0))
1100335640Shselasky			break;
1101335640Shselasky		consumed += cnt;
1102335640Shselasky		ptr += cnt;
1103335640Shselasky	}
1104335640Shselasky
1105335640Shselasky	return 0;
1106335640Shselasky}
1107335640Shselasky
1108335640Shselaskystatic int
1109335640Shselaskyusb_setdirection_linux(pcap_t *p, pcap_direction_t d)
1110335640Shselasky{
1111335640Shselasky	p->direction = d;
1112335640Shselasky	return 0;
1113335640Shselasky}
1114335640Shselasky
1115335640Shselasky
1116335640Shselaskystatic int
1117335640Shselaskyusb_stats_linux_bin(pcap_t *handle, struct pcap_stat *stats)
1118335640Shselasky{
1119335640Shselasky	struct pcap_usb_linux *handlep = handle->priv;
1120335640Shselasky	int ret;
1121335640Shselasky	struct mon_bin_stats st;
1122335640Shselasky	ret = ioctl(handle->fd, MON_IOCG_STATS, &st);
1123335640Shselasky	if (ret < 0)
1124335640Shselasky	{
1125335640Shselasky		pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
1126335640Shselasky		    errno, "Can't read stats from fd %d", handle->fd);
1127335640Shselasky		return -1;
1128335640Shselasky	}
1129335640Shselasky
1130335640Shselasky	stats->ps_recv = handlep->packets_read + st.queued;
1131335640Shselasky	stats->ps_drop = st.dropped;
1132335640Shselasky	stats->ps_ifdrop = 0;
1133335640Shselasky	return 0;
1134335640Shselasky}
1135335640Shselasky
1136335640Shselasky/*
1137335640Shselasky * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
1138335640Shselasky * <linux-kernel-source>/drivers/usb/mon/mon_bin.c binary ABI
1139335640Shselasky */
1140335640Shselaskystatic int
1141335640Shselaskyusb_read_linux_bin(pcap_t *handle, int max_packets _U_, pcap_handler callback, u_char *user)
1142335640Shselasky{
1143335640Shselasky	struct pcap_usb_linux *handlep = handle->priv;
1144335640Shselasky	struct mon_bin_get info;
1145335640Shselasky	int ret;
1146335640Shselasky	struct pcap_pkthdr pkth;
1147335640Shselasky	u_int clen = handle->snapshot - sizeof(pcap_usb_header);
1148335640Shselasky
1149335640Shselasky	/* the usb header is going to be part of 'packet' data*/
1150335640Shselasky	info.hdr = (pcap_usb_header*) handle->buffer;
1151335640Shselasky	info.data = (u_char *)handle->buffer + sizeof(pcap_usb_header);
1152335640Shselasky	info.data_len = clen;
1153335640Shselasky
1154335640Shselasky	/* ignore interrupt system call errors */
1155335640Shselasky	do {
1156335640Shselasky		ret = ioctl(handle->fd, MON_IOCX_GET, &info);
1157335640Shselasky		if (handle->break_loop)
1158335640Shselasky		{
1159335640Shselasky			handle->break_loop = 0;
1160335640Shselasky			return -2;
1161335640Shselasky		}
1162335640Shselasky	} while ((ret == -1) && (errno == EINTR));
1163335640Shselasky	if (ret < 0)
1164335640Shselasky	{
1165335640Shselasky		if (errno == EAGAIN)
1166335640Shselasky			return 0;	/* no data there */
1167335640Shselasky
1168335640Shselasky		pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
1169335640Shselasky		    errno, "Can't read from fd %d", handle->fd);
1170335640Shselasky		return -1;
1171335640Shselasky	}
1172335640Shselasky
1173356341Scy	/*
1174356341Scy	 * info.hdr->data_len is the number of bytes of isochronous
1175356341Scy	 * descriptors (if any) plus the number of bytes of data
1176356341Scy	 * provided.  There are no isochronous descriptors here,
1177356341Scy	 * because we're using the old 48-byte header.
1178356341Scy	 *
1179356341Scy	 * If info.hdr->data_flag is non-zero, there's no URB data;
1180356341Scy	 * info.hdr->urb_len is the size of the buffer into which
1181356341Scy	 * data is to be placed; it does not represent the amount
1182356341Scy	 * of data transferred.  If info.hdr->data_flag is zero,
1183356341Scy	 * there is URB data, and info.hdr->urb_len is the number
1184356341Scy	 * of bytes transmitted or received; it doesn't include
1185356341Scy	 * isochronous descriptors.
1186356341Scy	 *
1187356341Scy	 * The kernel may give us more data than the snaplen; if it did,
1188356341Scy	 * reduce the data length so that the total number of bytes we
1189356341Scy	 * tell our client we have is not greater than the snaplen.
1190356341Scy	 */
1191335640Shselasky	if (info.hdr->data_len < clen)
1192335640Shselasky		clen = info.hdr->data_len;
1193335640Shselasky	info.hdr->data_len = clen;
1194356341Scy	pkth.caplen = sizeof(pcap_usb_header) + clen;
1195356341Scy	if (info.hdr->data_flag) {
1196356341Scy		/*
1197356341Scy		 * No data; just base the on-the-wire length on
1198356341Scy		 * info.hdr->data_len (so that it's >= the captured
1199356341Scy		 * length).
1200356341Scy		 */
1201356341Scy		pkth.len = sizeof(pcap_usb_header) + info.hdr->data_len;
1202356341Scy	} else {
1203356341Scy		/*
1204356341Scy		 * We got data; base the on-the-wire length on
1205356341Scy		 * info.hdr->urb_len, so that it includes data
1206356341Scy		 * discarded by the USB monitor device due to
1207356341Scy		 * its buffer being too small.
1208356341Scy		 */
1209356341Scy		pkth.len = sizeof(pcap_usb_header) + info.hdr->urb_len;
1210356341Scy	}
1211335640Shselasky	pkth.ts.tv_sec = info.hdr->ts_sec;
1212335640Shselasky	pkth.ts.tv_usec = info.hdr->ts_usec;
1213335640Shselasky
1214335640Shselasky	if (handle->fcode.bf_insns == NULL ||
1215335640Shselasky	    bpf_filter(handle->fcode.bf_insns, handle->buffer,
1216335640Shselasky	      pkth.len, pkth.caplen)) {
1217335640Shselasky		handlep->packets_read++;
1218335640Shselasky		callback(user, &pkth, handle->buffer);
1219335640Shselasky		return 1;
1220335640Shselasky	}
1221335640Shselasky
1222335640Shselasky	return 0;	/* didn't pass filter */
1223335640Shselasky}
1224335640Shselasky
1225335640Shselasky/*
1226335640Shselasky * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
1227335640Shselasky * <linux-kernel-source>/drivers/usb/mon/mon_bin.c binary ABI
1228335640Shselasky */
1229335640Shselasky#define VEC_SIZE 32
1230335640Shselaskystatic int
1231335640Shselaskyusb_read_linux_mmap(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
1232335640Shselasky{
1233335640Shselasky	struct pcap_usb_linux *handlep = handle->priv;
1234335640Shselasky	struct mon_bin_mfetch fetch;
1235335640Shselasky	int32_t vec[VEC_SIZE];
1236335640Shselasky	struct pcap_pkthdr pkth;
1237356341Scy	pcap_usb_header_mmapped* hdr;
1238335640Shselasky	int nflush = 0;
1239335640Shselasky	int packets = 0;
1240335640Shselasky	u_int clen, max_clen;
1241335640Shselasky
1242356341Scy	max_clen = handle->snapshot - sizeof(pcap_usb_header_mmapped);
1243335640Shselasky
1244335640Shselasky	for (;;) {
1245335640Shselasky		int i, ret;
1246335640Shselasky		int limit = max_packets - packets;
1247335640Shselasky		if (limit <= 0)
1248335640Shselasky			limit = VEC_SIZE;
1249335640Shselasky		if (limit > VEC_SIZE)
1250335640Shselasky			limit = VEC_SIZE;
1251335640Shselasky
1252335640Shselasky		/* try to fetch as many events as possible*/
1253335640Shselasky		fetch.offvec = vec;
1254335640Shselasky		fetch.nfetch = limit;
1255335640Shselasky		fetch.nflush = nflush;
1256335640Shselasky		/* ignore interrupt system call errors */
1257335640Shselasky		do {
1258335640Shselasky			ret = ioctl(handle->fd, MON_IOCX_MFETCH, &fetch);
1259335640Shselasky			if (handle->break_loop)
1260335640Shselasky			{
1261335640Shselasky				handle->break_loop = 0;
1262335640Shselasky				return -2;
1263335640Shselasky			}
1264335640Shselasky		} while ((ret == -1) && (errno == EINTR));
1265335640Shselasky		if (ret < 0)
1266335640Shselasky		{
1267335640Shselasky			if (errno == EAGAIN)
1268335640Shselasky				return 0;	/* no data there */
1269335640Shselasky
1270335640Shselasky			pcap_fmt_errmsg_for_errno(handle->errbuf,
1271335640Shselasky			    PCAP_ERRBUF_SIZE, errno, "Can't mfetch fd %d",
1272335640Shselasky			    handle->fd);
1273335640Shselasky			return -1;
1274335640Shselasky		}
1275335640Shselasky
1276335640Shselasky		/* keep track of processed events, we will flush them later */
1277335640Shselasky		nflush = fetch.nfetch;
1278335640Shselasky		for (i=0; i<fetch.nfetch; ++i) {
1279335640Shselasky			/* discard filler */
1280356341Scy			hdr = (pcap_usb_header_mmapped*) &handlep->mmapbuf[vec[i]];
1281335640Shselasky			if (hdr->event_type == '@')
1282335640Shselasky				continue;
1283335640Shselasky
1284356341Scy			/*
1285356341Scy			 * hdr->data_len is the number of bytes of
1286356341Scy			 * isochronous descriptors (if any) plus the
1287356341Scy			 * number of bytes of data provided.
1288356341Scy			 *
1289356341Scy			 * If hdr->data_flag is non-zero, there's no
1290356341Scy			 * URB data; hdr->urb_len is the size of the
1291356341Scy			 * buffer into which data is to be placed; it does
1292356341Scy			 * not represent the amount of data transferred.
1293356341Scy			 * If hdr->data_flag is zero, there is URB data,
1294356341Scy			 * and hdr->urb_len is the number of bytes
1295356341Scy			 * transmitted or received; it doesn't include
1296356341Scy			 * isochronous descriptors.
1297356341Scy			 *
1298356341Scy			 * The kernel may give us more data than the
1299356341Scy			 * snaplen; if it did, reduce the data length
1300356341Scy			 * so that the total number of bytes we
1301356341Scy			 * tell our client we have is not greater than
1302356341Scy			 * the snaplen.
1303356341Scy			 */
1304335640Shselasky			clen = max_clen;
1305335640Shselasky			if (hdr->data_len < clen)
1306335640Shselasky				clen = hdr->data_len;
1307356341Scy			pkth.caplen = sizeof(pcap_usb_header_mmapped) + clen;
1308356341Scy			if (hdr->data_flag) {
1309356341Scy				/*
1310356341Scy				 * No data; just base the on-the-wire length
1311356341Scy				 * on hdr->data_len (so that it's >= the
1312356341Scy				 * captured length).
1313356341Scy				 */
1314356341Scy				pkth.len = sizeof(pcap_usb_header_mmapped) +
1315356341Scy				    hdr->data_len;
1316356341Scy			} else {
1317356341Scy				/*
1318356341Scy				 * We got data; base the on-the-wire length
1319356341Scy				 * on hdr->urb_len, so that it includes
1320356341Scy				 * data discarded by the USB monitor device
1321356341Scy				 * due to its buffer being too small.
1322356341Scy				 */
1323356341Scy				pkth.len = sizeof(pcap_usb_header_mmapped) +
1324356341Scy				    (hdr->ndesc * sizeof (usb_isodesc)) + hdr->urb_len;
1325356341Scy			}
1326335640Shselasky			pkth.ts.tv_sec = hdr->ts_sec;
1327335640Shselasky			pkth.ts.tv_usec = hdr->ts_usec;
1328335640Shselasky
1329335640Shselasky			if (handle->fcode.bf_insns == NULL ||
1330335640Shselasky			    bpf_filter(handle->fcode.bf_insns, (u_char*) hdr,
1331335640Shselasky			      pkth.len, pkth.caplen)) {
1332335640Shselasky				handlep->packets_read++;
1333335640Shselasky				callback(user, &pkth, (u_char*) hdr);
1334335640Shselasky				packets++;
1335335640Shselasky			}
1336335640Shselasky		}
1337335640Shselasky
1338335640Shselasky		/* with max_packets specifying "unlimited" we stop afer the first chunk*/
1339335640Shselasky		if (PACKET_COUNT_IS_UNLIMITED(max_packets) || (packets == max_packets))
1340335640Shselasky			break;
1341335640Shselasky	}
1342335640Shselasky
1343335640Shselasky	/* flush pending events*/
1344335640Shselasky	if (ioctl(handle->fd, MON_IOCH_MFLUSH, nflush) == -1) {
1345335640Shselasky		pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
1346335640Shselasky		    errno, "Can't mflush fd %d", handle->fd);
1347335640Shselasky		return -1;
1348335640Shselasky	}
1349335640Shselasky	return packets;
1350335640Shselasky}
1351335640Shselasky
1352335640Shselaskystatic void
1353335640Shselaskyusb_cleanup_linux_mmap(pcap_t* handle)
1354335640Shselasky{
1355335640Shselasky	struct pcap_usb_linux *handlep = handle->priv;
1356335640Shselasky
1357335640Shselasky	/* if we have a memory-mapped buffer, unmap it */
1358335640Shselasky	if (handlep->mmapbuf != NULL) {
1359335640Shselasky		munmap(handlep->mmapbuf, handlep->mmapbuflen);
1360335640Shselasky		handlep->mmapbuf = NULL;
1361335640Shselasky	}
1362335640Shselasky	pcap_cleanup_live_common(handle);
1363335640Shselasky}
1364