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