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