]> The Tcpdump Group git mirrors - libpcap/blob - pcap-usb-linux.c
Get rid of an unused variable.
[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 #ifdef HAVE_LINUX_USBDEVICE_FS_H
60 /*
61 * We might need <linux/compiler.h> to define __user for
62 * <linux/usbdevice_fs.h>.
63 */
64 #ifdef HAVE_LINUX_COMPILER_H
65 #include <linux/compiler.h>
66 #endif /* HAVE_LINUX_COMPILER_H */
67 #include <linux/usbdevice_fs.h>
68 #endif /* HAVE_LINUX_USBDEVICE_FS_H */
69
70 #define USB_IFACE "usbmon"
71 #define USB_TEXT_DIR_OLD "/sys/kernel/debug/usbmon"
72 #define USB_TEXT_DIR "/sys/kernel/debug/usb/usbmon"
73 #define SYS_USB_BUS_DIR "/sys/bus/usb/devices"
74 #define PROC_USB_BUS_DIR "/proc/bus/usb"
75 #define USB_LINE_LEN 4096
76
77 #if __BYTE_ORDER == __LITTLE_ENDIAN
78 #define htols(s) s
79 #define htoll(l) l
80 #define htol64(ll) ll
81 #else
82 #define htols(s) bswap_16(s)
83 #define htoll(l) bswap_32(l)
84 #define htol64(ll) bswap_64(ll)
85 #endif
86
87 struct mon_bin_stats {
88 u_int32_t queued;
89 u_int32_t dropped;
90 };
91
92 struct mon_bin_get {
93 pcap_usb_header *hdr;
94 void *data;
95 size_t data_len; /* Length of data (can be zero) */
96 };
97
98 struct mon_bin_mfetch {
99 int32_t *offvec; /* Vector of events fetched */
100 int32_t nfetch; /* Number of events to fetch (out: fetched) */
101 int32_t nflush; /* Number of events to flush */
102 };
103
104 #define MON_IOC_MAGIC 0x92
105
106 #define MON_IOCQ_URB_LEN _IO(MON_IOC_MAGIC, 1)
107 #define MON_IOCX_URB _IOWR(MON_IOC_MAGIC, 2, struct mon_bin_hdr)
108 #define MON_IOCG_STATS _IOR(MON_IOC_MAGIC, 3, struct mon_bin_stats)
109 #define MON_IOCT_RING_SIZE _IO(MON_IOC_MAGIC, 4)
110 #define MON_IOCQ_RING_SIZE _IO(MON_IOC_MAGIC, 5)
111 #define MON_IOCX_GET _IOW(MON_IOC_MAGIC, 6, struct mon_bin_get)
112 #define MON_IOCX_MFETCH _IOWR(MON_IOC_MAGIC, 7, struct mon_bin_mfetch)
113 #define MON_IOCH_MFLUSH _IO(MON_IOC_MAGIC, 8)
114
115 #define MON_BIN_SETUP 0x1 /* setup hdr is present*/
116 #define MON_BIN_SETUP_ZERO 0x2 /* setup buffer is not available */
117 #define MON_BIN_DATA_ZERO 0x4 /* data buffer is not available */
118 #define MON_BIN_ERROR 0x8
119
120 /*
121 * Private data for capturing on Linux USB.
122 */
123 struct pcap_usb_linux {
124 u_char *mmapbuf; /* memory-mapped region pointer */
125 size_t mmapbuflen; /* size of region */
126 int bus_index;
127 u_int packets_read;
128 };
129
130 /* forward declaration */
131 static int usb_activate(pcap_t *);
132 static int usb_stats_linux(pcap_t *, struct pcap_stat *);
133 static int usb_stats_linux_bin(pcap_t *, struct pcap_stat *);
134 static int usb_read_linux(pcap_t *, int , pcap_handler , u_char *);
135 static int usb_read_linux_bin(pcap_t *, int , pcap_handler , u_char *);
136 static int usb_read_linux_mmap(pcap_t *, int , pcap_handler , u_char *);
137 static int usb_inject_linux(pcap_t *, const void *, size_t);
138 static int usb_setdirection_linux(pcap_t *, pcap_direction_t);
139 static void usb_cleanup_linux_mmap(pcap_t *);
140
141 /* facility to add an USB device to the device list*/
142 static int
143 usb_dev_add(pcap_if_t** alldevsp, int n, char *err_str)
144 {
145 char dev_name[10];
146 char dev_descr[30];
147 pcap_snprintf(dev_name, 10, USB_IFACE"%d", n);
148 pcap_snprintf(dev_descr, 30, "USB bus number %d", n);
149
150 if (add_dev(alldevsp, dev_name, 0, dev_descr, err_str) == NULL)
151 return -1;
152 return 0;
153 }
154
155 int
156 usb_findalldevs(pcap_if_t **alldevsp, char *err_str)
157 {
158 int fd;
159 struct dirent* data;
160 int ret = 0;
161 DIR* dir;
162 int n;
163 char* name;
164 size_t len;
165
166 /*
167 * Do we have a "scan all buses" device?
168 * First, try the binary device.
169 */
170 fd = open(LINUX_USB_MON_DEV"0", O_RDONLY, 0);
171 if (fd >= 0) {
172 /*
173 * Yes.
174 */
175 close(fd);
176 if (add_dev(alldevsp, "usbmon0", 0, "All USB buses",
177 err_str) == NULL)
178 return -1;
179 } else {
180 /*
181 * No binary device; do we have the text device?
182 */
183 fd = open(USB_TEXT_DIR"/0t", O_RDONLY, 0);
184 if (fd < 0) {
185 /*
186 * Not at the new location; try the old location.
187 */
188 fd = open(USB_TEXT_DIR_OLD"/0t", O_RDONLY, 0);
189 }
190 if (fd >= 0) {
191 /*
192 * We found it.
193 */
194 close(fd);
195 if (add_dev(alldevsp, "usbmon0", 0, "All USB buses",
196 err_str) == NULL)
197 return -1;
198 }
199 }
200
201 /*
202 * Now look for individual USB buses.
203 *
204 * First, try scanning sysfs USB bus directory.
205 */
206 dir = opendir(SYS_USB_BUS_DIR);
207 if (dir != NULL) {
208 while ((ret == 0) && ((data = readdir(dir)) != 0)) {
209 name = data->d_name;
210
211 if (strncmp(name, "usb", 3) != 0)
212 continue;
213
214 if (sscanf(&name[3], "%d", &n) == 0)
215 continue;
216
217 ret = usb_dev_add(alldevsp, n, err_str);
218 }
219
220 closedir(dir);
221 return ret;
222 }
223
224 /* That didn't work; try scanning procfs USB bus directory. */
225 dir = opendir(PROC_USB_BUS_DIR);
226 if (dir != NULL) {
227 while ((ret == 0) && ((data = readdir(dir)) != 0)) {
228 name = data->d_name;
229 len = strlen(name);
230
231 /* if this file name does not end with a number it's not of our interest */
232 if ((len < 1) || !isdigit(name[--len]))
233 continue;
234 while (isdigit(name[--len]));
235 if (sscanf(&name[len+1], "%d", &n) != 1)
236 continue;
237
238 ret = usb_dev_add(alldevsp, n, err_str);
239 }
240
241 closedir(dir);
242 return ret;
243 }
244
245 /* neither of them worked */
246 return 0;
247 }
248
249 static
250 int usb_mmap(pcap_t* handle)
251 {
252 struct pcap_usb_linux *handlep = handle->priv;
253 int len = ioctl(handle->fd, MON_IOCQ_RING_SIZE);
254 if (len < 0)
255 return 0;
256
257 handlep->mmapbuflen = len;
258 handlep->mmapbuf = mmap(0, handlep->mmapbuflen, PROT_READ,
259 MAP_SHARED, handle->fd, 0);
260 return handlep->mmapbuf != MAP_FAILED;
261 }
262
263 #ifdef HAVE_LINUX_USBDEVICE_FS_H
264
265 #define CTRL_TIMEOUT (5*1000) /* milliseconds */
266
267 #define USB_DIR_IN 0x80
268 #define USB_TYPE_STANDARD 0x00
269 #define USB_RECIP_DEVICE 0x00
270
271 #define USB_REQ_GET_DESCRIPTOR 6
272
273 #define USB_DT_DEVICE 1
274
275 /* probe the descriptors of the devices attached to the bus */
276 /* the descriptors will end up in the captured packet stream */
277 /* and be decoded by external apps like wireshark */
278 /* without these identifying probes packet data can't be fully decoded */
279 static void
280 probe_devices(int bus)
281 {
282 struct usbdevfs_ctrltransfer ctrl;
283 struct dirent* data;
284 int ret = 0;
285 char buf[40];
286 DIR* dir;
287
288 /* scan usb bus directories for device nodes */
289 pcap_snprintf(buf, sizeof(buf), "/dev/bus/usb/%03d", bus);
290 dir = opendir(buf);
291 if (!dir)
292 return;
293
294 while ((ret >= 0) && ((data = readdir(dir)) != 0)) {
295 int fd;
296 char* name = data->d_name;
297
298 if (name[0] == '.')
299 continue;
300
301 pcap_snprintf(buf, sizeof(buf), "/dev/bus/usb/%03d/%s", bus, data->d_name);
302
303 fd = open(buf, O_RDWR);
304 if (fd == -1)
305 continue;
306
307 /*
308 * Sigh. Different kernels have different member names
309 * for this structure.
310 */
311 #ifdef HAVE_USBDEVFS_CTRLTRANSFER_BREQUESTTYPE
312 ctrl.bRequestType = USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE;
313 ctrl.bRequest = USB_REQ_GET_DESCRIPTOR;
314 ctrl.wValue = USB_DT_DEVICE << 8;
315 ctrl.wIndex = 0;
316 ctrl.wLength = sizeof(buf);
317 #else
318 ctrl.requesttype = USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE;
319 ctrl.request = USB_REQ_GET_DESCRIPTOR;
320 ctrl.value = USB_DT_DEVICE << 8;
321 ctrl.index = 0;
322 ctrl.length = sizeof(buf);
323 #endif
324 ctrl.data = buf;
325 ctrl.timeout = CTRL_TIMEOUT;
326
327 ret = ioctl(fd, USBDEVFS_CONTROL, &ctrl);
328
329 close(fd);
330 }
331 closedir(dir);
332 }
333 #endif /* HAVE_LINUX_USBDEVICE_FS_H */
334
335 pcap_t *
336 usb_create(const char *device, char *ebuf, int *is_ours)
337 {
338 const char *cp;
339 char *cpend;
340 long devnum;
341 pcap_t *p;
342
343 /* Does this look like a USB monitoring device? */
344 cp = strrchr(device, '/');
345 if (cp == NULL)
346 cp = device;
347 /* Does it begin with USB_IFACE? */
348 if (strncmp(cp, USB_IFACE, sizeof USB_IFACE - 1) != 0) {
349 /* Nope, doesn't begin with USB_IFACE */
350 *is_ours = 0;
351 return NULL;
352 }
353 /* Yes - is USB_IFACE followed by a number? */
354 cp += sizeof USB_IFACE - 1;
355 devnum = strtol(cp, &cpend, 10);
356 if (cpend == cp || *cpend != '\0') {
357 /* Not followed by a number. */
358 *is_ours = 0;
359 return NULL;
360 }
361 if (devnum < 0) {
362 /* Followed by a non-valid number. */
363 *is_ours = 0;
364 return NULL;
365 }
366
367 /* OK, it's probably ours. */
368 *is_ours = 1;
369
370 p = pcap_create_common(ebuf, sizeof (struct pcap_usb_linux));
371 if (p == NULL)
372 return (NULL);
373
374 p->activate_op = usb_activate;
375 return (p);
376 }
377
378 static int
379 usb_activate(pcap_t* handle)
380 {
381 struct pcap_usb_linux *handlep = handle->priv;
382 char full_path[USB_LINE_LEN];
383
384 /* Initialize some components of the pcap structure. */
385 handle->bufsize = handle->snapshot;
386 handle->offset = 0;
387 handle->linktype = DLT_USB_LINUX;
388
389 handle->inject_op = usb_inject_linux;
390 handle->setfilter_op = install_bpf_program; /* no kernel filtering */
391 handle->setdirection_op = usb_setdirection_linux;
392 handle->set_datalink_op = NULL; /* can't change data link type */
393 handle->getnonblock_op = pcap_getnonblock_fd;
394 handle->setnonblock_op = pcap_setnonblock_fd;
395
396 /*get usb bus index from device name */
397 if (sscanf(handle->opt.device, USB_IFACE"%d", &handlep->bus_index) != 1)
398 {
399 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
400 "Can't get USB bus index from %s", handle->opt.device);
401 return PCAP_ERROR;
402 }
403
404 /*now select the read method: try to open binary interface */
405 pcap_snprintf(full_path, USB_LINE_LEN, LINUX_USB_MON_DEV"%d", handlep->bus_index);
406 handle->fd = open(full_path, O_RDONLY, 0);
407 if (handle->fd >= 0)
408 {
409 if (handle->opt.rfmon) {
410 /*
411 * Monitor mode doesn't apply to USB devices.
412 */
413 close(handle->fd);
414 return PCAP_ERROR_RFMON_NOTSUP;
415 }
416
417 /* binary api is available, try to use fast mmap access */
418 if (usb_mmap(handle)) {
419 handle->linktype = DLT_USB_LINUX_MMAPPED;
420 handle->stats_op = usb_stats_linux_bin;
421 handle->read_op = usb_read_linux_mmap;
422 handle->cleanup_op = usb_cleanup_linux_mmap;
423 #ifdef HAVE_LINUX_USBDEVICE_FS_H
424 probe_devices(handlep->bus_index);
425 #endif
426
427 /*
428 * "handle->fd" is a real file, so "select()" and
429 * "poll()" work on it.
430 */
431 handle->selectable_fd = handle->fd;
432 return 0;
433 }
434
435 /* can't mmap, use plain binary interface access */
436 handle->stats_op = usb_stats_linux_bin;
437 handle->read_op = usb_read_linux_bin;
438 #ifdef HAVE_LINUX_USBDEVICE_FS_H
439 probe_devices(handlep->bus_index);
440 #endif
441 }
442 else {
443 /*Binary interface not available, try open text interface */
444 pcap_snprintf(full_path, USB_LINE_LEN, USB_TEXT_DIR"/%dt", handlep->bus_index);
445 handle->fd = open(full_path, O_RDONLY, 0);
446 if (handle->fd < 0)
447 {
448 if (errno == ENOENT)
449 {
450 /*
451 * Not found at the new location; try
452 * the old location.
453 */
454 pcap_snprintf(full_path, USB_LINE_LEN, USB_TEXT_DIR_OLD"/%dt", handlep->bus_index);
455 handle->fd = open(full_path, O_RDONLY, 0);
456 }
457 if (handle->fd < 0) {
458 /* no more fallback, give it up*/
459 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
460 "Can't open USB bus file %s: %s", full_path, strerror(errno));
461 return PCAP_ERROR;
462 }
463 }
464
465 if (handle->opt.rfmon) {
466 /*
467 * Monitor mode doesn't apply to USB devices.
468 */
469 close(handle->fd);
470 return PCAP_ERROR_RFMON_NOTSUP;
471 }
472
473 handle->stats_op = usb_stats_linux;
474 handle->read_op = usb_read_linux;
475 }
476
477 /*
478 * "handle->fd" is a real file, so "select()" and "poll()"
479 * work on it.
480 */
481 handle->selectable_fd = handle->fd;
482
483 /* for plain binary access and text access we need to allocate the read
484 * buffer */
485 handle->buffer = malloc(handle->bufsize);
486 if (!handle->buffer) {
487 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
488 "malloc: %s", pcap_strerror(errno));
489 close(handle->fd);
490 return PCAP_ERROR;
491 }
492 return 0;
493 }
494
495 static inline int
496 ascii_to_int(char c)
497 {
498 return c < 'A' ? c- '0': ((c<'a') ? c - 'A' + 10: c-'a'+10);
499 }
500
501 /*
502 * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
503 * <linux-kernel-source>/drivers/usb/mon/mon_text.c for urb string
504 * format description
505 */
506 static int
507 usb_read_linux(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
508 {
509 /* see:
510 * /usr/src/linux/Documentation/usb/usbmon.txt
511 * for message format
512 */
513 struct pcap_usb_linux *handlep = handle->priv;
514 unsigned timestamp;
515 int tag, cnt, ep_num, dev_addr, dummy, ret, urb_len, data_len;
516 char etype, pipeid1, pipeid2, status[16], urb_tag, line[USB_LINE_LEN];
517 char *string = line;
518 u_char * rawdata = handle->buffer;
519 struct pcap_pkthdr pkth;
520 pcap_usb_header* uhdr = (pcap_usb_header*)handle->buffer;
521 u_char urb_transfer=0;
522 int incoming=0;
523
524 /* ignore interrupt system call errors */
525 do {
526 ret = read(handle->fd, line, USB_LINE_LEN - 1);
527 if (handle->break_loop)
528 {
529 handle->break_loop = 0;
530 return -2;
531 }
532 } while ((ret == -1) && (errno == EINTR));
533 if (ret < 0)
534 {
535 if (errno == EAGAIN)
536 return 0; /* no data there */
537
538 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
539 "Can't read from fd %d: %s", handle->fd, strerror(errno));
540 return -1;
541 }
542
543 /* read urb header; %n argument may increment return value, but it's
544 * not mandatory, so does not count on it*/
545 string[ret] = 0;
546 ret = sscanf(string, "%x %d %c %c%c:%d:%d %s%n", &tag, &timestamp, &etype,
547 &pipeid1, &pipeid2, &dev_addr, &ep_num, status,
548 &cnt);
549 if (ret < 8)
550 {
551 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
552 "Can't parse USB bus message '%s', too few tokens (expected 8 got %d)",
553 string, ret);
554 return -1;
555 }
556 uhdr->id = tag;
557 uhdr->device_address = dev_addr;
558 uhdr->bus_id = handlep->bus_index;
559 uhdr->status = 0;
560 string += cnt;
561
562 /* don't use usbmon provided timestamp, since it have low precision*/
563 if (gettimeofday(&pkth.ts, NULL) < 0)
564 {
565 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
566 "Can't get timestamp for message '%s' %d:%s",
567 string, errno, strerror(errno));
568 return -1;
569 }
570 uhdr->ts_sec = pkth.ts.tv_sec;
571 uhdr->ts_usec = pkth.ts.tv_usec;
572
573 /* parse endpoint information */
574 if (pipeid1 == 'C')
575 urb_transfer = URB_CONTROL;
576 else if (pipeid1 == 'Z')
577 urb_transfer = URB_ISOCHRONOUS;
578 else if (pipeid1 == 'I')
579 urb_transfer = URB_INTERRUPT;
580 else if (pipeid1 == 'B')
581 urb_transfer = URB_BULK;
582 if (pipeid2 == 'i') {
583 ep_num |= URB_TRANSFER_IN;
584 incoming = 1;
585 }
586 if (etype == 'C')
587 incoming = !incoming;
588
589 /* direction check*/
590 if (incoming)
591 {
592 if (handle->direction == PCAP_D_OUT)
593 return 0;
594 }
595 else
596 if (handle->direction == PCAP_D_IN)
597 return 0;
598 uhdr->event_type = etype;
599 uhdr->transfer_type = urb_transfer;
600 uhdr->endpoint_number = ep_num;
601 pkth.caplen = sizeof(pcap_usb_header);
602 rawdata += sizeof(pcap_usb_header);
603
604 /* check if this is a setup packet */
605 ret = sscanf(status, "%d", &dummy);
606 if (ret != 1)
607 {
608 /* this a setup packet, setup data can be filled with underscore if
609 * usbmon has not been able to read them, so we must parse this fields as
610 * strings */
611 pcap_usb_setup* shdr;
612 char str1[3], str2[3], str3[5], str4[5], str5[5];
613 ret = sscanf(string, "%s %s %s %s %s%n", str1, str2, str3, str4,
614 str5, &cnt);
615 if (ret < 5)
616 {
617 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
618 "Can't parse USB bus message '%s', too few tokens (expected 5 got %d)",
619 string, ret);
620 return -1;
621 }
622 string += cnt;
623
624 /* try to convert to corresponding integer */
625 shdr = &uhdr->setup;
626 shdr->bmRequestType = strtoul(str1, 0, 16);
627 shdr->bRequest = strtoul(str2, 0, 16);
628 shdr->wValue = htols(strtoul(str3, 0, 16));
629 shdr->wIndex = htols(strtoul(str4, 0, 16));
630 shdr->wLength = htols(strtoul(str5, 0, 16));
631
632 uhdr->setup_flag = 0;
633 }
634 else
635 uhdr->setup_flag = 1;
636
637 /* read urb data */
638 ret = sscanf(string, " %d%n", &urb_len, &cnt);
639 if (ret < 1)
640 {
641 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
642 "Can't parse urb length from '%s'", string);
643 return -1;
644 }
645 string += cnt;
646
647 /* urb tag is not present if urb length is 0, so we can stop here
648 * text parsing */
649 pkth.len = urb_len+pkth.caplen;
650 uhdr->urb_len = urb_len;
651 uhdr->data_flag = 1;
652 data_len = 0;
653 if (uhdr->urb_len == 0)
654 goto got;
655
656 /* check for data presence; data is present if and only if urb tag is '=' */
657 if (sscanf(string, " %c", &urb_tag) != 1)
658 {
659 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
660 "Can't parse urb tag from '%s'", string);
661 return -1;
662 }
663
664 if (urb_tag != '=')
665 goto got;
666
667 /* skip urb tag and following space */
668 string += 3;
669
670 /* if we reach this point we got some urb data*/
671 uhdr->data_flag = 0;
672
673 /* read all urb data; if urb length is greater then the usbmon internal
674 * buffer length used by the kernel to spool the URB, we get only
675 * a partial information.
676 * At least until linux 2.6.17 there is no way to set usbmon intenal buffer
677 * length and default value is 130. */
678 while ((string[0] != 0) && (string[1] != 0) && (pkth.caplen < (bpf_u_int32)handle->snapshot))
679 {
680 rawdata[0] = ascii_to_int(string[0]) * 16 + ascii_to_int(string[1]);
681 rawdata++;
682 string+=2;
683 if (string[0] == ' ')
684 string++;
685 pkth.caplen++;
686 data_len++;
687 }
688
689 got:
690 uhdr->data_len = data_len;
691 if (pkth.caplen > (bpf_u_int32)handle->snapshot)
692 pkth.caplen = (bpf_u_int32)handle->snapshot;
693
694 if (handle->fcode.bf_insns == NULL ||
695 bpf_filter(handle->fcode.bf_insns, handle->buffer,
696 pkth.len, pkth.caplen)) {
697 handlep->packets_read++;
698 callback(user, &pkth, handle->buffer);
699 return 1;
700 }
701 return 0; /* didn't pass filter */
702 }
703
704 static int
705 usb_inject_linux(pcap_t *handle, const void *buf, size_t size)
706 {
707 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "inject not supported on "
708 "USB devices");
709 return (-1);
710 }
711
712 static int
713 usb_stats_linux(pcap_t *handle, struct pcap_stat *stats)
714 {
715 struct pcap_usb_linux *handlep = handle->priv;
716 int dummy, ret, consumed, cnt;
717 char string[USB_LINE_LEN];
718 char token[USB_LINE_LEN];
719 char * ptr = string;
720 int fd;
721
722 pcap_snprintf(string, USB_LINE_LEN, USB_TEXT_DIR"/%ds", handlep->bus_index);
723 fd = open(string, O_RDONLY, 0);
724 if (fd < 0)
725 {
726 if (errno == ENOENT)
727 {
728 /*
729 * Not found at the new location; try the old
730 * location.
731 */
732 pcap_snprintf(string, USB_LINE_LEN, USB_TEXT_DIR_OLD"/%ds", handlep->bus_index);
733 fd = open(string, O_RDONLY, 0);
734 }
735 if (fd < 0) {
736 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
737 "Can't open USB stats file %s: %s",
738 string, strerror(errno));
739 return -1;
740 }
741 }
742
743 /* read stats line */
744 do {
745 ret = read(fd, string, USB_LINE_LEN-1);
746 } while ((ret == -1) && (errno == EINTR));
747 close(fd);
748
749 if (ret < 0)
750 {
751 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
752 "Can't read stats from fd %d ", fd);
753 return -1;
754 }
755 string[ret] = 0;
756
757 /* extract info on dropped urbs */
758 for (consumed=0; consumed < ret; ) {
759 /* from the sscanf man page:
760 * The C standard says: "Execution of a %n directive does
761 * not increment the assignment count returned at the completion
762 * of execution" but the Corrigendum seems to contradict this.
763 * Do not make any assumptions on the effect of %n conversions
764 * on the return value and explicitly check for cnt assignmet*/
765 int ntok;
766
767 cnt = -1;
768 ntok = sscanf(ptr, "%s%n", token, &cnt);
769 if ((ntok < 1) || (cnt < 0))
770 break;
771 consumed += cnt;
772 ptr += cnt;
773 if (strcmp(token, "nreaders") == 0)
774 ret = sscanf(ptr, "%d", &stats->ps_drop);
775 else
776 ret = sscanf(ptr, "%d", &dummy);
777 if (ntok != 1)
778 break;
779 consumed += cnt;
780 ptr += cnt;
781 }
782
783 stats->ps_recv = handlep->packets_read;
784 stats->ps_ifdrop = 0;
785 return 0;
786 }
787
788 static int
789 usb_setdirection_linux(pcap_t *p, pcap_direction_t d)
790 {
791 p->direction = d;
792 return 0;
793 }
794
795
796 static int
797 usb_stats_linux_bin(pcap_t *handle, struct pcap_stat *stats)
798 {
799 struct pcap_usb_linux *handlep = handle->priv;
800 int ret;
801 struct mon_bin_stats st;
802 ret = ioctl(handle->fd, MON_IOCG_STATS, &st);
803 if (ret < 0)
804 {
805 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
806 "Can't read stats from fd %d:%s ", handle->fd, strerror(errno));
807 return -1;
808 }
809
810 stats->ps_recv = handlep->packets_read + st.queued;
811 stats->ps_drop = st.dropped;
812 stats->ps_ifdrop = 0;
813 return 0;
814 }
815
816 /*
817 * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
818 * <linux-kernel-source>/drivers/usb/mon/mon_bin.c binary ABI
819 */
820 static int
821 usb_read_linux_bin(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
822 {
823 struct pcap_usb_linux *handlep = handle->priv;
824 struct mon_bin_get info;
825 int ret;
826 struct pcap_pkthdr pkth;
827 u_int clen = handle->snapshot - sizeof(pcap_usb_header);
828
829 /* the usb header is going to be part of 'packet' data*/
830 info.hdr = (pcap_usb_header*) handle->buffer;
831 info.data = (u_char *)handle->buffer + sizeof(pcap_usb_header);
832 info.data_len = clen;
833
834 /* ignore interrupt system call errors */
835 do {
836 ret = ioctl(handle->fd, MON_IOCX_GET, &info);
837 if (handle->break_loop)
838 {
839 handle->break_loop = 0;
840 return -2;
841 }
842 } while ((ret == -1) && (errno == EINTR));
843 if (ret < 0)
844 {
845 if (errno == EAGAIN)
846 return 0; /* no data there */
847
848 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
849 "Can't read from fd %d: %s", handle->fd, strerror(errno));
850 return -1;
851 }
852
853 /* we can get less that than really captured from kernel, depending on
854 * snaplen, so adjust header accordingly */
855 if (info.hdr->data_len < clen)
856 clen = info.hdr->data_len;
857 info.hdr->data_len = clen;
858 pkth.caplen = clen + sizeof(pcap_usb_header);
859 pkth.len = info.hdr->data_len + sizeof(pcap_usb_header);
860 pkth.ts.tv_sec = info.hdr->ts_sec;
861 pkth.ts.tv_usec = info.hdr->ts_usec;
862
863 if (handle->fcode.bf_insns == NULL ||
864 bpf_filter(handle->fcode.bf_insns, handle->buffer,
865 pkth.len, pkth.caplen)) {
866 handlep->packets_read++;
867 callback(user, &pkth, handle->buffer);
868 return 1;
869 }
870
871 return 0; /* didn't pass filter */
872 }
873
874 /*
875 * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
876 * <linux-kernel-source>/drivers/usb/mon/mon_bin.c binary ABI
877 */
878 #define VEC_SIZE 32
879 static int
880 usb_read_linux_mmap(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
881 {
882 struct pcap_usb_linux *handlep = handle->priv;
883 struct mon_bin_mfetch fetch;
884 int32_t vec[VEC_SIZE];
885 struct pcap_pkthdr pkth;
886 pcap_usb_header* hdr;
887 int nflush = 0;
888 int packets = 0;
889 u_int clen, max_clen;
890
891 max_clen = handle->snapshot - sizeof(pcap_usb_header);
892
893 for (;;) {
894 int i, ret;
895 int limit = max_packets - packets;
896 if (limit <= 0)
897 limit = VEC_SIZE;
898 if (limit > VEC_SIZE)
899 limit = VEC_SIZE;
900
901 /* try to fetch as many events as possible*/
902 fetch.offvec = vec;
903 fetch.nfetch = limit;
904 fetch.nflush = nflush;
905 /* ignore interrupt system call errors */
906 do {
907 ret = ioctl(handle->fd, MON_IOCX_MFETCH, &fetch);
908 if (handle->break_loop)
909 {
910 handle->break_loop = 0;
911 return -2;
912 }
913 } while ((ret == -1) && (errno == EINTR));
914 if (ret < 0)
915 {
916 if (errno == EAGAIN)
917 return 0; /* no data there */
918
919 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
920 "Can't mfetch fd %d: %s", handle->fd, strerror(errno));
921 return -1;
922 }
923
924 /* keep track of processed events, we will flush them later */
925 nflush = fetch.nfetch;
926 for (i=0; i<fetch.nfetch; ++i) {
927 /* discard filler */
928 hdr = (pcap_usb_header*) &handlep->mmapbuf[vec[i]];
929 if (hdr->event_type == '@')
930 continue;
931
932 /* we can get less that than really captured from kernel, depending on
933 * snaplen, so adjust header accordingly */
934 clen = max_clen;
935 if (hdr->data_len < clen)
936 clen = hdr->data_len;
937
938 /* get packet info from header*/
939 pkth.caplen = clen + sizeof(pcap_usb_header_mmapped);
940 pkth.len = hdr->data_len + sizeof(pcap_usb_header_mmapped);
941 pkth.ts.tv_sec = hdr->ts_sec;
942 pkth.ts.tv_usec = hdr->ts_usec;
943
944 if (handle->fcode.bf_insns == NULL ||
945 bpf_filter(handle->fcode.bf_insns, (u_char*) hdr,
946 pkth.len, pkth.caplen)) {
947 handlep->packets_read++;
948 callback(user, &pkth, (u_char*) hdr);
949 packets++;
950 }
951 }
952
953 /* with max_packets specifying "unlimited" we stop afer the first chunk*/
954 if (PACKET_COUNT_IS_UNLIMITED(max_packets) || (packets == max_packets))
955 break;
956 }
957
958 /* flush pending events*/
959 if (ioctl(handle->fd, MON_IOCH_MFLUSH, nflush) == -1) {
960 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
961 "Can't mflush fd %d: %s", handle->fd, strerror(errno));
962 return -1;
963 }
964 return packets;
965 }
966
967 static void
968 usb_cleanup_linux_mmap(pcap_t* handle)
969 {
970 struct pcap_usb_linux *handlep = handle->priv;
971
972 /* if we have a memory-mapped buffer, unmap it */
973 if (handlep->mmapbuf != NULL) {
974 munmap(handlep->mmapbuf, handlep->mmapbuflen);
975 handlep->mmapbuf = NULL;
976 }
977 pcap_cleanup_live_common(handle);
978 }