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