File: pcap-usb-linux.c

package info (click to toggle)
libpcap 1.10.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 4,780 kB
  • sloc: ansic: 46,516; sh: 3,348; makefile: 977; lex: 596; python: 254; asm: 227; cpp: 189
file content (1404 lines) | stat: -rw-r--r-- 37,958 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
/*
 * Copyright (c) 2006 Paolo Abeni (Italy)
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote
 * products derived from this software without specific prior written
 * permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * USB sniffing API implementation for Linux platform
 * By Paolo Abeni <paolo.abeni@email.it>
 * Modifications: Kris Katterjohn <katterjohn@gmail.com>
 *
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "pcap-int.h"
#include "pcap-usb-linux.h"
#include "pcap/usb.h"

#include "extract.h"

#ifdef NEED_STRERROR_H
#include "strerror.h"
#endif

#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <limits.h>
#include <string.h>
#include <dirent.h>
#include <byteswap.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/utsname.h>
#ifdef HAVE_LINUX_USBDEVICE_FS_H
/*
 * We might need <linux/compiler.h> to define __user for
 * <linux/usbdevice_fs.h>.
 */
#ifdef HAVE_LINUX_COMPILER_H
#include <linux/compiler.h>
#endif /* HAVE_LINUX_COMPILER_H */
#include <linux/usbdevice_fs.h>
#endif /* HAVE_LINUX_USBDEVICE_FS_H */

#define USB_IFACE "usbmon"
#define USB_TEXT_DIR_OLD "/sys/kernel/debug/usbmon"
#define USB_TEXT_DIR "/sys/kernel/debug/usb/usbmon"
#define SYS_USB_BUS_DIR "/sys/bus/usb/devices"
#define PROC_USB_BUS_DIR "/dev/bus/usb"
#define USB_LINE_LEN 4096

#if __BYTE_ORDER == __LITTLE_ENDIAN
#define htols(s) s
#define htoll(l) l
#define htol64(ll) ll
#else
#define htols(s) bswap_16(s)
#define htoll(l) bswap_32(l)
#define htol64(ll) bswap_64(ll)
#endif

struct mon_bin_stats {
	uint32_t queued;
	uint32_t dropped;
};

struct mon_bin_get {
	pcap_usb_header *hdr;
	void *data;
	size_t data_len;   /* Length of data (can be zero) */
};

struct mon_bin_mfetch {
	int32_t *offvec;   /* Vector of events fetched */
	int32_t nfetch;    /* Number of events to fetch (out: fetched) */
	int32_t nflush;    /* Number of events to flush */
};

#define MON_IOC_MAGIC 0x92

#define MON_IOCQ_URB_LEN _IO(MON_IOC_MAGIC, 1)
#define MON_IOCX_URB  _IOWR(MON_IOC_MAGIC, 2, struct mon_bin_hdr)
#define MON_IOCG_STATS _IOR(MON_IOC_MAGIC, 3, struct mon_bin_stats)
#define MON_IOCT_RING_SIZE _IO(MON_IOC_MAGIC, 4)
#define MON_IOCQ_RING_SIZE _IO(MON_IOC_MAGIC, 5)
#define MON_IOCX_GET   _IOW(MON_IOC_MAGIC, 6, struct mon_bin_get)
#define MON_IOCX_MFETCH _IOWR(MON_IOC_MAGIC, 7, struct mon_bin_mfetch)
#define MON_IOCH_MFLUSH _IO(MON_IOC_MAGIC, 8)

#define MON_BIN_SETUP 	0x1 /* setup hdr is present*/
#define MON_BIN_SETUP_ZERO 	0x2 /* setup buffer is not available */
#define MON_BIN_DATA_ZERO 	0x4 /* data buffer is not available */
#define MON_BIN_ERROR 	0x8

/*
 * Private data for capturing on Linux USB.
 */
struct pcap_usb_linux {
	u_char *mmapbuf;	/* memory-mapped region pointer */
	size_t mmapbuflen;	/* size of region */
	int bus_index;
	u_int packets_read;
};

/* forward declaration */
static int usb_activate(pcap_t *);
static int usb_stats_linux(pcap_t *, struct pcap_stat *);
static int usb_stats_linux_bin(pcap_t *, struct pcap_stat *);
static int usb_read_linux(pcap_t *, int , pcap_handler , u_char *);
static int usb_read_linux_bin(pcap_t *, int , pcap_handler , u_char *);
static int usb_read_linux_mmap(pcap_t *, int , pcap_handler , u_char *);
static int usb_inject_linux(pcap_t *, const void *, int);
static int usb_setdirection_linux(pcap_t *, pcap_direction_t);
static void usb_cleanup_linux_mmap(pcap_t *);

