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