Coverage Report

Created: 2026-10-28 06:57

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