static int
have_binary_usbmon(void)
{
	struct utsname utsname;
	char *version_component, *endp;
	long major, minor, subminor;

	if (uname(&utsname) == 0) {
		/*
		 * 2.6.21 is the first release with the binary-mode
		 * USB monitoring.
		 */
		version_component = utsname.release;
		major = strtol(version_component, &endp, 10);
		if (endp != version_component && *endp == '.') {
			/*
			 * OK, that was a valid major version.
			 * Is it 3 or greater?  If so, we have binary
			 * mode support.
			 */
			if (major >= 3)
				return 1;

			/*
			 * Is it 1 or less?  If so, we don't have binary
			 * mode support.  (In fact, we don't have any
			 * USB monitoring....)
			 */
			if (major <= 1)
				return 0;
		}

		/*
		 * OK, this is a 2.x kernel.
		 * What's the minor version?
		 */
		version_component = endp + 1;
		minor = strtol(version_component, &endp, 10);
		if (endp != version_component &&
		    (*endp == '.' || *endp == '\0')) {
			/*
			 * OK, that was a valid minor version.
			 * Is is 2.6 or later?  (There shouldn't be a
			 * "later", as 2.6.x went to 3.x, but we'll
			 * check anyway.)
			 */
			if (minor < 6) {
				/*
				 * No, so no binary support (did 2.4 have
				 * any USB monitoring at all?)
				 */
				return 0;
			}

			/*
			 * OK, this is a 2.6.x kernel.
			 * What's the subminor version?
			 */
			version_component = endp + 1;
			subminor = strtol(version_component, &endp, 10);
			if (endp != version_component &&
			    (*endp == '.' || *endp == '\0')) {
				/*
				 * OK, that was a valid subminor version.
				 * Is it 21 or greater?
				 */
				if (subminor >= 21) {
					/*
					 * Yes - we have binary mode
					 * support.
					 */
					return 1;
				}
			}
		}
	}

	/*
	 * Either uname() failed, in which case we just say "no binary
	 * mode support", or we don't have binary mode support.
	 */
	return 0;
}

/* facility to add an USB device to the device list*/
static int
usb_dev_add(pcap_if_list_t *devlistp, int n, char *err_str)
{
	char dev_name[10];
	char dev_descr[30];
	snprintf(dev_name, 10, USB_IFACE"%d", n);
	/*
	 * XXX - is there any notion of "up" and "running"?
	 */
	if (n == 0) {
		/*
		 * As this refers to all buses, there's no notion of
		 * "connected" vs. "disconnected", as that's a property
		 * that would apply to a particular USB interface.
		 */
		if (add_dev(devlistp, dev_name,
		    PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE,
		    "Raw USB traffic, all USB buses", err_str) == NULL)
			return -1;
	} else {
		/*
		 * XXX - is there a way to determine whether anything's
		 * plugged into this bus interface or not, and set
		 * PCAP_IF_CONNECTION_STATUS_CONNECTED or
		 * PCAP_IF_CONNECTION_STATUS_DISCONNECTED?
		 */
		snprintf(dev_descr, 30, "Raw USB traffic, bus number %d", n);
		if (add_dev(devlistp, dev_name, 0, dev_descr, err_str) == NULL)
			return -1;
	}

	return 0;
}

int
usb_findalldevs(pcap_if_list_t *devlistp, char *err_str)
{
	char usb_mon_dir[PATH_MAX];
	char *usb_mon_prefix;
	size_t usb_mon_prefix_len;
	struct dirent* data;
	int ret = 0;
	DIR* dir;
	int n;
	char* name;
	size_t len;

	if (have_binary_usbmon()) {
		/*
		 * We have binary-mode support.
		 * What do the device names look like?
		 * Split LINUX_USB_MON_DEV into a directory that we'll
		 * scan and a file name prefix that we'll check for.
		 */
		pcap_strlcpy(usb_mon_dir, LINUX_USB_MON_DEV, sizeof usb_mon_dir);
		usb_mon_prefix = strrchr(usb_mon_dir, '/');
		if (usb_mon_prefix == NULL) {
			/*
			 * This "shouldn't happen".  Just give up if it
			 * does.
			 */
			return 0;
		}
		*usb_mon_prefix++ = '\0';
		usb_mon_prefix_len = strlen(usb_mon_prefix);

		/*
		 * Open the directory and scan it.
		 */
		dir = opendir(usb_mon_dir);
		if (dir != NULL) {
			while ((ret == 0) && ((data = readdir(dir)) != 0)) {
				name = data->d_name;

				/*
				 * Is this a usbmon device?
				 */
				if (strncmp(name, usb_mon_prefix, usb_mon_prefix_len) != 0)
					continue;	/* no */

				/*
				 * What's the device number?
				 */
				if (sscanf(&name[usb_mon_prefix_len], "%d", &n) == 0)
					continue;	/* failed */

				ret = usb_dev_add(devlistp, n, err_str);
			}

			closedir(dir);
		}
		return 0;
	} else {
		/*
		 * We have only text mode support.
		 * We don't look for the text devices because we can't
		 * look for them without root privileges, and we don't
		 * want to require root privileges to enumerate devices
		 * (we want to let the user to try a device and get
		 * an error, rather than seeing no devices and asking
		 * "why am I not seeing devices" and forcing a long
		 * process of poking to figure out whether it's "no
		 * privileges" or "your kernel is too old" or "the
		 * usbmon module isn't loaded" or...).
		 *
		 * Instead, we look to see what buses we have.
		 * If the kernel is so old that it doesn't have
		 * binary-mode support, it's also so old that
		 * it doesn't have a "scan all buses" device.
		 *
		 * First, try scanning sysfs USB bus directory.
		 */
		dir = opendir(SYS_USB_BUS_DIR);
		if (dir != NULL) {
			while ((ret == 0) && ((data = readdir(dir)) != 0)) {
				name = data->d_name;

				if (strncmp(name, "usb", 3) != 0)
					continue;

				if (sscanf(&name[3], "%d", &n) == 0)
					continue;

				ret = usb_dev_add(devlistp, n, err_str);
			}

			closedir(dir);
			return 0;
		}

		/* That didn't work; try scanning procfs USB bus directory. */
		dir = opendir(PROC_USB_BUS_DIR);
		if (dir != NULL) {
			while ((ret == 0) && ((data = readdir(dir)) != 0)) {
				name = data->d_name;
				len = strlen(name);

				/* if this file name does not end with a number it's not of our interest */
				if ((len < 1) || !PCAP_ISDIGIT(name[--len]))
					continue;
				while (PCAP_ISDIGIT(name[--len]));
				if (sscanf(&name[len+1], "%d", &n) != 1)
					continue;

				ret = usb_dev_add(devlistp, n, err_str);
			}

			closedir(dir);
			return ret;
		}

		/* neither of them worked */
		return 0;
	}
}

