]> The Tcpdump Group git mirrors - libpcap/blob - pcap-usb-linux.c
9f84852bd2db8d51902f7274983c7da6654356ad
[libpcap] / pcap-usb-linux.c
1 /*
2 * Copyright (c) 2006 Paolo Abeni (Italy)
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * 3. The name of the author may not be used to endorse or promote
15 * products derived from this software without specific prior written
16 * permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 *
30 * USB sniffing API implementation for Linux platform
31 * By Paolo Abeni <paolo.abeni@email.it>
32 * Modifications: Kris Katterjohn <katterjohn@gmail.com>
33 *
34 */
35
36 #ifdef HAVE_CONFIG_H
37 #include <config.h>
38 #endif
39
40 #include "pcap-int.h"
41 #include "pcap-usb-linux.h"
42 #include "pcap/usb.h"
43
44 #include "extract.h"
45
46 #ifdef NEED_STRERROR_H
47 #include "strerror.h"
48 #endif
49
50 #include <errno.h>
51 #include <stdlib.h>
52 #include <unistd.h>
53 #include <fcntl.h>
54 #include <limits.h>
55 #include <string.h>
56 #include <dirent.h>
57 #include <byteswap.h>
58 #include <netinet/in.h>
59 #include <sys/ioctl.h>
60 #include <sys/mman.h>
61 #include <sys/utsname.h>
62 #ifdef HAVE_LINUX_USBDEVICE_FS_H
63 /*
64 * We might need <linux/compiler.h> to define __user for
65 * <linux/usbdevice_fs.h>.
66 */
67 #ifdef HAVE_LINUX_COMPILER_H
68 #include <linux/compiler.h>
69 #endif /* HAVE_LINUX_COMPILER_H */
70 #include <linux/usbdevice_fs.h>
71 #endif /* HAVE_LINUX_USBDEVICE_FS_H */
72
73 #define USB_IFACE "usbmon"
74 #define USB_LINE_LEN 4096
75
76 #if __BYTE_ORDER == __LITTLE_ENDIAN
77 #define htols(s) s
78 #define htoll(l) l
79 #define htol64(ll) ll
80 #else
81 #define htols(s) bswap_16(s)
82 #define htoll(l) bswap_32(l)
83 #define htol64(ll) bswap_64(ll)
84 #endif
85
86 struct mon_bin_stats {
87 uint32_t queued;
88 uint32_t dropped;
89 };
90
91 struct mon_bin_get {
92 pcap_usb_header *hdr;
93 void *data;
94 size_t data_len; /* Length of data (can be zero) */
95 };
96
97 struct mon_bin_mfetch {
98 int32_t *offvec; /* Vector of events fetched */
99 int32_t nfetch; /* Number of events to fetch (out: fetched) */
100 int32_t nflush; /* Number of events to flush */
101 };
102
103 #define MON_IOC_MAGIC 0x92
104
105 #define MON_IOCQ_URB_LEN _IO(MON_IOC_MAGIC, 1)
106 #define MON_IOCX_URB _IOWR(MON_IOC_MAGIC, 2, struct mon_bin_hdr)
107 #define MON_IOCG_STATS _IOR(MON_IOC_MAGIC, 3, struct mon_bin_stats)
108 #define MON_IOCT_RING_SIZE _IO(MON_IOC_MAGIC, 4)
109 #define MON_IOCQ_RING_SIZE _IO(MON_IOC_MAGIC, 5)
110 #define MON_IOCX_GET _IOW(MON_IOC_MAGIC, 6, struct mon_bin_get)
111 #define MON_IOCX_MFETCH _IOWR(MON_IOC_MAGIC, 7, struct mon_bin_mfetch)
112 #define MON_IOCH_MFLUSH _IO(MON_IOC_MAGIC, 8)
113
114 #define MON_BIN_SETUP 0x1 /* setup hdr is present*/
115 #define MON_BIN_SETUP_ZERO 0x2 /* setup buffer is not available */
116 #define MON_BIN_DATA_ZERO 0x4 /* data buffer is not available */
117 #define MON_BIN_ERROR 0x8
118
119 /*
120 * Private data for capturing on Linux USB.
121 */
122 struct pcap_usb_linux {
123 u_char *mmapbuf; /* memory-mapped region pointer */
124 size_t mmapbuflen; /* size of region */
125 int bus_index;
126 u_int packets_read;
127 };
128
129 /* forward declaration */
130 static int usb_activate(pcap_t *);
131 static int usb_stats_linux_bin(pcap_t *, struct pcap_stat *);
132 static int usb_read_linux_bin(pcap_t *, int , pcap_handler , u_char *);
133 static int usb_read_linux_mmap(pcap_t *, int , pcap_handler , u_char *);
134 static int usb_inject_linux(pcap_t *, const void *, int);
135 static int usb_setdirection_linux(pcap_t *, pcap_direction_t);
136 static void usb_cleanup_linux_mmap(pcap_t *);
137
138 /* facility to add an USB device to the device list*/
139 static int
140 usb_dev_add(pcap_if_list_t *devlistp, int n, char *err_str)
141 {
142 char dev_name[10];
143 char dev_descr[30];
144 snprintf(dev_name, 10, USB_IFACE"%d", n);
145 /*
146 * XXX - is there any notion of "up" and "running"?
147 */
148 if (n == 0) {
149 /*
150 * As this refers to all buses, there's no notion of
151 * "connected" vs. "disconnected", as that's a property
152 * that would apply to a particular USB interface.
153 */
154 if (add_dev(devlistp, dev_name,
155 PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE,
156 "Raw USB traffic, all USB buses", err_str) == NULL)
157 return -1;
158 } else {
159 /*
160 * XXX - is there a way to determine whether anything's
161 * plugged into this bus interface or not, and set
162 * PCAP_IF_CONNECTION_STATUS_CONNECTED or
163 * PCAP_IF_CONNECTION_STATUS_DISCONNECTED?
164 */
165 snprintf(dev_descr, 30, "Raw USB traffic, bus number %d", n);
166 if (add_dev(devlistp, dev_name, 0, dev_descr, err_str) == NULL)
167 return -1;
168 }
169
170 return 0;
171 }
172
173 int
174 usb_findalldevs(pcap_if_list_t *devlistp, char *err_str)
175 {
176 char usb_mon_dir[PATH_MAX];
177 char *usb_mon_prefix;
178 size_t usb_mon_prefix_len;
179 struct dirent* data;
180 int ret = 0;
181 DIR* dir;
182 int n;
183 char* name;
184
185 /*
186 * We require 2.6.27 or later kernels, so we have binary-mode support.
187 * What do the device names look like?
188 * Split LINUX_USB_MON_DEV into a directory that we'll
189 * scan and a file name prefix that we'll check for.
190 */
191 pcap_strlcpy(usb_mon_dir, LINUX_USB_MON_DEV, sizeof usb_mon_dir);
192 usb_mon_prefix = strrchr(usb_mon_dir, '/');
193 if (usb_mon_prefix == NULL) {
194 /*
195 * This "shouldn't happen". Just give up if it
196 * does.
197 */
198 return 0;
199 }
200 *usb_mon_prefix++ = '\0';
201 usb_mon_prefix_len = strlen(usb_mon_prefix);
202
203 /*
204 * Open the directory and scan it.
205 */
206 dir = opendir(usb_mon_dir);
207 if (dir != NULL) {
208 while ((ret == 0) && ((data = readdir(dir)) != 0)) {
209 name = data->d_name;
210
211 /*
212 * Is this a usbmon device?
213 */
214 if (strncmp(name, usb_mon_prefix, usb_mon_prefix_len) != 0)
215 continue; /* no */
216
217 /*
218 * What's the device number?
219 */
220 if (sscanf(&name[usb_mon_prefix_len], "%d", &n) == 0)
221 continue; /* failed */
222
223 ret = usb_dev_add(devlistp, n, err_str);
224 }
225
226 closedir(dir);
227 }
228 return 0;
229 }
230
231 /*
232 * Matches what's in mon_bin.c in the Linux kernel.
233 */
234 #define MIN_RING_SIZE (8*1024)
235 #define MAX_RING_SIZE (1200*1024)
236
237 static int
238 usb_set_ring_size(pcap_t* handle, int header_size)
239 {
240 /*
241 * A packet from binary usbmon has:
242 *
243 * 1) a fixed-length header, of size header_size;
244 * 2) descriptors, for isochronous transfers;
245 * 3) the payload.
246 *
247 * The kernel buffer has a size, defaulting to 300KB, with a
248 * minimum of 8KB and a maximum of 1200KB. The size is set with
249 * the MON_IOCT_RING_SIZE ioctl; the size passed in is rounded up
250 * to a page size.
251 *
252 * No more than {buffer size}/5 bytes worth of payload is saved.
253 * Therefore, if we subtract the fixed-length size from the
254 * snapshot length, we have the biggest payload we want (we
255 * don't worry about the descriptors - if we have descriptors,
256 * we'll just discard the last bit of the payload to get it
257 * to fit). We multiply that result by 5 and set the buffer
258 * size to that value.
259 */
260 int ring_size;
261
262 if (handle->snapshot < header_size)
263 handle->snapshot = header_size;
264 /* The maximum snapshot size is small enough that this won't overflow */
265 ring_size = (handle->snapshot - header_size) * 5;
266
267 /*
268 * Will this get an error?
269 * (There's no wqy to query the minimum or maximum, so we just
270 * copy the value from the kernel source. We don't round it
271 * up to a multiple of the page size.)
272 */
273 if (ring_size > MAX_RING_SIZE) {
274 /*
275 * Yes. Lower the ring size to the maximum, and set the
276 * snapshot length to the value that would give us a
277 * maximum-size ring.
278 */
279 ring_size = MAX_RING_SIZE;
280 handle->snapshot = header_size + (MAX_RING_SIZE/5);
281 } else if (ring_size < MIN_RING_SIZE) {
282 /*
283 * Yes. Raise the ring size to the minimum, but leave
284 * the snapshot length unchanged, so we show the
285 * callback no more data than specified by the
286 * snapshot length.
287 */
288 ring_size = MIN_RING_SIZE;
289 }
290
291 if (ioctl(handle->fd, MON_IOCT_RING_SIZE, ring_size) == -1) {
292 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
293 errno, "Can't set ring size from fd %d", handle->fd);
294 return -1;
295 }
296 return ring_size;
297 }
298
299 static
300 int usb_mmap(pcap_t* handle)
301 {
302 struct pcap_usb_linux *handlep = handle->priv;
303 int len;
304
305 /*
306 * Attempt to set the ring size as appropriate for the snapshot
307 * length, reducing the snapshot length if that'd make the ring
308 * bigger than the kernel supports.
309 */
310 len = usb_set_ring_size(handle, (int)sizeof(pcap_usb_header_mmapped));
311 if (len == -1) {
312 /* Failed. Fall back on non-memory-mapped access. */
313 return 0;
314 }
315
316 handlep->mmapbuflen = len;
317 handlep->mmapbuf = mmap(0, handlep->mmapbuflen, PROT_READ,
318 MAP_SHARED, handle->fd, 0);
319 if (handlep->mmapbuf == MAP_FAILED) {
320 /*
321 * Failed. We don't treat that as a fatal error, we
322 * just try to fall back on non-memory-mapped access.
323 */
324 return 0;
325 }
326 return 1;
327 }
328
329 #ifdef HAVE_LINUX_USBDEVICE_FS_H
330
331 #define CTRL_TIMEOUT (5*1000) /* milliseconds */
332
333 #define USB_DIR_IN 0x80
334 #define USB_TYPE_STANDARD 0x00
335 #define USB_RECIP_DEVICE 0x00
336
337 #define USB_REQ_GET_DESCRIPTOR 6
338
339 #define USB_DT_DEVICE 1
340 #define USB_DT_CONFIG 2
341
342 #define USB_DEVICE_DESCRIPTOR_SIZE 18
343 #define USB_CONFIG_DESCRIPTOR_SIZE 9
344
345 /* probe the descriptors of the devices attached to the bus */
346 /* the descriptors will end up in the captured packet stream */
347 /* and be decoded by external apps like wireshark */
348 /* without these identifying probes packet data can't be fully decoded */
349 static void
350 probe_devices(int bus)
351 {
352 struct usbdevfs_ctrltransfer ctrl;
353 struct dirent* data;
354 int ret = 0;
355 char busdevpath[sizeof("/dev/bus/usb/000/") + NAME_MAX];
356 DIR* dir;
357 uint8_t descriptor[USB_DEVICE_DESCRIPTOR_SIZE];
358 uint8_t configdesc[USB_CONFIG_DESCRIPTOR_SIZE];
359
360 /* scan usb bus directories for device nodes */
361 snprintf(busdevpath, sizeof(busdevpath), "/dev/bus/usb/%03d", bus);
362 dir = opendir(busdevpath);
363 if (!dir)
364 return;
365
366 while ((ret >= 0) && ((data = readdir(dir)) != 0)) {
367 int fd;
368 char* name = data->d_name;
369
370 if (name[0] == '.')
371 continue;
372
373 snprintf(busdevpath, sizeof(busdevpath), "/dev/bus/usb/%03d/%s", bus, data->d_name);
374
375 fd = open(busdevpath, O_RDWR);
376 if (fd == -1)
377 continue;
378
379 /*
380 * Sigh. Different kernels have different member names
381 * for this structure.
382 */
383 #ifdef HAVE_STRUCT_USBDEVFS_CTRLTRANSFER_BREQUESTTYPE
384 ctrl.bRequestType = USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE;
385 ctrl.bRequest = USB_REQ_GET_DESCRIPTOR;
386 ctrl.wValue = USB_DT_DEVICE << 8;
387 ctrl.wIndex = 0;
388 ctrl.wLength = sizeof(descriptor);
389 #else
390 ctrl.requesttype = USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE;
391 ctrl.request = USB_REQ_GET_DESCRIPTOR;
392 ctrl.value = USB_DT_DEVICE << 8;
393 ctrl.index = 0;
394 ctrl.length = sizeof(descriptor);
395 #endif
396 ctrl.data = descriptor;
397 ctrl.timeout = CTRL_TIMEOUT;
398
399 ret = ioctl(fd, USBDEVFS_CONTROL, &ctrl);
400
401 /* Request CONFIGURATION descriptor alone to know wTotalLength */
402 #ifdef HAVE_STRUCT_USBDEVFS_CTRLTRANSFER_BREQUESTTYPE
403 ctrl.wValue = USB_DT_CONFIG << 8;
404 ctrl.wLength = sizeof(configdesc);
405 #else
406 ctrl.value = USB_DT_CONFIG << 8;
407 ctrl.length = sizeof(configdesc);
408 #endif
409 ctrl.data = configdesc;
410 ret = ioctl(fd, USBDEVFS_CONTROL, &ctrl);
411 if (ret >= 0) {
412 uint16_t wtotallength;
413 wtotallength = EXTRACT_LE_U_2(&configdesc[2]);
414 #ifdef HAVE_STRUCT_USBDEVFS_CTRLTRANSFER_BREQUESTTYPE
415 ctrl.wLength = wtotallength;
416 #else
417 ctrl.length = wtotallength;
418 #endif
419 ctrl.data = malloc(wtotallength);
420 if (ctrl.data) {
421 ret = ioctl(fd, USBDEVFS_CONTROL, &ctrl);
422 free(ctrl.data);
423 }
424 }
425 close(fd);
426 }
427 closedir(dir);
428 }
429 #endif /* HAVE_LINUX_USBDEVICE_FS_H */
430
431 pcap_t *
432 usb_create(const char *device, char *ebuf, int *is_ours)
433 {
434 const char *cp;
435 char *cpend;
436 long devnum;
437 pcap_t *p;
438
439 /* Does this look like a USB monitoring device? */
440 cp = strrchr(device, '/');
441 if (cp == NULL)
442 cp = device;
443 /* Does it begin with USB_IFACE? */
444 if (strncmp(cp, USB_IFACE, sizeof USB_IFACE - 1) != 0) {
445 /* Nope, doesn't begin with USB_IFACE */
446 *is_ours = 0;
447 return NULL;
448 }
449 /* Yes - is USB_IFACE followed by a number? */
450 cp += sizeof USB_IFACE - 1;
451 devnum = strtol(cp, &cpend, 10);
452 if (cpend == cp || *cpend != '\0') {
453 /* Not followed by a number. */
454 *is_ours = 0;
455 return NULL;
456 }
457 if (devnum < 0) {
458 /* Followed by a non-valid number. */
459 *is_ours = 0;
460 return NULL;
461 }
462
463 /* OK, it's probably ours. */
464 *is_ours = 1;
465
466 p = PCAP_CREATE_COMMON(ebuf, struct pcap_usb_linux);
467 if (p == NULL)
468 return (NULL);
469
470 p->activate_op = usb_activate;
471 return (p);
472 }
473
474 static int
475 usb_activate(pcap_t* handle)
476 {
477 struct pcap_usb_linux *handlep = handle->priv;
478 char full_path[USB_LINE_LEN];
479
480 /*
481 * Turn a negative snapshot value (invalid), a snapshot value of
482 * 0 (unspecified), or a value bigger than the normal maximum
483 * value, into the maximum allowed value.
484 *
485 * If some application really *needs* a bigger snapshot
486 * length, we should just increase MAXIMUM_SNAPLEN.
487 */
488 if (handle->snapshot <= 0 || handle->snapshot > MAXIMUM_SNAPLEN)
489 handle->snapshot = MAXIMUM_SNAPLEN;
490
491 /* Initialize some components of the pcap structure. */
492 handle->bufsize = handle->snapshot;
493 handle->offset = 0;
494 handle->linktype = DLT_USB_LINUX;
495
496 handle->inject_op = usb_inject_linux;
497 handle->setfilter_op = install_bpf_program; /* no kernel filtering */
498 handle->setdirection_op = usb_setdirection_linux;
499 handle->set_datalink_op = NULL; /* can't change data link type */
500 handle->getnonblock_op = pcap_getnonblock_fd;
501 handle->setnonblock_op = pcap_setnonblock_fd;
502
503 /*get usb bus index from device name */
504 if (sscanf(handle->opt.device, USB_IFACE"%d", &handlep->bus_index) != 1)
505 {
506 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
507 "Can't get USB bus index from %s", handle->opt.device);
508 return PCAP_ERROR;
509 }
510
511 /*
512 * We require 2.6.27 or later kernels, so we have binary-mode support.
513 * Try to open the binary interface.
514 */
515 snprintf(full_path, USB_LINE_LEN, LINUX_USB_MON_DEV"%d", handlep->bus_index);
516 handle->fd = open(full_path, O_RDONLY, 0);
517 if (handle->fd < 0)
518 {
519 /*
520 * The attempt failed; why?
521 */
522 switch (errno) {
523
524 case ENOENT:
525 /*
526 * The device doesn't exist.
527 * That could either mean that there's
528 * no support for monitoring USB buses
529 * (which probably means "the usbmon
530 * module isn't loaded") or that there
531 * is but that *particular* device
532 * doesn't exist (no "scan all buses"
533 * device if the bus index is 0, no
534 * such bus if the bus index isn't 0).
535 */
536 return PCAP_ERROR_NO_SUCH_DEVICE;
537
538 case EACCES:
539 /*
540 * We didn't have permission to open it.
541 */
542 DIAG_OFF_FORMAT_TRUNCATION
543 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
544 "Attempt to open %s failed with EACCES - root privileges may be required",
545 full_path);
546 DIAG_ON_FORMAT_TRUNCATION
547 return PCAP_ERROR_PERM_DENIED;
548
549 default:
550 /*
551 * Something went wrong.
552 */
553 pcap_fmt_errmsg_for_errno(handle->errbuf,
554 PCAP_ERRBUF_SIZE, errno,
555 "Can't open USB bus file %s", full_path);
556 return PCAP_ERROR;
557 }
558 }
559
560 if (handle->opt.rfmon)
561 {
562 /*
563 * Monitor mode doesn't apply to USB devices.
564 */
565 close(handle->fd);
566 return PCAP_ERROR_RFMON_NOTSUP;
567 }
568
569 /* try to use fast mmap access */
570 if (usb_mmap(handle))
571 {
572 /* We succeeded. */
573 handle->linktype = DLT_USB_LINUX_MMAPPED;
574 handle->stats_op = usb_stats_linux_bin;
575 handle->read_op = usb_read_linux_mmap;
576 handle->cleanup_op = usb_cleanup_linux_mmap;
577 #ifdef HAVE_LINUX_USBDEVICE_FS_H
578 probe_devices(handlep->bus_index);
579 #endif
580
581 /*
582 * "handle->fd" is a real file, so
583 * "select()" and "poll()" work on it.
584 */
585 handle->selectable_fd = handle->fd;
586 return 0;
587 }
588
589 /*
590 * We failed; try plain binary interface access.
591 *
592 * Attempt to set the ring size as appropriate for
593 * the snapshot length, reducing the snapshot length
594 * if that'd make the ring bigger than the kernel
595 * supports.
596 */
597 if (usb_set_ring_size(handle, (int)sizeof(pcap_usb_header)) == -1) {
598 /* Failed. */
599 close(handle->fd);
600 return PCAP_ERROR;
601 }
602 handle->stats_op = usb_stats_linux_bin;
603 handle->read_op = usb_read_linux_bin;
604 #ifdef HAVE_LINUX_USBDEVICE_FS_H
605 probe_devices(handlep->bus_index);
606 #endif
607
608 /*
609 * "handle->fd" is a real file, so "select()" and "poll()"
610 * work on it.
611 */
612 handle->selectable_fd = handle->fd;
613
614 /* for plain binary access and text access we need to allocate the read
615 * buffer */
616 handle->buffer = malloc(handle->bufsize);
617 if (!handle->buffer) {
618 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
619 errno, "malloc");
620 close(handle->fd);
621 return PCAP_ERROR;
622 }
623 return 0;
624 }
625
626 static int
627 usb_inject_linux(pcap_t *handle, const void *buf _U_, int size _U_)
628 {
629 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
630 "Packet injection is not supported on USB devices");
631 return (-1);
632 }
633
634 static int
635 usb_setdirection_linux(pcap_t *p, pcap_direction_t d)
636 {
637 /*
638 * It's guaranteed, at this point, that d is a valid
639 * direction value.
640 */
641 p->direction = d;
642 return 0;
643 }
644
645 static int
646 usb_stats_linux_bin(pcap_t *handle, struct pcap_stat *stats)
647 {
648 struct pcap_usb_linux *handlep = handle->priv;
649 int ret;
650 struct mon_bin_stats st;
651 ret = ioctl(handle->fd, MON_IOCG_STATS, &st);
652 if (ret < 0)
653 {
654 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
655 errno, "Can't read stats from fd %d", handle->fd);
656 return -1;
657 }
658
659 stats->ps_recv = handlep->packets_read + st.queued;
660 stats->ps_drop = st.dropped;
661 stats->ps_ifdrop = 0;
662 return 0;
663 }
664
665 /*
666 * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
667 * <linux-kernel-source>/drivers/usb/mon/mon_bin.c binary ABI
668 */
669 static int
670 usb_read_linux_bin(pcap_t *handle, int max_packets _U_, pcap_handler callback, u_char *user)
671 {
672 struct pcap_usb_linux *handlep = handle->priv;
673 struct mon_bin_get info;
674 int ret;
675 struct pcap_pkthdr pkth;
676 u_int clen = handle->snapshot - sizeof(pcap_usb_header);
677
678 /* the usb header is going to be part of 'packet' data*/
679 info.hdr = (pcap_usb_header*) handle->buffer;
680 info.data = (u_char *)handle->buffer + sizeof(pcap_usb_header);
681 info.data_len = clen;
682
683 /* ignore interrupt system call errors */
684 do {
685 ret = ioctl(handle->fd, MON_IOCX_GET, &info);
686 if (handle->break_loop)
687 {
688 handle->break_loop = 0;
689 return -2;
690 }
691 } while ((ret == -1) && (errno == EINTR));
692 if (ret < 0)
693 {
694 if (errno == EAGAIN)
695 return 0; /* no data there */
696
697 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
698 errno, "Can't read from fd %d", handle->fd);
699 return -1;
700 }
701
702 /*
703 * info.hdr->data_len is the number of bytes of isochronous
704 * descriptors (if any) plus the number of bytes of data
705 * provided. There are no isochronous descriptors here,
706 * because we're using the old 48-byte header.
707 *
708 * If info.hdr->data_flag is non-zero, there's no URB data;
709 * info.hdr->urb_len is the size of the buffer into which
710 * data is to be placed; it does not represent the amount
711 * of data transferred. If info.hdr->data_flag is zero,
712 * there is URB data, and info.hdr->urb_len is the number
713 * of bytes transmitted or received; it doesn't include
714 * isochronous descriptors.
715 *
716 * The kernel may give us more data than the snaplen; if it did,
717 * reduce the data length so that the total number of bytes we
718 * tell our client we have is not greater than the snaplen.
719 */
720 if (info.hdr->data_len < clen)
721 clen = info.hdr->data_len;
722 info.hdr->data_len = clen;
723 pkth.caplen = sizeof(pcap_usb_header) + clen;
724 if (info.hdr->data_flag) {
725 /*
726 * No data; just base the on-the-wire length on
727 * info.hdr->data_len (so that it's >= the captured
728 * length).
729 */
730 pkth.len = sizeof(pcap_usb_header) + info.hdr->data_len;
731 } else {
732 /*
733 * We got data; base the on-the-wire length on
734 * info.hdr->urb_len, so that it includes data
735 * discarded by the USB monitor device due to
736 * its buffer being too small.
737 */
738 pkth.len = sizeof(pcap_usb_header) + info.hdr->urb_len;
739 }
740 pkth.ts.tv_sec = (time_t)info.hdr->ts_sec;
741 pkth.ts.tv_usec = info.hdr->ts_usec;
742
743 if (handle->fcode.bf_insns == NULL ||
744 pcap_filter(handle->fcode.bf_insns, handle->buffer,
745 pkth.len, pkth.caplen)) {
746 handlep->packets_read++;
747 callback(user, &pkth, handle->buffer);
748 return 1;
749 }
750
751 return 0; /* didn't pass filter */
752 }
753
754 /*
755 * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
756 * <linux-kernel-source>/drivers/usb/mon/mon_bin.c binary ABI
757 */
758 #define VEC_SIZE 32
759 static int
760 usb_read_linux_mmap(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
761 {
762 struct pcap_usb_linux *handlep = handle->priv;
763 struct mon_bin_mfetch fetch;
764 int32_t vec[VEC_SIZE];
765 struct pcap_pkthdr pkth;
766 pcap_usb_header_mmapped* hdr;
767 int nflush = 0;
768 int packets = 0;
769 u_int clen, max_clen;
770
771 max_clen = handle->snapshot - sizeof(pcap_usb_header_mmapped);
772
773 for (;;) {
774 int i, ret;
775 int limit;
776
777 if (PACKET_COUNT_IS_UNLIMITED(max_packets)) {
778 /*
779 * There's no limit on the number of packets
780 * to process, so try to fetch VEC_SIZE packets.
781 */
782 limit = VEC_SIZE;
783 } else {
784 /*
785 * Try to fetch as many packets as we have left
786 * to process, or VEC_SIZE packets, whichever
787 * is less.
788 *
789 * At this point, max_packets > 0 (otherwise,
790 * PACKET_COUNT_IS_UNLIMITED(max_packets)
791 * would be true) and max_packets > packets
792 * (packet starts out as 0, and the test
793 * at the bottom of the loop exits if
794 * max_packets <= packets), so limit is
795 * guaranteed to be > 0.
796 */
797 limit = max_packets - packets;
798 if (limit > VEC_SIZE)
799 limit = VEC_SIZE;
800 }
801
802 /*
803 * Try to fetch as many events as possible, up to
804 * the limit, and flush the events we've processed
805 * earlier (nflush) - MON_IOCX_MFETCH does both
806 * (presumably to reduce the number of system
807 * calls in loops like this).
808 */
809 fetch.offvec = vec;
810 fetch.nfetch = limit;
811 fetch.nflush = nflush;
812 /* ignore interrupt system call errors */
813 do {
814 ret = ioctl(handle->fd, MON_IOCX_MFETCH, &fetch);
815 if (handle->break_loop)
816 {
817 handle->break_loop = 0;
818 return -2;
819 }
820 } while ((ret == -1) && (errno == EINTR));
821 if (ret < 0)
822 {
823 if (errno == EAGAIN)
824 return 0; /* no data there */
825
826 pcap_fmt_errmsg_for_errno(handle->errbuf,
827 PCAP_ERRBUF_SIZE, errno, "Can't mfetch fd %d",
828 handle->fd);
829 return -1;
830 }
831
832 /* keep track of processed events, we will flush them later */
833 nflush = fetch.nfetch;
834 for (i=0; i<fetch.nfetch; ++i) {
835 /*
836 * XXX - we can't check break_loop here, as
837 * we read the indices of packets into a
838 * local variable, so if we're later called
839 * to fetch more packets, those packets will
840 * not be seen - and won't be flushed, either.
841 *
842 * Instead, we would have to keep the array
843 * of indices in our private data, along
844 * with the count of packets to flush - or
845 * would have to flush the already-processed
846 * packets if we break out of the loop here.
847 */
848
849 /* discard filler */
850 hdr = (pcap_usb_header_mmapped*) &handlep->mmapbuf[vec[i]];
851 if (hdr->event_type == '@')
852 continue;
853
854 /*
855 * hdr->data_len is the number of bytes of
856 * isochronous descriptors (if any) plus the
857 * number of bytes of data provided.
858 *
859 * If hdr->data_flag is non-zero, there's no
860 * URB data; hdr->urb_len is the size of the
861 * buffer into which data is to be placed; it does
862 * not represent the amount of data transferred.
863 * If hdr->data_flag is zero, there is URB data,
864 * and hdr->urb_len is the number of bytes
865 * transmitted or received; it doesn't include
866 * isochronous descriptors.
867 *
868 * The kernel may give us more data than the
869 * snaplen; if it did, reduce the data length
870 * so that the total number of bytes we
871 * tell our client we have is not greater than
872 * the snaplen.
873 */
874 clen = max_clen;
875 if (hdr->data_len < clen)
876 clen = hdr->data_len;
877 pkth.caplen = sizeof(pcap_usb_header_mmapped) + clen;
878 if (hdr->data_flag) {
879 /*
880 * No data; just base the on-the-wire length
881 * on hdr->data_len (so that it's >= the
882 * captured length).
883 */
884 pkth.len = sizeof(pcap_usb_header_mmapped) +
885 hdr->data_len;
886 } else {
887 /*
888 * We got data; base the on-the-wire length
889 * on hdr->urb_len, so that it includes
890 * data discarded by the USB monitor device
891 * due to its buffer being too small.
892 */
893 pkth.len = sizeof(pcap_usb_header_mmapped) +
894 (hdr->ndesc * sizeof (usb_isodesc)) + hdr->urb_len;
895 }
896 pkth.ts.tv_sec = (time_t)hdr->ts_sec;
897 pkth.ts.tv_usec = hdr->ts_usec;
898
899 if (handle->fcode.bf_insns == NULL ||
900 pcap_filter(handle->fcode.bf_insns, (u_char*) hdr,
901 pkth.len, pkth.caplen)) {
902 handlep->packets_read++;
903 callback(user, &pkth, (u_char*) hdr);
904 packets++;
905 }
906 }
907
908 /*
909 * If max_packets specifiesg "unlimited", we stop after
910 * the first chunk.
911 */
912 if (PACKET_COUNT_IS_UNLIMITED(max_packets) ||
913 (packets >= max_packets))
914 break;
915 }
916
917 /* flush pending events*/
918 if (ioctl(handle->fd, MON_IOCH_MFLUSH, nflush) == -1) {
919 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
920 errno, "Can't mflush fd %d", handle->fd);
921 return -1;
922 }
923 return packets;
924 }
925
926 static void
927 usb_cleanup_linux_mmap(pcap_t* handle)
928 {
929 struct pcap_usb_linux *handlep = handle->priv;
930
931 /* if we have a memory-mapped buffer, unmap it */
932 if (handlep->mmapbuf != NULL) {
933 munmap(handlep->mmapbuf, handlep->mmapbuflen);
934 handlep->mmapbuf = NULL;
935 }
936 pcap_cleanup_live_common(handle);
937 }