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