/*
 * Matches what's in mon_bin.c in the Linux kernel.
 */
#define MIN_RING_SIZE	(8*1024)
#define MAX_RING_SIZE	(1200*1024)

static int
usb_set_ring_size(pcap_t* handle, int header_size)
{
	/*
	 * A packet from binary usbmon has:
	 *
	 *  1) a fixed-length header, of size header_size;
	 *  2) descriptors, for isochronous transfers;
	 *  3) the payload.
	 *
	 * The kernel buffer has a size, defaulting to 300KB, with a
	 * minimum of 8KB and a maximum of 1200KB.  The size is set with
	 * the MON_IOCT_RING_SIZE ioctl; the size passed in is rounded up
	 * to a page size.
	 *
	 * No more than {buffer size}/5 bytes worth of payload is saved.
	 * Therefore, if we subtract the fixed-length size from the
	 * snapshot length, we have the biggest payload we want (we
	 * don't worry about the descriptors - if we have descriptors,
	 * we'll just discard the last bit of the payload to get it
	 * to fit).  We multiply that result by 5 and set the buffer
	 * size to that value.
	 */
	int ring_size;

	if (handle->snapshot < header_size)
		handle->snapshot = header_size;
	/* The maximum snapshot size is small enough that this won't overflow */
	ring_size = (handle->snapshot - header_size) * 5;

	/*
	 * Will this get an error?
	 * (There's no wqy to query the minimum or maximum, so we just
	 * copy the value from the kernel source.  We don't round it
	 * up to a multiple of the page size.)
	 */
	if (ring_size > MAX_RING_SIZE) {
		/*
		 * Yes.  Lower the ring size to the maximum, and set the
		 * snapshot length to the value that would give us a
		 * maximum-size ring.
		 */
		ring_size = MAX_RING_SIZE;
		handle->snapshot = header_size + (MAX_RING_SIZE/5);
	} else if (ring_size < MIN_RING_SIZE) {
		/*
		 * Yes.  Raise the ring size to the minimum, but leave
		 * the snapshot length unchanged, so we show the
		 * callback no more data than specified by the
		 * snapshot length.
		 */
		ring_size = MIN_RING_SIZE;
	}

	if (ioctl(handle->fd, MON_IOCT_RING_SIZE, ring_size) == -1) {
		pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
		    errno, "Can't set ring size from fd %d", handle->fd);
		return -1;
	}
	return ring_size;
}

static
int usb_mmap(pcap_t* handle)
{
	struct pcap_usb_linux *handlep = handle->priv;
	int len;

	/*
	 * Attempt to set the ring size as appropriate for the snapshot
	 * length, reducing the snapshot length if that'd make the ring
	 * bigger than the kernel supports.
	 */
	len = usb_set_ring_size(handle, (int)sizeof(pcap_usb_header_mmapped));
	if (len == -1) {
		/* Failed.  Fall back on non-memory-mapped access. */
		return 0;
	}

	handlep->mmapbuflen = len;
	handlep->mmapbuf = mmap(0, handlep->mmapbuflen, PROT_READ,
	    MAP_SHARED, handle->fd, 0);
	if (handlep->mmapbuf == MAP_FAILED) {
		/*
		 * Failed.  We don't treat that as a fatal error, we
		 * just try to fall back on non-memory-mapped access.
		 */
		return 0;
	}
	return 1;
}

#ifdef HAVE_LINUX_USBDEVICE_FS_H

#define CTRL_TIMEOUT    (5*1000)        /* milliseconds */

#define USB_DIR_IN		0x80
#define USB_TYPE_STANDARD	0x00
#define USB_RECIP_DEVICE	0x00

#define USB_REQ_GET_DESCRIPTOR	6

#define USB_DT_DEVICE		1
#define USB_DT_CONFIG		2

#define USB_DEVICE_DESCRIPTOR_SIZE	18
#define USB_CONFIG_DESCRIPTOR_SIZE	9

