pcap-usb-linux.c 31 KB

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