]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/libpcap/pcap-usb-linux.c
Add two missing eventhandler.h headers
[FreeBSD/FreeBSD.git] / contrib / 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 #ifdef NEED_STRERROR_H
45 #include "strerror.h"
46 #endif
47
48 #include <ctype.h>
49 #include <errno.h>
50 #include <stdlib.h>
51 #include <unistd.h>
52 #include <fcntl.h>
53 #include <string.h>
54 #include <dirent.h>
55 #include <byteswap.h>
56 #include <netinet/in.h>
57 #include <sys/ioctl.h>
58 #include <sys/mman.h>
59 #include <sys/utsname.h>
60 #ifdef HAVE_LINUX_USBDEVICE_FS_H
61 /*
62  * We might need <linux/compiler.h> to define __user for
63  * <linux/usbdevice_fs.h>.
64  */
65 #ifdef HAVE_LINUX_COMPILER_H
66 #include <linux/compiler.h>
67 #endif /* HAVE_LINUX_COMPILER_H */
68 #include <linux/usbdevice_fs.h>
69 #endif /* HAVE_LINUX_USBDEVICE_FS_H */
70
71 #define USB_IFACE "usbmon"
72 #define USB_TEXT_DIR_OLD "/sys/kernel/debug/usbmon"
73 #define USB_TEXT_DIR "/sys/kernel/debug/usb/usbmon"
74 #define SYS_USB_BUS_DIR "/sys/bus/usb/devices"
75 #define PROC_USB_BUS_DIR "/proc/bus/usb"
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(pcap_t *, struct pcap_stat *);
134 static int usb_stats_linux_bin(pcap_t *, struct pcap_stat *);
135 static int usb_read_linux(pcap_t *, int , pcap_handler , u_char *);
136 static int usb_read_linux_bin(pcap_t *, int , pcap_handler , u_char *);
137 static int usb_read_linux_mmap(pcap_t *, int , pcap_handler , u_char *);
138 static int usb_inject_linux(pcap_t *, const void *, size_t);
139 static int usb_setdirection_linux(pcap_t *, pcap_direction_t);
140 static void usb_cleanup_linux_mmap(pcap_t *);
141
142 static int
143 have_binary_usbmon(void)
144 {
145         struct utsname utsname;
146         char *version_component, *endp;
147         int major, minor, subminor;
148
149         if (uname(&utsname) == 0) {
150                 /*
151                  * 2.6.21 is the first release with the binary-mode
152                  * USB monitoring.
153                  */
154                 version_component = utsname.release;
155                 major = strtol(version_component, &endp, 10);
156                 if (endp != version_component && *endp == '.') {
157                         /*
158                          * OK, that was a valid major version.
159                          * Is it 3 or greater?  If so, we have binary
160                          * mode support.
161                          */
162                         if (major >= 3)
163                                 return 1;
164
165                         /*
166                          * Is it 1 or less?  If so, we don't have binary
167                          * mode support.  (In fact, we don't have any
168                          * USB monitoring....)
169                          */
170                         if (major <= 1)
171                                 return 0;
172                 }
173
174                 /*
175                  * OK, this is a 2.x kernel.
176                  * What's the minor version?
177                  */
178                 version_component = endp + 1;
179                 minor = strtol(version_component, &endp, 10);
180                 if (endp != version_component &&
181                     (*endp == '.' || *endp == '\0')) {
182                         /*
183                          * OK, that was a valid minor version.
184                          * Is is 2.6 or later?  (There shouldn't be a
185                          * "later", as 2.6.x went to 3.x, but we'll
186                          * check anyway.)
187                          */
188                         if (minor < 6) {
189                                 /*
190                                  * No, so no binary support (did 2.4 have
191                                  * any USB monitoring at all?)
192                                  */
193                                 return 0;
194                         }
195
196                         /*
197                          * OK, this is a 2.6.x kernel.
198                          * What's the subminor version?
199                          */
200                         version_component = endp + 1;
201                         subminor = strtol(version_component, &endp, 10);
202                         if (endp != version_component &&
203                             (*endp == '.' || *endp == '\0')) {
204                                 /*
205                                  * OK, that was a valid subminor version.
206                                  * Is it 21 or greater?
207                                  */
208                                 if (subminor >= 21) {
209                                         /*
210                                          * Yes - we have binary mode
211                                          * support.
212                                          */
213                                         return 1;
214                                 }
215                         }
216                 }
217         }
218
219         /*
220          * Either uname() failed, in which case we just say "no binary
221          * mode support", or we don't have binary mode support.
222          */
223         return 0;
224 }
225
226 /* facility to add an USB device to the device list*/
227 static int
228 usb_dev_add(pcap_if_list_t *devlistp, int n, char *err_str)
229 {
230         char dev_name[10];
231         char dev_descr[30];
232         pcap_snprintf(dev_name, 10, USB_IFACE"%d", n);
233         /*
234          * XXX - is there any notion of "up" and "running"?
235          */
236         if (n == 0) {
237                 /*
238                  * As this refers to all buses, there's no notion of
239                  * "connected" vs. "disconnected", as that's a property
240                  * that would apply to a particular USB interface.
241                  */
242                 if (add_dev(devlistp, dev_name,
243                     PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE,
244                     "All USB buses", err_str) == NULL)
245                         return -1;
246         } else {
247                 /*
248                  * XXX - is there a way to determine whether anything's
249                  * plugged into this bus interface or not, and set
250                  * PCAP_IF_CONNECTION_STATUS_CONNECTED or
251                  * PCAP_IF_CONNECTION_STATUS_DISCONNECTED?
252                  */
253                 pcap_snprintf(dev_descr, 30, "USB bus number %d", n);
254                 if (add_dev(devlistp, dev_name, 0, dev_descr, err_str) == NULL)
255                         return -1;
256         }
257
258         return 0;
259 }
260
261 int
262 usb_findalldevs(pcap_if_list_t *devlistp, char *err_str)
263 {
264         char usb_mon_dir[PATH_MAX];
265         char *usb_mon_prefix;
266         size_t usb_mon_prefix_len;
267         struct dirent* data;
268         int ret = 0;
269         DIR* dir;
270         int n;
271         char* name;
272         size_t len;
273
274         if (have_binary_usbmon()) {
275                 /*
276                  * We have binary-mode support.
277                  * What do the device names look like?
278                  * Split LINUX_USB_MON_DEV into a directory that we'll
279                  * scan and a file name prefix that we'll check for.
280                  */
281                 strlcpy(usb_mon_dir, LINUX_USB_MON_DEV, sizeof usb_mon_dir);
282                 usb_mon_prefix = strrchr(usb_mon_dir, '/');
283                 if (usb_mon_prefix == NULL) {
284                         /*
285                          * This "shouldn't happen".  Just give up if it
286                          * does.
287                          */
288                         return 0;
289                 }
290                 *usb_mon_prefix++ = '\0';
291                 usb_mon_prefix_len = strlen(usb_mon_prefix);
292
293                 /*
294                  * Open the directory and scan it.
295                  */
296                 dir = opendir(usb_mon_dir);
297                 if (dir != NULL) {
298                         while ((ret == 0) && ((data = readdir(dir)) != 0)) {
299                                 name = data->d_name;
300
301                                 /*
302                                  * Is this a usbmon device?
303                                  */
304                                 if (strncmp(name, usb_mon_prefix, usb_mon_prefix_len) != 0)
305                                         continue;       /* no */
306
307                                 /*
308                                  * What's the device number?
309                                  */
310                                 if (sscanf(&name[usb_mon_prefix_len], "%d", &n) == 0)
311                                         continue;       /* failed */
312
313                                 ret = usb_dev_add(devlistp, n, err_str);
314                         }
315
316                         closedir(dir);
317                 }
318                 return 0;
319         } else {
320                 /*
321                  * We have only text mode support.
322                  * We don't look for the text devices because we can't
323                  * look for them without root privileges, and we don't
324                  * want to require root privileges to enumerate devices
325                  * (we want to let the user to try a device and get
326                  * an error, rather than seeing no devices and asking
327                  * "why am I not seeing devices" and forcing a long
328                  * process of poking to figure out whether it's "no
329                  * privileges" or "your kernel is too old" or "the
330                  * usbmon module isn't loaded" or...).
331                  *
332                  * Instead, we look to see what buses we have.
333                  * If the kernel is so old that it doesn't have
334                  * binary-mode support, it's also so old that
335                  * it doesn't have a "scan all buses" device.
336                  *
337                  * First, try scanning sysfs USB bus directory.
338                  */
339                 dir = opendir(SYS_USB_BUS_DIR);
340                 if (dir != NULL) {
341                         while ((ret == 0) && ((data = readdir(dir)) != 0)) {
342                                 name = data->d_name;
343
344                                 if (strncmp(name, "usb", 3) != 0)
345                                         continue;
346
347                                 if (sscanf(&name[3], "%d", &n) == 0)
348                                         continue;
349
350                                 ret = usb_dev_add(devlistp, n, err_str);
351                         }
352
353                         closedir(dir);
354                         return 0;
355                 }
356
357                 /* That didn't work; try scanning procfs USB bus directory. */
358                 dir = opendir(PROC_USB_BUS_DIR);
359                 if (dir != NULL) {
360                         while ((ret == 0) && ((data = readdir(dir)) != 0)) {
361                                 name = data->d_name;
362                                 len = strlen(name);
363
364                                 /* if this file name does not end with a number it's not of our interest */
365                                 if ((len < 1) || !isdigit(name[--len]))
366                                         continue;
367                                 while (isdigit(name[--len]));
368                                 if (sscanf(&name[len+1], "%d", &n) != 1)
369                                         continue;
370
371                                 ret = usb_dev_add(devlistp, n, err_str);
372                         }
373
374                         closedir(dir);
375                         return ret;
376                 }
377
378                 /* neither of them worked */
379                 return 0;
380         }
381 }
382
383 static
384 int usb_mmap(pcap_t* handle)
385 {
386         struct pcap_usb_linux *handlep = handle->priv;
387         int len = ioctl(handle->fd, MON_IOCQ_RING_SIZE);
388         if (len < 0)
389                 return 0;
390
391         handlep->mmapbuflen = len;
392         handlep->mmapbuf = mmap(0, handlep->mmapbuflen, PROT_READ,
393             MAP_SHARED, handle->fd, 0);
394         return handlep->mmapbuf != MAP_FAILED;
395 }
396
397 #ifdef HAVE_LINUX_USBDEVICE_FS_H
398
399 #define CTRL_TIMEOUT    (5*1000)        /* milliseconds */
400
401 #define USB_DIR_IN              0x80
402 #define USB_TYPE_STANDARD       0x00
403 #define USB_RECIP_DEVICE        0x00
404
405 #define USB_REQ_GET_DESCRIPTOR  6
406
407 #define USB_DT_DEVICE           1
408
409 /* probe the descriptors of the devices attached to the bus */
410 /* the descriptors will end up in the captured packet stream */
411 /* and be decoded by external apps like wireshark */
412 /* without these identifying probes packet data can't be fully decoded */
413 static void
414 probe_devices(int bus)
415 {
416         struct usbdevfs_ctrltransfer ctrl;
417         struct dirent* data;
418         int ret = 0;
419         char buf[sizeof("/dev/bus/usb/000/") + NAME_MAX];
420         DIR* dir;
421
422         /* scan usb bus directories for device nodes */
423         pcap_snprintf(buf, sizeof(buf), "/dev/bus/usb/%03d", bus);
424         dir = opendir(buf);
425         if (!dir)
426                 return;
427
428         while ((ret >= 0) && ((data = readdir(dir)) != 0)) {
429                 int fd;
430                 char* name = data->d_name;
431
432                 if (name[0] == '.')
433                         continue;
434
435                 pcap_snprintf(buf, sizeof(buf), "/dev/bus/usb/%03d/%s", bus, data->d_name);
436
437                 fd = open(buf, O_RDWR);
438                 if (fd == -1)
439                         continue;
440
441                 /*
442                  * Sigh.  Different kernels have different member names
443                  * for this structure.
444                  */
445 #ifdef HAVE_STRUCT_USBDEVFS_CTRLTRANSFER_BREQUESTTYPE
446                 ctrl.bRequestType = USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE;
447                 ctrl.bRequest = USB_REQ_GET_DESCRIPTOR;
448                 ctrl.wValue = USB_DT_DEVICE << 8;
449                 ctrl.wIndex = 0;
450                 ctrl.wLength = sizeof(buf);
451 #else
452                 ctrl.requesttype = USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE;
453                 ctrl.request = USB_REQ_GET_DESCRIPTOR;
454                 ctrl.value = USB_DT_DEVICE << 8;
455                 ctrl.index = 0;
456                 ctrl.length = sizeof(buf);
457 #endif
458                 ctrl.data = buf;
459                 ctrl.timeout = CTRL_TIMEOUT;
460
461                 ret = ioctl(fd, USBDEVFS_CONTROL, &ctrl);
462
463                 close(fd);
464         }
465         closedir(dir);
466 }
467 #endif /* HAVE_LINUX_USBDEVICE_FS_H */
468
469 pcap_t *
470 usb_create(const char *device, char *ebuf, int *is_ours)
471 {
472         const char *cp;
473         char *cpend;
474         long devnum;
475         pcap_t *p;
476
477         /* Does this look like a USB monitoring device? */
478         cp = strrchr(device, '/');
479         if (cp == NULL)
480                 cp = device;
481         /* Does it begin with USB_IFACE? */
482         if (strncmp(cp, USB_IFACE, sizeof USB_IFACE - 1) != 0) {
483                 /* Nope, doesn't begin with USB_IFACE */
484                 *is_ours = 0;
485                 return NULL;
486         }
487         /* Yes - is USB_IFACE followed by a number? */
488         cp += sizeof USB_IFACE - 1;
489         devnum = strtol(cp, &cpend, 10);
490         if (cpend == cp || *cpend != '\0') {
491                 /* Not followed by a number. */
492                 *is_ours = 0;
493                 return NULL;
494         }
495         if (devnum < 0) {
496                 /* Followed by a non-valid number. */
497                 *is_ours = 0;
498                 return NULL;
499         }
500
501         /* OK, it's probably ours. */
502         *is_ours = 1;
503
504         p = pcap_create_common(ebuf, sizeof (struct pcap_usb_linux));
505         if (p == NULL)
506                 return (NULL);
507
508         p->activate_op = usb_activate;
509         return (p);
510 }
511
512 static int
513 usb_activate(pcap_t* handle)
514 {
515         struct pcap_usb_linux *handlep = handle->priv;
516         char            full_path[USB_LINE_LEN];
517
518         /*
519          * Turn a negative snapshot value (invalid), a snapshot value of
520          * 0 (unspecified), or a value bigger than the normal maximum
521          * value, into the maximum allowed value.
522          *
523          * If some application really *needs* a bigger snapshot
524          * length, we should just increase MAXIMUM_SNAPLEN.
525          */
526         if (handle->snapshot <= 0 || handle->snapshot > MAXIMUM_SNAPLEN)
527                 handle->snapshot = MAXIMUM_SNAPLEN;
528
529         /* Initialize some components of the pcap structure. */
530         handle->bufsize = handle->snapshot;
531         handle->offset = 0;
532         handle->linktype = DLT_USB_LINUX;
533
534         handle->inject_op = usb_inject_linux;
535         handle->setfilter_op = install_bpf_program; /* no kernel filtering */
536         handle->setdirection_op = usb_setdirection_linux;
537         handle->set_datalink_op = NULL; /* can't change data link type */
538         handle->getnonblock_op = pcap_getnonblock_fd;
539         handle->setnonblock_op = pcap_setnonblock_fd;
540
541         /*get usb bus index from device name */
542         if (sscanf(handle->opt.device, USB_IFACE"%d", &handlep->bus_index) != 1)
543         {
544                 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
545                         "Can't get USB bus index from %s", handle->opt.device);
546                 return PCAP_ERROR;
547         }
548
549         if (have_binary_usbmon())
550         {
551                 /*
552                  * We have binary-mode support.
553                  * Try to open the binary interface.
554                  */
555                 pcap_snprintf(full_path, USB_LINE_LEN, LINUX_USB_MON_DEV"%d", handlep->bus_index);
556                 handle->fd = open(full_path, O_RDONLY, 0);
557                 if (handle->fd < 0)
558                 {
559                         /*
560                          * The attempt failed; why?
561                          */
562                         switch (errno) {
563
564                         case ENOENT:
565                                 /*
566                                  * The device doesn't exist.
567                                  * That could either mean that there's
568                                  * no support for monitoring USB buses
569                                  * (which probably means "the usbmon
570                                  * module isn't loaded") or that there
571                                  * is but that *particular* device
572                                  * doesn't exist (no "scan all buses"
573                                  * device if the bus index is 0, no
574                                  * such bus if the bus index isn't 0).
575                                  */
576                                 return PCAP_ERROR_NO_SUCH_DEVICE;
577
578                         case EACCES:
579                                 /*
580                                  * We didn't have permission to open it.
581                                  */
582                                 return PCAP_ERROR_PERM_DENIED;
583
584                         default:
585                                 /*
586                                  * Something went wrong.
587                                  */
588                                 pcap_fmt_errmsg_for_errno(handle->errbuf,
589                                     PCAP_ERRBUF_SIZE, errno,
590                                     "Can't open USB bus file %s", full_path);
591                                 return PCAP_ERROR;
592                         }
593                 }
594
595                 if (handle->opt.rfmon)
596                 {
597                         /*
598                          * Monitor mode doesn't apply to USB devices.
599                          */
600                         close(handle->fd);
601                         return PCAP_ERROR_RFMON_NOTSUP;
602                 }
603
604                 /* try to use fast mmap access */
605                 if (usb_mmap(handle))
606                 {
607                         handle->linktype = DLT_USB_LINUX_MMAPPED;
608                         handle->stats_op = usb_stats_linux_bin;
609                         handle->read_op = usb_read_linux_mmap;
610                         handle->cleanup_op = usb_cleanup_linux_mmap;
611 #ifdef HAVE_LINUX_USBDEVICE_FS_H
612                         probe_devices(handlep->bus_index);
613 #endif
614
615                         /*
616                          * "handle->fd" is a real file, so
617                          * "select()" and "poll()" work on it.
618                          */
619                         handle->selectable_fd = handle->fd;
620                         return 0;
621                 }
622
623                 /* can't mmap, use plain binary interface access */
624                 handle->stats_op = usb_stats_linux_bin;
625                 handle->read_op = usb_read_linux_bin;
626 #ifdef HAVE_LINUX_USBDEVICE_FS_H
627                 probe_devices(handlep->bus_index);
628 #endif
629         }
630         else {
631                 /*
632                  * We don't have binary mode support.
633                  * Try opening the text-mode device.
634                  */
635                 pcap_snprintf(full_path, USB_LINE_LEN, USB_TEXT_DIR"/%dt", handlep->bus_index);
636                 handle->fd = open(full_path, O_RDONLY, 0);
637                 if (handle->fd < 0)
638                 {
639                         if (errno == ENOENT)
640                         {
641                                 /*
642                                  * Not found at the new location; try
643                                  * the old location.
644                                  */
645                                 pcap_snprintf(full_path, USB_LINE_LEN, USB_TEXT_DIR_OLD"/%dt", handlep->bus_index);
646                                 handle->fd = open(full_path, O_RDONLY, 0);
647                         }
648                         if (handle->fd < 0) {
649                                 /*
650                                  * Is the problem that we didn't have
651                                  * sufficient permission to open it?
652                                  */
653                                 if (errno == EACCES) {
654                                         /*
655                                          * Yes - return that error.
656                                          */
657                                         return PCAP_ERROR_PERM_DENIED;
658                                 }
659
660                                 /*
661                                  * No - was the problem something other
662                                  * than "it doesn't exist"?
663                                  */
664                                 if (errno != ENOENT) {
665                                         /*
666                                          * Yes - return *that* error.
667                                          */
668                                         pcap_fmt_errmsg_for_errno(handle->errbuf,
669                                             PCAP_ERRBUF_SIZE, errno,
670                                             "Can't open USB bus file %s",
671                                             full_path);
672                                         return PCAP_ERROR;
673                                 }
674
675                                 /*
676                                  * No.  Report that as "no such device".
677                                  * (That could mean "no such USB bus"
678                                  * or "monitoring not supported".)
679                                  */
680                                 return PCAP_ERROR_NO_SUCH_DEVICE;
681                         }
682                 }
683
684                 if (handle->opt.rfmon)
685                 {
686                         /*
687                          * Monitor mode doesn't apply to USB devices.
688                          */
689                         close(handle->fd);
690                         return PCAP_ERROR_RFMON_NOTSUP;
691                 }
692
693                 handle->stats_op = usb_stats_linux;
694                 handle->read_op = usb_read_linux;
695         }
696
697         /*
698          * "handle->fd" is a real file, so "select()" and "poll()"
699          * work on it.
700          */
701         handle->selectable_fd = handle->fd;
702
703         /* for plain binary access and text access we need to allocate the read
704          * buffer */
705         handle->buffer = malloc(handle->bufsize);
706         if (!handle->buffer) {
707                 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
708                     errno, "malloc");
709                 close(handle->fd);
710                 return PCAP_ERROR;
711         }
712         return 0;
713 }
714
715 static inline int
716 ascii_to_int(char c)
717 {
718         return c < 'A' ? c- '0': ((c<'a') ? c - 'A' + 10: c-'a'+10);
719 }
720
721 /*
722  * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
723  * <linux-kernel-source>/drivers/usb/mon/mon_text.c for urb string
724  * format description
725  */
726 static int
727 usb_read_linux(pcap_t *handle, int max_packets _U_, pcap_handler callback, u_char *user)
728 {
729         /* see:
730         * /usr/src/linux/Documentation/usb/usbmon.txt
731         * for message format
732         */
733         struct pcap_usb_linux *handlep = handle->priv;
734         unsigned timestamp;
735         int tag, cnt, ep_num, dev_addr, dummy, ret, urb_len, data_len;
736         char etype, pipeid1, pipeid2, status[16], urb_tag, line[USB_LINE_LEN];
737         char *string = line;
738         u_char * rawdata = handle->buffer;
739         struct pcap_pkthdr pkth;
740         pcap_usb_header* uhdr = (pcap_usb_header*)handle->buffer;
741         u_char urb_transfer=0;
742         int incoming=0;
743
744         /* ignore interrupt system call errors */
745         do {
746                 ret = read(handle->fd, line, USB_LINE_LEN - 1);
747                 if (handle->break_loop)
748                 {
749                         handle->break_loop = 0;
750                         return -2;
751                 }
752         } while ((ret == -1) && (errno == EINTR));
753         if (ret < 0)
754         {
755                 if (errno == EAGAIN)
756                         return 0;       /* no data there */
757
758                 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
759                     errno, "Can't read from fd %d", handle->fd);
760                 return -1;
761         }
762
763         /* read urb header; %n argument may increment return value, but it's
764         * not mandatory, so does not count on it*/
765         string[ret] = 0;
766         ret = sscanf(string, "%x %d %c %c%c:%d:%d %s%n", &tag, &timestamp, &etype,
767                 &pipeid1, &pipeid2, &dev_addr, &ep_num, status,
768                 &cnt);
769         if (ret < 8)
770         {
771                 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
772                     "Can't parse USB bus message '%s', too few tokens (expected 8 got %d)",
773                     string, ret);
774                 return -1;
775         }
776         uhdr->id = tag;
777         uhdr->device_address = dev_addr;
778         uhdr->bus_id = handlep->bus_index;
779         uhdr->status = 0;
780         string += cnt;
781
782         /* don't use usbmon provided timestamp, since it have low precision*/
783         if (gettimeofday(&pkth.ts, NULL) < 0)
784         {
785                 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
786                     errno, "Can't get timestamp for message '%s'", string);
787                 return -1;
788         }
789         uhdr->ts_sec = pkth.ts.tv_sec;
790         uhdr->ts_usec = pkth.ts.tv_usec;
791
792         /* parse endpoint information */
793         if (pipeid1 == 'C')
794                 urb_transfer = URB_CONTROL;
795         else if (pipeid1 == 'Z')
796                 urb_transfer = URB_ISOCHRONOUS;
797         else if (pipeid1 == 'I')
798                 urb_transfer = URB_INTERRUPT;
799         else if (pipeid1 == 'B')
800                 urb_transfer = URB_BULK;
801         if (pipeid2 == 'i') {
802                 ep_num |= URB_TRANSFER_IN;
803                 incoming = 1;
804         }
805         if (etype == 'C')
806                 incoming = !incoming;
807
808         /* direction check*/
809         if (incoming)
810         {
811                 if (handle->direction == PCAP_D_OUT)
812                         return 0;
813         }
814         else
815                 if (handle->direction == PCAP_D_IN)
816                         return 0;
817         uhdr->event_type = etype;
818         uhdr->transfer_type = urb_transfer;
819         uhdr->endpoint_number = ep_num;
820         pkth.caplen = sizeof(pcap_usb_header);
821         rawdata += sizeof(pcap_usb_header);
822
823         /* check if this is a setup packet */
824         ret = sscanf(status, "%d", &dummy);
825         if (ret != 1)
826         {
827                 /* this a setup packet, setup data can be filled with underscore if
828                 * usbmon has not been able to read them, so we must parse this fields as
829                 * strings */
830                 pcap_usb_setup* shdr;
831                 char str1[3], str2[3], str3[5], str4[5], str5[5];
832                 ret = sscanf(string, "%s %s %s %s %s%n", str1, str2, str3, str4,
833                 str5, &cnt);
834                 if (ret < 5)
835                 {
836                         pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
837                                 "Can't parse USB bus message '%s', too few tokens (expected 5 got %d)",
838                                 string, ret);
839                         return -1;
840                 }
841                 string += cnt;
842
843                 /* try to convert to corresponding integer */
844                 shdr = &uhdr->setup;
845                 shdr->bmRequestType = strtoul(str1, 0, 16);
846                 shdr->bRequest = strtoul(str2, 0, 16);
847                 shdr->wValue = htols(strtoul(str3, 0, 16));
848                 shdr->wIndex = htols(strtoul(str4, 0, 16));
849                 shdr->wLength = htols(strtoul(str5, 0, 16));
850
851                 uhdr->setup_flag = 0;
852         }
853         else
854                 uhdr->setup_flag = 1;
855
856         /* read urb data */
857         ret = sscanf(string, " %d%n", &urb_len, &cnt);
858         if (ret < 1)
859         {
860                 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
861                   "Can't parse urb length from '%s'", string);
862                 return -1;
863         }
864         string += cnt;
865
866         /* urb tag is not present if urb length is 0, so we can stop here
867          * text parsing */
868         pkth.len = urb_len+pkth.caplen;
869         uhdr->urb_len = urb_len;
870         uhdr->data_flag = 1;
871         data_len = 0;
872         if (uhdr->urb_len == 0)
873                 goto got;
874
875         /* check for data presence; data is present if and only if urb tag is '=' */
876         if (sscanf(string, " %c", &urb_tag) != 1)
877         {
878                 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
879                         "Can't parse urb tag from '%s'", string);
880                 return -1;
881         }
882
883         if (urb_tag != '=')
884                 goto got;
885
886         /* skip urb tag and following space */
887         string += 3;
888
889         /* if we reach this point we got some urb data*/
890         uhdr->data_flag = 0;
891
892         /* read all urb data; if urb length is greater then the usbmon internal
893          * buffer length used by the kernel to spool the URB, we get only
894          * a partial information.
895          * At least until linux 2.6.17 there is no way to set usbmon intenal buffer
896          * length and default value is 130. */
897         while ((string[0] != 0) && (string[1] != 0) && (pkth.caplen < (bpf_u_int32)handle->snapshot))
898         {
899                 rawdata[0] = ascii_to_int(string[0]) * 16 + ascii_to_int(string[1]);
900                 rawdata++;
901                 string+=2;
902                 if (string[0] == ' ')
903                         string++;
904                 pkth.caplen++;
905                 data_len++;
906         }
907
908 got:
909         uhdr->data_len = data_len;
910         if (pkth.caplen > (bpf_u_int32)handle->snapshot)
911                 pkth.caplen = (bpf_u_int32)handle->snapshot;
912
913         if (handle->fcode.bf_insns == NULL ||
914             bpf_filter(handle->fcode.bf_insns, handle->buffer,
915               pkth.len, pkth.caplen)) {
916                 handlep->packets_read++;
917                 callback(user, &pkth, handle->buffer);
918                 return 1;
919         }
920         return 0;       /* didn't pass filter */
921 }
922
923 static int
924 usb_inject_linux(pcap_t *handle, const void *buf _U_, size_t size _U_)
925 {
926         pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "inject not supported on "
927                 "USB devices");
928         return (-1);
929 }
930
931 static int
932 usb_stats_linux(pcap_t *handle, struct pcap_stat *stats)
933 {
934         struct pcap_usb_linux *handlep = handle->priv;
935         int dummy, ret, consumed, cnt;
936         char string[USB_LINE_LEN];
937         char token[USB_LINE_LEN];
938         char * ptr = string;
939         int fd;
940
941         pcap_snprintf(string, USB_LINE_LEN, USB_TEXT_DIR"/%ds", handlep->bus_index);
942         fd = open(string, O_RDONLY, 0);
943         if (fd < 0)
944         {
945                 if (errno == ENOENT)
946                 {
947                         /*
948                          * Not found at the new location; try the old
949                          * location.
950                          */
951                         pcap_snprintf(string, USB_LINE_LEN, USB_TEXT_DIR_OLD"/%ds", handlep->bus_index);
952                         fd = open(string, O_RDONLY, 0);
953                 }
954                 if (fd < 0) {
955                         pcap_fmt_errmsg_for_errno(handle->errbuf,
956                             PCAP_ERRBUF_SIZE, errno,
957                             "Can't open USB stats file %s", string);
958                         return -1;
959                 }
960         }
961
962         /* read stats line */
963         do {
964                 ret = read(fd, string, USB_LINE_LEN-1);
965         } while ((ret == -1) && (errno == EINTR));
966         close(fd);
967
968         if (ret < 0)
969         {
970                 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
971                         "Can't read stats from fd %d ", fd);
972                 return -1;
973         }
974         string[ret] = 0;
975
976         /* extract info on dropped urbs */
977         for (consumed=0; consumed < ret; ) {
978                 /* from the sscanf man page:
979                  * The C standard says: "Execution of a %n directive does
980                  * not increment the assignment count returned at the completion
981                  * of  execution" but the Corrigendum seems to contradict this.
982                  * Do not make any assumptions on the effect of %n conversions
983                  * on the return value and explicitly check for cnt assignmet*/
984                 int ntok;
985
986                 cnt = -1;
987                 ntok = sscanf(ptr, "%s%n", token, &cnt);
988                 if ((ntok < 1) || (cnt < 0))
989                         break;
990                 consumed += cnt;
991                 ptr += cnt;
992                 if (strcmp(token, "nreaders") == 0)
993                         ret = sscanf(ptr, "%d", &stats->ps_drop);
994                 else
995                         ret = sscanf(ptr, "%d", &dummy);
996                 if (ntok != 1)
997                         break;
998                 consumed += cnt;
999                 ptr += cnt;
1000         }
1001
1002         stats->ps_recv = handlep->packets_read;
1003         stats->ps_ifdrop = 0;
1004         return 0;
1005 }
1006
1007 static int
1008 usb_setdirection_linux(pcap_t *p, pcap_direction_t d)
1009 {
1010         p->direction = d;
1011         return 0;
1012 }
1013
1014
1015 static int
1016 usb_stats_linux_bin(pcap_t *handle, struct pcap_stat *stats)
1017 {
1018         struct pcap_usb_linux *handlep = handle->priv;
1019         int ret;
1020         struct mon_bin_stats st;
1021         ret = ioctl(handle->fd, MON_IOCG_STATS, &st);
1022         if (ret < 0)
1023         {
1024                 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
1025                     errno, "Can't read stats from fd %d", handle->fd);
1026                 return -1;
1027         }
1028
1029         stats->ps_recv = handlep->packets_read + st.queued;
1030         stats->ps_drop = st.dropped;
1031         stats->ps_ifdrop = 0;
1032         return 0;
1033 }
1034
1035 /*
1036  * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
1037  * <linux-kernel-source>/drivers/usb/mon/mon_bin.c binary ABI
1038  */
1039 static int
1040 usb_read_linux_bin(pcap_t *handle, int max_packets _U_, pcap_handler callback, u_char *user)
1041 {
1042         struct pcap_usb_linux *handlep = handle->priv;
1043         struct mon_bin_get info;
1044         int ret;
1045         struct pcap_pkthdr pkth;
1046         u_int clen = handle->snapshot - sizeof(pcap_usb_header);
1047
1048         /* the usb header is going to be part of 'packet' data*/
1049         info.hdr = (pcap_usb_header*) handle->buffer;
1050         info.data = (u_char *)handle->buffer + sizeof(pcap_usb_header);
1051         info.data_len = clen;
1052
1053         /* ignore interrupt system call errors */
1054         do {
1055                 ret = ioctl(handle->fd, MON_IOCX_GET, &info);
1056                 if (handle->break_loop)
1057                 {
1058                         handle->break_loop = 0;
1059                         return -2;
1060                 }
1061         } while ((ret == -1) && (errno == EINTR));
1062         if (ret < 0)
1063         {
1064                 if (errno == EAGAIN)
1065                         return 0;       /* no data there */
1066
1067                 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
1068                     errno, "Can't read from fd %d", handle->fd);
1069                 return -1;
1070         }
1071
1072         /* we can get less that than really captured from kernel, depending on
1073          * snaplen, so adjust header accordingly */
1074         if (info.hdr->data_len < clen)
1075                 clen = info.hdr->data_len;
1076         info.hdr->data_len = clen;
1077         pkth.caplen = clen + sizeof(pcap_usb_header);
1078         pkth.len = info.hdr->data_len + sizeof(pcap_usb_header);
1079         pkth.ts.tv_sec = info.hdr->ts_sec;
1080         pkth.ts.tv_usec = info.hdr->ts_usec;
1081
1082         if (handle->fcode.bf_insns == NULL ||
1083             bpf_filter(handle->fcode.bf_insns, handle->buffer,
1084               pkth.len, pkth.caplen)) {
1085                 handlep->packets_read++;
1086                 callback(user, &pkth, handle->buffer);
1087                 return 1;
1088         }
1089
1090         return 0;       /* didn't pass filter */
1091 }
1092
1093 /*
1094  * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
1095  * <linux-kernel-source>/drivers/usb/mon/mon_bin.c binary ABI
1096  */
1097 #define VEC_SIZE 32
1098 static int
1099 usb_read_linux_mmap(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
1100 {
1101         struct pcap_usb_linux *handlep = handle->priv;
1102         struct mon_bin_mfetch fetch;
1103         int32_t vec[VEC_SIZE];
1104         struct pcap_pkthdr pkth;
1105         pcap_usb_header* hdr;
1106         int nflush = 0;
1107         int packets = 0;
1108         u_int clen, max_clen;
1109
1110         max_clen = handle->snapshot - sizeof(pcap_usb_header);
1111
1112         for (;;) {
1113                 int i, ret;
1114                 int limit = max_packets - packets;
1115                 if (limit <= 0)
1116                         limit = VEC_SIZE;
1117                 if (limit > VEC_SIZE)
1118                         limit = VEC_SIZE;
1119
1120                 /* try to fetch as many events as possible*/
1121                 fetch.offvec = vec;
1122                 fetch.nfetch = limit;
1123                 fetch.nflush = nflush;
1124                 /* ignore interrupt system call errors */
1125                 do {
1126                         ret = ioctl(handle->fd, MON_IOCX_MFETCH, &fetch);
1127                         if (handle->break_loop)
1128                         {
1129                                 handle->break_loop = 0;
1130                                 return -2;
1131                         }
1132                 } while ((ret == -1) && (errno == EINTR));
1133                 if (ret < 0)
1134                 {
1135                         if (errno == EAGAIN)
1136                                 return 0;       /* no data there */
1137
1138                         pcap_fmt_errmsg_for_errno(handle->errbuf,
1139                             PCAP_ERRBUF_SIZE, errno, "Can't mfetch fd %d",
1140                             handle->fd);
1141                         return -1;
1142                 }
1143
1144                 /* keep track of processed events, we will flush them later */
1145                 nflush = fetch.nfetch;
1146                 for (i=0; i<fetch.nfetch; ++i) {
1147                         /* discard filler */
1148                         hdr = (pcap_usb_header*) &handlep->mmapbuf[vec[i]];
1149                         if (hdr->event_type == '@')
1150                                 continue;
1151
1152                         /* we can get less that than really captured from kernel, depending on
1153                         * snaplen, so adjust header accordingly */
1154                         clen = max_clen;
1155                         if (hdr->data_len < clen)
1156                                 clen = hdr->data_len;
1157
1158                         /* get packet info from header*/
1159                         pkth.caplen = clen + sizeof(pcap_usb_header_mmapped);
1160                         pkth.len = hdr->data_len + sizeof(pcap_usb_header_mmapped);
1161                         pkth.ts.tv_sec = hdr->ts_sec;
1162                         pkth.ts.tv_usec = hdr->ts_usec;
1163
1164                         if (handle->fcode.bf_insns == NULL ||
1165                             bpf_filter(handle->fcode.bf_insns, (u_char*) hdr,
1166                               pkth.len, pkth.caplen)) {
1167                                 handlep->packets_read++;
1168                                 callback(user, &pkth, (u_char*) hdr);
1169                                 packets++;
1170                         }
1171                 }
1172
1173                 /* with max_packets specifying "unlimited" we stop afer the first chunk*/
1174                 if (PACKET_COUNT_IS_UNLIMITED(max_packets) || (packets == max_packets))
1175                         break;
1176         }
1177
1178         /* flush pending events*/
1179         if (ioctl(handle->fd, MON_IOCH_MFLUSH, nflush) == -1) {
1180                 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
1181                     errno, "Can't mflush fd %d", handle->fd);
1182                 return -1;
1183         }
1184         return packets;
1185 }
1186
1187 static void
1188 usb_cleanup_linux_mmap(pcap_t* handle)
1189 {
1190         struct pcap_usb_linux *handlep = handle->priv;
1191
1192         /* if we have a memory-mapped buffer, unmap it */
1193         if (handlep->mmapbuf != NULL) {
1194                 munmap(handlep->mmapbuf, handlep->mmapbuflen);
1195                 handlep->mmapbuf = NULL;
1196         }
1197         pcap_cleanup_live_common(handle);
1198 }