/* probe the descriptors of the devices attached to the bus */
/* the descriptors will end up in the captured packet stream */
/* and be decoded by external apps like wireshark */
/* without these identifying probes packet data can't be fully decoded */
static void
probe_devices(int bus)
{
	struct usbdevfs_ctrltransfer ctrl;
	struct dirent* data;
	int ret = 0;
	char busdevpath[sizeof("/dev/bus/usb/000/") + NAME_MAX];
	DIR* dir;
	uint8_t descriptor[USB_DEVICE_DESCRIPTOR_SIZE];
	uint8_t configdesc[USB_CONFIG_DESCRIPTOR_SIZE];

	/* scan usb bus directories for device nodes */
	snprintf(busdevpath, sizeof(busdevpath), "/dev/bus/usb/%03d", bus);
	dir = opendir(busdevpath);
	if (!dir)
		return;

	while ((ret >= 0) && ((data = readdir(dir)) != 0)) {
		int fd;
		char* name = data->d_name;

		if (name[0] == '.')
			continue;

		snprintf(busdevpath, sizeof(busdevpath), "/dev/bus/usb/%03d/%s", bus, data->d_name);

		fd = open(busdevpath, O_RDWR);
		if (fd == -1)
			continue;

		/*
		 * Sigh.  Different kernels have different member names
		 * for this structure.
		 */
#ifdef HAVE_STRUCT_USBDEVFS_CTRLTRANSFER_BREQUESTTYPE
		ctrl.bRequestType = USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE;
		ctrl.bRequest = USB_REQ_GET_DESCRIPTOR;
		ctrl.wValue = USB_DT_DEVICE << 8;
		ctrl.wIndex = 0;
 		ctrl.wLength = sizeof(descriptor);
#else
		ctrl.requesttype = USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE;
		ctrl.request = USB_REQ_GET_DESCRIPTOR;
		ctrl.value = USB_DT_DEVICE << 8;
		ctrl.index = 0;
 		ctrl.length = sizeof(descriptor);
#endif
		ctrl.data = descriptor;
		ctrl.timeout = CTRL_TIMEOUT;

		ret = ioctl(fd, USBDEVFS_CONTROL, &ctrl);

		/* Request CONFIGURATION descriptor alone to know wTotalLength */
#ifdef HAVE_STRUCT_USBDEVFS_CTRLTRANSFER_BREQUESTTYPE
		ctrl.wValue = USB_DT_CONFIG << 8;
		ctrl.wLength = sizeof(configdesc);
#else
		ctrl.value = USB_DT_CONFIG << 8;
		ctrl.length = sizeof(configdesc);
#endif
		ctrl.data = configdesc;
		ret = ioctl(fd, USBDEVFS_CONTROL, &ctrl);
		if (ret >= 0) {
			uint16_t wtotallength;
			wtotallength = EXTRACT_LE_U_2(&configdesc[2]);
#ifdef HAVE_STRUCT_USBDEVFS_CTRLTRANSFER_BREQUESTTYPE
			ctrl.wLength = wtotallength;
#else
			ctrl.length = wtotallength;
#endif
			ctrl.data = malloc(wtotallength);
			if (ctrl.data) {
				ret = ioctl(fd, USBDEVFS_CONTROL, &ctrl);
				free(ctrl.data);
			}
		}
		close(fd);
	}
	closedir(dir);
}
#endif /* HAVE_LINUX_USBDEVICE_FS_H */

pcap_t *
usb_create(const char *device, char *ebuf, int *is_ours)
{
	const char *cp;
	char *cpend;
	long devnum;
	pcap_t *p;

	/* Does this look like a USB monitoring device? */
	cp = strrchr(device, '/');
	if (cp == NULL)
		cp = device;
	/* Does it begin with USB_IFACE? */
	if (strncmp(cp, USB_IFACE, sizeof USB_IFACE - 1) != 0) {
		/* Nope, doesn't begin with USB_IFACE */
		*is_ours = 0;
		return NULL;
	}
	/* Yes - is USB_IFACE followed by a number? */
	cp += sizeof USB_IFACE - 1;
	devnum = strtol(cp, &cpend, 10);
	if (cpend == cp || *cpend != '\0') {
		/* Not followed by a number. */
		*is_ours = 0;
		return NULL;
	}
	if (devnum < 0) {
		/* Followed by a non-valid number. */
		*is_ours = 0;
		return NULL;
	}

	/* OK, it's probably ours. */
	*is_ours = 1;

	p = PCAP_CREATE_COMMON(ebuf, struct pcap_usb_linux);
	if (p == NULL)
		return (NULL);

	p->activate_op = usb_activate;
	return (p);
}

