2 * Copyright (c) 2006 Paolo Abeni (Italy)
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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
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.
30 * USB sniffing API implementation for Linux platform
31 * By Paolo Abeni <paolo.abeni@email.it>
32 * Modifications: Kris Katterjohn <katterjohn@gmail.com>
41 #include "pcap-usb-linux.h"
44 #ifdef NEED_STRERROR_H
56 #include <netinet/in.h>
57 #include <sys/ioctl.h>
59 #include <sys/utsname.h>
60 #ifdef HAVE_LINUX_USBDEVICE_FS_H
62 * We might need <linux/compiler.h> to define __user for
63 * <linux/usbdevice_fs.h>.
65 #ifdef HAVE_LINUX_COMPILER_H
66 #include <linux/compiler.h>
67 #endif /* HAVE_LINUX_COMPILER_H */
68 #include <linux/usbdevice_fs.h>
69 #endif /* HAVE_LINUX_USBDEVICE_FS_H */
71 #define USB_IFACE "usbmon"
72 #define USB_TEXT_DIR_OLD "/sys/kernel/debug/usbmon"
73 #define USB_TEXT_DIR "/sys/kernel/debug/usb/usbmon"
74 #define SYS_USB_BUS_DIR "/sys/bus/usb/devices"
75 #define PROC_USB_BUS_DIR "/proc/bus/usb"
76 #define USB_LINE_LEN 4096
78 #if __BYTE_ORDER == __LITTLE_ENDIAN
83 #define htols(s) bswap_16(s)
84 #define htoll(l) bswap_32(l)
85 #define htol64(ll) bswap_64(ll)
88 struct mon_bin_stats
{
96 size_t data_len
; /* Length of data (can be zero) */
99 struct mon_bin_mfetch
{
100 int32_t *offvec
; /* Vector of events fetched */
101 int32_t nfetch
; /* Number of events to fetch (out: fetched) */
102 int32_t nflush
; /* Number of events to flush */
105 #define MON_IOC_MAGIC 0x92
107 #define MON_IOCQ_URB_LEN _IO(MON_IOC_MAGIC, 1)
108 #define MON_IOCX_URB _IOWR(MON_IOC_MAGIC, 2, struct mon_bin_hdr)
109 #define MON_IOCG_STATS _IOR(MON_IOC_MAGIC, 3, struct mon_bin_stats)
110 #define MON_IOCT_RING_SIZE _IO(MON_IOC_MAGIC, 4)
111 #define MON_IOCQ_RING_SIZE _IO(MON_IOC_MAGIC, 5)
112 #define MON_IOCX_GET _IOW(MON_IOC_MAGIC, 6, struct mon_bin_get)
113 #define MON_IOCX_MFETCH _IOWR(MON_IOC_MAGIC, 7, struct mon_bin_mfetch)
114 #define MON_IOCH_MFLUSH _IO(MON_IOC_MAGIC, 8)
116 #define MON_BIN_SETUP 0x1 /* setup hdr is present*/
117 #define MON_BIN_SETUP_ZERO 0x2 /* setup buffer is not available */
118 #define MON_BIN_DATA_ZERO 0x4 /* data buffer is not available */
119 #define MON_BIN_ERROR 0x8
122 * Private data for capturing on Linux USB.
124 struct pcap_usb_linux
{
125 u_char
*mmapbuf
; /* memory-mapped region pointer */
126 size_t mmapbuflen
; /* size of region */
131 /* forward declaration */
132 static int usb_activate(pcap_t
*);
133 static int usb_stats_linux(pcap_t
*, struct pcap_stat
*);
134 static int usb_stats_linux_bin(pcap_t
*, struct pcap_stat
*);
135 static int usb_read_linux(pcap_t
*, int , pcap_handler
, u_char
*);
136 static int usb_read_linux_bin(pcap_t
*, int , pcap_handler
, u_char
*);
137 static int usb_read_linux_mmap(pcap_t
*, int , pcap_handler
, u_char
*);
138 static int usb_inject_linux(pcap_t
*, const void *, int);
139 static int usb_setdirection_linux(pcap_t
*, pcap_direction_t
);
140 static void usb_cleanup_linux_mmap(pcap_t
*);
143 have_binary_usbmon(void)
145 struct utsname utsname
;
146 char *version_component
, *endp
;
147 long major
, minor
, subminor
;
149 if (uname(&utsname
) == 0) {
151 * 2.6.21 is the first release with the binary-mode
154 version_component
= utsname
.release
;
155 major
= strtol(version_component
, &endp
, 10);
156 if (endp
!= version_component
&& *endp
== '.') {
158 * OK, that was a valid major version.
159 * Is it 3 or greater? If so, we have binary
166 * Is it 1 or less? If so, we don't have binary
167 * mode support. (In fact, we don't have any
168 * USB monitoring....)
175 * OK, this is a 2.x kernel.
176 * What's the minor version?
178 version_component
= endp
+ 1;
179 minor
= strtol(version_component
, &endp
, 10);
180 if (endp
!= version_component
&&
181 (*endp
== '.' || *endp
== '\0')) {
183 * OK, that was a valid minor version.
184 * Is is 2.6 or later? (There shouldn't be a
185 * "later", as 2.6.x went to 3.x, but we'll
190 * No, so no binary support (did 2.4 have
191 * any USB monitoring at all?)
197 * OK, this is a 2.6.x kernel.
198 * What's the subminor version?
200 version_component
= endp
+ 1;
201 subminor
= strtol(version_component
, &endp
, 10);
202 if (endp
!= version_component
&&
203 (*endp
== '.' || *endp
== '\0')) {
205 * OK, that was a valid subminor version.
206 * Is it 21 or greater?
208 if (subminor
>= 21) {
210 * Yes - we have binary mode
220 * Either uname() failed, in which case we just say "no binary
221 * mode support", or we don't have binary mode support.
226 /* facility to add an USB device to the device list*/
228 usb_dev_add(pcap_if_list_t
*devlistp
, int n
, char *err_str
)
232 snprintf(dev_name
, 10, USB_IFACE
"%d", n
);
234 * XXX - is there any notion of "up" and "running"?
238 * As this refers to all buses, there's no notion of
239 * "connected" vs. "disconnected", as that's a property
240 * that would apply to a particular USB interface.
242 if (add_dev(devlistp
, dev_name
,
243 PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
,
244 "Raw USB traffic, all USB buses", err_str
) == NULL
)
248 * XXX - is there a way to determine whether anything's
249 * plugged into this bus interface or not, and set
250 * PCAP_IF_CONNECTION_STATUS_CONNECTED or
251 * PCAP_IF_CONNECTION_STATUS_DISCONNECTED?
253 snprintf(dev_descr
, 30, "Raw USB traffic, bus number %d", n
);
254 if (add_dev(devlistp
, dev_name
, 0, dev_descr
, err_str
) == NULL
)
262 usb_findalldevs(pcap_if_list_t
*devlistp
, char *err_str
)
264 char usb_mon_dir
[PATH_MAX
];
265 char *usb_mon_prefix
;
266 size_t usb_mon_prefix_len
;
274 if (have_binary_usbmon()) {
276 * We have binary-mode support.
277 * What do the device names look like?
278 * Split LINUX_USB_MON_DEV into a directory that we'll
279 * scan and a file name prefix that we'll check for.
281 pcap_strlcpy(usb_mon_dir
, LINUX_USB_MON_DEV
, sizeof usb_mon_dir
);
282 usb_mon_prefix
= strrchr(usb_mon_dir
, '/');
283 if (usb_mon_prefix
== NULL
) {
285 * This "shouldn't happen". Just give up if it
290 *usb_mon_prefix
++ = '\0';
291 usb_mon_prefix_len
= strlen(usb_mon_prefix
);
294 * Open the directory and scan it.
296 dir
= opendir(usb_mon_dir
);
298 while ((ret
== 0) && ((data
= readdir(dir
)) != 0)) {
302 * Is this a usbmon device?
304 if (strncmp(name
, usb_mon_prefix
, usb_mon_prefix_len
) != 0)
308 * What's the device number?
310 if (sscanf(&name
[usb_mon_prefix_len
], "%d", &n
) == 0)
311 continue; /* failed */
313 ret
= usb_dev_add(devlistp
, n
, err_str
);
321 * We have only text mode support.
322 * We don't look for the text devices because we can't
323 * look for them without root privileges, and we don't
324 * want to require root privileges to enumerate devices
325 * (we want to let the user to try a device and get
326 * an error, rather than seeing no devices and asking
327 * "why am I not seeing devices" and forcing a long
328 * process of poking to figure out whether it's "no
329 * privileges" or "your kernel is too old" or "the
330 * usbmon module isn't loaded" or...).
332 * Instead, we look to see what buses we have.
333 * If the kernel is so old that it doesn't have
334 * binary-mode support, it's also so old that
335 * it doesn't have a "scan all buses" device.
337 * First, try scanning sysfs USB bus directory.
339 dir
= opendir(SYS_USB_BUS_DIR
);
341 while ((ret
== 0) && ((data
= readdir(dir
)) != 0)) {
344 if (strncmp(name
, "usb", 3) != 0)
347 if (sscanf(&name
[3], "%d", &n
) == 0)
350 ret
= usb_dev_add(devlistp
, n
, err_str
);
357 /* That didn't work; try scanning procfs USB bus directory. */
358 dir
= opendir(PROC_USB_BUS_DIR
);
360 while ((ret
== 0) && ((data
= readdir(dir
)) != 0)) {
364 /* if this file name does not end with a number it's not of our interest */
365 if ((len
< 1) || !PCAP_ISDIGIT(name
[--len
]))
367 while (PCAP_ISDIGIT(name
[--len
]));
368 if (sscanf(&name
[len
+1], "%d", &n
) != 1)
371 ret
= usb_dev_add(devlistp
, n
, err_str
);
378 /* neither of them worked */
384 * Matches what's in mon_bin.c in the Linux kernel.
386 #define MIN_RING_SIZE (8*1024)
387 #define MAX_RING_SIZE (1200*1024)
390 usb_set_ring_size(pcap_t
* handle
, int header_size
)
393 * A packet from binary usbmon has:
395 * 1) a fixed-length header, of size header_size;
396 * 2) descriptors, for isochronous transfers;
399 * The kernel buffer has a size, defaulting to 300KB, with a
400 * minimum of 8KB and a maximum of 1200KB. The size is set with
401 * the MON_IOCT_RING_SIZE ioctl; the size passed in is rounded up
404 * No more than {buffer size}/5 bytes worth of payload is saved.
405 * Therefore, if we subtract the fixed-length size from the
406 * snapshot length, we have the biggest payload we want (we
407 * don't worry about the descriptors - if we have descriptors,
408 * we'll just discard the last bit of the payload to get it
409 * to fit). We multiply that result by 5 and set the buffer
410 * size to that value.
414 if (handle
->snapshot
< header_size
)
415 handle
->snapshot
= header_size
;
416 /* The maximum snapshot size is small enough that this won't overflow */
417 ring_size
= (handle
->snapshot
- header_size
) * 5;
420 * Will this get an error?
421 * (There's no wqy to query the minimum or maximum, so we just
422 * copy the value from the kernel source. We don't round it
423 * up to a multiple of the page size.)
425 if (ring_size
> MAX_RING_SIZE
) {
427 * Yes. Lower the ring size to the maximum, and set the
428 * snapshot length to the value that would give us a
431 ring_size
= MAX_RING_SIZE
;
432 handle
->snapshot
= header_size
+ (MAX_RING_SIZE
/5);
433 } else if (ring_size
< MIN_RING_SIZE
) {
435 * Yes. Raise the ring size to the minimum, but leave
436 * the snapshot length unchanged, so we show the
437 * callback no more data than specified by the
440 ring_size
= MIN_RING_SIZE
;
443 if (ioctl(handle
->fd
, MON_IOCT_RING_SIZE
, ring_size
) == -1) {
444 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
445 errno
, "Can't set ring size from fd %d", handle
->fd
);
452 int usb_mmap(pcap_t
* handle
)
454 struct pcap_usb_linux
*handlep
= handle
->priv
;
458 * Attempt to set the ring size as appropriate for the snapshot
459 * length, reducing the snapshot length if that'd make the ring
460 * bigger than the kernel supports.
462 len
= usb_set_ring_size(handle
, (int)sizeof(pcap_usb_header_mmapped
));
464 /* Failed. Fall back on non-memory-mapped access. */
468 handlep
->mmapbuflen
= len
;
469 handlep
->mmapbuf
= mmap(0, handlep
->mmapbuflen
, PROT_READ
,
470 MAP_SHARED
, handle
->fd
, 0);
471 if (handlep
->mmapbuf
== MAP_FAILED
) {
473 * Failed. We don't treat that as a fatal error, we
474 * just try to fall back on non-memory-mapped access.
481 #ifdef HAVE_LINUX_USBDEVICE_FS_H
483 #define CTRL_TIMEOUT (5*1000) /* milliseconds */
485 #define USB_DIR_IN 0x80
486 #define USB_TYPE_STANDARD 0x00
487 #define USB_RECIP_DEVICE 0x00
489 #define USB_REQ_GET_DESCRIPTOR 6
491 #define USB_DT_DEVICE 1
493 #define USB_DEVICE_DESCRIPTOR_SIZE 18
495 /* probe the descriptors of the devices attached to the bus */
496 /* the descriptors will end up in the captured packet stream */
497 /* and be decoded by external apps like wireshark */
498 /* without these identifying probes packet data can't be fully decoded */
500 probe_devices(int bus
)
502 struct usbdevfs_ctrltransfer ctrl
;
505 char busdevpath
[sizeof("/dev/bus/usb/000/") + NAME_MAX
];
507 char descriptor
[USB_DEVICE_DESCRIPTOR_SIZE
];
509 /* scan usb bus directories for device nodes */
510 snprintf(busdevpath
, sizeof(busdevpath
), "/dev/bus/usb/%03d", bus
);
511 dir
= opendir(busdevpath
);
515 while ((ret
>= 0) && ((data
= readdir(dir
)) != 0)) {
517 char* name
= data
->d_name
;
522 snprintf(busdevpath
, sizeof(busdevpath
), "/dev/bus/usb/%03d/%s", bus
, data
->d_name
);
524 fd
= open(busdevpath
, O_RDWR
);
529 * Sigh. Different kernels have different member names
530 * for this structure.
532 #ifdef HAVE_STRUCT_USBDEVFS_CTRLTRANSFER_BREQUESTTYPE
533 ctrl
.bRequestType
= USB_DIR_IN
| USB_TYPE_STANDARD
| USB_RECIP_DEVICE
;
534 ctrl
.bRequest
= USB_REQ_GET_DESCRIPTOR
;
535 ctrl
.wValue
= USB_DT_DEVICE
<< 8;
537 ctrl
.wLength
= sizeof(descriptor
);
539 ctrl
.requesttype
= USB_DIR_IN
| USB_TYPE_STANDARD
| USB_RECIP_DEVICE
;
540 ctrl
.request
= USB_REQ_GET_DESCRIPTOR
;
541 ctrl
.value
= USB_DT_DEVICE
<< 8;
543 ctrl
.length
= sizeof(descriptor
);
545 ctrl
.data
= descriptor
;
546 ctrl
.timeout
= CTRL_TIMEOUT
;
548 ret
= ioctl(fd
, USBDEVFS_CONTROL
, &ctrl
);
554 #endif /* HAVE_LINUX_USBDEVICE_FS_H */
557 usb_create(const char *device
, char *ebuf
, int *is_ours
)
564 /* Does this look like a USB monitoring device? */
565 cp
= strrchr(device
, '/');
568 /* Does it begin with USB_IFACE? */
569 if (strncmp(cp
, USB_IFACE
, sizeof USB_IFACE
- 1) != 0) {
570 /* Nope, doesn't begin with USB_IFACE */
574 /* Yes - is USB_IFACE followed by a number? */
575 cp
+= sizeof USB_IFACE
- 1;
576 devnum
= strtol(cp
, &cpend
, 10);
577 if (cpend
== cp
|| *cpend
!= '\0') {
578 /* Not followed by a number. */
583 /* Followed by a non-valid number. */
588 /* OK, it's probably ours. */
591 p
= pcap_create_common(ebuf
, sizeof (struct pcap_usb_linux
));
595 p
->activate_op
= usb_activate
;
600 usb_activate(pcap_t
* handle
)
602 struct pcap_usb_linux
*handlep
= handle
->priv
;
603 char full_path
[USB_LINE_LEN
];
607 * Turn a negative snapshot value (invalid), a snapshot value of
608 * 0 (unspecified), or a value bigger than the normal maximum
609 * value, into the maximum allowed value.
611 * If some application really *needs* a bigger snapshot
612 * length, we should just increase MAXIMUM_SNAPLEN.
614 if (handle
->snapshot
<= 0 || handle
->snapshot
> MAXIMUM_SNAPLEN
)
615 handle
->snapshot
= MAXIMUM_SNAPLEN
;
617 /* Initialize some components of the pcap structure. */
618 handle
->bufsize
= handle
->snapshot
;
620 handle
->linktype
= DLT_USB_LINUX
;
622 handle
->inject_op
= usb_inject_linux
;
623 handle
->setfilter_op
= install_bpf_program
; /* no kernel filtering */
624 handle
->setdirection_op
= usb_setdirection_linux
;
625 handle
->set_datalink_op
= NULL
; /* can't change data link type */
626 handle
->getnonblock_op
= pcap_getnonblock_fd
;
627 handle
->setnonblock_op
= pcap_setnonblock_fd
;
629 /*get usb bus index from device name */
630 if (sscanf(handle
->opt
.device
, USB_IFACE
"%d", &handlep
->bus_index
) != 1)
632 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
633 "Can't get USB bus index from %s", handle
->opt
.device
);
637 if (have_binary_usbmon())
640 * We have binary-mode support.
641 * Try to open the binary interface.
643 snprintf(full_path
, USB_LINE_LEN
, LINUX_USB_MON_DEV
"%d", handlep
->bus_index
);
644 handle
->fd
= open(full_path
, O_RDONLY
, 0);
648 * The attempt failed; why?
654 * The device doesn't exist.
655 * That could either mean that there's
656 * no support for monitoring USB buses
657 * (which probably means "the usbmon
658 * module isn't loaded") or that there
659 * is but that *particular* device
660 * doesn't exist (no "scan all buses"
661 * device if the bus index is 0, no
662 * such bus if the bus index isn't 0).
664 return PCAP_ERROR_NO_SUCH_DEVICE
;
668 * We didn't have permission to open it.
670 return PCAP_ERROR_PERM_DENIED
;
674 * Something went wrong.
676 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
677 PCAP_ERRBUF_SIZE
, errno
,
678 "Can't open USB bus file %s", full_path
);
683 if (handle
->opt
.rfmon
)
686 * Monitor mode doesn't apply to USB devices.
689 return PCAP_ERROR_RFMON_NOTSUP
;
692 /* try to use fast mmap access */
693 if (usb_mmap(handle
))
696 handle
->linktype
= DLT_USB_LINUX_MMAPPED
;
697 handle
->stats_op
= usb_stats_linux_bin
;
698 handle
->read_op
= usb_read_linux_mmap
;
699 handle
->cleanup_op
= usb_cleanup_linux_mmap
;
700 #ifdef HAVE_LINUX_USBDEVICE_FS_H
701 probe_devices(handlep
->bus_index
);
705 * "handle->fd" is a real file, so
706 * "select()" and "poll()" work on it.
708 handle
->selectable_fd
= handle
->fd
;
713 * We failed; try plain binary interface access.
715 * Attempt to set the ring size as appropriate for
716 * the snapshot length, reducing the snapshot length
717 * if that'd make the ring bigger than the kernel
720 if (usb_set_ring_size(handle
, (int)sizeof(pcap_usb_header
)) == -1) {
725 handle
->stats_op
= usb_stats_linux_bin
;
726 handle
->read_op
= usb_read_linux_bin
;
727 #ifdef HAVE_LINUX_USBDEVICE_FS_H
728 probe_devices(handlep
->bus_index
);
733 * We don't have binary mode support.
734 * Try opening the text-mode device.
736 snprintf(full_path
, USB_LINE_LEN
, USB_TEXT_DIR
"/%dt", handlep
->bus_index
);
737 handle
->fd
= open(full_path
, O_RDONLY
, 0);
743 * Not found at the new location; try
746 snprintf(full_path
, USB_LINE_LEN
, USB_TEXT_DIR_OLD
"/%dt", handlep
->bus_index
);
747 handle
->fd
= open(full_path
, O_RDONLY
, 0);
749 if (handle
->fd
< 0) {
753 * The problem is that the file
754 * doesn't exist. Report that as
755 * "no such device". (That could
756 * mean "no such USB bus" or
757 * "monitoring not supported".)
759 ret
= PCAP_ERROR_NO_SUCH_DEVICE
;
761 else if (errno
== EACCES
)
764 * The problem is that we don't
765 * have sufficient permission to
766 * open the file. Report that.
768 ret
= PCAP_ERROR_PERM_DENIED
;
777 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
778 PCAP_ERRBUF_SIZE
, errno
,
779 "Can't open USB bus file %s",
785 if (handle
->opt
.rfmon
)
788 * Monitor mode doesn't apply to USB devices.
791 return PCAP_ERROR_RFMON_NOTSUP
;
794 handle
->stats_op
= usb_stats_linux
;
795 handle
->read_op
= usb_read_linux
;
799 * "handle->fd" is a real file, so "select()" and "poll()"
802 handle
->selectable_fd
= handle
->fd
;
804 /* for plain binary access and text access we need to allocate the read
806 handle
->buffer
= malloc(handle
->bufsize
);
807 if (!handle
->buffer
) {
808 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
819 return c
< 'A' ? c
- '0': ((c
<'a') ? c
- 'A' + 10: c
-'a'+10);
823 * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
824 * <linux-kernel-source>/drivers/usb/mon/mon_text.c for urb string
828 usb_read_linux(pcap_t
*handle
, int max_packets _U_
, pcap_handler callback
, u_char
*user
)
831 * /usr/src/linux/Documentation/usb/usbmon.txt
834 struct pcap_usb_linux
*handlep
= handle
->priv
;
836 int tag
, cnt
, ep_num
, dev_addr
, dummy
, ret
, urb_len
, data_len
;
838 char etype
, pipeid1
, pipeid2
, status
[16], urb_tag
, line
[USB_LINE_LEN
];
840 u_char
* rawdata
= handle
->buffer
;
841 struct pcap_pkthdr pkth
;
842 pcap_usb_header
* uhdr
= (pcap_usb_header
*)handle
->buffer
;
843 u_char urb_transfer
=0;
846 /* ignore interrupt system call errors */
848 read_ret
= read(handle
->fd
, line
, USB_LINE_LEN
- 1);
849 if (handle
->break_loop
)
851 handle
->break_loop
= 0;
854 } while ((read_ret
== -1) && (errno
== EINTR
));
858 return 0; /* no data there */
860 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
861 errno
, "Can't read from fd %d", handle
->fd
);
865 /* read urb header; %n argument may increment return value, but it's
866 * not mandatory, so does not count on it*/
867 string
[read_ret
] = 0;
868 ret
= sscanf(string
, "%x %d %c %c%c:%d:%d %s%n", &tag
, ×tamp
, &etype
,
869 &pipeid1
, &pipeid2
, &dev_addr
, &ep_num
, status
,
873 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
874 "Can't parse USB bus message '%s', too few tokens (expected 8 got %d)",
879 uhdr
->device_address
= dev_addr
;
880 uhdr
->bus_id
= handlep
->bus_index
;
884 /* don't use usbmon provided timestamp, since it have low precision*/
885 if (gettimeofday(&pkth
.ts
, NULL
) < 0)
887 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
888 errno
, "Can't get timestamp for message '%s'", string
);
891 uhdr
->ts_sec
= pkth
.ts
.tv_sec
;
892 uhdr
->ts_usec
= (int32_t)pkth
.ts
.tv_usec
;
894 /* parse endpoint information */
896 urb_transfer
= URB_CONTROL
;
897 else if (pipeid1
== 'Z')
898 urb_transfer
= URB_ISOCHRONOUS
;
899 else if (pipeid1
== 'I')
900 urb_transfer
= URB_INTERRUPT
;
901 else if (pipeid1
== 'B')
902 urb_transfer
= URB_BULK
;
903 if (pipeid2
== 'i') {
904 ep_num
|= URB_TRANSFER_IN
;
908 incoming
= !incoming
;
913 if (handle
->direction
== PCAP_D_OUT
)
917 if (handle
->direction
== PCAP_D_IN
)
919 uhdr
->event_type
= etype
;
920 uhdr
->transfer_type
= urb_transfer
;
921 uhdr
->endpoint_number
= ep_num
;
922 pkth
.caplen
= sizeof(pcap_usb_header
);
923 rawdata
+= sizeof(pcap_usb_header
);
925 /* check if this is a setup packet */
926 ret
= sscanf(status
, "%d", &dummy
);
929 /* this a setup packet, setup data can be filled with underscore if
930 * usbmon has not been able to read them, so we must parse this fields as
932 pcap_usb_setup
* shdr
;
933 char str1
[3], str2
[3], str3
[5], str4
[5], str5
[5];
934 ret
= sscanf(string
, "%s %s %s %s %s%n", str1
, str2
, str3
, str4
,
938 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
939 "Can't parse USB bus message '%s', too few tokens (expected 5 got %d)",
945 /* try to convert to corresponding integer */
947 shdr
->bmRequestType
= strtoul(str1
, 0, 16);
948 shdr
->bRequest
= strtoul(str2
, 0, 16);
949 shdr
->wValue
= htols(strtoul(str3
, 0, 16));
950 shdr
->wIndex
= htols(strtoul(str4
, 0, 16));
951 shdr
->wLength
= htols(strtoul(str5
, 0, 16));
953 uhdr
->setup_flag
= 0;
956 uhdr
->setup_flag
= 1;
959 ret
= sscanf(string
, " %d%n", &urb_len
, &cnt
);
962 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
963 "Can't parse urb length from '%s'", string
);
968 /* urb tag is not present if urb length is 0, so we can stop here
970 pkth
.len
= urb_len
+pkth
.caplen
;
971 uhdr
->urb_len
= urb_len
;
974 if (uhdr
->urb_len
== 0)
977 /* check for data presence; data is present if and only if urb tag is '=' */
978 if (sscanf(string
, " %c", &urb_tag
) != 1)
980 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
981 "Can't parse urb tag from '%s'", string
);
988 /* skip urb tag and following space */
991 /* if we reach this point we got some urb data*/
994 /* read all urb data; if urb length is greater then the usbmon internal
995 * buffer length used by the kernel to spool the URB, we get only
996 * a partial information.
997 * At least until linux 2.6.17 there is no way to set usbmon intenal buffer
998 * length and default value is 130. */
999 while ((string
[0] != 0) && (string
[1] != 0) && (pkth
.caplen
< (bpf_u_int32
)handle
->snapshot
))
1001 rawdata
[0] = ascii_to_int(string
[0]) * 16 + ascii_to_int(string
[1]);
1004 if (string
[0] == ' ')
1011 uhdr
->data_len
= data_len
;
1012 if (pkth
.caplen
> (bpf_u_int32
)handle
->snapshot
)
1013 pkth
.caplen
= (bpf_u_int32
)handle
->snapshot
;
1015 if (handle
->fcode
.bf_insns
== NULL
||
1016 pcap_filter(handle
->fcode
.bf_insns
, handle
->buffer
,
1017 pkth
.len
, pkth
.caplen
)) {
1018 handlep
->packets_read
++;
1019 callback(user
, &pkth
, handle
->buffer
);
1022 return 0; /* didn't pass filter */
1026 usb_inject_linux(pcap_t
*handle
, const void *buf _U_
, int size _U_
)
1028 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1029 "Packet injection is not supported on USB devices");
1034 usb_stats_linux(pcap_t
*handle
, struct pcap_stat
*stats
)
1036 struct pcap_usb_linux
*handlep
= handle
->priv
;
1038 ssize_t ret
, consumed
;
1039 char string
[USB_LINE_LEN
];
1040 char token
[USB_LINE_LEN
];
1041 char * ptr
= string
;
1044 snprintf(string
, USB_LINE_LEN
, USB_TEXT_DIR
"/%ds", handlep
->bus_index
);
1045 fd
= open(string
, O_RDONLY
, 0);
1048 if (errno
== ENOENT
)
1051 * Not found at the new location; try the old
1054 snprintf(string
, USB_LINE_LEN
, USB_TEXT_DIR_OLD
"/%ds", handlep
->bus_index
);
1055 fd
= open(string
, O_RDONLY
, 0);
1058 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
1059 PCAP_ERRBUF_SIZE
, errno
,
1060 "Can't open USB stats file %s", string
);
1065 /* read stats line */
1067 ret
= read(fd
, string
, USB_LINE_LEN
-1);
1068 } while ((ret
== -1) && (errno
== EINTR
));
1073 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1074 "Can't read stats from fd %d ", fd
);
1079 stats
->ps_recv
= handlep
->packets_read
;
1080 stats
->ps_drop
= 0; /* unless we find text_lost */
1081 stats
->ps_ifdrop
= 0;
1083 /* extract info on dropped urbs */
1084 for (consumed
=0; consumed
< ret
; ) {
1085 /* from the sscanf man page:
1086 * The C standard says: "Execution of a %n directive does
1087 * not increment the assignment count returned at the completion
1088 * of execution" but the Corrigendum seems to contradict this.
1089 * Do not make any assumptions on the effect of %n conversions
1090 * on the return value and explicitly check for cnt assignmet*/
1094 ntok
= sscanf(ptr
, "%s%n", token
, &cnt
);
1095 if ((ntok
< 1) || (cnt
< 0))
1099 if (strcmp(token
, "text_lost") == 0)
1100 ntok
= sscanf(ptr
, "%d%n", &stats
->ps_drop
, &cnt
);
1102 ntok
= sscanf(ptr
, "%d%n", &dummy
, &cnt
);
1103 if ((ntok
!= 1) || (cnt
< 0))
1113 usb_setdirection_linux(pcap_t
*p
, pcap_direction_t d
)
1116 * It's guaranteed, at this point, that d is a valid
1125 usb_stats_linux_bin(pcap_t
*handle
, struct pcap_stat
*stats
)
1127 struct pcap_usb_linux
*handlep
= handle
->priv
;
1129 struct mon_bin_stats st
;
1130 ret
= ioctl(handle
->fd
, MON_IOCG_STATS
, &st
);
1133 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1134 errno
, "Can't read stats from fd %d", handle
->fd
);
1138 stats
->ps_recv
= handlep
->packets_read
+ st
.queued
;
1139 stats
->ps_drop
= st
.dropped
;
1140 stats
->ps_ifdrop
= 0;
1145 * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
1146 * <linux-kernel-source>/drivers/usb/mon/mon_bin.c binary ABI
1149 usb_read_linux_bin(pcap_t
*handle
, int max_packets _U_
, pcap_handler callback
, u_char
*user
)
1151 struct pcap_usb_linux
*handlep
= handle
->priv
;
1152 struct mon_bin_get info
;
1154 struct pcap_pkthdr pkth
;
1155 u_int clen
= handle
->snapshot
- sizeof(pcap_usb_header
);
1157 /* the usb header is going to be part of 'packet' data*/
1158 info
.hdr
= (pcap_usb_header
*) handle
->buffer
;
1159 info
.data
= (u_char
*)handle
->buffer
+ sizeof(pcap_usb_header
);
1160 info
.data_len
= clen
;
1162 /* ignore interrupt system call errors */
1164 ret
= ioctl(handle
->fd
, MON_IOCX_GET
, &info
);
1165 if (handle
->break_loop
)
1167 handle
->break_loop
= 0;
1170 } while ((ret
== -1) && (errno
== EINTR
));
1173 if (errno
== EAGAIN
)
1174 return 0; /* no data there */
1176 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1177 errno
, "Can't read from fd %d", handle
->fd
);
1182 * info.hdr->data_len is the number of bytes of isochronous
1183 * descriptors (if any) plus the number of bytes of data
1184 * provided. There are no isochronous descriptors here,
1185 * because we're using the old 48-byte header.
1187 * If info.hdr->data_flag is non-zero, there's no URB data;
1188 * info.hdr->urb_len is the size of the buffer into which
1189 * data is to be placed; it does not represent the amount
1190 * of data transferred. If info.hdr->data_flag is zero,
1191 * there is URB data, and info.hdr->urb_len is the number
1192 * of bytes transmitted or received; it doesn't include
1193 * isochronous descriptors.
1195 * The kernel may give us more data than the snaplen; if it did,
1196 * reduce the data length so that the total number of bytes we
1197 * tell our client we have is not greater than the snaplen.
1199 if (info
.hdr
->data_len
< clen
)
1200 clen
= info
.hdr
->data_len
;
1201 info
.hdr
->data_len
= clen
;
1202 pkth
.caplen
= sizeof(pcap_usb_header
) + clen
;
1203 if (info
.hdr
->data_flag
) {
1205 * No data; just base the on-the-wire length on
1206 * info.hdr->data_len (so that it's >= the captured
1209 pkth
.len
= sizeof(pcap_usb_header
) + info
.hdr
->data_len
;
1212 * We got data; base the on-the-wire length on
1213 * info.hdr->urb_len, so that it includes data
1214 * discarded by the USB monitor device due to
1215 * its buffer being too small.
1217 pkth
.len
= sizeof(pcap_usb_header
) + info
.hdr
->urb_len
;
1219 pkth
.ts
.tv_sec
= (time_t)info
.hdr
->ts_sec
;
1220 pkth
.ts
.tv_usec
= info
.hdr
->ts_usec
;
1222 if (handle
->fcode
.bf_insns
== NULL
||
1223 pcap_filter(handle
->fcode
.bf_insns
, handle
->buffer
,
1224 pkth
.len
, pkth
.caplen
)) {
1225 handlep
->packets_read
++;
1226 callback(user
, &pkth
, handle
->buffer
);
1230 return 0; /* didn't pass filter */
1234 * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
1235 * <linux-kernel-source>/drivers/usb/mon/mon_bin.c binary ABI
1239 usb_read_linux_mmap(pcap_t
*handle
, int max_packets
, pcap_handler callback
, u_char
*user
)
1241 struct pcap_usb_linux
*handlep
= handle
->priv
;
1242 struct mon_bin_mfetch fetch
;
1243 int32_t vec
[VEC_SIZE
];
1244 struct pcap_pkthdr pkth
;
1245 pcap_usb_header_mmapped
* hdr
;
1248 u_int clen
, max_clen
;
1250 max_clen
= handle
->snapshot
- sizeof(pcap_usb_header_mmapped
);
1254 int limit
= max_packets
- packets
;
1257 if (limit
> VEC_SIZE
)
1260 /* try to fetch as many events as possible*/
1262 fetch
.nfetch
= limit
;
1263 fetch
.nflush
= nflush
;
1264 /* ignore interrupt system call errors */
1266 ret
= ioctl(handle
->fd
, MON_IOCX_MFETCH
, &fetch
);
1267 if (handle
->break_loop
)
1269 handle
->break_loop
= 0;
1272 } while ((ret
== -1) && (errno
== EINTR
));
1275 if (errno
== EAGAIN
)
1276 return 0; /* no data there */
1278 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
1279 PCAP_ERRBUF_SIZE
, errno
, "Can't mfetch fd %d",
1284 /* keep track of processed events, we will flush them later */
1285 nflush
= fetch
.nfetch
;
1286 for (i
=0; i
<fetch
.nfetch
; ++i
) {
1287 /* discard filler */
1288 hdr
= (pcap_usb_header_mmapped
*) &handlep
->mmapbuf
[vec
[i
]];
1289 if (hdr
->event_type
== '@')
1293 * hdr->data_len is the number of bytes of
1294 * isochronous descriptors (if any) plus the
1295 * number of bytes of data provided.
1297 * If hdr->data_flag is non-zero, there's no
1298 * URB data; hdr->urb_len is the size of the
1299 * buffer into which data is to be placed; it does
1300 * not represent the amount of data transferred.
1301 * If hdr->data_flag is zero, there is URB data,
1302 * and hdr->urb_len is the number of bytes
1303 * transmitted or received; it doesn't include
1304 * isochronous descriptors.
1306 * The kernel may give us more data than the
1307 * snaplen; if it did, reduce the data length
1308 * so that the total number of bytes we
1309 * tell our client we have is not greater than
1313 if (hdr
->data_len
< clen
)
1314 clen
= hdr
->data_len
;
1315 pkth
.caplen
= sizeof(pcap_usb_header_mmapped
) + clen
;
1316 if (hdr
->data_flag
) {
1318 * No data; just base the on-the-wire length
1319 * on hdr->data_len (so that it's >= the
1322 pkth
.len
= sizeof(pcap_usb_header_mmapped
) +
1326 * We got data; base the on-the-wire length
1327 * on hdr->urb_len, so that it includes
1328 * data discarded by the USB monitor device
1329 * due to its buffer being too small.
1331 pkth
.len
= sizeof(pcap_usb_header_mmapped
) +
1332 (hdr
->ndesc
* sizeof (usb_isodesc
)) + hdr
->urb_len
;
1334 pkth
.ts
.tv_sec
= (time_t)hdr
->ts_sec
;
1335 pkth
.ts
.tv_usec
= hdr
->ts_usec
;
1337 if (handle
->fcode
.bf_insns
== NULL
||
1338 pcap_filter(handle
->fcode
.bf_insns
, (u_char
*) hdr
,
1339 pkth
.len
, pkth
.caplen
)) {
1340 handlep
->packets_read
++;
1341 callback(user
, &pkth
, (u_char
*) hdr
);
1346 /* with max_packets specifying "unlimited" we stop afer the first chunk*/
1347 if (PACKET_COUNT_IS_UNLIMITED(max_packets
) || (packets
== max_packets
))
1351 /* flush pending events*/
1352 if (ioctl(handle
->fd
, MON_IOCH_MFLUSH
, nflush
) == -1) {
1353 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1354 errno
, "Can't mflush fd %d", handle
->fd
);
1361 usb_cleanup_linux_mmap(pcap_t
* handle
)
1363 struct pcap_usb_linux
*handlep
= handle
->priv
;
1365 /* if we have a memory-mapped buffer, unmap it */
1366 if (handlep
->mmapbuf
!= NULL
) {
1367 munmap(handlep
->mmapbuf
, handlep
->mmapbuflen
);
1368 handlep
->mmapbuf
= NULL
;
1370 pcap_cleanup_live_common(handle
);