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