static int
usb_activate(pcap_t* handle)
{
	struct pcap_usb_linux *handlep = handle->priv;
	char 		full_path[USB_LINE_LEN];
	int		ret;

	/*
	 * Turn a negative snapshot value (invalid), a snapshot value of
	 * 0 (unspecified), or a value bigger than the normal maximum
	 * value, into the maximum allowed value.
	 *
	 * If some application really *needs* a bigger snapshot
	 * length, we should just increase MAXIMUM_SNAPLEN.
	 */
	if (handle->snapshot <= 0 || handle->snapshot > MAXIMUM_SNAPLEN)
		handle->snapshot = MAXIMUM_SNAPLEN;

	/* Initialize some components of the pcap structure. */
	handle->bufsize = handle->snapshot;
	handle->offset = 0;
	handle->linktype = DLT_USB_LINUX;

	handle->inject_op = usb_inject_linux;
	handle->setfilter_op = install_bpf_program; /* no kernel filtering */
	handle->setdirection_op = usb_setdirection_linux;
	handle->set_datalink_op = NULL;	/* can't change data link type */
	handle->getnonblock_op = pcap_getnonblock_fd;
	handle->setnonblock_op = pcap_setnonblock_fd;

	/*get usb bus index from device name */
	if (sscanf(handle->opt.device, USB_IFACE"%d", &handlep->bus_index) != 1)
	{
		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
			"Can't get USB bus index from %s", handle->opt.device);
		return PCAP_ERROR;
	}

	if (have_binary_usbmon())
	{
		/*
		 * We have binary-mode support.
		 * Try to open the binary interface.
		 */
		snprintf(full_path, USB_LINE_LEN, LINUX_USB_MON_DEV"%d", handlep->bus_index);
		handle->fd = open(full_path, O_RDONLY, 0);
		if (handle->fd < 0)
		{
			/*
			 * The attempt failed; why?
			 */
			switch (errno) {

			case ENOENT:
				/*
				 * The device doesn't exist.
				 * That could either mean that there's
				 * no support for monitoring USB buses
				 * (which probably means "the usbmon
				 * module isn't loaded") or that there
				 * is but that *particular* device
				 * doesn't exist (no "scan all buses"
				 * device if the bus index is 0, no
				 * such bus if the bus index isn't 0).
				 */
				return PCAP_ERROR_NO_SUCH_DEVICE;

			case EACCES:
				/*
				 * We didn't have permission to open it.
				 */
				return PCAP_ERROR_PERM_DENIED;

			default:
				/*
				 * Something went wrong.
				 */
				pcap_fmt_errmsg_for_errno(handle->errbuf,
				    PCAP_ERRBUF_SIZE, errno,
				    "Can't open USB bus file %s", full_path);
				return PCAP_ERROR;
			}
		}

		if (handle->opt.rfmon)
		{
			/*
			 * Monitor mode doesn't apply to USB devices.
			 */
			close(handle->fd);
			return PCAP_ERROR_RFMON_NOTSUP;
		}

		/* try to use fast mmap access */
		if (usb_mmap(handle))
		{
			/* We succeeded. */
			handle->linktype = DLT_USB_LINUX_MMAPPED;
			handle->stats_op = usb_stats_linux_bin;
			handle->read_op = usb_read_linux_mmap;
			handle->cleanup_op = usb_cleanup_linux_mmap;
#ifdef HAVE_LINUX_USBDEVICE_FS_H
			probe_devices(handlep->bus_index);
#endif

			/*
			 * "handle->fd" is a real file, so
			 * "select()" and "poll()" work on it.
			 */
			handle->selectable_fd = handle->fd;
			return 0;
		}

		/*
		 * We failed; try plain binary interface access.
		 *
		 * Attempt to set the ring size as appropriate for
		 * the snapshot length, reducing the snapshot length
		 * if that'd make the ring bigger than the kernel
		 * supports.
		 */
		if (usb_set_ring_size(handle, (int)sizeof(pcap_usb_header)) == -1) {
			/* Failed. */
			close(handle->fd);
			return PCAP_ERROR;
		}
		handle->stats_op = usb_stats_linux_bin;
		handle->read_op = usb_read_linux_bin;
#ifdef HAVE_LINUX_USBDEVICE_FS_H
		probe_devices(handlep->bus_index);
#endif
	}
	else {
		/*
		 * We don't have binary mode support.
		 * Try opening the text-mode device.
		 */
		snprintf(full_path, USB_LINE_LEN, USB_TEXT_DIR"/%dt", handlep->bus_index);
		handle->fd = open(full_path, O_RDONLY, 0);
		if (handle->fd < 0)
		{
			if (errno == ENOENT)
			{
				/*
				 * Not found at the new location; try
				 * the old location.
				 */
				snprintf(full_path, USB_LINE_LEN, USB_TEXT_DIR_OLD"/%dt", handlep->bus_index);
				handle->fd = open(full_path, O_RDONLY, 0);
			}
			if (handle->fd < 0) {
				if (errno == ENOENT)
				{
					/*
					 * The problem is that the file
					 * doesn't exist.  Report that as
					 * "no such device".  (That could
					 * mean "no such USB bus" or
					 * "monitoring not supported".)
					 */
					ret = PCAP_ERROR_NO_SUCH_DEVICE;
				}
				else if (errno == EACCES)
				{
					/*
					 * The problem is that we don't
					 * have sufficient permission to
					 * open the file.  Report that.
					 */
					ret = PCAP_ERROR_PERM_DENIED;
				}
				else
				{
					/*
					 * Some other error.
					 */
					ret = PCAP_ERROR;
				}
				pcap_fmt_errmsg_for_errno(handle->errbuf,
				    PCAP_ERRBUF_SIZE, errno,
				    "Can't open USB bus file %s",
				    full_path);
				return ret;
			}
		}

		if (handle->opt.rfmon)
		{
			/*
			 * Monitor mode doesn't apply to USB devices.
			 */
			close(handle->fd);
			return PCAP_ERROR_RFMON_NOTSUP;
		}

		handle->stats_op = usb_stats_linux;
		handle->read_op = usb_read_linux;
	}

	/*
	 * "handle->fd" is a real file, so "select()" and "poll()"
	 * work on it.
	 */
	handle->selectable_fd = handle->fd;

	/* for plain binary access and text access we need to allocate the read
	 * buffer */
	handle->buffer = malloc(handle->bufsize);
	if (!handle->buffer) {
		pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
		    errno, "malloc");
		close(handle->fd);
		return PCAP_ERROR;
	}
	return 0;
}

static inline int
ascii_to_int(char c)
{
	return c < 'A' ? c- '0': ((c<'a') ? c - 'A' + 10: c-'a'+10);
}

/*
 * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
 * <linux-kernel-source>/drivers/usb/mon/mon_text.c for urb string
 * format description
 */
