1 /* $NetBSD: pcap-usb-linux.c,v 1.6 2019/10/01 16:02:12 christos Exp $ */
2
3 /*
4 * Copyright (c) 2006 Paolo Abeni (Italy)
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 *
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. The name of the author may not be used to endorse or promote
17 * products derived from this software without specific prior written
18 * permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 *
32 * USB sniffing API implementation for Linux platform
33 * By Paolo Abeni <paolo.abeni@email.it>
34 * Modifications: Kris Katterjohn <katterjohn@gmail.com>
35 *
36 */
37
38 #include <sys/cdefs.h>
39 __RCSID("$NetBSD: pcap-usb-linux.c,v 1.6 2019/10/01 16:02:12 christos Exp $");
40
41 #ifdef HAVE_CONFIG_H
42 #include <config.h>
43 #endif
44
45 #include "pcap-int.h"
46 #include "pcap-usb-linux.h"
47 #include "pcap/usb.h"
48
49 #ifdef NEED_STRERROR_H
50 #include "strerror.h"
51 #endif
52
53 #include <ctype.h>
54 #include <errno.h>
55 #include <stdlib.h>
56 #include <unistd.h>
57 #include <fcntl.h>
58 #include <limits.h>
59 #include <string.h>
60 #include <dirent.h>
61 #include <byteswap.h>
62 #include <netinet/in.h>
63 #include <sys/ioctl.h>
64 #include <sys/mman.h>
65 #include <sys/utsname.h>
66 #ifdef HAVE_LINUX_USBDEVICE_FS_H
67 /*
68 * We might need <linux/compiler.h> to define __user for
69 * <linux/usbdevice_fs.h>.
70 */
71 #ifdef HAVE_LINUX_COMPILER_H
72 #include <linux/compiler.h>
73 #endif /* HAVE_LINUX_COMPILER_H */
74 #include <linux/usbdevice_fs.h>
75 #endif /* HAVE_LINUX_USBDEVICE_FS_H */
76
77 #define USB_IFACE "usbmon"
78 #define USB_TEXT_DIR_OLD "/sys/kernel/debug/usbmon"
79 #define USB_TEXT_DIR "/sys/kernel/debug/usb/usbmon"
80 #define SYS_USB_BUS_DIR "/sys/bus/usb/devices"
81 #define PROC_USB_BUS_DIR "/proc/bus/usb"
82 #define USB_LINE_LEN 4096
83
84 #if __BYTE_ORDER == __LITTLE_ENDIAN
85 #define htols(s) s
86 #define htoll(l) l
87 #define htol64(ll) ll
88 #else
89 #define htols(s) bswap_16(s)
90 #define htoll(l) bswap_32(l)
91 #define htol64(ll) bswap_64(ll)
92 #endif
93
94 struct mon_bin_stats {
95 uint32_t queued;
96 uint32_t dropped;
97 };
98
99 struct mon_bin_get {
100 pcap_usb_header *hdr;
101 void *data;
102 size_t data_len; /* Length of data (can be zero) */
103 };
104
105 struct mon_bin_mfetch {
106 int32_t *offvec; /* Vector of events fetched */
107 int32_t nfetch; /* Number of events to fetch (out: fetched) */
108 int32_t nflush; /* Number of events to flush */
109 };
110
111 #define MON_IOC_MAGIC 0x92
112
113 #define MON_IOCQ_URB_LEN _IO(MON_IOC_MAGIC, 1)
114 #define MON_IOCX_URB _IOWR(MON_IOC_MAGIC, 2, struct mon_bin_hdr)
115 #define MON_IOCG_STATS _IOR(MON_IOC_MAGIC, 3, struct mon_bin_stats)
116 #define MON_IOCT_RING_SIZE _IO(MON_IOC_MAGIC, 4)
117 #define MON_IOCQ_RING_SIZE _IO(MON_IOC_MAGIC, 5)
118 #define MON_IOCX_GET _IOW(MON_IOC_MAGIC, 6, struct mon_bin_get)
119 #define MON_IOCX_MFETCH _IOWR(MON_IOC_MAGIC, 7, struct mon_bin_mfetch)
120 #define MON_IOCH_MFLUSH _IO(MON_IOC_MAGIC, 8)
121
122 #define MON_BIN_SETUP 0x1 /* setup hdr is present*/
123 #define MON_BIN_SETUP_ZERO 0x2 /* setup buffer is not available */
124 #define MON_BIN_DATA_ZERO 0x4 /* data buffer is not available */
125 #define MON_BIN_ERROR 0x8
126
127 /*
128 * Private data for capturing on Linux USB.
129 */
130 struct pcap_usb_linux {
131 u_char *mmapbuf; /* memory-mapped region pointer */
132 size_t mmapbuflen; /* size of region */
133 int bus_index;
134 u_int packets_read;
135 };
136
137 /* forward declaration */
138 static int usb_activate(pcap_t *);
139 static int usb_stats_linux(pcap_t *, struct pcap_stat *);
140 static int usb_stats_linux_bin(pcap_t *, struct pcap_stat *);
141 static int usb_read_linux(pcap_t *, int , pcap_handler , u_char *);
142 static int usb_read_linux_bin(pcap_t *, int , pcap_handler , u_char *);
143 static int usb_read_linux_mmap(pcap_t *, int , pcap_handler , u_char *);
144 static int usb_inject_linux(pcap_t *, const void *, size_t);
145 static int usb_setdirection_linux(pcap_t *, pcap_direction_t);
146 static void usb_cleanup_linux_mmap(pcap_t *);
147
148 static int
have_binary_usbmon(void)149 have_binary_usbmon(void)
150 {
151 struct utsname utsname;
152 char *version_component, *endp;
153 int major, minor, subminor;
154
155 if (uname(&utsname) == 0) {
156 /*
157 * 2.6.21 is the first release with the binary-mode
158 * USB monitoring.
159 */
160 version_component = utsname.release;
161 major = strtol(version_component, &endp, 10);
162 if (endp != version_component && *endp == '.') {
163 /*
164 * OK, that was a valid major version.
165 * Is it 3 or greater? If so, we have binary
166 * mode support.
167 */
168 if (major >= 3)
169 return 1;
170
171 /*
172 * Is it 1 or less? If so, we don't have binary
173 * mode support. (In fact, we don't have any
174 * USB monitoring....)
175 */
176 if (major <= 1)
177 return 0;
178 }
179
180 /*
181 * OK, this is a 2.x kernel.
182 * What's the minor version?
183 */
184 version_component = endp + 1;
185 minor = strtol(version_component, &endp, 10);
186 if (endp != version_component &&
187 (*endp == '.' || *endp == '\0')) {
188 /*
189 * OK, that was a valid minor version.
190 * Is is 2.6 or later? (There shouldn't be a
191 * "later", as 2.6.x went to 3.x, but we'll
192 * check anyway.)
193 */
194 if (minor < 6) {
195 /*
196 * No, so no binary support (did 2.4 have
197 * any USB monitoring at all?)
198 */
199 return 0;
200 }
201
202 /*
203 * OK, this is a 2.6.x kernel.
204 * What's the subminor version?
205 */
206 version_component = endp + 1;
207 subminor = strtol(version_component, &endp, 10);
208 if (endp != version_component &&
209 (*endp == '.' || *endp == '\0')) {
210 /*
211 * OK, that was a valid subminor version.
212 * Is it 21 or greater?
213 */
214 if (subminor >= 21) {
215 /*
216 * Yes - we have binary mode
217 * support.
218 */
219 return 1;
220 }
221 }
222 }
223 }
224
225 /*
226 * Either uname() failed, in which case we just say "no binary
227 * mode support", or we don't have binary mode support.
228 */
229 return 0;
230 }
231
232 /* facility to add an USB device to the device list*/
233 static int
usb_dev_add(pcap_if_list_t * devlistp,int n,char * err_str)234 usb_dev_add(pcap_if_list_t *devlistp, int n, char *err_str)
235 {
236 char dev_name[10];
237 char dev_descr[30];
238 pcap_snprintf(dev_name, 10, USB_IFACE"%d", n);
239 /*
240 * XXX - is there any notion of "up" and "running"?
241 */
242 if (n == 0) {
243 /*
244 * As this refers to all buses, there's no notion of
245 * "connected" vs. "disconnected", as that's a property
246 * that would apply to a particular USB interface.
247 */
248 if (add_dev(devlistp, dev_name,
249 PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE,
250 "Raw USB traffic, all USB buses", err_str) == NULL)
251 return -1;
252 } else {
253 /*
254 * XXX - is there a way to determine whether anything's
255 * plugged into this bus interface or not, and set
256 * PCAP_IF_CONNECTION_STATUS_CONNECTED or
257 * PCAP_IF_CONNECTION_STATUS_DISCONNECTED?
258 */
259 pcap_snprintf(dev_descr, 30, "Raw USB traffic, bus number %d", n);
260 if (add_dev(devlistp, dev_name, 0, dev_descr, err_str) == NULL)
261 return -1;
262 }
263
264 return 0;
265 }
266
267 int
usb_findalldevs(pcap_if_list_t * devlistp,char * err_str)268 usb_findalldevs(pcap_if_list_t *devlistp, char *err_str)
269 {
270 char usb_mon_dir[PATH_MAX];
271 char *usb_mon_prefix;
272 size_t usb_mon_prefix_len;
273 struct dirent* data;
274 int ret = 0;
275 DIR* dir;
276 int n;
277 char* name;
278 size_t len;
279
280 if (have_binary_usbmon()) {
281 /*
282 * We have binary-mode support.
283 * What do the device names look like?
284 * Split LINUX_USB_MON_DEV into a directory that we'll
285 * scan and a file name prefix that we'll check for.
286 */
287 pcap_strlcpy(usb_mon_dir, LINUX_USB_MON_DEV, sizeof usb_mon_dir);
288 usb_mon_prefix = strrchr(usb_mon_dir, '/');
289 if (usb_mon_prefix == NULL) {
290 /*
291 * This "shouldn't happen". Just give up if it
292 * does.
293 */
294 return 0;
295 }
296 *usb_mon_prefix++ = '\0';
297 usb_mon_prefix_len = strlen(usb_mon_prefix);
298
299 /*
300 * Open the directory and scan it.
301 */
302 dir = opendir(usb_mon_dir);
303 if (dir != NULL) {
304 while ((ret == 0) && ((data = readdir(dir)) != 0)) {
305 name = data->d_name;
306
307 /*
308 * Is this a usbmon device?
309 */
310 if (strncmp(name, usb_mon_prefix, usb_mon_prefix_len) != 0)
311 continue; /* no */
312
313 /*
314 * What's the device number?
315 */
316 if (sscanf(&name[usb_mon_prefix_len], "%d", &n) == 0)
317 continue; /* failed */
318
319 ret = usb_dev_add(devlistp, n, err_str);
320 }
321
322 closedir(dir);
323 }
324 return 0;
325 } else {
326 /*
327 * We have only text mode support.
328 * We don't look for the text devices because we can't
329 * look for them without root privileges, and we don't
330 * want to require root privileges to enumerate devices
331 * (we want to let the user to try a device and get
332 * an error, rather than seeing no devices and asking
333 * "why am I not seeing devices" and forcing a long
334 * process of poking to figure out whether it's "no
335 * privileges" or "your kernel is too old" or "the
336 * usbmon module isn't loaded" or...).
337 *
338 * Instead, we look to see what buses we have.
339 * If the kernel is so old that it doesn't have
340 * binary-mode support, it's also so old that
341 * it doesn't have a "scan all buses" device.
342 *
343 * First, try scanning sysfs USB bus directory.
344 */
345 dir = opendir(SYS_USB_BUS_DIR);
346 if (dir != NULL) {
347 while ((ret == 0) && ((data = readdir(dir)) != 0)) {
348 name = data->d_name;
349
350 if (strncmp(name, "usb", 3) != 0)
351 continue;
352
353 if (sscanf(&name[3], "%d", &n) == 0)
354 continue;
355
356 ret = usb_dev_add(devlistp, n, err_str);
357 }
358
359 closedir(dir);
360 return 0;
361 }
362
363 /* That didn't work; try scanning procfs USB bus directory. */
364 dir = opendir(PROC_USB_BUS_DIR);
365 if (dir != NULL) {
366 while ((ret == 0) && ((data = readdir(dir)) != 0)) {
367 name = data->d_name;
368 len = strlen(name);
369
370 /* if this file name does not end with a number it's not of our interest */
371 if ((len < 1) || !isdigit(name[--len]))
372 continue;
373 while (isdigit(name[--len]));
374 if (sscanf(&name[len+1], "%d", &n) != 1)
375 continue;
376
377 ret = usb_dev_add(devlistp, n, err_str);
378 }
379
380 closedir(dir);
381 return ret;
382 }
383
384 /* neither of them worked */
385 return 0;
386 }
387 }
388
389 /*
390 * Matches what's in mon_bin.c in the Linux kernel.
391 */
392 #define MIN_RING_SIZE (8*1024)
393 #define MAX_RING_SIZE (1200*1024)
394
395 static int
usb_set_ring_size(pcap_t * handle,int header_size)396 usb_set_ring_size(pcap_t* handle, int header_size)
397 {
398 /*
399 * A packet from binary usbmon has:
400 *
401 * 1) a fixed-length header, of size header_size;
402 * 2) descriptors, for isochronous transfers;
403 * 3) the payload.
404 *
405 * The kernel buffer has a size, defaulting to 300KB, with a
406 * minimum of 8KB and a maximum of 1200KB. The size is set with
407 * the MON_IOCT_RING_SIZE ioctl; the size passed in is rounded up
408 * to a page size.
409 *
410 * No more than {buffer size}/5 bytes worth of payload is saved.
411 * Therefore, if we subtract the fixed-length size from the
412 * snapshot length, we have the biggest payload we want (we
413 * don't worry about the descriptors - if we have descriptors,
414 * we'll just discard the last bit of the payload to get it
415 * to fit). We multiply that result by 5 and set the buffer
416 * size to that value.
417 */
418 int ring_size;
419
420 if (handle->snapshot < header_size)
421 handle->snapshot = header_size;
422 /* The maximum snapshot size is small enough that this won't overflow */
423 ring_size = (handle->snapshot - header_size) * 5;
424
425 /*
426 * Will this get an error?
427 * (There's no wqy to query the minimum or maximum, so we just
428 * copy the value from the kernel source. We don't round it
429 * up to a multiple of the page size.)
430 */
431 if (ring_size > MAX_RING_SIZE) {
432 /*
433 * Yes. Lower the ring size to the maximum, and set the
434 * snapshot length to the value that would give us a
435 * maximum-size ring.
436 */
437 ring_size = MAX_RING_SIZE;
438 handle->snapshot = header_size + (MAX_RING_SIZE/5);
439 } else if (ring_size < MIN_RING_SIZE) {
440 /*
441 * Yes. Raise the ring size to the minimum, but leave
442 * the snapshot length unchanged, so we show the
443 * callback no more data than specified by the
444 * snapshot length.
445 */
446 ring_size = MIN_RING_SIZE;
447 }
448
449 if (ioctl(handle->fd, MON_IOCT_RING_SIZE, ring_size) == -1) {
450 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
451 errno, "Can't set ring size from fd %d", handle->fd);
452 return -1;
453 }
454 return ring_size;
455 }
456
457 static
usb_mmap(pcap_t * handle)458 int usb_mmap(pcap_t* handle)
459 {
460 struct pcap_usb_linux *handlep = handle->priv;
461 int len;
462
463 /*
464 * Attempt to set the ring size as appropriate for the snapshot
465 * length, reducing the snapshot length if that'd make the ring
466 * bigger than the kernel supports.
467 */
468 len = usb_set_ring_size(handle, (int)sizeof(pcap_usb_header_mmapped));
469 if (len == -1) {
470 /* Failed. Fall back on non-memory-mapped access. */
471 return 0;
472 }
473
474 handlep->mmapbuflen = len;
475 handlep->mmapbuf = mmap(0, handlep->mmapbuflen, PROT_READ,
476 MAP_SHARED, handle->fd, 0);
477 if (handlep->mmapbuf == MAP_FAILED) {
478 /*
479 * Failed. We don't treat that as a fatal error, we
480 * just try to fall back on non-memory-mapped access.
481 */
482 return 0;
483 }
484 return 1;
485 }
486
487 #ifdef HAVE_LINUX_USBDEVICE_FS_H
488
489 #define CTRL_TIMEOUT (5*1000) /* milliseconds */
490
491 #define USB_DIR_IN 0x80
492 #define USB_TYPE_STANDARD 0x00
493 #define USB_RECIP_DEVICE 0x00
494
495 #define USB_REQ_GET_DESCRIPTOR 6
496
497 #define USB_DT_DEVICE 1
498
499 /* probe the descriptors of the devices attached to the bus */
500 /* the descriptors will end up in the captured packet stream */
501 /* and be decoded by external apps like wireshark */
502 /* without these identifying probes packet data can't be fully decoded */
503 static void
probe_devices(int bus)504 probe_devices(int bus)
505 {
506 struct usbdevfs_ctrltransfer ctrl;
507 struct dirent* data;
508 int ret = 0;
509 char buf[sizeof("/dev/bus/usb/000/") + NAME_MAX];
510 DIR* dir;
511
512 /* scan usb bus directories for device nodes */
513 pcap_snprintf(buf, sizeof(buf), "/dev/bus/usb/%03d", bus);
514 dir = opendir(buf);
515 if (!dir)
516 return;
517
518 while ((ret >= 0) && ((data = readdir(dir)) != 0)) {
519 int fd;
520 char* name = data->d_name;
521
522 if (name[0] == '.')
523 continue;
524
525 pcap_snprintf(buf, sizeof(buf), "/dev/bus/usb/%03d/%s", bus, data->d_name);
526
527 fd = open(buf, O_RDWR);
528 if (fd == -1)
529 continue;
530
531 /*
532 * Sigh. Different kernels have different member names
533 * for this structure.
534 */
535 #ifdef HAVE_STRUCT_USBDEVFS_CTRLTRANSFER_BREQUESTTYPE
536 ctrl.bRequestType = USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE;
537 ctrl.bRequest = USB_REQ_GET_DESCRIPTOR;
538 ctrl.wValue = USB_DT_DEVICE << 8;
539 ctrl.wIndex = 0;
540 ctrl.wLength = sizeof(buf);
541 #else
542 ctrl.requesttype = USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE;
543 ctrl.request = USB_REQ_GET_DESCRIPTOR;
544 ctrl.value = USB_DT_DEVICE << 8;
545 ctrl.index = 0;
546 ctrl.length = sizeof(buf);
547 #endif
548 ctrl.data = buf;
549 ctrl.timeout = CTRL_TIMEOUT;
550
551 ret = ioctl(fd, USBDEVFS_CONTROL, &ctrl);
552
553 close(fd);
554 }
555 closedir(dir);
556 }
557 #endif /* HAVE_LINUX_USBDEVICE_FS_H */
558
559 pcap_t *
usb_create(const char * device,char * ebuf,int * is_ours)560 usb_create(const char *device, char *ebuf, int *is_ours)
561 {
562 const char *cp;
563 char *cpend;
564 long devnum;
565 pcap_t *p;
566
567 /* Does this look like a USB monitoring device? */
568 cp = strrchr(device, '/');
569 if (cp == NULL)
570 cp = device;
571 /* Does it begin with USB_IFACE? */
572 if (strncmp(cp, USB_IFACE, sizeof USB_IFACE - 1) != 0) {
573 /* Nope, doesn't begin with USB_IFACE */
574 *is_ours = 0;
575 return NULL;
576 }
577 /* Yes - is USB_IFACE followed by a number? */
578 cp += sizeof USB_IFACE - 1;
579 devnum = strtol(cp, &cpend, 10);
580 if (cpend == cp || *cpend != '\0') {
581 /* Not followed by a number. */
582 *is_ours = 0;
583 return NULL;
584 }
585 if (devnum < 0) {
586 /* Followed by a non-valid number. */
587 *is_ours = 0;
588 return NULL;
589 }
590
591 /* OK, it's probably ours. */
592 *is_ours = 1;
593
594 p = pcap_create_common(ebuf, sizeof (struct pcap_usb_linux));
595 if (p == NULL)
596 return (NULL);
597
598 p->activate_op = usb_activate;
599 return (p);
600 }
601
602 static int
usb_activate(pcap_t * handle)603 usb_activate(pcap_t* handle)
604 {
605 struct pcap_usb_linux *handlep = handle->priv;
606 char full_path[USB_LINE_LEN];
607 int ret;
608
609 /*
610 * Turn a negative snapshot value (invalid), a snapshot value of
611 * 0 (unspecified), or a value bigger than the normal maximum
612 * value, into the maximum allowed value.
613 *
614 * If some application really *needs* a bigger snapshot
615 * length, we should just increase MAXIMUM_SNAPLEN.
616 */
617 if (handle->snapshot <= 0 || handle->snapshot > MAXIMUM_SNAPLEN)
618 handle->snapshot = MAXIMUM_SNAPLEN;
619
620 /* Initialize some components of the pcap structure. */
621 handle->bufsize = handle->snapshot;
622 handle->offset = 0;
623 handle->linktype = DLT_USB_LINUX;
624
625 handle->inject_op = usb_inject_linux;
626 handle->setfilter_op = install_bpf_program; /* no kernel filtering */
627 handle->setdirection_op = usb_setdirection_linux;
628 handle->set_datalink_op = NULL; /* can't change data link type */
629 handle->getnonblock_op = pcap_getnonblock_fd;
630 handle->setnonblock_op = pcap_setnonblock_fd;
631
632 /*get usb bus index from device name */
633 if (sscanf(handle->opt.device, USB_IFACE"%d", &handlep->bus_index) != 1)
634 {
635 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
636 "Can't get USB bus index from %s", handle->opt.device);
637 return PCAP_ERROR;
638 }
639
640 if (have_binary_usbmon())
641 {
642 /*
643 * We have binary-mode support.
644 * Try to open the binary interface.
645 */
646 pcap_snprintf(full_path, USB_LINE_LEN, LINUX_USB_MON_DEV"%d", handlep->bus_index);
647 handle->fd = open(full_path, O_RDONLY, 0);
648 if (handle->fd < 0)
649 {
650 /*
651 * The attempt failed; why?
652 */
653 switch (errno) {
654
655 case ENOENT:
656 /*
657 * The device doesn't exist.
658 * That could either mean that there's
659 * no support for monitoring USB buses
660 * (which probably means "the usbmon
661 * module isn't loaded") or that there
662 * is but that *particular* device
663 * doesn't exist (no "scan all buses"
664 * device if the bus index is 0, no
665 * such bus if the bus index isn't 0).
666 */
667 return PCAP_ERROR_NO_SUCH_DEVICE;
668
669 case EACCES:
670 /*
671 * We didn't have permission to open it.
672 */
673 return PCAP_ERROR_PERM_DENIED;
674
675 default:
676 /*
677 * Something went wrong.
678 */
679 pcap_fmt_errmsg_for_errno(handle->errbuf,
680 PCAP_ERRBUF_SIZE, errno,
681 "Can't open USB bus file %s", full_path);
682 return PCAP_ERROR;
683 }
684 }
685
686 if (handle->opt.rfmon)
687 {
688 /*
689 * Monitor mode doesn't apply to USB devices.
690 */
691 close(handle->fd);
692 return PCAP_ERROR_RFMON_NOTSUP;
693 }
694
695 /* try to use fast mmap access */
696 if (usb_mmap(handle))
697 {
698 /* We succeeded. */
699 handle->linktype = DLT_USB_LINUX_MMAPPED;
700 handle->stats_op = usb_stats_linux_bin;
701 handle->read_op = usb_read_linux_mmap;
702 handle->cleanup_op = usb_cleanup_linux_mmap;
703 #ifdef HAVE_LINUX_USBDEVICE_FS_H
704 probe_devices(handlep->bus_index);
705 #endif
706
707 /*
708 * "handle->fd" is a real file, so
709 * "select()" and "poll()" work on it.
710 */
711 handle->selectable_fd = handle->fd;
712 return 0;
713 }
714
715 /*
716 * We failed; try plain binary interface access.
717 *
718 * Attempt to set the ring size as appropriate for
719 * the snapshot length, reducing the snapshot length
720 * if that'd make the ring bigger than the kernel
721 * supports.
722 */
723 if (usb_set_ring_size(handle, (int)sizeof(pcap_usb_header)) == -1) {
724 /* Failed. */
725 close(handle->fd);
726 return PCAP_ERROR;
727 }
728 handle->stats_op = usb_stats_linux_bin;
729 handle->read_op = usb_read_linux_bin;
730 #ifdef HAVE_LINUX_USBDEVICE_FS_H
731 probe_devices(handlep->bus_index);
732 #endif
733 }
734 else {
735 /*
736 * We don't have binary mode support.
737 * Try opening the text-mode device.
738 */
739 pcap_snprintf(full_path, USB_LINE_LEN, USB_TEXT_DIR"/%dt", handlep->bus_index);
740 handle->fd = open(full_path, O_RDONLY, 0);
741 if (handle->fd < 0)
742 {
743 if (errno == ENOENT)
744 {
745 /*
746 * Not found at the new location; try
747 * the old location.
748 */
749 pcap_snprintf(full_path, USB_LINE_LEN, USB_TEXT_DIR_OLD"/%dt", handlep->bus_index);
750 handle->fd = open(full_path, O_RDONLY, 0);
751 }
752 if (handle->fd < 0) {
753 if (errno == ENOENT)
754 {
755 /*
756 * The problem is that the file
757 * doesn't exist. Report that as
758 * "no such device". (That could
759 * mean "no such USB bus" or
760 * "monitoring not supported".)
761 */
762 ret = PCAP_ERROR_NO_SUCH_DEVICE;
763 }
764 else if (errno == EACCES)
765 {
766 /*
767 * The problem is that we don't
768 * have sufficient permission to
769 * open the file. Report that.
770 */
771 ret = PCAP_ERROR_PERM_DENIED;
772 }
773 else
774 {
775 /*
776 * Some other error.
777 */
778 ret = PCAP_ERROR;
779 }
780 pcap_fmt_errmsg_for_errno(handle->errbuf,
781 PCAP_ERRBUF_SIZE, errno,
782 "Can't open USB bus file %s",
783 full_path);
784 return ret;
785 }
786 }
787
788 if (handle->opt.rfmon)
789 {
790 /*
791 * Monitor mode doesn't apply to USB devices.
792 */
793 close(handle->fd);
794 return PCAP_ERROR_RFMON_NOTSUP;
795 }
796
797 handle->stats_op = usb_stats_linux;
798 handle->read_op = usb_read_linux;
799 }
800
801 /*
802 * "handle->fd" is a real file, so "select()" and "poll()"
803 * work on it.
804 */
805 handle->selectable_fd = handle->fd;
806
807 /* for plain binary access and text access we need to allocate the read
808 * buffer */
809 handle->buffer = malloc(handle->bufsize);
810 if (!handle->buffer) {
811 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
812 errno, "malloc");
813 close(handle->fd);
814 return PCAP_ERROR;
815 }
816 return 0;
817 }
818
819 static inline int
ascii_to_int(char c)820 ascii_to_int(char c)
821 {
822 return c < 'A' ? c- '0': ((c<'a') ? c - 'A' + 10: c-'a'+10);
823 }
824
825 /*
826 * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
827 * <linux-kernel-source>/drivers/usb/mon/mon_text.c for urb string
828 * format description
829 */
830 static int
usb_read_linux(pcap_t * handle,int max_packets _U_,pcap_handler callback,u_char * user)831 usb_read_linux(pcap_t *handle, int max_packets _U_, pcap_handler callback, u_char *user)
832 {
833 /* see:
834 * /usr/src/linux/Documentation/usb/usbmon.txt
835 * for message format
836 */
837 struct pcap_usb_linux *handlep = handle->priv;
838 unsigned timestamp;
839 int tag, cnt, ep_num, dev_addr, dummy, ret, urb_len, data_len;
840 char etype, pipeid1, pipeid2, status[16], urb_tag, line[USB_LINE_LEN];
841 char *string = line;
842 u_char * rawdata = handle->buffer;
843 struct pcap_pkthdr pkth;
844 pcap_usb_header* uhdr = (pcap_usb_header*)handle->buffer;
845 u_char urb_transfer=0;
846 int incoming=0;
847
848 /* ignore interrupt system call errors */
849 do {
850 ret = read(handle->fd, line, USB_LINE_LEN - 1);
851 if (handle->break_loop)
852 {
853 handle->break_loop = 0;
854 return -2;
855 }
856 } while ((ret == -1) && (errno == EINTR));
857 if (ret < 0)
858 {
859 if (errno == EAGAIN)
860 return 0; /* no data there */
861
862 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
863 errno, "Can't read from fd %d", handle->fd);
864 return -1;
865 }
866
867 /* read urb header; %n argument may increment return value, but it's
868 * not mandatory, so does not count on it*/
869 string[ret] = 0;
870 ret = sscanf(string, "%x %d %c %c%c:%d:%d %s%n", &tag, ×tamp, &etype,
871 &pipeid1, &pipeid2, &dev_addr, &ep_num, status,
872 &cnt);
873 if (ret < 8)
874 {
875 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
876 "Can't parse USB bus message '%s', too few tokens (expected 8 got %d)",
877 string, ret);
878 return -1;
879 }
880 uhdr->id = tag;
881 uhdr->device_address = dev_addr;
882 uhdr->bus_id = handlep->bus_index;
883 uhdr->status = 0;
884 string += cnt;
885
886 /* don't use usbmon provided timestamp, since it have low precision*/
887 if (gettimeofday(&pkth.ts, NULL) < 0)
888 {
889 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
890 errno, "Can't get timestamp for message '%s'", string);
891 return -1;
892 }
893 uhdr->ts_sec = pkth.ts.tv_sec;
894 uhdr->ts_usec = pkth.ts.tv_usec;
895
896 /* parse endpoint information */
897 if (pipeid1 == 'C')
898 urb_transfer = URB_CONTROL;
899 else if (pipeid1 == 'Z')
900 urb_transfer = URB_ISOCHRONOUS;
901 else if (pipeid1 == 'I')
902 urb_transfer = URB_INTERRUPT;
903 else if (pipeid1 == 'B')
904 urb_transfer = URB_BULK;
905 if (pipeid2 == 'i') {
906 ep_num |= URB_TRANSFER_IN;
907 incoming = 1;
908 }
909 if (etype == 'C')
910 incoming = !incoming;
911
912 /* direction check*/
913 if (incoming)
914 {
915 if (handle->direction == PCAP_D_OUT)
916 return 0;
917 }
918 else
919 if (handle->direction == PCAP_D_IN)
920 return 0;
921 uhdr->event_type = etype;
922 uhdr->transfer_type = urb_transfer;
923 uhdr->endpoint_number = ep_num;
924 pkth.caplen = sizeof(pcap_usb_header);
925 rawdata += sizeof(pcap_usb_header);
926
927 /* check if this is a setup packet */
928 ret = sscanf(status, "%d", &dummy);
929 if (ret != 1)
930 {
931 /* this a setup packet, setup data can be filled with underscore if
932 * usbmon has not been able to read them, so we must parse this fields as
933 * strings */
934 pcap_usb_setup* shdr;
935 char str1[3], str2[3], str3[5], str4[5], str5[5];
936 ret = sscanf(string, "%s %s %s %s %s%n", str1, str2, str3, str4,
937 str5, &cnt);
938 if (ret < 5)
939 {
940 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
941 "Can't parse USB bus message '%s', too few tokens (expected 5 got %d)",
942 string, ret);
943 return -1;
944 }
945 string += cnt;
946
947 /* try to convert to corresponding integer */
948 shdr = &uhdr->setup;
949 shdr->bmRequestType = strtoul(str1, 0, 16);
950 shdr->bRequest = strtoul(str2, 0, 16);
951 shdr->wValue = htols(strtoul(str3, 0, 16));
952 shdr->wIndex = htols(strtoul(str4, 0, 16));
953 shdr->wLength = htols(strtoul(str5, 0, 16));
954
955 uhdr->setup_flag = 0;
956 }
957 else
958 uhdr->setup_flag = 1;
959
960 /* read urb data */
961 ret = sscanf(string, " %d%n", &urb_len, &cnt);
962 if (ret < 1)
963 {
964 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
965 "Can't parse urb length from '%s'", string);
966 return -1;
967 }
968 string += cnt;
969
970 /* urb tag is not present if urb length is 0, so we can stop here
971 * text parsing */
972 pkth.len = urb_len+pkth.caplen;
973 uhdr->urb_len = urb_len;
974 uhdr->data_flag = 1;
975 data_len = 0;
976 if (uhdr->urb_len == 0)
977 goto got;
978
979 /* check for data presence; data is present if and only if urb tag is '=' */
980 if (sscanf(string, " %c", &urb_tag) != 1)
981 {
982 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
983 "Can't parse urb tag from '%s'", string);
984 return -1;
985 }
986
987 if (urb_tag != '=')
988 goto got;
989
990 /* skip urb tag and following space */
991 string += 3;
992
993 /* if we reach this point we got some urb data*/
994 uhdr->data_flag = 0;
995
996 /* read all urb data; if urb length is greater then the usbmon internal
997 * buffer length used by the kernel to spool the URB, we get only
998 * a partial information.
999 * At least until linux 2.6.17 there is no way to set usbmon intenal buffer
1000 * length and default value is 130. */
1001 while ((string[0] != 0) && (string[1] != 0) && (pkth.caplen < (bpf_u_int32)handle->snapshot))
1002 {
1003 rawdata[0] = ascii_to_int(string[0]) * 16 + ascii_to_int(string[1]);
1004 rawdata++;
1005 string+=2;
1006 if (string[0] == ' ')
1007 string++;
1008 pkth.caplen++;
1009 data_len++;
1010 }
1011
1012 got:
1013 uhdr->data_len = data_len;
1014 if (pkth.caplen > (bpf_u_int32)handle->snapshot)
1015 pkth.caplen = (bpf_u_int32)handle->snapshot;
1016
1017 if (handle->fcode.bf_insns == NULL ||
1018 bpf_filter(handle->fcode.bf_insns, handle->buffer,
1019 pkth.len, pkth.caplen)) {
1020 handlep->packets_read++;
1021 callback(user, &pkth, handle->buffer);
1022 return 1;
1023 }
1024 return 0; /* didn't pass filter */
1025 }
1026
1027 static int
usb_inject_linux(pcap_t * handle,const void * buf _U_,size_t size _U_)1028 usb_inject_linux(pcap_t *handle, const void *buf _U_, size_t size _U_)
1029 {
1030 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1031 "Packet injection is not supported on USB devices");
1032 return (-1);
1033 }
1034
1035 static int
usb_stats_linux(pcap_t * handle,struct pcap_stat * stats)1036 usb_stats_linux(pcap_t *handle, struct pcap_stat *stats)
1037 {
1038 struct pcap_usb_linux *handlep = handle->priv;
1039 int dummy, ret, consumed, cnt;
1040 char string[USB_LINE_LEN];
1041 char token[USB_LINE_LEN];
1042 char * ptr = string;
1043 int fd;
1044
1045 pcap_snprintf(string, USB_LINE_LEN, USB_TEXT_DIR"/%ds", handlep->bus_index);
1046 fd = open(string, O_RDONLY, 0);
1047 if (fd < 0)
1048 {
1049 if (errno == ENOENT)
1050 {
1051 /*
1052 * Not found at the new location; try the old
1053 * location.
1054 */
1055 pcap_snprintf(string, USB_LINE_LEN, USB_TEXT_DIR_OLD"/%ds", handlep->bus_index);
1056 fd = open(string, O_RDONLY, 0);
1057 }
1058 if (fd < 0) {
1059 pcap_fmt_errmsg_for_errno(handle->errbuf,
1060 PCAP_ERRBUF_SIZE, errno,
1061 "Can't open USB stats file %s", string);
1062 return -1;
1063 }
1064 }
1065
1066 /* read stats line */
1067 do {
1068 ret = read(fd, string, USB_LINE_LEN-1);
1069 } while ((ret == -1) && (errno == EINTR));
1070 close(fd);
1071
1072 if (ret < 0)
1073 {
1074 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1075 "Can't read stats from fd %d ", fd);
1076 return -1;
1077 }
1078 string[ret] = 0;
1079
1080 stats->ps_recv = handlep->packets_read;
1081 stats->ps_drop = 0; /* unless we find text_lost */
1082 stats->ps_ifdrop = 0;
1083
1084 /* extract info on dropped urbs */
1085 for (consumed=0; consumed < ret; ) {
1086 /* from the sscanf man page:
1087 * The C standard says: "Execution of a %n directive does
1088 * not increment the assignment count returned at the completion
1089 * of execution" but the Corrigendum seems to contradict this.
1090 * Do not make any assumptions on the effect of %n conversions
1091 * on the return value and explicitly check for cnt assignmet*/
1092 int ntok;
1093
1094 cnt = -1;
1095 ntok = sscanf(ptr, "%s%n", token, &cnt);
1096 if ((ntok < 1) || (cnt < 0))
1097 break;
1098 consumed += cnt;
1099 ptr += cnt;
1100 if (strcmp(token, "text_lost") == 0)
1101 ntok = sscanf(ptr, "%d%n", &stats->ps_drop, &cnt);
1102 else
1103 ntok = sscanf(ptr, "%d%n", &dummy, &cnt);
1104 if ((ntok != 1) || (cnt < 0))
1105 break;
1106 consumed += cnt;
1107 ptr += cnt;
1108 }
1109
1110 return 0;
1111 }
1112
1113 static int
usb_setdirection_linux(pcap_t * p,pcap_direction_t d)1114 usb_setdirection_linux(pcap_t *p, pcap_direction_t d)
1115 {
1116 p->direction = d;
1117 return 0;
1118 }
1119
1120
1121 static int
usb_stats_linux_bin(pcap_t * handle,struct pcap_stat * stats)1122 usb_stats_linux_bin(pcap_t *handle, struct pcap_stat *stats)
1123 {
1124 struct pcap_usb_linux *handlep = handle->priv;
1125 int ret;
1126 struct mon_bin_stats st;
1127 ret = ioctl(handle->fd, MON_IOCG_STATS, &st);
1128 if (ret < 0)
1129 {
1130 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
1131 errno, "Can't read stats from fd %d", handle->fd);
1132 return -1;
1133 }
1134
1135 stats->ps_recv = handlep->packets_read + st.queued;
1136 stats->ps_drop = st.dropped;
1137 stats->ps_ifdrop = 0;
1138 return 0;
1139 }
1140
1141 /*
1142 * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
1143 * <linux-kernel-source>/drivers/usb/mon/mon_bin.c binary ABI
1144 */
1145 static int
usb_read_linux_bin(pcap_t * handle,int max_packets _U_,pcap_handler callback,u_char * user)1146 usb_read_linux_bin(pcap_t *handle, int max_packets _U_, pcap_handler callback, u_char *user)
1147 {
1148 struct pcap_usb_linux *handlep = handle->priv;
1149 struct mon_bin_get info;
1150 int ret;
1151 struct pcap_pkthdr pkth;
1152 u_int clen = handle->snapshot - sizeof(pcap_usb_header);
1153
1154 /* the usb header is going to be part of 'packet' data*/
1155 info.hdr = (pcap_usb_header*) handle->buffer;
1156 info.data = (u_char *)handle->buffer + sizeof(pcap_usb_header);
1157 info.data_len = clen;
1158
1159 /* ignore interrupt system call errors */
1160 do {
1161 ret = ioctl(handle->fd, MON_IOCX_GET, &info);
1162 if (handle->break_loop)
1163 {
1164 handle->break_loop = 0;
1165 return -2;
1166 }
1167 } while ((ret == -1) && (errno == EINTR));
1168 if (ret < 0)
1169 {
1170 if (errno == EAGAIN)
1171 return 0; /* no data there */
1172
1173 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
1174 errno, "Can't read from fd %d", handle->fd);
1175 return -1;
1176 }
1177
1178 /*
1179 * info.hdr->data_len is the number of bytes of isochronous
1180 * descriptors (if any) plus the number of bytes of data
1181 * provided. There are no isochronous descriptors here,
1182 * because we're using the old 48-byte header.
1183 *
1184 * If info.hdr->data_flag is non-zero, there's no URB data;
1185 * info.hdr->urb_len is the size of the buffer into which
1186 * data is to be placed; it does not represent the amount
1187 * of data transferred. If info.hdr->data_flag is zero,
1188 * there is URB data, and info.hdr->urb_len is the number
1189 * of bytes transmitted or received; it doesn't include
1190 * isochronous descriptors.
1191 *
1192 * The kernel may give us more data than the snaplen; if it did,
1193 * reduce the data length so that the total number of bytes we
1194 * tell our client we have is not greater than the snaplen.
1195 */
1196 if (info.hdr->data_len < clen)
1197 clen = info.hdr->data_len;
1198 info.hdr->data_len = clen;
1199 pkth.caplen = sizeof(pcap_usb_header) + clen;
1200 if (info.hdr->data_flag) {
1201 /*
1202 * No data; just base the on-the-wire length on
1203 * info.hdr->data_len (so that it's >= the captured
1204 * length).
1205 */
1206 pkth.len = sizeof(pcap_usb_header) + info.hdr->data_len;
1207 } else {
1208 /*
1209 * We got data; base the on-the-wire length on
1210 * info.hdr->urb_len, so that it includes data
1211 * discarded by the USB monitor device due to
1212 * its buffer being too small.
1213 */
1214 pkth.len = sizeof(pcap_usb_header) + info.hdr->urb_len;
1215 }
1216 pkth.ts.tv_sec = info.hdr->ts_sec;
1217 pkth.ts.tv_usec = info.hdr->ts_usec;
1218
1219 if (handle->fcode.bf_insns == NULL ||
1220 bpf_filter(handle->fcode.bf_insns, handle->buffer,
1221 pkth.len, pkth.caplen)) {
1222 handlep->packets_read++;
1223 callback(user, &pkth, handle->buffer);
1224 return 1;
1225 }
1226
1227 return 0; /* didn't pass filter */
1228 }
1229
1230 /*
1231 * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
1232 * <linux-kernel-source>/drivers/usb/mon/mon_bin.c binary ABI
1233 */
1234 #define VEC_SIZE 32
1235 static int
usb_read_linux_mmap(pcap_t * handle,int max_packets,pcap_handler callback,u_char * user)1236 usb_read_linux_mmap(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
1237 {
1238 struct pcap_usb_linux *handlep = handle->priv;
1239 struct mon_bin_mfetch fetch;
1240 int32_t vec[VEC_SIZE];
1241 struct pcap_pkthdr pkth;
1242 pcap_usb_header_mmapped* hdr;
1243 int nflush = 0;
1244 int packets = 0;
1245 u_int clen, max_clen;
1246
1247 max_clen = handle->snapshot - sizeof(pcap_usb_header_mmapped);
1248
1249 for (;;) {
1250 int i, ret;
1251 int limit = max_packets - packets;
1252 if (limit <= 0)
1253 limit = VEC_SIZE;
1254 if (limit > VEC_SIZE)
1255 limit = VEC_SIZE;
1256
1257 /* try to fetch as many events as possible*/
1258 fetch.offvec = vec;
1259 fetch.nfetch = limit;
1260 fetch.nflush = nflush;
1261 /* ignore interrupt system call errors */
1262 do {
1263 ret = ioctl(handle->fd, MON_IOCX_MFETCH, &fetch);
1264 if (handle->break_loop)
1265 {
1266 handle->break_loop = 0;
1267 return -2;
1268 }
1269 } while ((ret == -1) && (errno == EINTR));
1270 if (ret < 0)
1271 {
1272 if (errno == EAGAIN)
1273 return 0; /* no data there */
1274
1275 pcap_fmt_errmsg_for_errno(handle->errbuf,
1276 PCAP_ERRBUF_SIZE, errno, "Can't mfetch fd %d",
1277 handle->fd);
1278 return -1;
1279 }
1280
1281 /* keep track of processed events, we will flush them later */
1282 nflush = fetch.nfetch;
1283 for (i=0; i<fetch.nfetch; ++i) {
1284 /* discard filler */
1285 hdr = (pcap_usb_header_mmapped*) &handlep->mmapbuf[vec[i]];
1286 if (hdr->event_type == '@')
1287 continue;
1288
1289 /*
1290 * hdr->data_len is the number of bytes of
1291 * isochronous descriptors (if any) plus the
1292 * number of bytes of data provided.
1293 *
1294 * If hdr->data_flag is non-zero, there's no
1295 * URB data; hdr->urb_len is the size of the
1296 * buffer into which data is to be placed; it does
1297 * not represent the amount of data transferred.
1298 * If hdr->data_flag is zero, there is URB data,
1299 * and hdr->urb_len is the number of bytes
1300 * transmitted or received; it doesn't include
1301 * isochronous descriptors.
1302 *
1303 * The kernel may give us more data than the
1304 * snaplen; if it did, reduce the data length
1305 * so that the total number of bytes we
1306 * tell our client we have is not greater than
1307 * the snaplen.
1308 */
1309 clen = max_clen;
1310 if (hdr->data_len < clen)
1311 clen = hdr->data_len;
1312 pkth.caplen = sizeof(pcap_usb_header_mmapped) + clen;
1313 if (hdr->data_flag) {
1314 /*
1315 * No data; just base the on-the-wire length
1316 * on hdr->data_len (so that it's >= the
1317 * captured length).
1318 */
1319 pkth.len = sizeof(pcap_usb_header_mmapped) +
1320 hdr->data_len;
1321 } else {
1322 /*
1323 * We got data; base the on-the-wire length
1324 * on hdr->urb_len, so that it includes
1325 * data discarded by the USB monitor device
1326 * due to its buffer being too small.
1327 */
1328 pkth.len = sizeof(pcap_usb_header_mmapped) +
1329 (hdr->ndesc * sizeof (usb_isodesc)) + hdr->urb_len;
1330 }
1331 pkth.ts.tv_sec = hdr->ts_sec;
1332 pkth.ts.tv_usec = hdr->ts_usec;
1333
1334 if (handle->fcode.bf_insns == NULL ||
1335 bpf_filter(handle->fcode.bf_insns, (u_char*) hdr,
1336 pkth.len, pkth.caplen)) {
1337 handlep->packets_read++;
1338 callback(user, &pkth, (u_char*) hdr);
1339 packets++;
1340 }
1341 }
1342
1343 /* with max_packets specifying "unlimited" we stop afer the first chunk*/
1344 if (PACKET_COUNT_IS_UNLIMITED(max_packets) || (packets == max_packets))
1345 break;
1346 }
1347
1348 /* flush pending events*/
1349 if (ioctl(handle->fd, MON_IOCH_MFLUSH, nflush) == -1) {
1350 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
1351 errno, "Can't mflush fd %d", handle->fd);
1352 return -1;
1353 }
1354 return packets;
1355 }
1356
1357 static void
usb_cleanup_linux_mmap(pcap_t * handle)1358 usb_cleanup_linux_mmap(pcap_t* handle)
1359 {
1360 struct pcap_usb_linux *handlep = handle->priv;
1361
1362 /* if we have a memory-mapped buffer, unmap it */
1363 if (handlep->mmapbuf != NULL) {
1364 munmap(handlep->mmapbuf, handlep->mmapbuflen);
1365 handlep->mmapbuf = NULL;
1366 }
1367 pcap_cleanup_live_common(handle);
1368 }
1369