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