static int
usb_read_linux(pcap_t *handle, int max_packets _U_, pcap_handler callback, u_char *user)
{
	/* see:
	* /usr/src/linux/Documentation/usb/usbmon.txt
	* for message format
	*/
	struct pcap_usb_linux *handlep = handle->priv;
	unsigned timestamp;
	int tag, cnt, ep_num, dev_addr, dummy, ret, urb_len, data_len;
	ssize_t read_ret;
	char etype, pipeid1, pipeid2, status[16], urb_tag, line[USB_LINE_LEN];
	char *string = line;
	u_char * rawdata = handle->buffer;
	struct pcap_pkthdr pkth;
	pcap_usb_header* uhdr = (pcap_usb_header*)handle->buffer;
	u_char urb_transfer=0;
	int incoming=0;

	/* ignore interrupt system call errors */
	do {
		read_ret = read(handle->fd, line, USB_LINE_LEN - 1);
		if (handle->break_loop)
		{
			handle->break_loop = 0;
			return -2;
		}
	} while ((read_ret == -1) && (errno == EINTR));
	if (read_ret < 0)
	{
		if (errno == EAGAIN)
			return 0;	/* no data there */

		pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
		    errno, "Can't read from fd %d", handle->fd);
		return -1;
	}

	/* read urb header; %n argument may increment return value, but it's
	* not mandatory, so does not count on it*/
	string[read_ret] = 0;
	ret = sscanf(string, "%x %d %c %c%c:%d:%d %s%n", &tag, &timestamp, &etype,
		&pipeid1, &pipeid2, &dev_addr, &ep_num, status,
		&cnt);
	if (ret < 8)
	{
		char string_truncated[181];

		strncpy(string_truncated, string, sizeof(string_truncated));
		string_truncated[sizeof(string_truncated) - 1] = 0;
		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
			 "Can't parse USB bus message '%s', too few tokens (expected 8 got %d)",
			 string_truncated, ret);
		return -1;
	}
	uhdr->id = tag;
	uhdr->device_address = dev_addr;
	uhdr->bus_id = handlep->bus_index;
	uhdr->status = 0;
	string += cnt;

	/* don't use usbmon provided timestamp, since it have low precision*/
	if (gettimeofday(&pkth.ts, NULL) < 0)
	{
		pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
		    errno, "Can't get timestamp for message '%s'", string);
		return -1;
	}
	uhdr->ts_sec = pkth.ts.tv_sec;
	uhdr->ts_usec = (int32_t)pkth.ts.tv_usec;

	/* parse endpoint information */
	if (pipeid1 == 'C')
		urb_transfer = URB_CONTROL;
	else if (pipeid1 == 'Z')
		urb_transfer = URB_ISOCHRONOUS;
	else if (pipeid1 == 'I')
		urb_transfer = URB_INTERRUPT;
	else if (pipeid1 == 'B')
		urb_transfer = URB_BULK;
	if (pipeid2 == 'i') {
		ep_num |= URB_TRANSFER_IN;
		incoming = 1;
	}
	if (etype == 'C')
		incoming = !incoming;

	/* direction check*/
	if (incoming)
	{
		if (handle->direction == PCAP_D_OUT)
			return 0;
	}
	else
		if (handle->direction == PCAP_D_IN)
			return 0;
	uhdr->event_type = etype;
	uhdr->transfer_type = urb_transfer;
	uhdr->endpoint_number = ep_num;
	pkth.caplen = sizeof(pcap_usb_header);
	rawdata += sizeof(pcap_usb_header);

	/* check if this is a setup packet */
	ret = sscanf(status, "%d", &dummy);
	if (ret != 1)
	{
		/* this a setup packet, setup data can be filled with underscore if
		* usbmon has not been able to read them, so we must parse this fields as
		* strings */
		pcap_usb_setup* shdr;
		char str1[3], str2[3], str3[5], str4[5], str5[5];
		ret = sscanf(string, "%s %s %s %s %s%n", str1, str2, str3, str4,
		str5, &cnt);
		if (ret < 5)
		{
			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
				"Can't parse USB bus message '%s', too few tokens (expected 5 got %d)",
				string, ret);
			return -1;
		}
		string += cnt;

		/* try to convert to corresponding integer */
		shdr = &uhdr->setup;
		shdr->bmRequestType = strtoul(str1, 0, 16);
		shdr->bRequest = strtoul(str2, 0, 16);
		shdr->wValue = htols(strtoul(str3, 0, 16));
		shdr->wIndex = htols(strtoul(str4, 0, 16));
		shdr->wLength = htols(strtoul(str5, 0, 16));

		uhdr->setup_flag = 0;
	}
	else
		uhdr->setup_flag = 1;

	/* read urb data */
	ret = sscanf(string, " %d%n", &urb_len, &cnt);
	if (ret < 1)
	{
		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
		  "Can't parse urb length from '%s'", string);
		return -1;
	}
	string += cnt;

	/* urb tag is not present if urb length is 0, so we can stop here
	 * text parsing */
	pkth.len = urb_len+pkth.caplen;
	uhdr->urb_len = urb_len;
	uhdr->data_flag = 1;
	data_len = 0;
	if (uhdr->urb_len == 0)
		goto got;

	/* check for data presence; data is present if and only if urb tag is '=' */
	if (sscanf(string, " %c", &urb_tag) != 1)
	{
		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
			"Can't parse urb tag from '%s'", string);
		return -1;
	}

	if (urb_tag != '=')
		goto got;

	/* skip urb tag and following space */
	string += 3;

	/* if we reach this point we got some urb data*/
	uhdr->data_flag = 0;

	/* read all urb data; if urb length is greater then the usbmon internal
	 * buffer length used by the kernel to spool the URB, we get only
	 * a partial information.
	 * At least until linux 2.6.17 there is no way to set usbmon intenal buffer
	 * length and default value is 130. */
	while ((string[0] != 0) && (string[1] != 0) && (pkth.caplen < (bpf_u_int32)handle->snapshot))
	{
		rawdata[0] = ascii_to_int(string[0]) * 16 + ascii_to_int(string[1]);
		rawdata++;
		string+=2;
		if (string[0] == ' ')
			string++;
		pkth.caplen++;
		data_len++;
	}

got:
	uhdr->data_len = data_len;
	if (pkth.caplen > (bpf_u_int32)handle->snapshot)
		pkth.caplen = (bpf_u_int32)handle->snapshot;

	if (handle->fcode.bf_insns == NULL ||
	    pcap_filter(handle->fcode.bf_insns, handle->buffer,
	      pkth.len, pkth.caplen)) {
		handlep->packets_read++;
		callback(user, &pkth, handle->buffer);
		return 1;
	}
	return 0;	/* didn't pass filter */
}

static int
usb_inject_linux(pcap_t *handle, const void *buf _U_, int size _U_)
{
	snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
	    "Packet injection is not supported on USB devices");
	return (-1);
}

