]> The Tcpdump Group git mirrors - libpcap/blob - pcap-usb-linux.c
Provide out own strlcpy() and strlcat() routines if necessary.
[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
519 /*
520 * Turn a negative snapshot value (invalid), a snapshot value of
521 * 0 (unspecified), or a value bigger than the normal maximum
522 * value, into the maximum allowed value.
523 *
524 * If some application really *needs* a bigger snapshot
525 * length, we should just increase MAXIMUM_SNAPLEN.
526 */
527 if (handle->snapshot <= 0 || handle->snapshot > MAXIMUM_SNAPLEN)
528 handle->snapshot = MAXIMUM_SNAPLEN;
529
530 /* Initialize some components of the pcap structure. */
531 handle->bufsize = handle->snapshot;
532 handle->offset = 0;
533 handle->linktype = DLT_USB_LINUX;
534
535 handle->inject_op = usb_inject_linux;
536 handle->setfilter_op = install_bpf_program; /* no kernel filtering */
537 handle->setdirection_op = usb_setdirection_linux;
538 handle->set_datalink_op = NULL; /* can't change data link type */
539 handle->getnonblock_op = pcap_getnonblock_fd;
540 handle->setnonblock_op = pcap_setnonblock_fd;
541
542 /*get usb bus index from device name */
543 if (sscanf(handle->opt.device, USB_IFACE"%d", &handlep->bus_index) != 1)
544 {
545 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
546 "Can't get USB bus index from %s", handle->opt.device);
547 return PCAP_ERROR;
548 }
549
550 if (have_binary_usbmon())
551 {
552 /*
553 * We have binary-mode support.
554 * Try to open the binary interface.
555 */
556 pcap_snprintf(full_path, USB_LINE_LEN, LINUX_USB_MON_DEV"%d", handlep->bus_index);
557 handle->fd = open(full_path, O_RDONLY, 0);
558 if (handle->fd < 0)
559 {
560 /*
561 * The attempt failed; why?
562 */
563 switch (errno) {
564
565 case ENOENT:
566 /*
567 * The device doesn't exist.
568 * That could either mean that there's
569 * no support for monitoring USB buses
570 * (which probably means "the usbmon
571 * module isn't loaded") or that there
572 * is but that *particular* device
573 * doesn't exist (no "scan all buses"
574 * device if the bus index is 0, no
575 * such bus if the bus index isn't 0).
576 */
577 return PCAP_ERROR_NO_SUCH_DEVICE;
578
579 case EACCES:
580 /*
581 * We didn't have permission to open it.
582 */
583 return PCAP_ERROR_PERM_DENIED;
584
585 default:
586 /*
587 * Something went wrong.
588 */
589 pcap_fmt_errmsg_for_errno(handle->errbuf,
590 PCAP_ERRBUF_SIZE, errno,
591 "Can't open USB bus file %s", full_path);
592 return PCAP_ERROR;
593 }
594 }
595
596 if (handle->opt.rfmon)
597 {
598 /*
599 * Monitor mode doesn't apply to USB devices.
600 */
601 close(handle->fd);
602 return PCAP_ERROR_RFMON_NOTSUP;
603 }
604
605 /* try to use fast mmap access */
606 if (usb_mmap(handle))
607 {
608 handle->linktype = DLT_USB_LINUX_MMAPPED;
609 handle->stats_op = usb_stats_linux_bin;
610 handle->read_op = usb_read_linux_mmap;
611 handle->cleanup_op = usb_cleanup_linux_mmap;
612 #ifdef HAVE_LINUX_USBDEVICE_FS_H
613 probe_devices(handlep->bus_index);
614 #endif
615
616 /*
617 * "handle->fd" is a real file, so
618 * "select()" and "poll()" work on it.
619 */
620 handle->selectable_fd = handle->fd;
621 return 0;
622 }
623
624 /* can't mmap, use plain binary interface access */
625 handle->stats_op = usb_stats_linux_bin;
626 handle->read_op = usb_read_linux_bin;
627 #ifdef HAVE_LINUX_USBDEVICE_FS_H
628 probe_devices(handlep->bus_index);
629 #endif
630 }
631 else {
632 /*
633 * We don't have binary mode support.
634 * Try opening the text-mode device.
635 */
636 pcap_snprintf(full_path, USB_LINE_LEN, USB_TEXT_DIR"/%dt", handlep->bus_index);
637 handle->fd = open(full_path, O_RDONLY, 0);
638 if (handle->fd < 0)
639 {
640 if (errno == ENOENT)
641 {
642 /*
643 * Not found at the new location; try
644 * the old location.
645 */
646 pcap_snprintf(full_path, USB_LINE_LEN, USB_TEXT_DIR_OLD"/%dt", handlep->bus_index);
647 handle->fd = open(full_path, O_RDONLY, 0);
648 }
649 if (handle->fd < 0) {
650 /*
651 * Is the problem that we didn't have
652 * sufficient permission to open it?
653 */
654 if (errno == EACCES) {
655 /*
656 * Yes - return that error.
657 */
658 return PCAP_ERROR_PERM_DENIED;
659 }
660
661 /*
662 * No - was the problem something other
663 * than "it doesn't exist"?
664 */
665 if (errno != ENOENT) {
666 /*
667 * Yes - return *that* error.
668 */
669 pcap_fmt_errmsg_for_errno(handle->errbuf,
670 PCAP_ERRBUF_SIZE, errno,
671 "Can't open USB bus file %s",
672 full_path);
673 return PCAP_ERROR;
674 }
675
676 /*
677 * No. Report that as "no such device".
678 * (That could mean "no such USB bus"
679 * or "monitoring not supported".)
680 */
681 return PCAP_ERROR_NO_SUCH_DEVICE;
682 }
683 }
684
685 if (handle->opt.rfmon)
686 {
687 /*
688 * Monitor mode doesn't apply to USB devices.
689 */
690 close(handle->fd);
691 return PCAP_ERROR_RFMON_NOTSUP;
692 }
693
694 handle->stats_op = usb_stats_linux;
695 handle->read_op = usb_read_linux;
696 }
697
698 /*
699 * "handle->fd" is a real file, so "select()" and "poll()"
700 * work on it.
701 */
702 handle->selectable_fd = handle->fd;
703
704 /* for plain binary access and text access we need to allocate the read
705 * buffer */
706 handle->buffer = malloc(handle->bufsize);
707 if (!handle->buffer) {
708 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
709 errno, "malloc");
710 close(handle->fd);
711 return PCAP_ERROR;
712 }
713 return 0;
714 }
715
716 static inline int
717 ascii_to_int(char c)
718 {
719 return c < 'A' ? c- '0': ((c<'a') ? c - 'A' + 10: c-'a'+10);
720 }
721
722 /*
723 * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
724 * <linux-kernel-source>/drivers/usb/mon/mon_text.c for urb string
725 * format description
726 */
727 static int
728 usb_read_linux(pcap_t *handle, int max_packets _U_, pcap_handler callback, u_char *user)
729 {
730 /* see:
731 * /usr/src/linux/Documentation/usb/usbmon.txt
732 * for message format
733 */
734 struct pcap_usb_linux *handlep = handle->priv;
735 unsigned timestamp;
736 int tag, cnt, ep_num, dev_addr, dummy, ret, urb_len, data_len;
737 ssize_t read_ret;
738 char etype, pipeid1, pipeid2, status[16], urb_tag, line[USB_LINE_LEN];
739 char *string = line;
740 u_char * rawdata = handle->buffer;
741 struct pcap_pkthdr pkth;
742 pcap_usb_header* uhdr = (pcap_usb_header*)handle->buffer;
743 u_char urb_transfer=0;
744 int incoming=0;
745
746 /* ignore interrupt system call errors */
747 do {
748 read_ret = read(handle->fd, line, USB_LINE_LEN - 1);
749 if (handle->break_loop)
750 {
751 handle->break_loop = 0;
752 return -2;
753 }
754 } while ((read_ret == -1) && (errno == EINTR));
755 if (read_ret < 0)
756 {
757 if (errno == EAGAIN)
758 return 0; /* no data there */
759
760 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
761 errno, "Can't read from fd %d", handle->fd);
762 return -1;
763 }
764
765 /* read urb header; %n argument may increment return value, but it's
766 * not mandatory, so does not count on it*/
767 string[read_ret] = 0;
768 ret = sscanf(string, "%x %d %c %c%c:%d:%d %s%n", &tag, &timestamp, &etype,
769 &pipeid1, &pipeid2, &dev_addr, &ep_num, status,
770 &cnt);
771 if (ret < 8)
772 {
773 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
774 "Can't parse USB bus message '%s', too few tokens (expected 8 got %d)",
775 string, ret);
776 return -1;
777 }
778 uhdr->id = tag;
779 uhdr->device_address = dev_addr;
780 uhdr->bus_id = handlep->bus_index;
781 uhdr->status = 0;
782 string += cnt;
783
784 /* don't use usbmon provided timestamp, since it have low precision*/
785 if (gettimeofday(&pkth.ts, NULL) < 0)
786 {
787 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
788 errno, "Can't get timestamp for message '%s'", string);
789 return -1;
790 }
791 uhdr->ts_sec = pkth.ts.tv_sec;
792 uhdr->ts_usec = (int32_t)pkth.ts.tv_usec;
793
794 /* parse endpoint information */
795 if (pipeid1 == 'C')
796 urb_transfer = URB_CONTROL;
797 else if (pipeid1 == 'Z')
798 urb_transfer = URB_ISOCHRONOUS;
799 else if (pipeid1 == 'I')
800 urb_transfer = URB_INTERRUPT;
801 else if (pipeid1 == 'B')
802 urb_transfer = URB_BULK;
803 if (pipeid2 == 'i') {
804 ep_num |= URB_TRANSFER_IN;
805 incoming = 1;
806 }
807 if (etype == 'C')
808 incoming = !incoming;
809
810 /* direction check*/
811 if (incoming)
812 {
813 if (handle->direction == PCAP_D_OUT)
814 return 0;
815 }
816 else
817 if (handle->direction == PCAP_D_IN)
818 return 0;
819 uhdr->event_type = etype;
820 uhdr->transfer_type = urb_transfer;
821 uhdr->endpoint_number = ep_num;
822 pkth.caplen = sizeof(pcap_usb_header);
823 rawdata += sizeof(pcap_usb_header);
824
825 /* check if this is a setup packet */
826 ret = sscanf(status, "%d", &dummy);
827 if (ret != 1)
828 {
829 /* this a setup packet, setup data can be filled with underscore if
830 * usbmon has not been able to read them, so we must parse this fields as
831 * strings */
832 pcap_usb_setup* shdr;
833 char str1[3], str2[3], str3[5], str4[5], str5[5];
834 ret = sscanf(string, "%s %s %s %s %s%n", str1, str2, str3, str4,
835 str5, &cnt);
836 if (ret < 5)
837 {
838 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
839 "Can't parse USB bus message '%s', too few tokens (expected 5 got %d)",
840 string, ret);
841 return -1;
842 }
843 string += cnt;
844
845 /* try to convert to corresponding integer */
846 shdr = &uhdr->setup;
847 shdr->bmRequestType = strtoul(str1, 0, 16);
848 shdr->bRequest = strtoul(str2, 0, 16);
849 shdr->wValue = htols(strtoul(str3, 0, 16));
850 shdr->wIndex = htols(strtoul(str4, 0, 16));
851 shdr->wLength = htols(strtoul(str5, 0, 16));
852
853 uhdr->setup_flag = 0;
854 }
855 else
856 uhdr->setup_flag = 1;
857
858 /* read urb data */
859 ret = sscanf(string, " %d%n", &urb_len, &cnt);
860 if (ret < 1)
861 {
862 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
863 "Can't parse urb length from '%s'", string);
864 return -1;
865 }
866 string += cnt;
867
868 /* urb tag is not present if urb length is 0, so we can stop here
869 * text parsing */
870 pkth.len = urb_len+pkth.caplen;
871 uhdr->urb_len = urb_len;
872 uhdr->data_flag = 1;
873 data_len = 0;
874 if (uhdr->urb_len == 0)
875 goto got;
876
877 /* check for data presence; data is present if and only if urb tag is '=' */
878 if (sscanf(string, " %c", &urb_tag) != 1)
879 {
880 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
881 "Can't parse urb tag from '%s'", string);
882 return -1;
883 }
884
885 if (urb_tag != '=')
886 goto got;
887
888 /* skip urb tag and following space */
889 string += 3;
890
891 /* if we reach this point we got some urb data*/
892 uhdr->data_flag = 0;
893
894 /* read all urb data; if urb length is greater then the usbmon internal
895 * buffer length used by the kernel to spool the URB, we get only
896 * a partial information.
897 * At least until linux 2.6.17 there is no way to set usbmon intenal buffer
898 * length and default value is 130. */
899 while ((string[0] != 0) && (string[1] != 0) && (pkth.caplen < (bpf_u_int32)handle->snapshot))
900 {
901 rawdata[0] = ascii_to_int(string[0]) * 16 + ascii_to_int(string[1]);
902 rawdata++;
903 string+=2;
904 if (string[0] == ' ')
905 string++;
906 pkth.caplen++;
907 data_len++;
908 }
909
910 got:
911 uhdr->data_len = data_len;
912 if (pkth.caplen > (bpf_u_int32)handle->snapshot)
913 pkth.caplen = (bpf_u_int32)handle->snapshot;
914
915 if (handle->fcode.bf_insns == NULL ||
916 pcap_filter(handle->fcode.bf_insns, handle->buffer,
917 pkth.len, pkth.caplen)) {
918 handlep->packets_read++;
919 callback(user, &pkth, handle->buffer);
920 return 1;
921 }
922 return 0; /* didn't pass filter */
923 }
924
925 static int
926 usb_inject_linux(pcap_t *handle, const void *buf _U_, int size _U_)
927 {
928 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "inject not supported on "
929 "USB devices");
930 return (-1);
931 }
932
933 static int
934 usb_stats_linux(pcap_t *handle, struct pcap_stat *stats)
935 {
936 struct pcap_usb_linux *handlep = handle->priv;
937 int dummy, cnt;
938 ssize_t ret, consumed;
939 char string[USB_LINE_LEN];
940 char token[USB_LINE_LEN];
941 char * ptr = string;
942 int fd;
943
944 pcap_snprintf(string, USB_LINE_LEN, USB_TEXT_DIR"/%ds", handlep->bus_index);
945 fd = open(string, O_RDONLY, 0);
946 if (fd < 0)
947 {
948 if (errno == ENOENT)
949 {
950 /*
951 * Not found at the new location; try the old
952 * location.
953 */
954 pcap_snprintf(string, USB_LINE_LEN, USB_TEXT_DIR_OLD"/%ds", handlep->bus_index);
955 fd = open(string, O_RDONLY, 0);
956 }
957 if (fd < 0) {
958 pcap_fmt_errmsg_for_errno(handle->errbuf,
959 PCAP_ERRBUF_SIZE, errno,
960 "Can't open USB stats file %s", string);
961 return -1;
962 }
963 }
964
965 /* read stats line */
966 do {
967 ret = read(fd, string, USB_LINE_LEN-1);
968 } while ((ret == -1) && (errno == EINTR));
969 close(fd);
970
971 if (ret < 0)
972 {
973 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
974 "Can't read stats from fd %d ", fd);
975 return -1;
976 }
977 string[ret] = 0;
978
979 stats->ps_recv = handlep->packets_read;
980 stats->ps_drop = 0; /* unless we find text_lost */
981 stats->ps_ifdrop = 0;
982
983 /* extract info on dropped urbs */
984 for (consumed=0; consumed < ret; ) {
985 /* from the sscanf man page:
986 * The C standard says: "Execution of a %n directive does
987 * not increment the assignment count returned at the completion
988 * of execution" but the Corrigendum seems to contradict this.
989 * Do not make any assumptions on the effect of %n conversions
990 * on the return value and explicitly check for cnt assignmet*/
991 int ntok;
992
993 cnt = -1;
994 ntok = sscanf(ptr, "%s%n", token, &cnt);
995 if ((ntok < 1) || (cnt < 0))
996 break;
997 consumed += cnt;
998 ptr += cnt;
999 if (strcmp(token, "text_lost") == 0)
1000 ntok = sscanf(ptr, "%d%n", &stats->ps_drop, &cnt);
1001 else
1002 ntok = sscanf(ptr, "%d%n", &dummy, &cnt);
1003 if ((ntok != 1) || (cnt < 0))
1004 break;
1005 consumed += cnt;
1006 ptr += cnt;
1007 }
1008
1009 return 0;
1010 }
1011
1012 static int
1013 usb_setdirection_linux(pcap_t *p, pcap_direction_t d)
1014 {
1015 p->direction = d;
1016 return 0;
1017 }
1018
1019
1020 static int
1021 usb_stats_linux_bin(pcap_t *handle, struct pcap_stat *stats)
1022 {
1023 struct pcap_usb_linux *handlep = handle->priv;
1024 int ret;
1025 struct mon_bin_stats st;
1026 ret = ioctl(handle->fd, MON_IOCG_STATS, &st);
1027 if (ret < 0)
1028 {
1029 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
1030 errno, "Can't read stats from fd %d", handle->fd);
1031 return -1;
1032 }
1033
1034 stats->ps_recv = handlep->packets_read + st.queued;
1035 stats->ps_drop = st.dropped;
1036 stats->ps_ifdrop = 0;
1037 return 0;
1038 }
1039
1040 /*
1041 * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
1042 * <linux-kernel-source>/drivers/usb/mon/mon_bin.c binary ABI
1043 */
1044 static int
1045 usb_read_linux_bin(pcap_t *handle, int max_packets _U_, pcap_handler callback, u_char *user)
1046 {
1047 struct pcap_usb_linux *handlep = handle->priv;
1048 struct mon_bin_get info;
1049 int ret;
1050 struct pcap_pkthdr pkth;
1051 u_int clen = handle->snapshot - sizeof(pcap_usb_header);
1052
1053 /* the usb header is going to be part of 'packet' data*/
1054 info.hdr = (pcap_usb_header*) handle->buffer;
1055 info.data = (u_char *)handle->buffer + sizeof(pcap_usb_header);
1056 info.data_len = clen;
1057
1058 /* ignore interrupt system call errors */
1059 do {
1060 ret = ioctl(handle->fd, MON_IOCX_GET, &info);
1061 if (handle->break_loop)
1062 {
1063 handle->break_loop = 0;
1064 return -2;
1065 }
1066 } while ((ret == -1) && (errno == EINTR));
1067 if (ret < 0)
1068 {
1069 if (errno == EAGAIN)
1070 return 0; /* no data there */
1071
1072 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
1073 errno, "Can't read from fd %d", handle->fd);
1074 return -1;
1075 }
1076
1077 /* we can get less that than really captured from kernel, depending on
1078 * snaplen, so adjust header accordingly */
1079 if (info.hdr->data_len < clen)
1080 clen = info.hdr->data_len;
1081 info.hdr->data_len = clen;
1082 pkth.caplen = clen + sizeof(pcap_usb_header);
1083 pkth.len = info.hdr->data_len + sizeof(pcap_usb_header);
1084 pkth.ts.tv_sec = info.hdr->ts_sec;
1085 pkth.ts.tv_usec = info.hdr->ts_usec;
1086
1087 if (handle->fcode.bf_insns == NULL ||
1088 pcap_filter(handle->fcode.bf_insns, handle->buffer,
1089 pkth.len, pkth.caplen)) {
1090 handlep->packets_read++;
1091 callback(user, &pkth, handle->buffer);
1092 return 1;
1093 }
1094
1095 return 0; /* didn't pass filter */
1096 }
1097
1098 /*
1099 * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
1100 * <linux-kernel-source>/drivers/usb/mon/mon_bin.c binary ABI
1101 */
1102 #define VEC_SIZE 32
1103 static int
1104 usb_read_linux_mmap(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
1105 {
1106 struct pcap_usb_linux *handlep = handle->priv;
1107 struct mon_bin_mfetch fetch;
1108 int32_t vec[VEC_SIZE];
1109 struct pcap_pkthdr pkth;
1110 pcap_usb_header* hdr;
1111 int nflush = 0;
1112 int packets = 0;
1113 u_int clen, max_clen;
1114
1115 max_clen = handle->snapshot - sizeof(pcap_usb_header);
1116
1117 for (;;) {
1118 int i, ret;
1119 int limit = max_packets - packets;
1120 if (limit <= 0)
1121 limit = VEC_SIZE;
1122 if (limit > VEC_SIZE)
1123 limit = VEC_SIZE;
1124
1125 /* try to fetch as many events as possible*/
1126 fetch.offvec = vec;
1127 fetch.nfetch = limit;
1128 fetch.nflush = nflush;
1129 /* ignore interrupt system call errors */
1130 do {
1131 ret = ioctl(handle->fd, MON_IOCX_MFETCH, &fetch);
1132 if (handle->break_loop)
1133 {
1134 handle->break_loop = 0;
1135 return -2;
1136 }
1137 } while ((ret == -1) && (errno == EINTR));
1138 if (ret < 0)
1139 {
1140 if (errno == EAGAIN)
1141 return 0; /* no data there */
1142
1143 pcap_fmt_errmsg_for_errno(handle->errbuf,
1144 PCAP_ERRBUF_SIZE, errno, "Can't mfetch fd %d",
1145 handle->fd);
1146 return -1;
1147 }
1148
1149 /* keep track of processed events, we will flush them later */
1150 nflush = fetch.nfetch;
1151 for (i=0; i<fetch.nfetch; ++i) {
1152 /* discard filler */
1153 hdr = (pcap_usb_header*) &handlep->mmapbuf[vec[i]];
1154 if (hdr->event_type == '@')
1155 continue;
1156
1157 /* we can get less that than really captured from kernel, depending on
1158 * snaplen, so adjust header accordingly */
1159 clen = max_clen;
1160 if (hdr->data_len < clen)
1161 clen = hdr->data_len;
1162
1163 /* get packet info from header*/
1164 pkth.caplen = clen + sizeof(pcap_usb_header_mmapped);
1165 pkth.len = hdr->data_len + sizeof(pcap_usb_header_mmapped);
1166 pkth.ts.tv_sec = hdr->ts_sec;
1167 pkth.ts.tv_usec = hdr->ts_usec;
1168
1169 if (handle->fcode.bf_insns == NULL ||
1170 pcap_filter(handle->fcode.bf_insns, (u_char*) hdr,
1171 pkth.len, pkth.caplen)) {
1172 handlep->packets_read++;
1173 callback(user, &pkth, (u_char*) hdr);
1174 packets++;
1175 }
1176 }
1177
1178 /* with max_packets specifying "unlimited" we stop afer the first chunk*/
1179 if (PACKET_COUNT_IS_UNLIMITED(max_packets) || (packets == max_packets))
1180 break;
1181 }
1182
1183 /* flush pending events*/
1184 if (ioctl(handle->fd, MON_IOCH_MFLUSH, nflush) == -1) {
1185 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
1186 errno, "Can't mflush fd %d", handle->fd);
1187 return -1;
1188 }
1189 return packets;
1190 }
1191
1192 static void
1193 usb_cleanup_linux_mmap(pcap_t* handle)
1194 {
1195 struct pcap_usb_linux *handlep = handle->priv;
1196
1197 /* if we have a memory-mapped buffer, unmap it */
1198 if (handlep->mmapbuf != NULL) {
1199 munmap(handlep->mmapbuf, handlep->mmapbuflen);
1200 handlep->mmapbuf = NULL;
1201 }
1202 pcap_cleanup_live_common(handle);
1203 }