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