static int
usb_stats_linux(pcap_t *handle, struct pcap_stat *stats)
{
	struct pcap_usb_linux *handlep = handle->priv;
	int dummy, cnt;
	ssize_t ret, consumed;
	char string[USB_LINE_LEN];
	char token[USB_LINE_LEN];
	char * ptr = string;
	int fd;

	snprintf(string, USB_LINE_LEN, USB_TEXT_DIR"/%ds", handlep->bus_index);
	fd = open(string, O_RDONLY, 0);
	if (fd < 0)
	{
		if (errno == ENOENT)
		{
			/*
			 * Not found at the new location; try the old
			 * location.
			 */
			snprintf(string, USB_LINE_LEN, USB_TEXT_DIR_OLD"/%ds", handlep->bus_index);
			fd = open(string, O_RDONLY, 0);
		}
		if (fd < 0) {
			pcap_fmt_errmsg_for_errno(handle->errbuf,
			    PCAP_ERRBUF_SIZE, errno,
			    "Can't open USB stats file %s", string);
			return -1;
		}
	}

	/* read stats line */
	do {
		ret = read(fd, string, USB_LINE_LEN-1);
	} while ((ret == -1) && (errno == EINTR));
	close(fd);

	if (ret < 0)
	{
		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
			"Can't read stats from fd %d ", fd);
		return -1;
	}
	string[ret] = 0;

	stats->ps_recv = handlep->packets_read;
	stats->ps_drop = 0;	/* unless we find text_lost */
	stats->ps_ifdrop = 0;

	/* extract info on dropped urbs */
	for (consumed=0; consumed < ret; ) {
		/* from the sscanf man page:
 		 * The C standard says: "Execution of a %n directive does
 		 * not increment the assignment count returned at the completion
		 * of  execution" but the Corrigendum seems to contradict this.
		 * Do not make any assumptions on the effect of %n conversions
		 * on the return value and explicitly check for cnt assignmet*/
		int ntok;

		cnt = -1;
		ntok = sscanf(ptr, "%s%n", token, &cnt);
		if ((ntok < 1) || (cnt < 0))
			break;
		consumed += cnt;
		ptr += cnt;
		if (strcmp(token, "text_lost") == 0)
			ntok = sscanf(ptr, "%d%n", &stats->ps_drop, &cnt);
		else
			ntok = sscanf(ptr, "%d%n", &dummy, &cnt);
		if ((ntok != 1) || (cnt < 0))
			break;
		consumed += cnt;
		ptr += cnt;
	}

	return 0;
}

static int
usb_setdirection_linux(pcap_t *p, pcap_direction_t d)
{
	/*
	 * It's guaranteed, at this point, that d is a valid
	 * direction value.
	 */
	p->direction = d;
	return 0;
}


static int
usb_stats_linux_bin(pcap_t *handle, struct pcap_stat *stats)
{
	struct pcap_usb_linux *handlep = handle->priv;
	int ret;
	struct mon_bin_stats st;
	ret = ioctl(handle->fd, MON_IOCG_STATS, &st);
	if (ret < 0)
	{
		pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
		    errno, "Can't read stats from fd %d", handle->fd);
		return -1;
	}

	stats->ps_recv = handlep->packets_read + st.queued;
	stats->ps_drop = st.dropped;
	stats->ps_ifdrop = 0;
	return 0;
}

/*
 * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
 * <linux-kernel-source>/drivers/usb/mon/mon_bin.c binary ABI
 */
static int
usb_read_linux_bin(pcap_t *handle, int max_packets _U_, pcap_handler callback, u_char *user)
{
	struct pcap_usb_linux *handlep = handle->priv;
	struct mon_bin_get info;
	int ret;
	struct pcap_pkthdr pkth;
	u_int clen = handle->snapshot - sizeof(pcap_usb_header);

	/* the usb header is going to be part of 'packet' data*/
	info.hdr = (pcap_usb_header*) handle->buffer;
	info.data = (u_char *)handle->buffer + sizeof(pcap_usb_header);
	info.data_len = clen;

	/* ignore interrupt system call errors */
	do {
		ret = ioctl(handle->fd, MON_IOCX_GET, &info);
		if (handle->break_loop)
		{
			handle->break_loop = 0;
			return -2;
		}
	} while ((ret == -1) && (errno == EINTR));
	if (ret < 0)
	{
		if (errno == EAGAIN)
			return 0;	/* no data there */

		pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
		    errno, "Can't read from fd %d", handle->fd);
		return -1;
	}

	/*
	 * info.hdr->data_len is the number of bytes of isochronous
	 * descriptors (if any) plus the number of bytes of data
	 * provided.  There are no isochronous descriptors here,
	 * because we're using the old 48-byte header.
	 *
	 * If info.hdr->data_flag is non-zero, there's no URB data;
	 * info.hdr->urb_len is the size of the buffer into which
	 * data is to be placed; it does not represent the amount
	 * of data transferred.  If info.hdr->data_flag is zero,
	 * there is URB data, and info.hdr->urb_len is the number
	 * of bytes transmitted or received; it doesn't include
	 * isochronous descriptors.
	 *
	 * The kernel may give us more data than the snaplen; if it did,
	 * reduce the data length so that the total number of bytes we
	 * tell our client we have is not greater than the snaplen.
	 */
	if (info.hdr->data_len < clen)
		clen = info.hdr->data_len;
	info.hdr->data_len = clen;
	pkth.caplen = sizeof(pcap_usb_header) + clen;
	if (info.hdr->data_flag) {
		/*
		 * No data; just base the on-the-wire length on
		 * info.hdr->data_len (so that it's >= the captured
		 * length).
		 */
		pkth.len = sizeof(pcap_usb_header) + info.hdr->data_len;
	} else {
		/*
		 * We got data; base the on-the-wire length on
		 * info.hdr->urb_len, so that it includes data
		 * discarded by the USB monitor device due to
		 * its buffer being too small.
		 */
		pkth.len = sizeof(pcap_usb_header) + info.hdr->urb_len;
	}
	pkth.ts.tv_sec = (time_t)info.hdr->ts_sec;
	pkth.ts.tv_usec = info.hdr->ts_usec;

	if (handle->fcode.bf_insns == NULL ||
	    pcap_filter(handle->fcode.bf_insns, handle->buffer,
	      pkth.len, pkth.caplen)) {
		handlep->packets_read++;
		callback(user, &pkth, handle->buffer);
		return 1;
	}

	return 0;	/* didn't pass filter */
}

