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