/*
 * see <linux-kernel-source>/Documentation/usb/usbmon.txt and
 * <linux-kernel-source>/drivers/usb/mon/mon_bin.c binary ABI
 */
#define VEC_SIZE 32
static int
usb_read_linux_mmap(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
{
	struct pcap_usb_linux *handlep = handle->priv;
	struct mon_bin_mfetch fetch;
	int32_t vec[VEC_SIZE];
	struct pcap_pkthdr pkth;
	pcap_usb_header_mmapped* hdr;
	int nflush = 0;
	int packets = 0;
	u_int clen, max_clen;

	max_clen = handle->snapshot - sizeof(pcap_usb_header_mmapped);

	for (;;) {
		int i, ret;
		int limit = max_packets - packets;
		if (limit <= 0)
			limit = VEC_SIZE;
		if (limit > VEC_SIZE)
			limit = VEC_SIZE;

		/* try to fetch as many events as possible*/
		fetch.offvec = vec;
		fetch.nfetch = limit;
		fetch.nflush = nflush;
		/* ignore interrupt system call errors */
		do {
			ret = ioctl(handle->fd, MON_IOCX_MFETCH, &fetch);
			if (handle->break_loop)
			{
				handle->break_loop = 0;
				return -2;
			}
		} while ((ret == -1) && (errno == EINTR));
		if (ret < 0)
		{
			if (errno == EAGAIN)
				return 0;	/* no data there */

			pcap_fmt_errmsg_for_errno(handle->errbuf,
			    PCAP_ERRBUF_SIZE, errno, "Can't mfetch fd %d",
			    handle->fd);
			return -1;
		}

		/* keep track of processed events, we will flush them later */
		nflush = fetch.nfetch;
		for (i=0; i<fetch.nfetch; ++i) {
			/* discard filler */
			hdr = (pcap_usb_header_mmapped*) &handlep->mmapbuf[vec[i]];
			if (hdr->event_type == '@')
				continue;

			/*
			 * hdr->data_len is the number of bytes of
			 * isochronous descriptors (if any) plus the
			 * number of bytes of data provided.
			 *
			 * If hdr->data_flag is non-zero, there's no
			 * URB data; hdr->urb_len is the size of the
			 * buffer into which data is to be placed; it does
			 * not represent the amount of data transferred.
			 * If hdr->data_flag is zero, there is URB data,
			 * and hdr->urb_len is the number of bytes
			 * transmitted or received; it doesn't include
			 * isochronous descriptors.
			 *
			 * The kernel may give us more data than the
			 * snaplen; if it did, reduce the data length
			 * so that the total number of bytes we
			 * tell our client we have is not greater than
			 * the snaplen.
			 */
			clen = max_clen;
			if (hdr->data_len < clen)
				clen = hdr->data_len;
			pkth.caplen = sizeof(pcap_usb_header_mmapped) + clen;
			if (hdr->data_flag) {
				/*
				 * No data; just base the on-the-wire length
				 * on hdr->data_len (so that it's >= the
				 * captured length).
				 */
				pkth.len = sizeof(pcap_usb_header_mmapped) +
				    hdr->data_len;
			} else {
				/*
				 * We got data; base the on-the-wire length
				 * on hdr->urb_len, so that it includes
				 * data discarded by the USB monitor device
				 * due to its buffer being too small.
				 */
				pkth.len = sizeof(pcap_usb_header_mmapped) +
				    (hdr->ndesc * sizeof (usb_isodesc)) + hdr->urb_len;
			}
			pkth.ts.tv_sec = (time_t)hdr->ts_sec;
			pkth.ts.tv_usec = hdr->ts_usec;

			if (handle->fcode.bf_insns == NULL ||
			    pcap_filter(handle->fcode.bf_insns, (u_char*) hdr,
			      pkth.len, pkth.caplen)) {
				handlep->packets_read++;
				callback(user, &pkth, (u_char*) hdr);
				packets++;
			}
		}

		/* with max_packets specifying "unlimited" we stop after the first chunk*/
		if (PACKET_COUNT_IS_UNLIMITED(max_packets) || (packets == max_packets))
			break;
	}

	/* flush pending events*/
	if (ioctl(handle->fd, MON_IOCH_MFLUSH, nflush) == -1) {
		pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
		    errno, "Can't mflush fd %d", handle->fd);
		return -1;
	}
	return packets;
}

static void
usb_cleanup_linux_mmap(pcap_t* handle)
{
	struct pcap_usb_linux *handlep = handle->priv;

	/* if we have a memory-mapped buffer, unmap it */
	if (handlep->mmapbuf != NULL) {
		munmap(handlep->mmapbuf, handlep->mmapbuflen);
		handlep->mmapbuf = NULL;
	}
	pcap_cleanup_live_common(handle);
}