PageRenderTime 43ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 1ms

/libpcap/pcap-linux.c

https://gitlab.com/g10h4ck/nmap-gsoc2015
C | 6603 lines | 3429 code | 559 blank | 2615 comment | 832 complexity | 03a345b611892f4e8203020796700711 MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-2.0, Apache-2.0, LGPL-2.0, LGPL-2.1, MIT
  1. /*
  2. * pcap-linux.c: Packet capture interface to the Linux kernel
  3. *
  4. * Copyright (c) 2000 Torsten Landschoff <torsten@debian.org>
  5. * Sebastian Krahmer <krahmer@cs.uni-potsdam.de>
  6. *
  7. * License: BSD
  8. *
  9. * Redistribution and use in source and binary forms, with or without
  10. * modification, are permitted provided that the following conditions
  11. * are met:
  12. *
  13. * 1. Redistributions of source code must retain the above copyright
  14. * notice, this list of conditions and the following disclaimer.
  15. * 2. Redistributions in binary form must reproduce the above copyright
  16. * notice, this list of conditions and the following disclaimer in
  17. * the documentation and/or other materials provided with the
  18. * distribution.
  19. * 3. The names of the authors may not be used to endorse or promote
  20. * products derived from this software without specific prior
  21. * written permission.
  22. *
  23. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
  24. * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
  25. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
  26. *
  27. * Modifications: Added PACKET_MMAP support
  28. * Paolo Abeni <paolo.abeni@email.it>
  29. * Added TPACKET_V3 support
  30. * Gabor Tatarka <gabor.tatarka@ericsson.com>
  31. *
  32. * based on previous works of:
  33. * Simon Patarin <patarin@cs.unibo.it>
  34. * Phil Wood <cpw@lanl.gov>
  35. *
  36. * Monitor-mode support for mac80211 includes code taken from the iw
  37. * command; the copyright notice for that code is
  38. *
  39. * Copyright (c) 2007, 2008 Johannes Berg
  40. * Copyright (c) 2007 Andy Lutomirski
  41. * Copyright (c) 2007 Mike Kershaw
  42. * Copyright (c) 2008 Gรกbor Stefanik
  43. *
  44. * All rights reserved.
  45. *
  46. * Redistribution and use in source and binary forms, with or without
  47. * modification, are permitted provided that the following conditions
  48. * are met:
  49. * 1. Redistributions of source code must retain the above copyright
  50. * notice, this list of conditions and the following disclaimer.
  51. * 2. Redistributions in binary form must reproduce the above copyright
  52. * notice, this list of conditions and the following disclaimer in the
  53. * documentation and/or other materials provided with the distribution.
  54. * 3. The name of the author may not be used to endorse or promote products
  55. * derived from this software without specific prior written permission.
  56. *
  57. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  58. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  59. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  60. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  61. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  62. * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  63. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
  64. * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  65. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  66. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  67. * SUCH DAMAGE.
  68. */
  69. /*
  70. * Known problems with 2.0[.x] kernels:
  71. *
  72. * - The loopback device gives every packet twice; on 2.2[.x] kernels,
  73. * if we use PF_PACKET, we can filter out the transmitted version
  74. * of the packet by using data in the "sockaddr_ll" returned by
  75. * "recvfrom()", but, on 2.0[.x] kernels, we have to use
  76. * PF_INET/SOCK_PACKET, which means "recvfrom()" supplies a
  77. * "sockaddr_pkt" which doesn't give us enough information to let
  78. * us do that.
  79. *
  80. * - We have to set the interface's IFF_PROMISC flag ourselves, if
  81. * we're to run in promiscuous mode, which means we have to turn
  82. * it off ourselves when we're done; the kernel doesn't keep track
  83. * of how many sockets are listening promiscuously, which means
  84. * it won't get turned off automatically when no sockets are
  85. * listening promiscuously. We catch "pcap_close()" and, for
  86. * interfaces we put into promiscuous mode, take them out of
  87. * promiscuous mode - which isn't necessarily the right thing to
  88. * do, if another socket also requested promiscuous mode between
  89. * the time when we opened the socket and the time when we close
  90. * the socket.
  91. *
  92. * - MSG_TRUNC isn't supported, so you can't specify that "recvfrom()"
  93. * return the amount of data that you could have read, rather than
  94. * the amount that was returned, so we can't just allocate a buffer
  95. * whose size is the snapshot length and pass the snapshot length
  96. * as the byte count, and also pass MSG_TRUNC, so that the return
  97. * value tells us how long the packet was on the wire.
  98. *
  99. * This means that, if we want to get the actual size of the packet,
  100. * so we can return it in the "len" field of the packet header,
  101. * we have to read the entire packet, not just the part that fits
  102. * within the snapshot length, and thus waste CPU time copying data
  103. * from the kernel that our caller won't see.
  104. *
  105. * We have to get the actual size, and supply it in "len", because
  106. * otherwise, the IP dissector in tcpdump, for example, will complain
  107. * about "truncated-ip", as the packet will appear to have been
  108. * shorter, on the wire, than the IP header said it should have been.
  109. */
  110. #define _GNU_SOURCE
  111. #ifdef HAVE_CONFIG_H
  112. #include "config.h"
  113. #endif
  114. #include <errno.h>
  115. #include <stdio.h>
  116. #include <stdlib.h>
  117. #include <ctype.h>
  118. #include <unistd.h>
  119. #include <fcntl.h>
  120. #include <string.h>
  121. #include <limits.h>
  122. #include <sys/stat.h>
  123. #include <sys/socket.h>
  124. #include <sys/ioctl.h>
  125. #include <sys/utsname.h>
  126. #include <sys/mman.h>
  127. #include <linux/if.h>
  128. #include <linux/if_packet.h>
  129. #include <linux/sockios.h>
  130. #include <netinet/in.h>
  131. #include <linux/if_ether.h>
  132. #include <net/if_arp.h>
  133. #include <poll.h>
  134. #include <dirent.h>
  135. #include "pcap-int.h"
  136. #include "pcap/sll.h"
  137. #include "pcap/vlan.h"
  138. /*
  139. * If PF_PACKET is defined, we can use {SOCK_RAW,SOCK_DGRAM}/PF_PACKET
  140. * sockets rather than SOCK_PACKET sockets.
  141. *
  142. * To use them, we include <linux/if_packet.h> rather than
  143. * <netpacket/packet.h>; we do so because
  144. *
  145. * some Linux distributions (e.g., Slackware 4.0) have 2.2 or
  146. * later kernels and libc5, and don't provide a <netpacket/packet.h>
  147. * file;
  148. *
  149. * not all versions of glibc2 have a <netpacket/packet.h> file
  150. * that defines stuff needed for some of the 2.4-or-later-kernel
  151. * features, so if the system has a 2.4 or later kernel, we
  152. * still can't use those features.
  153. *
  154. * We're already including a number of other <linux/XXX.h> headers, and
  155. * this code is Linux-specific (no other OS has PF_PACKET sockets as
  156. * a raw packet capture mechanism), so it's not as if you gain any
  157. * useful portability by using <netpacket/packet.h>
  158. *
  159. * XXX - should we just include <linux/if_packet.h> even if PF_PACKET
  160. * isn't defined? It only defines one data structure in 2.0.x, so
  161. * it shouldn't cause any problems.
  162. */
  163. #ifdef PF_PACKET
  164. # include <linux/if_packet.h>
  165. /*
  166. * On at least some Linux distributions (for example, Red Hat 5.2),
  167. * there's no <netpacket/packet.h> file, but PF_PACKET is defined if
  168. * you include <sys/socket.h>, but <linux/if_packet.h> doesn't define
  169. * any of the PF_PACKET stuff such as "struct sockaddr_ll" or any of
  170. * the PACKET_xxx stuff.
  171. *
  172. * So we check whether PACKET_HOST is defined, and assume that we have
  173. * PF_PACKET sockets only if it is defined.
  174. */
  175. # ifdef PACKET_HOST
  176. # define HAVE_PF_PACKET_SOCKETS
  177. # ifdef PACKET_AUXDATA
  178. # define HAVE_PACKET_AUXDATA
  179. # endif /* PACKET_AUXDATA */
  180. # endif /* PACKET_HOST */
  181. /* check for memory mapped access avaibility. We assume every needed
  182. * struct is defined if the macro TPACKET_HDRLEN is defined, because it
  183. * uses many ring related structs and macros */
  184. # ifdef PCAP_SUPPORT_PACKET_RING
  185. # ifdef TPACKET_HDRLEN
  186. # define HAVE_PACKET_RING
  187. # ifdef TPACKET3_HDRLEN
  188. # define HAVE_TPACKET3
  189. # endif /* TPACKET3_HDRLEN */
  190. # ifdef TPACKET2_HDRLEN
  191. # define HAVE_TPACKET2
  192. # else /* TPACKET2_HDRLEN */
  193. # define TPACKET_V1 0 /* Old kernel with only V1, so no TPACKET_Vn defined */
  194. # endif /* TPACKET2_HDRLEN */
  195. # endif /* TPACKET_HDRLEN */
  196. # endif /* PCAP_SUPPORT_PACKET_RING */
  197. #endif /* PF_PACKET */
  198. #ifdef SO_ATTACH_FILTER
  199. #include <linux/types.h>
  200. #include <linux/filter.h>
  201. #endif
  202. #ifdef HAVE_LINUX_NET_TSTAMP_H
  203. #include <linux/net_tstamp.h>
  204. #endif
  205. #ifdef HAVE_LINUX_SOCKIOS_H
  206. #include <linux/sockios.h>
  207. #endif
  208. #ifdef HAVE_LINUX_IF_BONDING_H
  209. #include <linux/if_bonding.h>
  210. #endif
  211. /*
  212. * Got Wireless Extensions?
  213. */
  214. #ifdef HAVE_LINUX_WIRELESS_H
  215. #include <linux/wireless.h>
  216. #endif /* HAVE_LINUX_WIRELESS_H */
  217. /*
  218. * Got libnl?
  219. */
  220. #ifdef HAVE_LIBNL
  221. #include <linux/nl80211.h>
  222. #include <netlink/genl/genl.h>
  223. #include <netlink/genl/family.h>
  224. #include <netlink/genl/ctrl.h>
  225. #include <netlink/msg.h>
  226. #include <netlink/attr.h>
  227. #endif /* HAVE_LIBNL */
  228. /*
  229. * Got ethtool support?
  230. */
  231. #ifdef HAVE_LINUX_ETHTOOL_H
  232. #include <linux/ethtool.h>
  233. #endif
  234. #ifndef HAVE_SOCKLEN_T
  235. typedef int socklen_t;
  236. #endif
  237. #ifndef MSG_TRUNC
  238. /*
  239. * This is being compiled on a system that lacks MSG_TRUNC; define it
  240. * with the value it has in the 2.2 and later kernels, so that, on
  241. * those kernels, when we pass it in the flags argument to "recvfrom()"
  242. * we're passing the right value and thus get the MSG_TRUNC behavior
  243. * we want. (We don't get that behavior on 2.0[.x] kernels, because
  244. * they didn't support MSG_TRUNC.)
  245. */
  246. #define MSG_TRUNC 0x20
  247. #endif
  248. #ifndef SOL_PACKET
  249. /*
  250. * This is being compiled on a system that lacks SOL_PACKET; define it
  251. * with the value it has in the 2.2 and later kernels, so that we can
  252. * set promiscuous mode in the good modern way rather than the old
  253. * 2.0-kernel crappy way.
  254. */
  255. #define SOL_PACKET 263
  256. #endif
  257. #define MAX_LINKHEADER_SIZE 256
  258. /*
  259. * When capturing on all interfaces we use this as the buffer size.
  260. * Should be bigger then all MTUs that occur in real life.
  261. * 64kB should be enough for now.
  262. */
  263. #define BIGGER_THAN_ALL_MTUS (64*1024)
  264. /*
  265. * Private data for capturing on Linux SOCK_PACKET or PF_PACKET sockets.
  266. */
  267. struct pcap_linux {
  268. u_int packets_read; /* count of packets read with recvfrom() */
  269. long proc_dropped; /* packets reported dropped by /proc/net/dev */
  270. struct pcap_stat stat;
  271. char *device; /* device name */
  272. int filter_in_userland; /* must filter in userland */
  273. int blocks_to_filter_in_userland;
  274. int must_do_on_close; /* stuff we must do when we close */
  275. int timeout; /* timeout for buffering */
  276. int sock_packet; /* using Linux 2.0 compatible interface */
  277. int cooked; /* using SOCK_DGRAM rather than SOCK_RAW */
  278. int ifindex; /* interface index of device we're bound to */
  279. int lo_ifindex; /* interface index of the loopback device */
  280. bpf_u_int32 oldmode; /* mode to restore when turning monitor mode off */
  281. char *mondevice; /* mac80211 monitor device we created */
  282. u_char *mmapbuf; /* memory-mapped region pointer */
  283. size_t mmapbuflen; /* size of region */
  284. int vlan_offset; /* offset at which to insert vlan tags; if -1, don't insert */
  285. u_int tp_version; /* version of tpacket_hdr for mmaped ring */
  286. u_int tp_hdrlen; /* hdrlen of tpacket_hdr for mmaped ring */
  287. u_char *oneshot_buffer; /* buffer for copy of packet */
  288. #ifdef HAVE_TPACKET3
  289. unsigned char *current_packet; /* Current packet within the TPACKET_V3 block. Move to next block if NULL. */
  290. int packets_left; /* Unhandled packets left within the block from previous call to pcap_read_linux_mmap_v3 in case of TPACKET_V3. */
  291. #endif
  292. };
  293. /*
  294. * Stuff to do when we close.
  295. */
  296. #define MUST_CLEAR_PROMISC 0x00000001 /* clear promiscuous mode */
  297. #define MUST_CLEAR_RFMON 0x00000002 /* clear rfmon (monitor) mode */
  298. #define MUST_DELETE_MONIF 0x00000004 /* delete monitor-mode interface */
  299. /*
  300. * Prototypes for internal functions and methods.
  301. */
  302. static void map_arphrd_to_dlt(pcap_t *, int, int, const char *, int);
  303. #ifdef HAVE_PF_PACKET_SOCKETS
  304. static short int map_packet_type_to_sll_type(short int);
  305. #endif
  306. static int pcap_activate_linux(pcap_t *);
  307. static int activate_old(pcap_t *);
  308. static int activate_new(pcap_t *);
  309. static int activate_mmap(pcap_t *, int *);
  310. static int pcap_can_set_rfmon_linux(pcap_t *);
  311. static int pcap_read_linux(pcap_t *, int, pcap_handler, u_char *);
  312. static int pcap_read_packet(pcap_t *, pcap_handler, u_char *);
  313. static int pcap_inject_linux(pcap_t *, const void *, size_t);
  314. static int pcap_stats_linux(pcap_t *, struct pcap_stat *);
  315. static int pcap_setfilter_linux(pcap_t *, struct bpf_program *);
  316. static int pcap_setdirection_linux(pcap_t *, pcap_direction_t);
  317. static int pcap_set_datalink_linux(pcap_t *, int);
  318. static void pcap_cleanup_linux(pcap_t *);
  319. /*
  320. * This is what the header structure looks like in a 64-bit kernel;
  321. * we use this, rather than struct tpacket_hdr, if we're using
  322. * TPACKET_V1 in 32-bit code running on a 64-bit kernel.
  323. */
  324. struct tpacket_hdr_64 {
  325. uint64_t tp_status;
  326. unsigned int tp_len;
  327. unsigned int tp_snaplen;
  328. unsigned short tp_mac;
  329. unsigned short tp_net;
  330. unsigned int tp_sec;
  331. unsigned int tp_usec;
  332. };
  333. /*
  334. * We use this internally as the tpacket version for TPACKET_V1 in
  335. * 32-bit code on a 64-bit kernel.
  336. */
  337. #define TPACKET_V1_64 99
  338. union thdr {
  339. struct tpacket_hdr *h1;
  340. struct tpacket_hdr_64 *h1_64;
  341. #ifdef HAVE_TPACKET2
  342. struct tpacket2_hdr *h2;
  343. #endif
  344. #ifdef HAVE_TPACKET3
  345. struct tpacket_block_desc *h3;
  346. #endif
  347. void *raw;
  348. };
  349. #ifdef HAVE_PACKET_RING
  350. #define RING_GET_FRAME(h) (((union thdr **)h->buffer)[h->offset])
  351. static void destroy_ring(pcap_t *handle);
  352. static int create_ring(pcap_t *handle, int *status);
  353. static int prepare_tpacket_socket(pcap_t *handle);
  354. static void pcap_cleanup_linux_mmap(pcap_t *);
  355. static int pcap_read_linux_mmap_v1(pcap_t *, int, pcap_handler , u_char *);
  356. static int pcap_read_linux_mmap_v1_64(pcap_t *, int, pcap_handler , u_char *);
  357. #ifdef HAVE_TPACKET2
  358. static int pcap_read_linux_mmap_v2(pcap_t *, int, pcap_handler , u_char *);
  359. #endif
  360. #ifdef HAVE_TPACKET3
  361. static int pcap_read_linux_mmap_v3(pcap_t *, int, pcap_handler , u_char *);
  362. #endif
  363. static int pcap_setfilter_linux_mmap(pcap_t *, struct bpf_program *);
  364. static int pcap_setnonblock_mmap(pcap_t *p, int nonblock, char *errbuf);
  365. static int pcap_getnonblock_mmap(pcap_t *p, char *errbuf);
  366. static void pcap_oneshot_mmap(u_char *user, const struct pcap_pkthdr *h,
  367. const u_char *bytes);
  368. #endif
  369. #ifdef TP_STATUS_VLAN_TPID_VALID
  370. # define VLAN_TPID(hdr, hv) (((hv)->tp_vlan_tpid || ((hdr)->tp_status & TP_STATUS_VLAN_TPID_VALID)) ? (hv)->tp_vlan_tpid : ETH_P_8021Q)
  371. #else
  372. # define VLAN_TPID(hdr, hv) ETH_P_8021Q
  373. #endif
  374. /*
  375. * Wrap some ioctl calls
  376. */
  377. #ifdef HAVE_PF_PACKET_SOCKETS
  378. static int iface_get_id(int fd, const char *device, char *ebuf);
  379. #endif /* HAVE_PF_PACKET_SOCKETS */
  380. static int iface_get_mtu(int fd, const char *device, char *ebuf);
  381. static int iface_get_arptype(int fd, const char *device, char *ebuf);
  382. #ifdef HAVE_PF_PACKET_SOCKETS
  383. static int iface_bind(int fd, int ifindex, char *ebuf);
  384. #ifdef IW_MODE_MONITOR
  385. static int has_wext(int sock_fd, const char *device, char *ebuf);
  386. #endif /* IW_MODE_MONITOR */
  387. static int enter_rfmon_mode(pcap_t *handle, int sock_fd,
  388. const char *device);
  389. #endif /* HAVE_PF_PACKET_SOCKETS */
  390. #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
  391. static int iface_ethtool_get_ts_info(pcap_t *handle, char *ebuf);
  392. #endif
  393. #ifdef HAVE_PACKET_RING
  394. static int iface_get_offload(pcap_t *handle);
  395. #endif
  396. static int iface_bind_old(int fd, const char *device, char *ebuf);
  397. #ifdef SO_ATTACH_FILTER
  398. static int fix_program(pcap_t *handle, struct sock_fprog *fcode,
  399. int is_mapped);
  400. static int fix_offset(struct bpf_insn *p);
  401. static int set_kernel_filter(pcap_t *handle, struct sock_fprog *fcode);
  402. static int reset_kernel_filter(pcap_t *handle);
  403. static struct sock_filter total_insn
  404. = BPF_STMT(BPF_RET | BPF_K, 0);
  405. static struct sock_fprog total_fcode
  406. = { 1, &total_insn };
  407. #endif /* SO_ATTACH_FILTER */
  408. pcap_t *
  409. pcap_create_interface(const char *device, char *ebuf)
  410. {
  411. pcap_t *handle;
  412. handle = pcap_create_common(device, ebuf, sizeof (struct pcap_linux));
  413. if (handle == NULL)
  414. return NULL;
  415. handle->activate_op = pcap_activate_linux;
  416. handle->can_set_rfmon_op = pcap_can_set_rfmon_linux;
  417. #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
  418. /*
  419. * See what time stamp types we support.
  420. */
  421. if (iface_ethtool_get_ts_info(handle, ebuf) == -1) {
  422. free(handle);
  423. return NULL;
  424. }
  425. #endif
  426. #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
  427. /*
  428. * We claim that we support microsecond and nanosecond time
  429. * stamps.
  430. *
  431. * XXX - with adapter-supplied time stamps, can we choose
  432. * microsecond or nanosecond time stamps on arbitrary
  433. * adapters?
  434. */
  435. handle->tstamp_precision_count = 2;
  436. handle->tstamp_precision_list = malloc(2 * sizeof(u_int));
  437. if (handle->tstamp_precision_list == NULL) {
  438. snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
  439. pcap_strerror(errno));
  440. if (handle->tstamp_type_list != NULL)
  441. free(handle->tstamp_type_list);
  442. free(handle);
  443. return NULL;
  444. }
  445. handle->tstamp_precision_list[0] = PCAP_TSTAMP_PRECISION_MICRO;
  446. handle->tstamp_precision_list[1] = PCAP_TSTAMP_PRECISION_NANO;
  447. #endif /* defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS) */
  448. return handle;
  449. }
  450. #ifdef HAVE_LIBNL
  451. /*
  452. * If interface {if} is a mac80211 driver, the file
  453. * /sys/class/net/{if}/phy80211 is a symlink to
  454. * /sys/class/ieee80211/{phydev}, for some {phydev}.
  455. *
  456. * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
  457. * least, has a "wmaster0" device and a "wlan0" device; the
  458. * latter is the one with the IP address. Both show up in
  459. * "tcpdump -D" output. Capturing on the wmaster0 device
  460. * captures with 802.11 headers.
  461. *
  462. * airmon-ng searches through /sys/class/net for devices named
  463. * monN, starting with mon0; as soon as one *doesn't* exist,
  464. * it chooses that as the monitor device name. If the "iw"
  465. * command exists, it does "iw dev {if} interface add {monif}
  466. * type monitor", where {monif} is the monitor device. It
  467. * then (sigh) sleeps .1 second, and then configures the
  468. * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
  469. * is a file, it writes {mondev}, without a newline, to that file,
  470. * and again (sigh) sleeps .1 second, and then iwconfig's that
  471. * device into monitor mode and configures it up. Otherwise,
  472. * you can't do monitor mode.
  473. *
  474. * All these devices are "glued" together by having the
  475. * /sys/class/net/{device}/phy80211 links pointing to the same
  476. * place, so, given a wmaster, wlan, or mon device, you can
  477. * find the other devices by looking for devices with
  478. * the same phy80211 link.
  479. *
  480. * To turn monitor mode off, delete the monitor interface,
  481. * either with "iw dev {monif} interface del" or by sending
  482. * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
  483. *
  484. * Note: if you try to create a monitor device named "monN", and
  485. * there's already a "monN" device, it fails, as least with
  486. * the netlink interface (which is what iw uses), with a return
  487. * value of -ENFILE. (Return values are negative errnos.) We
  488. * could probably use that to find an unused device.
  489. *
  490. * Yes, you can have multiple monitor devices for a given
  491. * physical device.
  492. */
  493. /*
  494. * Is this a mac80211 device? If so, fill in the physical device path and
  495. * return 1; if not, return 0. On an error, fill in handle->errbuf and
  496. * return PCAP_ERROR.
  497. */
  498. static int
  499. get_mac80211_phydev(pcap_t *handle, const char *device, char *phydev_path,
  500. size_t phydev_max_pathlen)
  501. {
  502. char *pathstr;
  503. ssize_t bytes_read;
  504. /*
  505. * Generate the path string for the symlink to the physical device.
  506. */
  507. if (asprintf(&pathstr, "/sys/class/net/%s/phy80211", device) == -1) {
  508. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  509. "%s: Can't generate path name string for /sys/class/net device",
  510. device);
  511. return PCAP_ERROR;
  512. }
  513. bytes_read = readlink(pathstr, phydev_path, phydev_max_pathlen);
  514. if (bytes_read == -1) {
  515. if (errno == ENOENT || errno == EINVAL) {
  516. /*
  517. * Doesn't exist, or not a symlink; assume that
  518. * means it's not a mac80211 device.
  519. */
  520. free(pathstr);
  521. return 0;
  522. }
  523. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  524. "%s: Can't readlink %s: %s", device, pathstr,
  525. strerror(errno));
  526. free(pathstr);
  527. return PCAP_ERROR;
  528. }
  529. free(pathstr);
  530. phydev_path[bytes_read] = '\0';
  531. return 1;
  532. }
  533. #ifdef HAVE_LIBNL_SOCKETS
  534. #define get_nl_errmsg nl_geterror
  535. #else
  536. /* libnl 2.x compatibility code */
  537. #define nl_sock nl_handle
  538. static inline struct nl_handle *
  539. nl_socket_alloc(void)
  540. {
  541. return nl_handle_alloc();
  542. }
  543. static inline void
  544. nl_socket_free(struct nl_handle *h)
  545. {
  546. nl_handle_destroy(h);
  547. }
  548. #define get_nl_errmsg strerror
  549. static inline int
  550. __genl_ctrl_alloc_cache(struct nl_handle *h, struct nl_cache **cache)
  551. {
  552. struct nl_cache *tmp = genl_ctrl_alloc_cache(h);
  553. if (!tmp)
  554. return -ENOMEM;
  555. *cache = tmp;
  556. return 0;
  557. }
  558. #define genl_ctrl_alloc_cache __genl_ctrl_alloc_cache
  559. #endif /* !HAVE_LIBNL_SOCKETS */
  560. struct nl80211_state {
  561. struct nl_sock *nl_sock;
  562. struct nl_cache *nl_cache;
  563. struct genl_family *nl80211;
  564. };
  565. static int
  566. nl80211_init(pcap_t *handle, struct nl80211_state *state, const char *device)
  567. {
  568. int err;
  569. state->nl_sock = nl_socket_alloc();
  570. if (!state->nl_sock) {
  571. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  572. "%s: failed to allocate netlink handle", device);
  573. return PCAP_ERROR;
  574. }
  575. if (genl_connect(state->nl_sock)) {
  576. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  577. "%s: failed to connect to generic netlink", device);
  578. goto out_handle_destroy;
  579. }
  580. err = genl_ctrl_alloc_cache(state->nl_sock, &state->nl_cache);
  581. if (err < 0) {
  582. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  583. "%s: failed to allocate generic netlink cache: %s",
  584. device, get_nl_errmsg(-err));
  585. goto out_handle_destroy;
  586. }
  587. state->nl80211 = genl_ctrl_search_by_name(state->nl_cache, "nl80211");
  588. if (!state->nl80211) {
  589. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  590. "%s: nl80211 not found", device);
  591. goto out_cache_free;
  592. }
  593. return 0;
  594. out_cache_free:
  595. nl_cache_free(state->nl_cache);
  596. out_handle_destroy:
  597. nl_socket_free(state->nl_sock);
  598. return PCAP_ERROR;
  599. }
  600. static void
  601. nl80211_cleanup(struct nl80211_state *state)
  602. {
  603. genl_family_put(state->nl80211);
  604. nl_cache_free(state->nl_cache);
  605. nl_socket_free(state->nl_sock);
  606. }
  607. static int
  608. add_mon_if(pcap_t *handle, int sock_fd, struct nl80211_state *state,
  609. const char *device, const char *mondevice)
  610. {
  611. int ifindex;
  612. struct nl_msg *msg;
  613. int err;
  614. ifindex = iface_get_id(sock_fd, device, handle->errbuf);
  615. if (ifindex == -1)
  616. return PCAP_ERROR;
  617. msg = nlmsg_alloc();
  618. if (!msg) {
  619. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  620. "%s: failed to allocate netlink msg", device);
  621. return PCAP_ERROR;
  622. }
  623. genlmsg_put(msg, 0, 0, genl_family_get_id(state->nl80211), 0,
  624. 0, NL80211_CMD_NEW_INTERFACE, 0);
  625. NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
  626. NLA_PUT_STRING(msg, NL80211_ATTR_IFNAME, mondevice);
  627. NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, NL80211_IFTYPE_MONITOR);
  628. err = nl_send_auto_complete(state->nl_sock, msg);
  629. if (err < 0) {
  630. #if defined HAVE_LIBNL_NLE
  631. if (err == -NLE_FAILURE) {
  632. #else
  633. if (err == -ENFILE) {
  634. #endif
  635. /*
  636. * Device not available; our caller should just
  637. * keep trying. (libnl 2.x maps ENFILE to
  638. * NLE_FAILURE; it can also map other errors
  639. * to that, but there's not much we can do
  640. * about that.)
  641. */
  642. nlmsg_free(msg);
  643. return 0;
  644. } else {
  645. /*
  646. * Real failure, not just "that device is not
  647. * available.
  648. */
  649. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  650. "%s: nl_send_auto_complete failed adding %s interface: %s",
  651. device, mondevice, get_nl_errmsg(-err));
  652. nlmsg_free(msg);
  653. return PCAP_ERROR;
  654. }
  655. }
  656. err = nl_wait_for_ack(state->nl_sock);
  657. if (err < 0) {
  658. #if defined HAVE_LIBNL_NLE
  659. if (err == -NLE_FAILURE) {
  660. #else
  661. if (err == -ENFILE) {
  662. #endif
  663. /*
  664. * Device not available; our caller should just
  665. * keep trying. (libnl 2.x maps ENFILE to
  666. * NLE_FAILURE; it can also map other errors
  667. * to that, but there's not much we can do
  668. * about that.)
  669. */
  670. nlmsg_free(msg);
  671. return 0;
  672. } else {
  673. /*
  674. * Real failure, not just "that device is not
  675. * available.
  676. */
  677. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  678. "%s: nl_wait_for_ack failed adding %s interface: %s",
  679. device, mondevice, get_nl_errmsg(-err));
  680. nlmsg_free(msg);
  681. return PCAP_ERROR;
  682. }
  683. }
  684. /*
  685. * Success.
  686. */
  687. nlmsg_free(msg);
  688. return 1;
  689. nla_put_failure:
  690. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  691. "%s: nl_put failed adding %s interface",
  692. device, mondevice);
  693. nlmsg_free(msg);
  694. return PCAP_ERROR;
  695. }
  696. static int
  697. del_mon_if(pcap_t *handle, int sock_fd, struct nl80211_state *state,
  698. const char *device, const char *mondevice)
  699. {
  700. int ifindex;
  701. struct nl_msg *msg;
  702. int err;
  703. ifindex = iface_get_id(sock_fd, mondevice, handle->errbuf);
  704. if (ifindex == -1)
  705. return PCAP_ERROR;
  706. msg = nlmsg_alloc();
  707. if (!msg) {
  708. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  709. "%s: failed to allocate netlink msg", device);
  710. return PCAP_ERROR;
  711. }
  712. genlmsg_put(msg, 0, 0, genl_family_get_id(state->nl80211), 0,
  713. 0, NL80211_CMD_DEL_INTERFACE, 0);
  714. NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
  715. err = nl_send_auto_complete(state->nl_sock, msg);
  716. if (err < 0) {
  717. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  718. "%s: nl_send_auto_complete failed deleting %s interface: %s",
  719. device, mondevice, get_nl_errmsg(-err));
  720. nlmsg_free(msg);
  721. return PCAP_ERROR;
  722. }
  723. err = nl_wait_for_ack(state->nl_sock);
  724. if (err < 0) {
  725. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  726. "%s: nl_wait_for_ack failed adding %s interface: %s",
  727. device, mondevice, get_nl_errmsg(-err));
  728. nlmsg_free(msg);
  729. return PCAP_ERROR;
  730. }
  731. /*
  732. * Success.
  733. */
  734. nlmsg_free(msg);
  735. return 1;
  736. nla_put_failure:
  737. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  738. "%s: nl_put failed deleting %s interface",
  739. device, mondevice);
  740. nlmsg_free(msg);
  741. return PCAP_ERROR;
  742. }
  743. static int
  744. enter_rfmon_mode_mac80211(pcap_t *handle, int sock_fd, const char *device)
  745. {
  746. struct pcap_linux *handlep = handle->priv;
  747. int ret;
  748. char phydev_path[PATH_MAX+1];
  749. struct nl80211_state nlstate;
  750. struct ifreq ifr;
  751. u_int n;
  752. /*
  753. * Is this a mac80211 device?
  754. */
  755. ret = get_mac80211_phydev(handle, device, phydev_path, PATH_MAX);
  756. if (ret < 0)
  757. return ret; /* error */
  758. if (ret == 0)
  759. return 0; /* no error, but not mac80211 device */
  760. /*
  761. * XXX - is this already a monN device?
  762. * If so, we're done.
  763. * Is that determined by old Wireless Extensions ioctls?
  764. */
  765. /*
  766. * OK, it's apparently a mac80211 device.
  767. * Try to find an unused monN device for it.
  768. */
  769. ret = nl80211_init(handle, &nlstate, device);
  770. if (ret != 0)
  771. return ret;
  772. for (n = 0; n < UINT_MAX; n++) {
  773. /*
  774. * Try mon{n}.
  775. */
  776. char mondevice[3+10+1]; /* mon{UINT_MAX}\0 */
  777. snprintf(mondevice, sizeof mondevice, "mon%u", n);
  778. ret = add_mon_if(handle, sock_fd, &nlstate, device, mondevice);
  779. if (ret == 1) {
  780. handlep->mondevice = strdup(mondevice);
  781. goto added;
  782. }
  783. if (ret < 0) {
  784. /*
  785. * Hard failure. Just return ret; handle->errbuf
  786. * has already been set.
  787. */
  788. nl80211_cleanup(&nlstate);
  789. return ret;
  790. }
  791. }
  792. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  793. "%s: No free monN interfaces", device);
  794. nl80211_cleanup(&nlstate);
  795. return PCAP_ERROR;
  796. added:
  797. #if 0
  798. /*
  799. * Sleep for .1 seconds.
  800. */
  801. delay.tv_sec = 0;
  802. delay.tv_nsec = 500000000;
  803. nanosleep(&delay, NULL);
  804. #endif
  805. /*
  806. * If we haven't already done so, arrange to have
  807. * "pcap_close_all()" called when we exit.
  808. */
  809. if (!pcap_do_addexit(handle)) {
  810. /*
  811. * "atexit()" failed; don't put the interface
  812. * in rfmon mode, just give up.
  813. */
  814. return PCAP_ERROR_RFMON_NOTSUP;
  815. }
  816. /*
  817. * Now configure the monitor interface up.
  818. */
  819. memset(&ifr, 0, sizeof(ifr));
  820. strlcpy(ifr.ifr_name, handlep->mondevice, sizeof(ifr.ifr_name));
  821. if (ioctl(sock_fd, SIOCGIFFLAGS, &ifr) == -1) {
  822. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  823. "%s: Can't get flags for %s: %s", device,
  824. handlep->mondevice, strerror(errno));
  825. del_mon_if(handle, sock_fd, &nlstate, device,
  826. handlep->mondevice);
  827. nl80211_cleanup(&nlstate);
  828. return PCAP_ERROR;
  829. }
  830. ifr.ifr_flags |= IFF_UP|IFF_RUNNING;
  831. if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
  832. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  833. "%s: Can't set flags for %s: %s", device,
  834. handlep->mondevice, strerror(errno));
  835. del_mon_if(handle, sock_fd, &nlstate, device,
  836. handlep->mondevice);
  837. nl80211_cleanup(&nlstate);
  838. return PCAP_ERROR;
  839. }
  840. /*
  841. * Success. Clean up the libnl state.
  842. */
  843. nl80211_cleanup(&nlstate);
  844. /*
  845. * Note that we have to delete the monitor device when we close
  846. * the handle.
  847. */
  848. handlep->must_do_on_close |= MUST_DELETE_MONIF;
  849. /*
  850. * Add this to the list of pcaps to close when we exit.
  851. */
  852. pcap_add_to_pcaps_to_close(handle);
  853. return 1;
  854. }
  855. #endif /* HAVE_LIBNL */
  856. #ifdef IW_MODE_MONITOR
  857. /*
  858. * Bonding devices mishandle unknown ioctls; they fail with ENODEV
  859. * rather than ENOTSUP, EOPNOTSUPP, or ENOTTY, so Wireless Extensions
  860. * will fail with ENODEV if we try to do them on a bonding device,
  861. * making us return a "no such device" indication rather than just
  862. * saying "no Wireless Extensions".
  863. *
  864. * So we check for bonding devices, if we can, before trying those
  865. * ioctls, by trying a bonding device information query ioctl to see
  866. * whether it succeeds.
  867. */
  868. static int
  869. is_bonding_device(int fd, const char *device)
  870. {
  871. #if defined(BOND_INFO_QUERY_OLD) || defined(SIOCBONDINFOQUERY)
  872. struct ifreq ifr;
  873. ifbond ifb;
  874. memset(&ifr, 0, sizeof ifr);
  875. strlcpy(ifr.ifr_name, device, sizeof ifr.ifr_name);
  876. memset(&ifb, 0, sizeof ifb);
  877. ifr.ifr_data = (caddr_t)&ifb;
  878. #ifdef SIOCBONDINFOQUERY
  879. if (ioctl(fd, SIOCBONDINFOQUERY, &ifr) == 0)
  880. #else /* SIOCBONDINFOQUERY */
  881. if (ioctl(fd, BOND_INFO_QUERY_OLD, &ifr) == 0)
  882. #endif /* SIOCBONDINFOQUERY */
  883. return 1; /* success, so it's a bonding device */
  884. #endif /* defined(BOND_INFO_QUERY_OLD) || defined(SIOCBONDINFOQUERY) */
  885. return 0; /* no, it's not a bonding device */
  886. }
  887. #endif /* IW_MODE_MONITOR */
  888. static int
  889. pcap_can_set_rfmon_linux(pcap_t *handle)
  890. {
  891. #ifdef HAVE_LIBNL
  892. char phydev_path[PATH_MAX+1];
  893. int ret;
  894. #endif
  895. #ifdef IW_MODE_MONITOR
  896. int sock_fd;
  897. struct iwreq ireq;
  898. #endif
  899. if (strcmp(handle->opt.source, "any") == 0) {
  900. /*
  901. * Monitor mode makes no sense on the "any" device.
  902. */
  903. return 0;
  904. }
  905. #ifdef HAVE_LIBNL
  906. /*
  907. * Bleah. There doesn't seem to be a way to ask a mac80211
  908. * device, through libnl, whether it supports monitor mode;
  909. * we'll just check whether the device appears to be a
  910. * mac80211 device and, if so, assume the device supports
  911. * monitor mode.
  912. *
  913. * wmaster devices don't appear to support the Wireless
  914. * Extensions, but we can create a mon device for a
  915. * wmaster device, so we don't bother checking whether
  916. * a mac80211 device supports the Wireless Extensions.
  917. */
  918. ret = get_mac80211_phydev(handle, handle->opt.source, phydev_path,
  919. PATH_MAX);
  920. if (ret < 0)
  921. return ret; /* error */
  922. if (ret == 1)
  923. return 1; /* mac80211 device */
  924. #endif
  925. #ifdef IW_MODE_MONITOR
  926. /*
  927. * Bleah. There doesn't appear to be an ioctl to use to ask
  928. * whether a device supports monitor mode; we'll just do
  929. * SIOCGIWMODE and, if it succeeds, assume the device supports
  930. * monitor mode.
  931. *
  932. * Open a socket on which to attempt to get the mode.
  933. * (We assume that if we have Wireless Extensions support
  934. * we also have PF_PACKET support.)
  935. */
  936. sock_fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
  937. if (sock_fd == -1) {
  938. (void)snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  939. "socket: %s", pcap_strerror(errno));
  940. return PCAP_ERROR;
  941. }
  942. if (is_bonding_device(sock_fd, handle->opt.source)) {
  943. /* It's a bonding device, so don't even try. */
  944. close(sock_fd);
  945. return 0;
  946. }
  947. /*
  948. * Attempt to get the current mode.
  949. */
  950. strlcpy(ireq.ifr_ifrn.ifrn_name, handle->opt.source,
  951. sizeof ireq.ifr_ifrn.ifrn_name);
  952. if (ioctl(sock_fd, SIOCGIWMODE, &ireq) != -1) {
  953. /*
  954. * Well, we got the mode; assume we can set it.
  955. */
  956. close(sock_fd);
  957. return 1;
  958. }
  959. if (errno == ENODEV) {
  960. /* The device doesn't even exist. */
  961. (void)snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  962. "SIOCGIWMODE failed: %s", pcap_strerror(errno));
  963. close(sock_fd);
  964. return PCAP_ERROR_NO_SUCH_DEVICE;
  965. }
  966. close(sock_fd);
  967. #endif
  968. return 0;
  969. }
  970. /*
  971. * Grabs the number of dropped packets by the interface from /proc/net/dev.
  972. *
  973. * XXX - what about /sys/class/net/{interface name}/rx_*? There are
  974. * individual devices giving, in ASCII, various rx_ and tx_ statistics.
  975. *
  976. * Or can we get them in binary form from netlink?
  977. */
  978. static long int
  979. linux_if_drops(const char * if_name)
  980. {
  981. char buffer[512];
  982. char * bufptr;
  983. FILE * file;
  984. int field_to_convert = 3, if_name_sz = strlen(if_name);
  985. long int dropped_pkts = 0;
  986. file = fopen("/proc/net/dev", "r");
  987. if (!file)
  988. return 0;
  989. while (!dropped_pkts && fgets( buffer, sizeof(buffer), file ))
  990. {
  991. /* search for 'bytes' -- if its in there, then
  992. that means we need to grab the fourth field. otherwise
  993. grab the third field. */
  994. if (field_to_convert != 4 && strstr(buffer, "bytes"))
  995. {
  996. field_to_convert = 4;
  997. continue;
  998. }
  999. /* find iface and make sure it actually matches -- space before the name and : after it */
  1000. if ((bufptr = strstr(buffer, if_name)) &&
  1001. (bufptr == buffer || *(bufptr-1) == ' ') &&
  1002. *(bufptr + if_name_sz) == ':')
  1003. {
  1004. bufptr = bufptr + if_name_sz + 1;
  1005. /* grab the nth field from it */
  1006. while( --field_to_convert && *bufptr != '\0')
  1007. {
  1008. while (*bufptr != '\0' && *(bufptr++) == ' ');
  1009. while (*bufptr != '\0' && *(bufptr++) != ' ');
  1010. }
  1011. /* get rid of any final spaces */
  1012. while (*bufptr != '\0' && *bufptr == ' ') bufptr++;
  1013. if (*bufptr != '\0')
  1014. dropped_pkts = strtol(bufptr, NULL, 10);
  1015. break;
  1016. }
  1017. }
  1018. fclose(file);
  1019. return dropped_pkts;
  1020. }
  1021. /*
  1022. * With older kernels promiscuous mode is kind of interesting because we
  1023. * have to reset the interface before exiting. The problem can't really
  1024. * be solved without some daemon taking care of managing usage counts.
  1025. * If we put the interface into promiscuous mode, we set a flag indicating
  1026. * that we must take it out of that mode when the interface is closed,
  1027. * and, when closing the interface, if that flag is set we take it out
  1028. * of promiscuous mode.
  1029. *
  1030. * Even with newer kernels, we have the same issue with rfmon mode.
  1031. */
  1032. static void pcap_cleanup_linux( pcap_t *handle )
  1033. {
  1034. struct pcap_linux *handlep = handle->priv;
  1035. struct ifreq ifr;
  1036. #ifdef HAVE_LIBNL
  1037. struct nl80211_state nlstate;
  1038. int ret;
  1039. #endif /* HAVE_LIBNL */
  1040. #ifdef IW_MODE_MONITOR
  1041. int oldflags;
  1042. struct iwreq ireq;
  1043. #endif /* IW_MODE_MONITOR */
  1044. if (handlep->must_do_on_close != 0) {
  1045. /*
  1046. * There's something we have to do when closing this
  1047. * pcap_t.
  1048. */
  1049. if (handlep->must_do_on_close & MUST_CLEAR_PROMISC) {
  1050. /*
  1051. * We put the interface into promiscuous mode;
  1052. * take it out of promiscuous mode.
  1053. *
  1054. * XXX - if somebody else wants it in promiscuous
  1055. * mode, this code cannot know that, so it'll take
  1056. * it out of promiscuous mode. That's not fixable
  1057. * in 2.0[.x] kernels.
  1058. */
  1059. memset(&ifr, 0, sizeof(ifr));
  1060. strlcpy(ifr.ifr_name, handlep->device,
  1061. sizeof(ifr.ifr_name));
  1062. if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) == -1) {
  1063. fprintf(stderr,
  1064. "Can't restore interface %s flags (SIOCGIFFLAGS failed: %s).\n"
  1065. "Please adjust manually.\n"
  1066. "Hint: This can't happen with Linux >= 2.2.0.\n",
  1067. handlep->device, strerror(errno));
  1068. } else {
  1069. if (ifr.ifr_flags & IFF_PROMISC) {
  1070. /*
  1071. * Promiscuous mode is currently on;
  1072. * turn it off.
  1073. */
  1074. ifr.ifr_flags &= ~IFF_PROMISC;
  1075. if (ioctl(handle->fd, SIOCSIFFLAGS,
  1076. &ifr) == -1) {
  1077. fprintf(stderr,
  1078. "Can't restore interface %s flags (SIOCSIFFLAGS failed: %s).\n"
  1079. "Please adjust manually.\n"
  1080. "Hint: This can't happen with Linux >= 2.2.0.\n",
  1081. handlep->device,
  1082. strerror(errno));
  1083. }
  1084. }
  1085. }
  1086. }
  1087. #ifdef HAVE_LIBNL
  1088. if (handlep->must_do_on_close & MUST_DELETE_MONIF) {
  1089. ret = nl80211_init(handle, &nlstate, handlep->device);
  1090. if (ret >= 0) {
  1091. ret = del_mon_if(handle, handle->fd, &nlstate,
  1092. handlep->device, handlep->mondevice);
  1093. nl80211_cleanup(&nlstate);
  1094. }
  1095. if (ret < 0) {
  1096. fprintf(stderr,
  1097. "Can't delete monitor interface %s (%s).\n"
  1098. "Please delete manually.\n",
  1099. handlep->mondevice, handle->errbuf);
  1100. }
  1101. }
  1102. #endif /* HAVE_LIBNL */
  1103. #ifdef IW_MODE_MONITOR
  1104. if (handlep->must_do_on_close & MUST_CLEAR_RFMON) {
  1105. /*
  1106. * We put the interface into rfmon mode;
  1107. * take it out of rfmon mode.
  1108. *
  1109. * XXX - if somebody else wants it in rfmon
  1110. * mode, this code cannot know that, so it'll take
  1111. * it out of rfmon mode.
  1112. */
  1113. /*
  1114. * First, take the interface down if it's up;
  1115. * otherwise, we might get EBUSY.
  1116. * If we get errors, just drive on and print
  1117. * a warning if we can't restore the mode.
  1118. */
  1119. oldflags = 0;
  1120. memset(&ifr, 0, sizeof(ifr));
  1121. strlcpy(ifr.ifr_name, handlep->device,
  1122. sizeof(ifr.ifr_name));
  1123. if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) != -1) {
  1124. if (ifr.ifr_flags & IFF_UP) {
  1125. oldflags = ifr.ifr_flags;
  1126. ifr.ifr_flags &= ~IFF_UP;
  1127. if (ioctl(handle->fd, SIOCSIFFLAGS, &ifr) == -1)
  1128. oldflags = 0; /* didn't set, don't restore */
  1129. }
  1130. }
  1131. /*
  1132. * Now restore the mode.
  1133. */
  1134. strlcpy(ireq.ifr_ifrn.ifrn_name, handlep->device,
  1135. sizeof ireq.ifr_ifrn.ifrn_name);
  1136. ireq.u.mode = handlep->oldmode;
  1137. if (ioctl(handle->fd, SIOCSIWMODE, &ireq) == -1) {
  1138. /*
  1139. * Scientist, you've failed.
  1140. */
  1141. fprintf(stderr,
  1142. "Can't restore interface %s wireless mode (SIOCSIWMODE failed: %s).\n"
  1143. "Please adjust manually.\n",
  1144. handlep->device, strerror(errno));
  1145. }
  1146. /*
  1147. * Now bring the interface back up if we brought
  1148. * it down.
  1149. */
  1150. if (oldflags != 0) {
  1151. ifr.ifr_flags = oldflags;
  1152. if (ioctl(handle->fd, SIOCSIFFLAGS, &ifr) == -1) {
  1153. fprintf(stderr,
  1154. "Can't bring interface %s back up (SIOCSIFFLAGS failed: %s).\n"
  1155. "Please adjust manually.\n",
  1156. handlep->device, strerror(errno));
  1157. }
  1158. }
  1159. }
  1160. #endif /* IW_MODE_MONITOR */
  1161. /*
  1162. * Take this pcap out of the list of pcaps for which we
  1163. * have to take the interface out of some mode.
  1164. */
  1165. pcap_remove_from_pcaps_to_close(handle);
  1166. }
  1167. if (handlep->mondevice != NULL) {
  1168. free(handlep->mondevice);
  1169. handlep->mondevice = NULL;
  1170. }
  1171. if (handlep->device != NULL) {
  1172. free(handlep->device);
  1173. handlep->device = NULL;
  1174. }
  1175. pcap_cleanup_live_common(handle);
  1176. }
  1177. /*
  1178. * Get a handle for a live capture from the given device. You can
  1179. * pass NULL as device to get all packages (without link level
  1180. * information of course). If you pass 1 as promisc the interface
  1181. * will be set to promiscous mode (XXX: I think this usage should
  1182. * be deprecated and functions be added to select that later allow
  1183. * modification of that values -- Torsten).
  1184. */
  1185. static int
  1186. pcap_activate_linux(pcap_t *handle)
  1187. {
  1188. struct pcap_linux *handlep = handle->priv;
  1189. const char *device;
  1190. struct ifreq ifr;
  1191. int status = 0;
  1192. int ret;
  1193. device = handle->opt.source;
  1194. /*
  1195. * Make sure the name we were handed will fit into the ioctls we
  1196. * might perform on the device; if not, return a "No such device"
  1197. * indication, as the Linux kernel shouldn't support creating
  1198. * a device whose name won't fit into those ioctls.
  1199. *
  1200. * "Will fit" means "will fit, complete with a null terminator",
  1201. * so if the length, which does *not* include the null terminator,
  1202. * is greater than *or equal to* the size of the field into which
  1203. * we'll be copying it, that won't fit.
  1204. */
  1205. if (strlen(device) >= sizeof(ifr.ifr_name)) {
  1206. status = PCAP_ERROR_NO_SUCH_DEVICE;
  1207. goto fail;
  1208. }
  1209. handle->inject_op = pcap_inject_linux;
  1210. handle->setfilter_op = pcap_setfilter_linux;
  1211. handle->setdirection_op = pcap_setdirection_linux;
  1212. handle->set_datalink_op = pcap_set_datalink_linux;
  1213. handle->getnonblock_op = pcap_getnonblock_fd;
  1214. handle->setnonblock_op = pcap_setnonblock_fd;
  1215. handle->cleanup_op = pcap_cleanup_linux;
  1216. handle->read_op = pcap_read_linux;
  1217. handle->stats_op = pcap_stats_linux;
  1218. /*
  1219. * The "any" device is a special device which causes us not
  1220. * to bind to a particular device and thus to look at all
  1221. * devices.
  1222. */
  1223. if (strcmp(device, "any") == 0) {
  1224. if (handle->opt.promisc) {
  1225. handle->opt.promisc = 0;
  1226. /* Just a warning. */
  1227. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  1228. "Promiscuous mode not supported on the \"any\" device");
  1229. status = PCAP_WARNING_PROMISC_NOTSUP;
  1230. }
  1231. }
  1232. handlep->device = strdup(device);
  1233. if (handlep->device == NULL) {
  1234. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "strdup: %s",
  1235. pcap_strerror(errno) );
  1236. return PCAP_ERROR;
  1237. }
  1238. /* copy timeout value */
  1239. handlep->timeout = handle->opt.timeout;
  1240. /*
  1241. * If we're in promiscuous mode, then we probably want
  1242. * to see when the interface drops packets too, so get an
  1243. * initial count from /proc/net/dev
  1244. */
  1245. if (handle->opt.promisc)
  1246. handlep->proc_dropped = linux_if_drops(handlep->device);
  1247. /*
  1248. * Current Linux kernels use the protocol family PF_PACKET to
  1249. * allow direct access to all packets on the network while
  1250. * older kernels had a special socket type SOCK_PACKET to
  1251. * implement this feature.
  1252. * While this old implementation is kind of obsolete we need
  1253. * to be compatible with older kernels for a while so we are
  1254. * trying both methods with the newer method preferred.
  1255. */
  1256. ret = activate_new(handle);
  1257. if (ret < 0) {
  1258. /*
  1259. * Fatal error with the new way; just fail.
  1260. * ret has the error return; if it's PCAP_ERROR,
  1261. * handle->errbuf has been set appropriately.
  1262. */
  1263. status = ret;
  1264. goto fail;
  1265. }
  1266. if (ret == 1) {
  1267. /*
  1268. * Success.
  1269. * Try to use memory-mapped access.
  1270. */
  1271. switch (activate_mmap(handle, &status)) {
  1272. case 1:
  1273. /*
  1274. * We succeeded. status has been
  1275. * set to the status to return,
  1276. * which might be 0, or might be
  1277. * a PCAP_WARNING_ value.
  1278. */
  1279. return status;
  1280. case 0:
  1281. /*
  1282. * Kernel doesn't support it - just continue
  1283. * with non-memory-mapped access.
  1284. */
  1285. break;
  1286. case -1:
  1287. /*
  1288. * We failed to set up to use it, or the kernel
  1289. * supports it, but we failed to enable it.
  1290. * ret has been set to the error status to
  1291. * return and, if it's PCAP_ERROR, handle->errbuf
  1292. * contains the error message.
  1293. */
  1294. status = ret;
  1295. goto fail;
  1296. }
  1297. }
  1298. else if (ret == 0) {
  1299. /* Non-fatal error; try old way */
  1300. if ((ret = activate_old(handle)) != 1) {
  1301. /*
  1302. * Both methods to open the packet socket failed.
  1303. * Tidy up and report our failure (handle->errbuf
  1304. * is expected to be set by the functions above).
  1305. */
  1306. status = ret;
  1307. goto fail;
  1308. }
  1309. }
  1310. /*
  1311. * We set up the socket, but not with memory-mapped access.
  1312. */
  1313. if (handle->opt.buffer_size != 0) {
  1314. /*
  1315. * Set the socket buffer size to the specified value.
  1316. */
  1317. if (setsockopt(handle->fd, SOL_SOCKET, SO_RCVBUF,
  1318. &handle->opt.buffer_size,
  1319. sizeof(handle->opt.buffer_size)) == -1) {
  1320. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  1321. "SO_RCVBUF: %s", pcap_strerror(errno));
  1322. status = PCAP_ERROR;
  1323. goto fail;
  1324. }
  1325. }
  1326. /* Allocate the buffer */
  1327. handle->buffer = malloc(handle->bufsize + handle->offset);
  1328. if (!handle->buffer) {
  1329. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  1330. "malloc: %s", pcap_strerror(errno));
  1331. status = PCAP_ERROR;
  1332. goto fail;
  1333. }
  1334. /*
  1335. * "handle->fd" is a socket, so "select()" and "poll()"
  1336. * should work on it.
  1337. */
  1338. handle->selectable_fd = handle->fd;
  1339. return status;
  1340. fail:
  1341. pcap_cleanup_linux(handle);
  1342. return status;
  1343. }
  1344. /*
  1345. * Read at most max_packets from the capture stream and call the callback
  1346. * for each of them. Returns the number of packets handled or -1 if an
  1347. * error occured.
  1348. */
  1349. static int
  1350. pcap_read_linux(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
  1351. {
  1352. /*
  1353. * Currently, on Linux only one packet is delivered per read,
  1354. * so we don't loop.
  1355. */
  1356. return pcap_read_packet(handle, callback, user);
  1357. }
  1358. static int
  1359. pcap_set_datalink_linux(pcap_t *handle, int dlt)
  1360. {
  1361. handle->linktype = dlt;
  1362. return 0;
  1363. }
  1364. /*
  1365. * linux_check_direction()
  1366. *
  1367. * Do checks based on packet direction.
  1368. */
  1369. static inline int
  1370. linux_check_direction(const pcap_t *handle, const struct sockaddr_ll *sll)
  1371. {
  1372. struct pcap_linux *handlep = handle->priv;
  1373. if (sll->sll_pkttype == PACKET_OUTGOING) {
  1374. /*
  1375. * Outgoing packet.
  1376. * If this is from the loopback device, reject it;
  1377. * we'll see the packet as an incoming packet as well,
  1378. * and we don't want to see it twice.
  1379. */
  1380. if (sll->sll_ifindex == handlep->lo_ifindex)
  1381. return 0;
  1382. /*
  1383. * If the user only wants incoming packets, reject it.
  1384. */
  1385. if (handle->direction == PCAP_D_IN)
  1386. return 0;
  1387. } else {
  1388. /*
  1389. * Incoming packet.
  1390. * If the user only wants outgoing packets, reject it.
  1391. */
  1392. if (handle->direction == PCAP_D_OUT)
  1393. return 0;
  1394. }
  1395. return 1;
  1396. }
  1397. /*
  1398. * Read a packet from the socket calling the handler provided by
  1399. * the user. Returns the number of packets received or -1 if an
  1400. * error occured.
  1401. */
  1402. static int
  1403. pcap_read_packet(pcap_t *handle, pcap_handler callback, u_char *userdata)
  1404. {
  1405. struct pcap_linux *handlep = handle->priv;
  1406. u_char *bp;
  1407. int offset;
  1408. #ifdef HAVE_PF_PACKET_SOCKETS
  1409. struct sockaddr_ll from;
  1410. struct sll_header *hdrp;
  1411. #else
  1412. struct sockaddr from;
  1413. #endif
  1414. #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
  1415. struct iovec iov;
  1416. struct msghdr msg;
  1417. struct cmsghdr *cmsg;
  1418. union {
  1419. struct cmsghdr cmsg;
  1420. char buf[CMSG_SPACE(sizeof(struct tpacket_auxdata))];
  1421. } cmsg_buf;
  1422. #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
  1423. socklen_t fromlen;
  1424. #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
  1425. int packet_len, caplen;
  1426. struct pcap_pkthdr pcap_header;
  1427. struct bpf_aux_data aux_data;
  1428. #ifdef HAVE_PF_PACKET_SOCKETS
  1429. /*
  1430. * If this is a cooked device, leave extra room for a
  1431. * fake packet header.
  1432. */
  1433. if (handlep->cooked)
  1434. offset = SLL_HDR_LEN;
  1435. else
  1436. offset = 0;
  1437. #else
  1438. /*
  1439. * This system doesn't have PF_PACKET sockets, so it doesn't
  1440. * support cooked devices.
  1441. */
  1442. offset = 0;
  1443. #endif
  1444. /*
  1445. * Receive a single packet from the kernel.
  1446. * We ignore EINTR, as that might just be due to a signal
  1447. * being delivered - if the signal should interrupt the
  1448. * loop, the signal handler should call pcap_breakloop()
  1449. * to set handle->break_loop (we ignore it on other
  1450. * platforms as well).
  1451. * We also ignore ENETDOWN, so that we can continue to
  1452. * capture traffic if the interface goes down and comes
  1453. * back up again; comments in the kernel indicate that
  1454. * we'll just block waiting for packets if we try to
  1455. * receive from a socket that delivered ENETDOWN, and,
  1456. * if we're using a memory-mapped buffer, we won't even
  1457. * get notified of "network down" events.
  1458. */
  1459. bp = handle->buffer + handle->offset;
  1460. #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
  1461. msg.msg_name = &from;
  1462. msg.msg_namelen = sizeof(from);
  1463. msg.msg_iov = &iov;
  1464. msg.msg_iovlen = 1;
  1465. msg.msg_control = &cmsg_buf;
  1466. msg.msg_controllen = sizeof(cmsg_buf);
  1467. msg.msg_flags = 0;
  1468. iov.iov_len = handle->bufsize - offset;
  1469. iov.iov_base = bp + offset;
  1470. #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
  1471. do {
  1472. /*
  1473. * Has "pcap_breakloop()" been called?
  1474. */
  1475. if (handle->break_loop) {
  1476. /*
  1477. * Yes - clear the flag that indicates that it has,
  1478. * and return PCAP_ERROR_BREAK as an indication that
  1479. * we were told to break out of the loop.
  1480. */
  1481. handle->break_loop = 0;
  1482. return PCAP_ERROR_BREAK;
  1483. }
  1484. #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
  1485. packet_len = recvmsg(handle->fd, &msg, MSG_TRUNC);
  1486. #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
  1487. fromlen = sizeof(from);
  1488. packet_len = recvfrom(
  1489. handle->fd, bp + offset,
  1490. handle->bufsize - offset, MSG_TRUNC,
  1491. (struct sockaddr *) &from, &fromlen);
  1492. #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
  1493. } while (packet_len == -1 && errno == EINTR);
  1494. /* Check if an error occured */
  1495. if (packet_len == -1) {
  1496. switch (errno) {
  1497. case EAGAIN:
  1498. return 0; /* no packet there */
  1499. case ENETDOWN:
  1500. /*
  1501. * The device on which we're capturing went away.
  1502. *
  1503. * XXX - we should really return
  1504. * PCAP_ERROR_IFACE_NOT_UP, but pcap_dispatch()
  1505. * etc. aren't defined to return that.
  1506. */
  1507. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  1508. "The interface went down");
  1509. return PCAP_ERROR;
  1510. default:
  1511. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  1512. "recvfrom: %s", pcap_strerror(errno));
  1513. return PCAP_ERROR;
  1514. }
  1515. }
  1516. #ifdef HAVE_PF_PACKET_SOCKETS
  1517. if (!handlep->sock_packet) {
  1518. /*
  1519. * Unfortunately, there is a window between socket() and
  1520. * bind() where the kernel may queue packets from any
  1521. * interface. If we're bound to a particular interface,
  1522. * discard packets not from that interface.
  1523. *
  1524. * (If socket filters are supported, we could do the
  1525. * same thing we do when changing the filter; however,
  1526. * that won't handle packet sockets without socket
  1527. * filter support, and it's a bit more complicated.
  1528. * It would save some instructions per packet, however.)
  1529. */
  1530. if (handlep->ifindex != -1 &&
  1531. from.sll_ifindex != handlep->ifindex)
  1532. return 0;
  1533. /*
  1534. * Do checks based on packet direction.
  1535. * We can only do this if we're using PF_PACKET; the
  1536. * address returned for SOCK_PACKET is a "sockaddr_pkt"
  1537. * which lacks the relevant packet type information.
  1538. */
  1539. if (!linux_check_direction(handle, &from))
  1540. return 0;
  1541. }
  1542. #endif
  1543. #ifdef HAVE_PF_PACKET_SOCKETS
  1544. /*
  1545. * If this is a cooked device, fill in the fake packet header.
  1546. */
  1547. if (handlep->cooked) {
  1548. /*
  1549. * Add the length of the fake header to the length
  1550. * of packet data we read.
  1551. */
  1552. packet_len += SLL_HDR_LEN;
  1553. hdrp = (struct sll_header *)bp;
  1554. hdrp->sll_pkttype = map_packet_type_to_sll_type(from.sll_pkttype);
  1555. hdrp->sll_hatype = htons(from.sll_hatype);
  1556. hdrp->sll_halen = htons(from.sll_halen);
  1557. memcpy(hdrp->sll_addr, from.sll_addr,
  1558. (from.sll_halen > SLL_ADDRLEN) ?
  1559. SLL_ADDRLEN :
  1560. from.sll_halen);
  1561. hdrp->sll_protocol = from.sll_protocol;
  1562. }
  1563. #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
  1564. if (handlep->vlan_offset != -1) {
  1565. for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
  1566. struct tpacket_auxdata *aux;
  1567. unsigned int len;
  1568. struct vlan_tag *tag;
  1569. if (cmsg->cmsg_len < CMSG_LEN(sizeof(struct tpacket_auxdata)) ||
  1570. cmsg->cmsg_level != SOL_PACKET ||
  1571. cmsg->cmsg_type != PACKET_AUXDATA)
  1572. continue;
  1573. aux = (struct tpacket_auxdata *)CMSG_DATA(cmsg);
  1574. #if defined(TP_STATUS_VLAN_VALID)
  1575. if ((aux->tp_vlan_tci == 0) && !(aux->tp_status & TP_STATUS_VLAN_VALID))
  1576. #else
  1577. if (aux->tp_vlan_tci == 0) /* this is ambigious but without the
  1578. TP_STATUS_VLAN_VALID flag, there is
  1579. nothing that we can do */
  1580. #endif
  1581. continue;
  1582. len = packet_len > iov.iov_len ? iov.iov_len : packet_len;
  1583. if (len < (unsigned int) handlep->vlan_offset)
  1584. break;
  1585. bp -= VLAN_TAG_LEN;
  1586. memmove(bp, bp + VLAN_TAG_LEN, handlep->vlan_offset);
  1587. tag = (struct vlan_tag *)(bp + handlep->vlan_offset);
  1588. tag->vlan_tpid = htons(VLAN_TPID(aux, aux));
  1589. tag->vlan_tci = htons(aux->tp_vlan_tci);
  1590. /* store vlan tci to bpf_aux_data struct for userland bpf filter */
  1591. #if defined(TP_STATUS_VLAN_VALID)
  1592. aux_data.vlan_tag = htons(aux->tp_vlan_tci) & 0x0fff;
  1593. aux_data.vlan_tag_present = (aux->tp_status & TP_STATUS_VLAN_VALID);
  1594. #endif
  1595. packet_len += VLAN_TAG_LEN;
  1596. }
  1597. }
  1598. #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
  1599. #endif /* HAVE_PF_PACKET_SOCKETS */
  1600. /*
  1601. * XXX: According to the kernel source we should get the real
  1602. * packet len if calling recvfrom with MSG_TRUNC set. It does
  1603. * not seem to work here :(, but it is supported by this code
  1604. * anyway.
  1605. * To be honest the code RELIES on that feature so this is really
  1606. * broken with 2.2.x kernels.
  1607. * I spend a day to figure out what's going on and I found out
  1608. * that the following is happening:
  1609. *
  1610. * The packet comes from a random interface and the packet_rcv
  1611. * hook is called with a clone of the packet. That code inserts
  1612. * the packet into the receive queue of the packet socket.
  1613. * If a filter is attached to that socket that filter is run
  1614. * first - and there lies the problem. The default filter always
  1615. * cuts the packet at the snaplen:
  1616. *
  1617. * # tcpdump -d
  1618. * (000) ret #68
  1619. *
  1620. * So the packet filter cuts down the packet. The recvfrom call
  1621. * says "hey, it's only 68 bytes, it fits into the buffer" with
  1622. * the result that we don't get the real packet length. This
  1623. * is valid at least until kernel 2.2.17pre6.
  1624. *
  1625. * We currently handle this by making a copy of the filter
  1626. * program, fixing all "ret" instructions with non-zero
  1627. * operands to have an operand of MAXIMUM_SNAPLEN so that the
  1628. * filter doesn't truncate the packet, and supplying that modified
  1629. * filter to the kernel.
  1630. */
  1631. caplen = packet_len;
  1632. if (caplen > handle->snapshot)
  1633. caplen = handle->snapshot;
  1634. /* Run the packet filter if not using kernel filter */
  1635. if (handlep->filter_in_userland && handle->fcode.bf_insns) {
  1636. if (bpf_filter_with_aux_data(handle->fcode.bf_insns, bp,
  1637. packet_len, caplen, &aux_data) == 0) {
  1638. /* rejected by filter */
  1639. return 0;
  1640. }
  1641. }
  1642. /* Fill in our own header data */
  1643. /* get timestamp for this packet */
  1644. #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
  1645. if (handle->opt.tstamp_precision == PCAP_TSTAMP_PRECISION_NANO) {
  1646. if (ioctl(handle->fd, SIOCGSTAMPNS, &pcap_header.ts) == -1) {
  1647. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  1648. "SIOCGSTAMPNS: %s", pcap_strerror(errno));
  1649. return PCAP_ERROR;
  1650. }
  1651. } else
  1652. #endif
  1653. {
  1654. if (ioctl(handle->fd, SIOCGSTAMP, &pcap_header.ts) == -1) {
  1655. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  1656. "SIOCGSTAMP: %s", pcap_strerror(errno));
  1657. return PCAP_ERROR;
  1658. }
  1659. }
  1660. pcap_header.caplen = caplen;
  1661. pcap_header.len = packet_len;
  1662. /*
  1663. * Count the packet.
  1664. *
  1665. * Arguably, we should count them before we check the filter,
  1666. * as on many other platforms "ps_recv" counts packets
  1667. * handed to the filter rather than packets that passed
  1668. * the filter, but if filtering is done in the kernel, we
  1669. * can't get a count of packets that passed the filter,
  1670. * and that would mean the meaning of "ps_recv" wouldn't
  1671. * be the same on all Linux systems.
  1672. *
  1673. * XXX - it's not the same on all systems in any case;
  1674. * ideally, we should have a "get the statistics" call
  1675. * that supplies more counts and indicates which of them
  1676. * it supplies, so that we supply a count of packets
  1677. * handed to the filter only on platforms where that
  1678. * information is available.
  1679. *
  1680. * We count them here even if we can get the packet count
  1681. * from the kernel, as we can only determine at run time
  1682. * whether we'll be able to get it from the kernel (if
  1683. * HAVE_TPACKET_STATS isn't defined, we can't get it from
  1684. * the kernel, but if it is defined, the library might
  1685. * have been built with a 2.4 or later kernel, but we
  1686. * might be running on a 2.2[.x] kernel without Alexey
  1687. * Kuznetzov's turbopacket patches, and thus the kernel
  1688. * might not be able to supply those statistics). We
  1689. * could, I guess, try, when opening the socket, to get
  1690. * the statistics, and if we can not increment the count
  1691. * here, but it's not clear that always incrementing
  1692. * the count is more expensive than always testing a flag
  1693. * in memory.
  1694. *
  1695. * We keep the count in "handlep->packets_read", and use that
  1696. * for "ps_recv" if we can't get the statistics from the kernel.
  1697. * We do that because, if we *can* get the statistics from
  1698. * the kernel, we use "handlep->stat.ps_recv" and
  1699. * "handlep->stat.ps_drop" as running counts, as reading the
  1700. * statistics from the kernel resets the kernel statistics,
  1701. * and if we directly increment "handlep->stat.ps_recv" here,
  1702. * that means it will count packets *twice* on systems where
  1703. * we can get kernel statistics - once here, and once in
  1704. * pcap_stats_linux().
  1705. */
  1706. handlep->packets_read++;
  1707. /* Call the user supplied callback function */
  1708. callback(userdata, &pcap_header, bp);
  1709. return 1;
  1710. }
  1711. static int
  1712. pcap_inject_linux(pcap_t *handle, const void *buf, size_t size)
  1713. {
  1714. struct pcap_linux *handlep = handle->priv;
  1715. int ret;
  1716. #ifdef HAVE_PF_PACKET_SOCKETS
  1717. if (!handlep->sock_packet) {
  1718. /* PF_PACKET socket */
  1719. if (handlep->ifindex == -1) {
  1720. /*
  1721. * We don't support sending on the "any" device.
  1722. */
  1723. strlcpy(handle->errbuf,
  1724. "Sending packets isn't supported on the \"any\" device",
  1725. PCAP_ERRBUF_SIZE);
  1726. return (-1);
  1727. }
  1728. if (handlep->cooked) {
  1729. /*
  1730. * We don't support sending on the "any" device.
  1731. *
  1732. * XXX - how do you send on a bound cooked-mode
  1733. * socket?
  1734. * Is a "sendto()" required there?
  1735. */
  1736. strlcpy(handle->errbuf,
  1737. "Sending packets isn't supported in cooked mode",
  1738. PCAP_ERRBUF_SIZE);
  1739. return (-1);
  1740. }
  1741. }
  1742. #endif
  1743. ret = send(handle->fd, buf, size, 0);
  1744. if (ret == -1) {
  1745. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "send: %s",
  1746. pcap_strerror(errno));
  1747. return (-1);
  1748. }
  1749. return (ret);
  1750. }
  1751. /*
  1752. * Get the statistics for the given packet capture handle.
  1753. * Reports the number of dropped packets iff the kernel supports
  1754. * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
  1755. * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
  1756. * patches); otherwise, that information isn't available, and we lie
  1757. * and report 0 as the count of dropped packets.
  1758. */
  1759. static int
  1760. pcap_stats_linux(pcap_t *handle, struct pcap_stat *stats)
  1761. {
  1762. struct pcap_linux *handlep = handle->priv;
  1763. #ifdef HAVE_TPACKET_STATS
  1764. #ifdef HAVE_TPACKET3
  1765. /*
  1766. * For sockets using TPACKET_V1 or TPACKET_V2, the extra
  1767. * stuff at the end of a struct tpacket_stats_v3 will not
  1768. * be filled in, and we don't look at it so this is OK even
  1769. * for those sockets. In addition, the PF_PACKET socket
  1770. * code in the kernel only uses the length parameter to
  1771. * compute how much data to copy out and to indicate how
  1772. * much data was copied out, so it's OK to base it on the
  1773. * size of a struct tpacket_stats.
  1774. *
  1775. * XXX - it's probably OK, in fact, to just use a
  1776. * struct tpacket_stats for V3 sockets, as we don't
  1777. * care about the tp_freeze_q_cnt stat.
  1778. */
  1779. struct tpacket_stats_v3 kstats;
  1780. #else /* HAVE_TPACKET3 */
  1781. struct tpacket_stats kstats;
  1782. #endif /* HAVE_TPACKET3 */
  1783. socklen_t len = sizeof (struct tpacket_stats);
  1784. #endif /* HAVE_TPACKET_STATS */
  1785. long if_dropped = 0;
  1786. /*
  1787. * To fill in ps_ifdrop, we parse /proc/net/dev for the number
  1788. */
  1789. if (handle->opt.promisc)
  1790. {
  1791. if_dropped = handlep->proc_dropped;
  1792. handlep->proc_dropped = linux_if_drops(handlep->device);
  1793. handlep->stat.ps_ifdrop += (handlep->proc_dropped - if_dropped);
  1794. }
  1795. #ifdef HAVE_TPACKET_STATS
  1796. /*
  1797. * Try to get the packet counts from the kernel.
  1798. */
  1799. if (getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS,
  1800. &kstats, &len) > -1) {
  1801. /*
  1802. * On systems where the PACKET_STATISTICS "getsockopt()"
  1803. * argument is supported on PF_PACKET sockets:
  1804. *
  1805. * "ps_recv" counts only packets that *passed* the
  1806. * filter, not packets that didn't pass the filter.
  1807. * This includes packets later dropped because we
  1808. * ran out of buffer space.
  1809. *
  1810. * "ps_drop" counts packets dropped because we ran
  1811. * out of buffer space. It doesn't count packets
  1812. * dropped by the interface driver. It counts only
  1813. * packets that passed the filter.
  1814. *
  1815. * See above for ps_ifdrop.
  1816. *
  1817. * Both statistics include packets not yet read from
  1818. * the kernel by libpcap, and thus not yet seen by
  1819. * the application.
  1820. *
  1821. * In "linux/net/packet/af_packet.c", at least in the
  1822. * 2.4.9 kernel, "tp_packets" is incremented for every
  1823. * packet that passes the packet filter *and* is
  1824. * successfully queued on the socket; "tp_drops" is
  1825. * incremented for every packet dropped because there's
  1826. * not enough free space in the socket buffer.
  1827. *
  1828. * When the statistics are returned for a PACKET_STATISTICS
  1829. * "getsockopt()" call, "tp_drops" is added to "tp_packets",
  1830. * so that "tp_packets" counts all packets handed to
  1831. * the PF_PACKET socket, including packets dropped because
  1832. * there wasn't room on the socket buffer - but not
  1833. * including packets that didn't pass the filter.
  1834. *
  1835. * In the BSD BPF, the count of received packets is
  1836. * incremented for every packet handed to BPF, regardless
  1837. * of whether it passed the filter.
  1838. *
  1839. * We can't make "pcap_stats()" work the same on both
  1840. * platforms, but the best approximation is to return
  1841. * "tp_packets" as the count of packets and "tp_drops"
  1842. * as the count of drops.
  1843. *
  1844. * Keep a running total because each call to
  1845. * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
  1846. * resets the counters to zero.
  1847. */
  1848. handlep->stat.ps_recv += kstats.tp_packets;
  1849. handlep->stat.ps_drop += kstats.tp_drops;
  1850. *stats = handlep->stat;
  1851. return 0;
  1852. }
  1853. else
  1854. {
  1855. /*
  1856. * If the error was EOPNOTSUPP, fall through, so that
  1857. * if you build the library on a system with
  1858. * "struct tpacket_stats" and run it on a system
  1859. * that doesn't, it works as it does if the library
  1860. * is built on a system without "struct tpacket_stats".
  1861. */
  1862. if (errno != EOPNOTSUPP) {
  1863. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  1864. "pcap_stats: %s", pcap_strerror(errno));
  1865. return -1;
  1866. }
  1867. }
  1868. #endif
  1869. /*
  1870. * On systems where the PACKET_STATISTICS "getsockopt()" argument
  1871. * is not supported on PF_PACKET sockets:
  1872. *
  1873. * "ps_recv" counts only packets that *passed* the filter,
  1874. * not packets that didn't pass the filter. It does not
  1875. * count packets dropped because we ran out of buffer
  1876. * space.
  1877. *
  1878. * "ps_drop" is not supported.
  1879. *
  1880. * "ps_ifdrop" is supported. It will return the number
  1881. * of drops the interface reports in /proc/net/dev,
  1882. * if that is available.
  1883. *
  1884. * "ps_recv" doesn't include packets not yet read from
  1885. * the kernel by libpcap.
  1886. *
  1887. * We maintain the count of packets processed by libpcap in
  1888. * "handlep->packets_read", for reasons described in the comment
  1889. * at the end of pcap_read_packet(). We have no idea how many
  1890. * packets were dropped by the kernel buffers -- but we know
  1891. * how many the interface dropped, so we can return that.
  1892. */
  1893. stats->ps_recv = handlep->packets_read;
  1894. stats->ps_drop = 0;
  1895. stats->ps_ifdrop = handlep->stat.ps_ifdrop;
  1896. return 0;
  1897. }
  1898. static int
  1899. add_linux_if(pcap_if_t **devlistp, const char *ifname, int fd, char *errbuf)
  1900. {
  1901. const char *p;
  1902. char name[512]; /* XXX - pick a size */
  1903. char *q, *saveq;
  1904. struct ifreq ifrflags;
  1905. /*
  1906. * Get the interface name.
  1907. */
  1908. p = ifname;
  1909. q = &name[0];
  1910. while (*p != '\0' && isascii(*p) && !isspace(*p)) {
  1911. if (*p == ':') {
  1912. /*
  1913. * This could be the separator between a
  1914. * name and an alias number, or it could be
  1915. * the separator between a name with no
  1916. * alias number and the next field.
  1917. *
  1918. * If there's a colon after digits, it
  1919. * separates the name and the alias number,
  1920. * otherwise it separates the name and the
  1921. * next field.
  1922. */
  1923. saveq = q;
  1924. while (isascii(*p) && isdigit(*p))
  1925. *q++ = *p++;
  1926. if (*p != ':') {
  1927. /*
  1928. * That was the next field,
  1929. * not the alias number.
  1930. */
  1931. q = saveq;
  1932. }
  1933. break;
  1934. } else
  1935. *q++ = *p++;
  1936. }
  1937. *q = '\0';
  1938. /*
  1939. * Get the flags for this interface.
  1940. */
  1941. strlcpy(ifrflags.ifr_name, name, sizeof(ifrflags.ifr_name));
  1942. if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifrflags) < 0) {
  1943. if (errno == ENXIO || errno == ENODEV)
  1944. return (0); /* device doesn't actually exist - ignore it */
  1945. (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
  1946. "SIOCGIFFLAGS: %.*s: %s",
  1947. (int)sizeof(ifrflags.ifr_name),
  1948. ifrflags.ifr_name,
  1949. pcap_strerror(errno));
  1950. return (-1);
  1951. }
  1952. /*
  1953. * Add an entry for this interface, with no addresses.
  1954. */
  1955. if (pcap_add_if(devlistp, name, ifrflags.ifr_flags, NULL,
  1956. errbuf) == -1) {
  1957. /*
  1958. * Failure.
  1959. */
  1960. return (-1);
  1961. }
  1962. return (0);
  1963. }
  1964. /*
  1965. * Get from "/sys/class/net" all interfaces listed there; if they're
  1966. * already in the list of interfaces we have, that won't add another
  1967. * instance, but if they're not, that'll add them.
  1968. *
  1969. * We don't bother getting any addresses for them; it appears you can't
  1970. * use SIOCGIFADDR on Linux to get IPv6 addresses for interfaces, and,
  1971. * although some other types of addresses can be fetched with SIOCGIFADDR,
  1972. * we don't bother with them for now.
  1973. *
  1974. * We also don't fail if we couldn't open "/sys/class/net"; we just leave
  1975. * the list of interfaces as is, and return 0, so that we can try
  1976. * scanning /proc/net/dev.
  1977. *
  1978. * Otherwise, we return 1 if we don't get an error and -1 if we do.
  1979. */
  1980. static int
  1981. scan_sys_class_net(pcap_if_t **devlistp, char *errbuf)
  1982. {
  1983. DIR *sys_class_net_d;
  1984. int fd;
  1985. struct dirent *ent;
  1986. char subsystem_path[PATH_MAX+1];
  1987. struct stat statb;
  1988. int ret = 1;
  1989. sys_class_net_d = opendir("/sys/class/net");
  1990. if (sys_class_net_d == NULL) {
  1991. /*
  1992. * Don't fail if it doesn't exist at all.
  1993. */
  1994. if (errno == ENOENT)
  1995. return (0);
  1996. /*
  1997. * Fail if we got some other error.
  1998. */
  1999. (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
  2000. "Can't open /sys/class/net: %s", pcap_strerror(errno));
  2001. return (-1);
  2002. }
  2003. /*
  2004. * Create a socket from which to fetch interface information.
  2005. */
  2006. fd = socket(AF_INET, SOCK_DGRAM, 0);
  2007. if (fd < 0) {
  2008. (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
  2009. "socket: %s", pcap_strerror(errno));
  2010. (void)closedir(sys_class_net_d);
  2011. return (-1);
  2012. }
  2013. for (;;) {
  2014. errno = 0;
  2015. ent = readdir(sys_class_net_d);
  2016. if (ent == NULL) {
  2017. /*
  2018. * Error or EOF; if errno != 0, it's an error.
  2019. */
  2020. break;
  2021. }
  2022. /*
  2023. * Ignore "." and "..".
  2024. */
  2025. if (strcmp(ent->d_name, ".") == 0 ||
  2026. strcmp(ent->d_name, "..") == 0)
  2027. continue;
  2028. /*
  2029. * Ignore plain files; they do not have subdirectories
  2030. * and thus have no attributes.
  2031. */
  2032. if (ent->d_type == DT_REG)
  2033. continue;
  2034. /*
  2035. * Is there an "ifindex" file under that name?
  2036. * (We don't care whether it's a directory or
  2037. * a symlink; older kernels have directories
  2038. * for devices, newer kernels have symlinks to
  2039. * directories.)
  2040. */
  2041. snprintf(subsystem_path, sizeof subsystem_path,
  2042. "/sys/class/net/%s/ifindex", ent->d_name);
  2043. if (lstat(subsystem_path, &statb) != 0) {
  2044. /*
  2045. * Stat failed. Either there was an error
  2046. * other than ENOENT, and we don't know if
  2047. * this is an interface, or it's ENOENT,
  2048. * and either some part of "/sys/class/net/{if}"
  2049. * disappeared, in which case it probably means
  2050. * the interface disappeared, or there's no
  2051. * "ifindex" file, which means it's not a
  2052. * network interface.
  2053. */
  2054. continue;
  2055. }
  2056. /*
  2057. * Attempt to add the interface.
  2058. */
  2059. if (add_linux_if(devlistp, &ent->d_name[0], fd, errbuf) == -1) {
  2060. /* Fail. */
  2061. ret = -1;
  2062. break;
  2063. }
  2064. }
  2065. if (ret != -1) {
  2066. /*
  2067. * Well, we didn't fail for any other reason; did we
  2068. * fail due to an error reading the directory?
  2069. */
  2070. if (errno != 0) {
  2071. (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
  2072. "Error reading /sys/class/net: %s",
  2073. pcap_strerror(errno));
  2074. ret = -1;
  2075. }
  2076. }
  2077. (void)close(fd);
  2078. (void)closedir(sys_class_net_d);
  2079. return (ret);
  2080. }
  2081. /*
  2082. * Get from "/proc/net/dev" all interfaces listed there; if they're
  2083. * already in the list of interfaces we have, that won't add another
  2084. * instance, but if they're not, that'll add them.
  2085. *
  2086. * See comments from scan_sys_class_net().
  2087. */
  2088. static int
  2089. scan_proc_net_dev(pcap_if_t **devlistp, char *errbuf)
  2090. {
  2091. FILE *proc_net_f;
  2092. int fd;
  2093. char linebuf[512];
  2094. int linenum;
  2095. char *p;
  2096. int ret = 0;
  2097. proc_net_f = fopen("/proc/net/dev", "r");
  2098. if (proc_net_f == NULL) {
  2099. /*
  2100. * Don't fail if it doesn't exist at all.
  2101. */
  2102. if (errno == ENOENT)
  2103. return (0);
  2104. /*
  2105. * Fail if we got some other error.
  2106. */
  2107. (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
  2108. "Can't open /proc/net/dev: %s", pcap_strerror(errno));
  2109. return (-1);
  2110. }
  2111. /*
  2112. * Create a socket from which to fetch interface information.
  2113. */
  2114. fd = socket(AF_INET, SOCK_DGRAM, 0);
  2115. if (fd < 0) {
  2116. (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
  2117. "socket: %s", pcap_strerror(errno));
  2118. (void)fclose(proc_net_f);
  2119. return (-1);
  2120. }
  2121. for (linenum = 1;
  2122. fgets(linebuf, sizeof linebuf, proc_net_f) != NULL; linenum++) {
  2123. /*
  2124. * Skip the first two lines - they're headers.
  2125. */
  2126. if (linenum <= 2)
  2127. continue;
  2128. p = &linebuf[0];
  2129. /*
  2130. * Skip leading white space.
  2131. */
  2132. while (*p != '\0' && isascii(*p) && isspace(*p))
  2133. p++;
  2134. if (*p == '\0' || *p == '\n')
  2135. continue; /* blank line */
  2136. /*
  2137. * Attempt to add the interface.
  2138. */
  2139. if (add_linux_if(devlistp, p, fd, errbuf) == -1) {
  2140. /* Fail. */
  2141. ret = -1;
  2142. break;
  2143. }
  2144. }
  2145. if (ret != -1) {
  2146. /*
  2147. * Well, we didn't fail for any other reason; did we
  2148. * fail due to an error reading the file?
  2149. */
  2150. if (ferror(proc_net_f)) {
  2151. (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
  2152. "Error reading /proc/net/dev: %s",
  2153. pcap_strerror(errno));
  2154. ret = -1;
  2155. }
  2156. }
  2157. (void)close(fd);
  2158. (void)fclose(proc_net_f);
  2159. return (ret);
  2160. }
  2161. /*
  2162. * Description string for the "any" device.
  2163. */
  2164. static const char any_descr[] = "Pseudo-device that captures on all interfaces";
  2165. int
  2166. pcap_platform_finddevs(pcap_if_t **alldevsp, char *errbuf)
  2167. {
  2168. int ret;
  2169. /*
  2170. * Read "/sys/class/net", and add to the list of interfaces all
  2171. * interfaces listed there that we don't already have, because,
  2172. * on Linux, SIOCGIFCONF reports only interfaces with IPv4 addresses,
  2173. * and even getifaddrs() won't return information about
  2174. * interfaces with no addresses, so you need to read "/sys/class/net"
  2175. * to get the names of the rest of the interfaces.
  2176. */
  2177. ret = scan_sys_class_net(alldevsp, errbuf);
  2178. if (ret == -1)
  2179. return (-1); /* failed */
  2180. if (ret == 0) {
  2181. /*
  2182. * No /sys/class/net; try reading /proc/net/dev instead.
  2183. */
  2184. if (scan_proc_net_dev(alldevsp, errbuf) == -1)
  2185. return (-1);
  2186. }
  2187. /*
  2188. * Add the "any" device.
  2189. */
  2190. if (pcap_add_if(alldevsp, "any", IFF_UP|IFF_RUNNING,
  2191. any_descr, errbuf) < 0)
  2192. return (-1);
  2193. return (0);
  2194. }
  2195. /*
  2196. * Attach the given BPF code to the packet capture device.
  2197. */
  2198. static int
  2199. pcap_setfilter_linux_common(pcap_t *handle, struct bpf_program *filter,
  2200. int is_mmapped)
  2201. {
  2202. struct pcap_linux *handlep;
  2203. #ifdef SO_ATTACH_FILTER
  2204. struct sock_fprog fcode;
  2205. int can_filter_in_kernel;
  2206. int err = 0;
  2207. #endif
  2208. if (!handle)
  2209. return -1;
  2210. if (!filter) {
  2211. strlcpy(handle->errbuf, "setfilter: No filter specified",
  2212. PCAP_ERRBUF_SIZE);
  2213. return -1;
  2214. }
  2215. handlep = handle->priv;
  2216. /* Make our private copy of the filter */
  2217. if (install_bpf_program(handle, filter) < 0)
  2218. /* install_bpf_program() filled in errbuf */
  2219. return -1;
  2220. /*
  2221. * Run user level packet filter by default. Will be overriden if
  2222. * installing a kernel filter succeeds.
  2223. */
  2224. handlep->filter_in_userland = 1;
  2225. /* Install kernel level filter if possible */
  2226. #ifdef SO_ATTACH_FILTER
  2227. #ifdef USHRT_MAX
  2228. if (handle->fcode.bf_len > USHRT_MAX) {
  2229. /*
  2230. * fcode.len is an unsigned short for current kernel.
  2231. * I have yet to see BPF-Code with that much
  2232. * instructions but still it is possible. So for the
  2233. * sake of correctness I added this check.
  2234. */
  2235. fprintf(stderr, "Warning: Filter too complex for kernel\n");
  2236. fcode.len = 0;
  2237. fcode.filter = NULL;
  2238. can_filter_in_kernel = 0;
  2239. } else
  2240. #endif /* USHRT_MAX */
  2241. {
  2242. /*
  2243. * Oh joy, the Linux kernel uses struct sock_fprog instead
  2244. * of struct bpf_program and of course the length field is
  2245. * of different size. Pointed out by Sebastian
  2246. *
  2247. * Oh, and we also need to fix it up so that all "ret"
  2248. * instructions with non-zero operands have MAXIMUM_SNAPLEN
  2249. * as the operand if we're not capturing in memory-mapped
  2250. * mode, and so that, if we're in cooked mode, all memory-
  2251. * reference instructions use special magic offsets in
  2252. * references to the link-layer header and assume that the
  2253. * link-layer payload begins at 0; "fix_program()" will do
  2254. * that.
  2255. */
  2256. switch (fix_program(handle, &fcode, is_mmapped)) {
  2257. case -1:
  2258. default:
  2259. /*
  2260. * Fatal error; just quit.
  2261. * (The "default" case shouldn't happen; we
  2262. * return -1 for that reason.)
  2263. */
  2264. return -1;
  2265. case 0:
  2266. /*
  2267. * The program performed checks that we can't make
  2268. * work in the kernel.
  2269. */
  2270. can_filter_in_kernel = 0;
  2271. break;
  2272. case 1:
  2273. /*
  2274. * We have a filter that'll work in the kernel.
  2275. */
  2276. can_filter_in_kernel = 1;
  2277. break;
  2278. }
  2279. }
  2280. /*
  2281. * NOTE: at this point, we've set both the "len" and "filter"
  2282. * fields of "fcode". As of the 2.6.32.4 kernel, at least,
  2283. * those are the only members of the "sock_fprog" structure,
  2284. * so we initialize every member of that structure.
  2285. *
  2286. * If there is anything in "fcode" that is not initialized,
  2287. * it is either a field added in a later kernel, or it's
  2288. * padding.
  2289. *
  2290. * If a new field is added, this code needs to be updated
  2291. * to set it correctly.
  2292. *
  2293. * If there are no other fields, then:
  2294. *
  2295. * if the Linux kernel looks at the padding, it's
  2296. * buggy;
  2297. *
  2298. * if the Linux kernel doesn't look at the padding,
  2299. * then if some tool complains that we're passing
  2300. * uninitialized data to the kernel, then the tool
  2301. * is buggy and needs to understand that it's just
  2302. * padding.
  2303. */
  2304. if (can_filter_in_kernel) {
  2305. if ((err = set_kernel_filter(handle, &fcode)) == 0)
  2306. {
  2307. /*
  2308. * Installation succeded - using kernel filter,
  2309. * so userland filtering not needed.
  2310. */
  2311. handlep->filter_in_userland = 0;
  2312. }
  2313. else if (err == -1) /* Non-fatal error */
  2314. {
  2315. /*
  2316. * Print a warning if we weren't able to install
  2317. * the filter for a reason other than "this kernel
  2318. * isn't configured to support socket filters.
  2319. */
  2320. if (errno != ENOPROTOOPT && errno != EOPNOTSUPP) {
  2321. fprintf(stderr,
  2322. "Warning: Kernel filter failed: %s\n",
  2323. pcap_strerror(errno));
  2324. }
  2325. }
  2326. }
  2327. /*
  2328. * If we're not using the kernel filter, get rid of any kernel
  2329. * filter that might've been there before, e.g. because the
  2330. * previous filter could work in the kernel, or because some other
  2331. * code attached a filter to the socket by some means other than
  2332. * calling "pcap_setfilter()". Otherwise, the kernel filter may
  2333. * filter out packets that would pass the new userland filter.
  2334. */
  2335. if (handlep->filter_in_userland) {
  2336. if (reset_kernel_filter(handle) == -1) {
  2337. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  2338. "can't remove kernel filter: %s",
  2339. pcap_strerror(errno));
  2340. err = -2; /* fatal error */
  2341. }
  2342. }
  2343. /*
  2344. * Free up the copy of the filter that was made by "fix_program()".
  2345. */
  2346. if (fcode.filter != NULL)
  2347. free(fcode.filter);
  2348. if (err == -2)
  2349. /* Fatal error */
  2350. return -1;
  2351. #endif /* SO_ATTACH_FILTER */
  2352. return 0;
  2353. }
  2354. static int
  2355. pcap_setfilter_linux(pcap_t *handle, struct bpf_program *filter)
  2356. {
  2357. return pcap_setfilter_linux_common(handle, filter, 0);
  2358. }
  2359. /*
  2360. * Set direction flag: Which packets do we accept on a forwarding
  2361. * single device? IN, OUT or both?
  2362. */
  2363. static int
  2364. pcap_setdirection_linux(pcap_t *handle, pcap_direction_t d)
  2365. {
  2366. #ifdef HAVE_PF_PACKET_SOCKETS
  2367. struct pcap_linux *handlep = handle->priv;
  2368. if (!handlep->sock_packet) {
  2369. handle->direction = d;
  2370. return 0;
  2371. }
  2372. #endif
  2373. /*
  2374. * We're not using PF_PACKET sockets, so we can't determine
  2375. * the direction of the packet.
  2376. */
  2377. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  2378. "Setting direction is not supported on SOCK_PACKET sockets");
  2379. return -1;
  2380. }
  2381. #ifdef HAVE_PF_PACKET_SOCKETS
  2382. /*
  2383. * Map the PACKET_ value to a LINUX_SLL_ value; we
  2384. * want the same numerical value to be used in
  2385. * the link-layer header even if the numerical values
  2386. * for the PACKET_ #defines change, so that programs
  2387. * that look at the packet type field will always be
  2388. * able to handle DLT_LINUX_SLL captures.
  2389. */
  2390. static short int
  2391. map_packet_type_to_sll_type(short int sll_pkttype)
  2392. {
  2393. switch (sll_pkttype) {
  2394. case PACKET_HOST:
  2395. return htons(LINUX_SLL_HOST);
  2396. case PACKET_BROADCAST:
  2397. return htons(LINUX_SLL_BROADCAST);
  2398. case PACKET_MULTICAST:
  2399. return htons(LINUX_SLL_MULTICAST);
  2400. case PACKET_OTHERHOST:
  2401. return htons(LINUX_SLL_OTHERHOST);
  2402. case PACKET_OUTGOING:
  2403. return htons(LINUX_SLL_OUTGOING);
  2404. default:
  2405. return -1;
  2406. }
  2407. }
  2408. #endif
  2409. static int
  2410. is_wifi(int sock_fd
  2411. #ifndef IW_MODE_MONITOR
  2412. _U_
  2413. #endif
  2414. , const char *device)
  2415. {
  2416. char *pathstr;
  2417. struct stat statb;
  2418. #ifdef IW_MODE_MONITOR
  2419. char errbuf[PCAP_ERRBUF_SIZE];
  2420. #endif
  2421. /*
  2422. * See if there's a sysfs wireless directory for it.
  2423. * If so, it's a wireless interface.
  2424. */
  2425. if (asprintf(&pathstr, "/sys/class/net/%s/wireless", device) == -1) {
  2426. /*
  2427. * Just give up here.
  2428. */
  2429. return 0;
  2430. }
  2431. if (stat(pathstr, &statb) == 0) {
  2432. free(pathstr);
  2433. return 1;
  2434. }
  2435. free(pathstr);
  2436. #ifdef IW_MODE_MONITOR
  2437. /*
  2438. * OK, maybe it's not wireless, or maybe this kernel doesn't
  2439. * support sysfs. Try the wireless extensions.
  2440. */
  2441. if (has_wext(sock_fd, device, errbuf) == 1) {
  2442. /*
  2443. * It supports the wireless extensions, so it's a Wi-Fi
  2444. * device.
  2445. */
  2446. return 1;
  2447. }
  2448. #endif
  2449. return 0;
  2450. }
  2451. /*
  2452. * Linux uses the ARP hardware type to identify the type of an
  2453. * interface. pcap uses the DLT_xxx constants for this. This
  2454. * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
  2455. * constant, as arguments, and sets "handle->linktype" to the
  2456. * appropriate DLT_XXX constant and sets "handle->offset" to
  2457. * the appropriate value (to make "handle->offset" plus link-layer
  2458. * header length be a multiple of 4, so that the link-layer payload
  2459. * will be aligned on a 4-byte boundary when capturing packets).
  2460. * (If the offset isn't set here, it'll be 0; add code as appropriate
  2461. * for cases where it shouldn't be 0.)
  2462. *
  2463. * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
  2464. * in cooked mode; otherwise, we can't use cooked mode, so we have
  2465. * to pick some type that works in raw mode, or fail.
  2466. *
  2467. * Sets the link type to -1 if unable to map the type.
  2468. */
  2469. static void map_arphrd_to_dlt(pcap_t *handle, int sock_fd, int arptype,
  2470. const char *device, int cooked_ok)
  2471. {
  2472. static const char cdma_rmnet[] = "cdma_rmnet";
  2473. switch (arptype) {
  2474. case ARPHRD_ETHER:
  2475. /*
  2476. * For various annoying reasons having to do with DHCP
  2477. * software, some versions of Android give the mobile-
  2478. * phone-network interface an ARPHRD_ value of
  2479. * ARPHRD_ETHER, even though the packets supplied by
  2480. * that interface have no link-layer header, and begin
  2481. * with an IP header, so that the ARPHRD_ value should
  2482. * be ARPHRD_NONE.
  2483. *
  2484. * Detect those devices by checking the device name, and
  2485. * use DLT_RAW for them.
  2486. */
  2487. if (strncmp(device, cdma_rmnet, sizeof cdma_rmnet - 1) == 0) {
  2488. handle->linktype = DLT_RAW;
  2489. return;
  2490. }
  2491. /*
  2492. * Is this a real Ethernet device? If so, give it a
  2493. * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
  2494. * that an application can let you choose it, in case you're
  2495. * capturing DOCSIS traffic that a Cisco Cable Modem
  2496. * Termination System is putting out onto an Ethernet (it
  2497. * doesn't put an Ethernet header onto the wire, it puts raw
  2498. * DOCSIS frames out on the wire inside the low-level
  2499. * Ethernet framing).
  2500. *
  2501. * XXX - are there any other sorts of "fake Ethernet" that
  2502. * have ARPHRD_ETHER but that shouldn't offer DLT_DOCSIS as
  2503. * a Cisco CMTS won't put traffic onto it or get traffic
  2504. * bridged onto it? ISDN is handled in "activate_new()",
  2505. * as we fall back on cooked mode there, and we use
  2506. * is_wifi() to check for 802.11 devices; are there any
  2507. * others?
  2508. */
  2509. if (!is_wifi(sock_fd, device)) {
  2510. /*
  2511. * It's not a Wi-Fi device; offer DOCSIS.
  2512. */
  2513. handle->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
  2514. /*
  2515. * If that fails, just leave the list empty.
  2516. */
  2517. if (handle->dlt_list != NULL) {
  2518. handle->dlt_list[0] = DLT_EN10MB;
  2519. handle->dlt_list[1] = DLT_DOCSIS;
  2520. handle->dlt_count = 2;
  2521. }
  2522. }
  2523. /* FALLTHROUGH */
  2524. case ARPHRD_METRICOM:
  2525. case ARPHRD_LOOPBACK:
  2526. handle->linktype = DLT_EN10MB;
  2527. handle->offset = 2;
  2528. break;
  2529. case ARPHRD_EETHER:
  2530. handle->linktype = DLT_EN3MB;
  2531. break;
  2532. case ARPHRD_AX25:
  2533. handle->linktype = DLT_AX25_KISS;
  2534. break;
  2535. case ARPHRD_PRONET:
  2536. handle->linktype = DLT_PRONET;
  2537. break;
  2538. case ARPHRD_CHAOS:
  2539. handle->linktype = DLT_CHAOS;
  2540. break;
  2541. #ifndef ARPHRD_CAN
  2542. #define ARPHRD_CAN 280
  2543. #endif
  2544. case ARPHRD_CAN:
  2545. handle->linktype = DLT_CAN_SOCKETCAN;
  2546. break;
  2547. #ifndef ARPHRD_IEEE802_TR
  2548. #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
  2549. #endif
  2550. case ARPHRD_IEEE802_TR:
  2551. case ARPHRD_IEEE802:
  2552. handle->linktype = DLT_IEEE802;
  2553. handle->offset = 2;
  2554. break;
  2555. case ARPHRD_ARCNET:
  2556. handle->linktype = DLT_ARCNET_LINUX;
  2557. break;
  2558. #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
  2559. #define ARPHRD_FDDI 774
  2560. #endif
  2561. case ARPHRD_FDDI:
  2562. handle->linktype = DLT_FDDI;
  2563. handle->offset = 3;
  2564. break;
  2565. #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
  2566. #define ARPHRD_ATM 19
  2567. #endif
  2568. case ARPHRD_ATM:
  2569. /*
  2570. * The Classical IP implementation in ATM for Linux
  2571. * supports both what RFC 1483 calls "LLC Encapsulation",
  2572. * in which each packet has an LLC header, possibly
  2573. * with a SNAP header as well, prepended to it, and
  2574. * what RFC 1483 calls "VC Based Multiplexing", in which
  2575. * different virtual circuits carry different network
  2576. * layer protocols, and no header is prepended to packets.
  2577. *
  2578. * They both have an ARPHRD_ type of ARPHRD_ATM, so
  2579. * you can't use the ARPHRD_ type to find out whether
  2580. * captured packets will have an LLC header, and,
  2581. * while there's a socket ioctl to *set* the encapsulation
  2582. * type, there's no ioctl to *get* the encapsulation type.
  2583. *
  2584. * This means that
  2585. *
  2586. * programs that dissect Linux Classical IP frames
  2587. * would have to check for an LLC header and,
  2588. * depending on whether they see one or not, dissect
  2589. * the frame as LLC-encapsulated or as raw IP (I
  2590. * don't know whether there's any traffic other than
  2591. * IP that would show up on the socket, or whether
  2592. * there's any support for IPv6 in the Linux
  2593. * Classical IP code);
  2594. *
  2595. * filter expressions would have to compile into
  2596. * code that checks for an LLC header and does
  2597. * the right thing.
  2598. *
  2599. * Both of those are a nuisance - and, at least on systems
  2600. * that support PF_PACKET sockets, we don't have to put
  2601. * up with those nuisances; instead, we can just capture
  2602. * in cooked mode. That's what we'll do, if we can.
  2603. * Otherwise, we'll just fail.
  2604. */
  2605. if (cooked_ok)
  2606. handle->linktype = DLT_LINUX_SLL;
  2607. else
  2608. handle->linktype = -1;
  2609. break;
  2610. #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
  2611. #define ARPHRD_IEEE80211 801
  2612. #endif
  2613. case ARPHRD_IEEE80211:
  2614. handle->linktype = DLT_IEEE802_11;
  2615. break;
  2616. #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
  2617. #define ARPHRD_IEEE80211_PRISM 802
  2618. #endif
  2619. case ARPHRD_IEEE80211_PRISM:
  2620. handle->linktype = DLT_PRISM_HEADER;
  2621. break;
  2622. #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
  2623. #define ARPHRD_IEEE80211_RADIOTAP 803
  2624. #endif
  2625. case ARPHRD_IEEE80211_RADIOTAP:
  2626. handle->linktype = DLT_IEEE802_11_RADIO;
  2627. break;
  2628. case ARPHRD_PPP:
  2629. /*
  2630. * Some PPP code in the kernel supplies no link-layer
  2631. * header whatsoever to PF_PACKET sockets; other PPP
  2632. * code supplies PPP link-layer headers ("syncppp.c");
  2633. * some PPP code might supply random link-layer
  2634. * headers (PPP over ISDN - there's code in Ethereal,
  2635. * for example, to cope with PPP-over-ISDN captures
  2636. * with which the Ethereal developers have had to cope,
  2637. * heuristically trying to determine which of the
  2638. * oddball link-layer headers particular packets have).
  2639. *
  2640. * As such, we just punt, and run all PPP interfaces
  2641. * in cooked mode, if we can; otherwise, we just treat
  2642. * it as DLT_RAW, for now - if somebody needs to capture,
  2643. * on a 2.0[.x] kernel, on PPP devices that supply a
  2644. * link-layer header, they'll have to add code here to
  2645. * map to the appropriate DLT_ type (possibly adding a
  2646. * new DLT_ type, if necessary).
  2647. */
  2648. if (cooked_ok)
  2649. handle->linktype = DLT_LINUX_SLL;
  2650. else {
  2651. /*
  2652. * XXX - handle ISDN types here? We can't fall
  2653. * back on cooked sockets, so we'd have to
  2654. * figure out from the device name what type of
  2655. * link-layer encapsulation it's using, and map
  2656. * that to an appropriate DLT_ value, meaning
  2657. * we'd map "isdnN" devices to DLT_RAW (they
  2658. * supply raw IP packets with no link-layer
  2659. * header) and "isdY" devices to a new DLT_I4L_IP
  2660. * type that has only an Ethernet packet type as
  2661. * a link-layer header.
  2662. *
  2663. * But sometimes we seem to get random crap
  2664. * in the link-layer header when capturing on
  2665. * ISDN devices....
  2666. */
  2667. handle->linktype = DLT_RAW;
  2668. }
  2669. break;
  2670. #ifndef ARPHRD_CISCO
  2671. #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
  2672. #endif
  2673. case ARPHRD_CISCO:
  2674. handle->linktype = DLT_C_HDLC;
  2675. break;
  2676. /* Not sure if this is correct for all tunnels, but it
  2677. * works for CIPE */
  2678. case ARPHRD_TUNNEL:
  2679. #ifndef ARPHRD_SIT
  2680. #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
  2681. #endif
  2682. case ARPHRD_SIT:
  2683. case ARPHRD_CSLIP:
  2684. case ARPHRD_SLIP6:
  2685. case ARPHRD_CSLIP6:
  2686. case ARPHRD_ADAPT:
  2687. case ARPHRD_SLIP:
  2688. #ifndef ARPHRD_RAWHDLC
  2689. #define ARPHRD_RAWHDLC 518
  2690. #endif
  2691. case ARPHRD_RAWHDLC:
  2692. #ifndef ARPHRD_DLCI
  2693. #define ARPHRD_DLCI 15
  2694. #endif
  2695. case ARPHRD_DLCI:
  2696. /*
  2697. * XXX - should some of those be mapped to DLT_LINUX_SLL
  2698. * instead? Should we just map all of them to DLT_LINUX_SLL?
  2699. */
  2700. handle->linktype = DLT_RAW;
  2701. break;
  2702. #ifndef ARPHRD_FRAD
  2703. #define ARPHRD_FRAD 770
  2704. #endif
  2705. case ARPHRD_FRAD:
  2706. handle->linktype = DLT_FRELAY;
  2707. break;
  2708. case ARPHRD_LOCALTLK:
  2709. handle->linktype = DLT_LTALK;
  2710. break;
  2711. case 18:
  2712. /*
  2713. * RFC 4338 defines an encapsulation for IP and ARP
  2714. * packets that's compatible with the RFC 2625
  2715. * encapsulation, but that uses a different ARP
  2716. * hardware type and hardware addresses. That
  2717. * ARP hardware type is 18; Linux doesn't define
  2718. * any ARPHRD_ value as 18, but if it ever officially
  2719. * supports RFC 4338-style IP-over-FC, it should define
  2720. * one.
  2721. *
  2722. * For now, we map it to DLT_IP_OVER_FC, in the hopes
  2723. * that this will encourage its use in the future,
  2724. * should Linux ever officially support RFC 4338-style
  2725. * IP-over-FC.
  2726. */
  2727. handle->linktype = DLT_IP_OVER_FC;
  2728. break;
  2729. #ifndef ARPHRD_FCPP
  2730. #define ARPHRD_FCPP 784
  2731. #endif
  2732. case ARPHRD_FCPP:
  2733. #ifndef ARPHRD_FCAL
  2734. #define ARPHRD_FCAL 785
  2735. #endif
  2736. case ARPHRD_FCAL:
  2737. #ifndef ARPHRD_FCPL
  2738. #define ARPHRD_FCPL 786
  2739. #endif
  2740. case ARPHRD_FCPL:
  2741. #ifndef ARPHRD_FCFABRIC
  2742. #define ARPHRD_FCFABRIC 787
  2743. #endif
  2744. case ARPHRD_FCFABRIC:
  2745. /*
  2746. * Back in 2002, Donald Lee at Cray wanted a DLT_ for
  2747. * IP-over-FC:
  2748. *
  2749. * http://www.mail-archive.com/tcpdump-workers@sandelman.ottawa.on.ca/msg01043.html
  2750. *
  2751. * and one was assigned.
  2752. *
  2753. * In a later private discussion (spun off from a message
  2754. * on the ethereal-users list) on how to get that DLT_
  2755. * value in libpcap on Linux, I ended up deciding that
  2756. * the best thing to do would be to have him tweak the
  2757. * driver to set the ARPHRD_ value to some ARPHRD_FCxx
  2758. * type, and map all those types to DLT_IP_OVER_FC:
  2759. *
  2760. * I've checked into the libpcap and tcpdump CVS tree
  2761. * support for DLT_IP_OVER_FC. In order to use that,
  2762. * you'd have to modify your modified driver to return
  2763. * one of the ARPHRD_FCxxx types, in "fcLINUXfcp.c" -
  2764. * change it to set "dev->type" to ARPHRD_FCFABRIC, for
  2765. * example (the exact value doesn't matter, it can be
  2766. * any of ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL, or
  2767. * ARPHRD_FCFABRIC).
  2768. *
  2769. * 11 years later, Christian Svensson wanted to map
  2770. * various ARPHRD_ values to DLT_FC_2 and
  2771. * DLT_FC_2_WITH_FRAME_DELIMS for raw Fibre Channel
  2772. * frames:
  2773. *
  2774. * https://github.com/mcr/libpcap/pull/29
  2775. *
  2776. * There doesn't seem to be any network drivers that uses
  2777. * any of the ARPHRD_FC* values for IP-over-FC, and
  2778. * it's not exactly clear what the "Dummy types for non
  2779. * ARP hardware" are supposed to mean (link-layer
  2780. * header type? Physical network type?), so it's
  2781. * not exactly clear why the ARPHRD_FC* types exist
  2782. * in the first place.
  2783. *
  2784. * For now, we map them to DLT_FC_2, and provide an
  2785. * option of DLT_FC_2_WITH_FRAME_DELIMS, as well as
  2786. * DLT_IP_OVER_FC just in case there's some old
  2787. * driver out there that uses one of those types for
  2788. * IP-over-FC on which somebody wants to capture
  2789. * packets.
  2790. */
  2791. handle->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
  2792. /*
  2793. * If that fails, just leave the list empty.
  2794. */
  2795. if (handle->dlt_list != NULL) {
  2796. handle->dlt_list[0] = DLT_FC_2;
  2797. handle->dlt_list[1] = DLT_FC_2_WITH_FRAME_DELIMS;
  2798. handle->dlt_list[2] = DLT_IP_OVER_FC;
  2799. handle->dlt_count = 3;
  2800. }
  2801. handle->linktype = DLT_FC_2;
  2802. break;
  2803. #ifndef ARPHRD_IRDA
  2804. #define ARPHRD_IRDA 783
  2805. #endif
  2806. case ARPHRD_IRDA:
  2807. /* Don't expect IP packet out of this interfaces... */
  2808. handle->linktype = DLT_LINUX_IRDA;
  2809. /* We need to save packet direction for IrDA decoding,
  2810. * so let's use "Linux-cooked" mode. Jean II
  2811. *
  2812. * XXX - this is handled in activate_new(). */
  2813. //handlep->cooked = 1;
  2814. break;
  2815. /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
  2816. * is needed, please report it to <daniele@orlandi.com> */
  2817. #ifndef ARPHRD_LAPD
  2818. #define ARPHRD_LAPD 8445
  2819. #endif
  2820. case ARPHRD_LAPD:
  2821. /* Don't expect IP packet out of this interfaces... */
  2822. handle->linktype = DLT_LINUX_LAPD;
  2823. break;
  2824. #ifndef ARPHRD_NONE
  2825. #define ARPHRD_NONE 0xFFFE
  2826. #endif
  2827. case ARPHRD_NONE:
  2828. /*
  2829. * No link-layer header; packets are just IP
  2830. * packets, so use DLT_RAW.
  2831. */
  2832. handle->linktype = DLT_RAW;
  2833. break;
  2834. #ifndef ARPHRD_IEEE802154
  2835. #define ARPHRD_IEEE802154 804
  2836. #endif
  2837. case ARPHRD_IEEE802154:
  2838. handle->linktype = DLT_IEEE802_15_4_NOFCS;
  2839. break;
  2840. #ifndef ARPHRD_NETLINK
  2841. #define ARPHRD_NETLINK 824
  2842. #endif
  2843. case ARPHRD_NETLINK:
  2844. handle->linktype = DLT_NETLINK;
  2845. /*
  2846. * We need to use cooked mode, so that in sll_protocol we
  2847. * pick up the netlink protocol type such as NETLINK_ROUTE,
  2848. * NETLINK_GENERIC, NETLINK_FIB_LOOKUP, etc.
  2849. *
  2850. * XXX - this is handled in activate_new().
  2851. */
  2852. //handlep->cooked = 1;
  2853. break;
  2854. default:
  2855. handle->linktype = -1;
  2856. break;
  2857. }
  2858. }
  2859. /* ===== Functions to interface to the newer kernels ================== */
  2860. /*
  2861. * Try to open a packet socket using the new kernel PF_PACKET interface.
  2862. * Returns 1 on success, 0 on an error that means the new interface isn't
  2863. * present (so the old SOCK_PACKET interface should be tried), and a
  2864. * PCAP_ERROR_ value on an error that means that the old mechanism won't
  2865. * work either (so it shouldn't be tried).
  2866. */
  2867. static int
  2868. activate_new(pcap_t *handle)
  2869. {
  2870. #ifdef HAVE_PF_PACKET_SOCKETS
  2871. struct pcap_linux *handlep = handle->priv;
  2872. const char *device = handle->opt.source;
  2873. int is_any_device = (strcmp(device, "any") == 0);
  2874. int sock_fd = -1, arptype;
  2875. #ifdef HAVE_PACKET_AUXDATA
  2876. int val;
  2877. #endif
  2878. int err = 0;
  2879. struct packet_mreq mr;
  2880. #ifdef SO_BPF_EXTENSIONS
  2881. int bpf_extensions;
  2882. socklen_t len = sizeof(bpf_extensions);
  2883. #endif
  2884. /*
  2885. * Open a socket with protocol family packet. If the
  2886. * "any" device was specified, we open a SOCK_DGRAM
  2887. * socket for the cooked interface, otherwise we first
  2888. * try a SOCK_RAW socket for the raw interface.
  2889. */
  2890. sock_fd = is_any_device ?
  2891. socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_ALL)) :
  2892. socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
  2893. if (sock_fd == -1) {
  2894. if (errno == EINVAL || errno == EAFNOSUPPORT) {
  2895. /*
  2896. * We don't support PF_PACKET/SOCK_whatever
  2897. * sockets; try the old mechanism.
  2898. */
  2899. return 0;
  2900. }
  2901. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "socket: %s",
  2902. pcap_strerror(errno) );
  2903. if (errno == EPERM || errno == EACCES) {
  2904. /*
  2905. * You don't have permission to open the
  2906. * socket.
  2907. */
  2908. return PCAP_ERROR_PERM_DENIED;
  2909. } else {
  2910. /*
  2911. * Other error.
  2912. */
  2913. return PCAP_ERROR;
  2914. }
  2915. }
  2916. /* It seems the kernel supports the new interface. */
  2917. handlep->sock_packet = 0;
  2918. /*
  2919. * Get the interface index of the loopback device.
  2920. * If the attempt fails, don't fail, just set the
  2921. * "handlep->lo_ifindex" to -1.
  2922. *
  2923. * XXX - can there be more than one device that loops
  2924. * packets back, i.e. devices other than "lo"? If so,
  2925. * we'd need to find them all, and have an array of
  2926. * indices for them, and check all of them in
  2927. * "pcap_read_packet()".
  2928. */
  2929. handlep->lo_ifindex = iface_get_id(sock_fd, "lo", handle->errbuf);
  2930. /*
  2931. * Default value for offset to align link-layer payload
  2932. * on a 4-byte boundary.
  2933. */
  2934. handle->offset = 0;
  2935. /*
  2936. * What kind of frames do we have to deal with? Fall back
  2937. * to cooked mode if we have an unknown interface type
  2938. * or a type we know doesn't work well in raw mode.
  2939. */
  2940. if (!is_any_device) {
  2941. /* Assume for now we don't need cooked mode. */
  2942. handlep->cooked = 0;
  2943. if (handle->opt.rfmon) {
  2944. /*
  2945. * We were asked to turn on monitor mode.
  2946. * Do so before we get the link-layer type,
  2947. * because entering monitor mode could change
  2948. * the link-layer type.
  2949. */
  2950. err = enter_rfmon_mode(handle, sock_fd, device);
  2951. if (err < 0) {
  2952. /* Hard failure */
  2953. close(sock_fd);
  2954. return err;
  2955. }
  2956. if (err == 0) {
  2957. /*
  2958. * Nothing worked for turning monitor mode
  2959. * on.
  2960. */
  2961. close(sock_fd);
  2962. return PCAP_ERROR_RFMON_NOTSUP;
  2963. }
  2964. /*
  2965. * Either monitor mode has been turned on for
  2966. * the device, or we've been given a different
  2967. * device to open for monitor mode. If we've
  2968. * been given a different device, use it.
  2969. */
  2970. if (handlep->mondevice != NULL)
  2971. device = handlep->mondevice;
  2972. }
  2973. arptype = iface_get_arptype(sock_fd, device, handle->errbuf);
  2974. if (arptype < 0) {
  2975. close(sock_fd);
  2976. return arptype;
  2977. }
  2978. map_arphrd_to_dlt(handle, sock_fd, arptype, device, 1);
  2979. if (handle->linktype == -1 ||
  2980. handle->linktype == DLT_LINUX_SLL ||
  2981. handle->linktype == DLT_LINUX_IRDA ||
  2982. handle->linktype == DLT_LINUX_LAPD ||
  2983. handle->linktype == DLT_NETLINK ||
  2984. (handle->linktype == DLT_EN10MB &&
  2985. (strncmp("isdn", device, 4) == 0 ||
  2986. strncmp("isdY", device, 4) == 0))) {
  2987. /*
  2988. * Unknown interface type (-1), or a
  2989. * device we explicitly chose to run
  2990. * in cooked mode (e.g., PPP devices),
  2991. * or an ISDN device (whose link-layer
  2992. * type we can only determine by using
  2993. * APIs that may be different on different
  2994. * kernels) - reopen in cooked mode.
  2995. */
  2996. if (close(sock_fd) == -1) {
  2997. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  2998. "close: %s", pcap_strerror(errno));
  2999. return PCAP_ERROR;
  3000. }
  3001. sock_fd = socket(PF_PACKET, SOCK_DGRAM,
  3002. htons(ETH_P_ALL));
  3003. if (sock_fd == -1) {
  3004. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  3005. "socket: %s", pcap_strerror(errno));
  3006. if (errno == EPERM || errno == EACCES) {
  3007. /*
  3008. * You don't have permission to
  3009. * open the socket.
  3010. */
  3011. return PCAP_ERROR_PERM_DENIED;
  3012. } else {
  3013. /*
  3014. * Other error.
  3015. */
  3016. return PCAP_ERROR;
  3017. }
  3018. }
  3019. handlep->cooked = 1;
  3020. /*
  3021. * Get rid of any link-layer type list
  3022. * we allocated - this only supports cooked
  3023. * capture.
  3024. */
  3025. if (handle->dlt_list != NULL) {
  3026. free(handle->dlt_list);
  3027. handle->dlt_list = NULL;
  3028. handle->dlt_count = 0;
  3029. }
  3030. if (handle->linktype == -1) {
  3031. /*
  3032. * Warn that we're falling back on
  3033. * cooked mode; we may want to
  3034. * update "map_arphrd_to_dlt()"
  3035. * to handle the new type.
  3036. */
  3037. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  3038. "arptype %d not "
  3039. "supported by libpcap - "
  3040. "falling back to cooked "
  3041. "socket",
  3042. arptype);
  3043. }
  3044. /*
  3045. * IrDA capture is not a real "cooked" capture,
  3046. * it's IrLAP frames, not IP packets. The
  3047. * same applies to LAPD capture.
  3048. */
  3049. if (handle->linktype != DLT_LINUX_IRDA &&
  3050. handle->linktype != DLT_LINUX_LAPD &&
  3051. handle->linktype != DLT_NETLINK)
  3052. handle->linktype = DLT_LINUX_SLL;
  3053. }
  3054. handlep->ifindex = iface_get_id(sock_fd, device,
  3055. handle->errbuf);
  3056. if (handlep->ifindex == -1) {
  3057. close(sock_fd);
  3058. return PCAP_ERROR;
  3059. }
  3060. if ((err = iface_bind(sock_fd, handlep->ifindex,
  3061. handle->errbuf)) != 1) {
  3062. close(sock_fd);
  3063. if (err < 0)
  3064. return err;
  3065. else
  3066. return 0; /* try old mechanism */
  3067. }
  3068. } else {
  3069. /*
  3070. * The "any" device.
  3071. */
  3072. if (handle->opt.rfmon) {
  3073. /*
  3074. * It doesn't support monitor mode.
  3075. */
  3076. close(sock_fd);
  3077. return PCAP_ERROR_RFMON_NOTSUP;
  3078. }
  3079. /*
  3080. * It uses cooked mode.
  3081. */
  3082. handlep->cooked = 1;
  3083. handle->linktype = DLT_LINUX_SLL;
  3084. /*
  3085. * We're not bound to a device.
  3086. * For now, we're using this as an indication
  3087. * that we can't transmit; stop doing that only
  3088. * if we figure out how to transmit in cooked
  3089. * mode.
  3090. */
  3091. handlep->ifindex = -1;
  3092. }
  3093. /*
  3094. * Select promiscuous mode on if "promisc" is set.
  3095. *
  3096. * Do not turn allmulti mode on if we don't select
  3097. * promiscuous mode - on some devices (e.g., Orinoco
  3098. * wireless interfaces), allmulti mode isn't supported
  3099. * and the driver implements it by turning promiscuous
  3100. * mode on, and that screws up the operation of the
  3101. * card as a normal networking interface, and on no
  3102. * other platform I know of does starting a non-
  3103. * promiscuous capture affect which multicast packets
  3104. * are received by the interface.
  3105. */
  3106. /*
  3107. * Hmm, how can we set promiscuous mode on all interfaces?
  3108. * I am not sure if that is possible at all. For now, we
  3109. * silently ignore attempts to turn promiscuous mode on
  3110. * for the "any" device (so you don't have to explicitly
  3111. * disable it in programs such as tcpdump).
  3112. */
  3113. if (!is_any_device && handle->opt.promisc) {
  3114. memset(&mr, 0, sizeof(mr));
  3115. mr.mr_ifindex = handlep->ifindex;
  3116. mr.mr_type = PACKET_MR_PROMISC;
  3117. if (setsockopt(sock_fd, SOL_PACKET, PACKET_ADD_MEMBERSHIP,
  3118. &mr, sizeof(mr)) == -1) {
  3119. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  3120. "setsockopt: %s", pcap_strerror(errno));
  3121. close(sock_fd);
  3122. return PCAP_ERROR;
  3123. }
  3124. }
  3125. /* Enable auxillary data if supported and reserve room for
  3126. * reconstructing VLAN headers. */
  3127. #ifdef HAVE_PACKET_AUXDATA
  3128. val = 1;
  3129. if (setsockopt(sock_fd, SOL_PACKET, PACKET_AUXDATA, &val,
  3130. sizeof(val)) == -1 && errno != ENOPROTOOPT) {
  3131. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  3132. "setsockopt: %s", pcap_strerror(errno));
  3133. close(sock_fd);
  3134. return PCAP_ERROR;
  3135. }
  3136. handle->offset += VLAN_TAG_LEN;
  3137. #endif /* HAVE_PACKET_AUXDATA */
  3138. /*
  3139. * This is a 2.2[.x] or later kernel (we know that
  3140. * because we're not using a SOCK_PACKET socket -
  3141. * PF_PACKET is supported only in 2.2 and later
  3142. * kernels).
  3143. *
  3144. * We can safely pass "recvfrom()" a byte count
  3145. * based on the snapshot length.
  3146. *
  3147. * If we're in cooked mode, make the snapshot length
  3148. * large enough to hold a "cooked mode" header plus
  3149. * 1 byte of packet data (so we don't pass a byte
  3150. * count of 0 to "recvfrom()").
  3151. */
  3152. if (handlep->cooked) {
  3153. if (handle->snapshot < SLL_HDR_LEN + 1)
  3154. handle->snapshot = SLL_HDR_LEN + 1;
  3155. }
  3156. handle->bufsize = handle->snapshot;
  3157. /*
  3158. * Set the offset at which to insert VLAN tags.
  3159. */
  3160. switch (handle->linktype) {
  3161. case DLT_EN10MB:
  3162. handlep->vlan_offset = 2 * ETH_ALEN;
  3163. break;
  3164. case DLT_LINUX_SLL:
  3165. handlep->vlan_offset = 14;
  3166. break;
  3167. default:
  3168. handlep->vlan_offset = -1; /* unknown */
  3169. break;
  3170. }
  3171. #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
  3172. if (handle->opt.tstamp_precision == PCAP_TSTAMP_PRECISION_NANO) {
  3173. int nsec_tstamps = 1;
  3174. if (setsockopt(sock_fd, SOL_SOCKET, SO_TIMESTAMPNS, &nsec_tstamps, sizeof(nsec_tstamps)) < 0) {
  3175. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "setsockopt: unable to set SO_TIMESTAMPNS");
  3176. close(sock_fd);
  3177. return PCAP_ERROR;
  3178. }
  3179. }
  3180. #endif /* defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS) */
  3181. /*
  3182. * We've succeeded. Save the socket FD in the pcap structure.
  3183. */
  3184. handle->fd = sock_fd;
  3185. #ifdef SO_BPF_EXTENSIONS
  3186. /*
  3187. * Can we generate special code for VLAN checks?
  3188. * (XXX - what if we need the special code but it's not supported
  3189. * by the OS? Is that possible?)
  3190. */
  3191. if (getsockopt(sock_fd, SOL_SOCKET, SO_BPF_EXTENSIONS,
  3192. &bpf_extensions, &len) == 0) {
  3193. if (bpf_extensions >= SKF_AD_VLAN_TAG_PRESENT) {
  3194. /*
  3195. * Yes, we can. Request that we do so.
  3196. */
  3197. handle->bpf_codegen_flags |= BPF_SPECIAL_VLAN_HANDLING;
  3198. }
  3199. }
  3200. #endif /* SO_BPF_EXTENSIONS */
  3201. return 1;
  3202. #else /* HAVE_PF_PACKET_SOCKETS */
  3203. strlcpy(ebuf,
  3204. "New packet capturing interface not supported by build "
  3205. "environment", PCAP_ERRBUF_SIZE);
  3206. return 0;
  3207. #endif /* HAVE_PF_PACKET_SOCKETS */
  3208. }
  3209. #ifdef HAVE_PACKET_RING
  3210. /*
  3211. * Attempt to activate with memory-mapped access.
  3212. *
  3213. * On success, returns 1, and sets *status to 0 if there are no warnings
  3214. * or to a PCAP_WARNING_ code if there is a warning.
  3215. *
  3216. * On failure due to lack of support for memory-mapped capture, returns
  3217. * 0.
  3218. *
  3219. * On error, returns -1, and sets *status to the appropriate error code;
  3220. * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
  3221. */
  3222. static int
  3223. activate_mmap(pcap_t *handle, int *status)
  3224. {
  3225. struct pcap_linux *handlep = handle->priv;
  3226. int ret;
  3227. /*
  3228. * Attempt to allocate a buffer to hold the contents of one
  3229. * packet, for use by the oneshot callback.
  3230. */
  3231. handlep->oneshot_buffer = malloc(handle->snapshot);
  3232. if (handlep->oneshot_buffer == NULL) {
  3233. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  3234. "can't allocate oneshot buffer: %s",
  3235. pcap_strerror(errno));
  3236. *status = PCAP_ERROR;
  3237. return -1;
  3238. }
  3239. if (handle->opt.buffer_size == 0) {
  3240. /* by default request 2M for the ring buffer */
  3241. handle->opt.buffer_size = 2*1024*1024;
  3242. }
  3243. ret = prepare_tpacket_socket(handle);
  3244. if (ret == -1) {
  3245. free(handlep->oneshot_buffer);
  3246. *status = PCAP_ERROR;
  3247. return ret;
  3248. }
  3249. ret = create_ring(handle, status);
  3250. if (ret == 0) {
  3251. /*
  3252. * We don't support memory-mapped capture; our caller
  3253. * will fall back on reading from the socket.
  3254. */
  3255. free(handlep->oneshot_buffer);
  3256. return 0;
  3257. }
  3258. if (ret == -1) {
  3259. /*
  3260. * Error attempting to enable memory-mapped capture;
  3261. * fail. create_ring() has set *status.
  3262. */
  3263. free(handlep->oneshot_buffer);
  3264. return -1;
  3265. }
  3266. /*
  3267. * Success. *status has been set either to 0 if there are no
  3268. * warnings or to a PCAP_WARNING_ value if there is a warning.
  3269. *
  3270. * Override some defaults and inherit the other fields from
  3271. * activate_new.
  3272. * handle->offset is used to get the current position into the rx ring.
  3273. * handle->cc is used to store the ring size.
  3274. */
  3275. switch (handlep->tp_version) {
  3276. case TPACKET_V1:
  3277. handle->read_op = pcap_read_linux_mmap_v1;
  3278. break;
  3279. case TPACKET_V1_64:
  3280. handle->read_op = pcap_read_linux_mmap_v1_64;
  3281. break;
  3282. #ifdef HAVE_TPACKET2
  3283. case TPACKET_V2:
  3284. handle->read_op = pcap_read_linux_mmap_v2;
  3285. break;
  3286. #endif
  3287. #ifdef HAVE_TPACKET3
  3288. case TPACKET_V3:
  3289. handle->read_op = pcap_read_linux_mmap_v3;
  3290. break;
  3291. #endif
  3292. }
  3293. handle->cleanup_op = pcap_cleanup_linux_mmap;
  3294. handle->setfilter_op = pcap_setfilter_linux_mmap;
  3295. handle->setnonblock_op = pcap_setnonblock_mmap;
  3296. handle->getnonblock_op = pcap_getnonblock_mmap;
  3297. handle->oneshot_callback = pcap_oneshot_mmap;
  3298. handle->selectable_fd = handle->fd;
  3299. return 1;
  3300. }
  3301. #else /* HAVE_PACKET_RING */
  3302. static int
  3303. activate_mmap(pcap_t *handle _U_, int *status _U_)
  3304. {
  3305. return 0;
  3306. }
  3307. #endif /* HAVE_PACKET_RING */
  3308. #ifdef HAVE_PACKET_RING
  3309. #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
  3310. /*
  3311. * Attempt to set the socket to the specified version of the memory-mapped
  3312. * header.
  3313. *
  3314. * Return 0 if we succeed; return 1 if we fail because that version isn't
  3315. * supported; return -1 on any other error, and set handle->errbuf.
  3316. */
  3317. static int
  3318. init_tpacket(pcap_t *handle, int version, const char *version_str)
  3319. {
  3320. struct pcap_linux *handlep = handle->priv;
  3321. int val = version;
  3322. socklen_t len = sizeof(val);
  3323. /*
  3324. * Probe whether kernel supports the specified TPACKET version;
  3325. * this also gets the length of the header for that version.
  3326. */
  3327. if (getsockopt(handle->fd, SOL_PACKET, PACKET_HDRLEN, &val, &len) < 0) {
  3328. if (errno == ENOPROTOOPT || errno == EINVAL)
  3329. return 1; /* no */
  3330. /* Failed to even find out; this is a fatal error. */
  3331. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  3332. "can't get %s header len on packet socket: %s",
  3333. version_str,
  3334. pcap_strerror(errno));
  3335. return -1;
  3336. }
  3337. handlep->tp_hdrlen = val;
  3338. val = version;
  3339. if (setsockopt(handle->fd, SOL_PACKET, PACKET_VERSION, &val,
  3340. sizeof(val)) < 0) {
  3341. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  3342. "can't activate %s on packet socket: %s",
  3343. version_str,
  3344. pcap_strerror(errno));
  3345. return -1;
  3346. }
  3347. handlep->tp_version = version;
  3348. /* Reserve space for VLAN tag reconstruction */
  3349. val = VLAN_TAG_LEN;
  3350. if (setsockopt(handle->fd, SOL_PACKET, PACKET_RESERVE, &val,
  3351. sizeof(val)) < 0) {
  3352. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  3353. "can't set up reserve on packet socket: %s",
  3354. pcap_strerror(errno));
  3355. return -1;
  3356. }
  3357. return 0;
  3358. }
  3359. #endif /* defined HAVE_TPACKET2 || defined HAVE_TPACKET3 */
  3360. /*
  3361. * If the instruction set for which we're compiling has both 32-bit
  3362. * and 64-bit versions, and Linux support for the 64-bit version
  3363. * predates TPACKET_V2, define ISA_64_BIT as the .machine value
  3364. * you get from uname() for the 64-bit version. Otherwise, leave
  3365. * it undefined. (This includes ARM, which has a 64-bit version,
  3366. * but Linux support for it appeared well after TPACKET_V2 support
  3367. * did, so there should never be a case where 32-bit ARM code is
  3368. * running o a 64-bit kernel that only supports TPACKET_V1.)
  3369. *
  3370. * If we've omitted your favorite such architecture, please contribute
  3371. * a patch. (No patch is needed for architectures that are 32-bit-only
  3372. * or for which Linux has no support for 32-bit userland - or for which,
  3373. * as noted, 64-bit support appeared in Linux after TPACKET_V2 support
  3374. * did.)
  3375. */
  3376. #if defined(__i386__)
  3377. #define ISA_64_BIT "x86_64"
  3378. #elif defined(__ppc__)
  3379. #define ISA_64_BIT "ppc64"
  3380. #elif defined(__sparc__)
  3381. #define ISA_64_BIT "sparc64"
  3382. #elif defined(__s390__)
  3383. #define ISA_64_BIT "s390x"
  3384. #elif defined(__mips__)
  3385. #define ISA_64_BIT "mips64"
  3386. #elif defined(__hppa__)
  3387. #define ISA_64_BIT "parisc64"
  3388. #endif
  3389. /*
  3390. * Attempt to set the socket to version 3 of the memory-mapped header and,
  3391. * if that fails because version 3 isn't supported, attempt to fall
  3392. * back to version 2. If version 2 isn't supported, just leave it at
  3393. * version 1.
  3394. *
  3395. * Return 1 if we succeed or if we fail because neither version 2 nor 3 is
  3396. * supported; return -1 on any other error, and set handle->errbuf.
  3397. */
  3398. static int
  3399. prepare_tpacket_socket(pcap_t *handle)
  3400. {
  3401. struct pcap_linux *handlep = handle->priv;
  3402. #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
  3403. int ret;
  3404. #endif
  3405. #ifdef HAVE_TPACKET3
  3406. /*
  3407. * Try setting the version to TPACKET_V3.
  3408. *
  3409. * The only mode in which buffering is done on PF_PACKET
  3410. * sockets, so that packets might not be delivered
  3411. * immediately, is TPACKET_V3 mode.
  3412. *
  3413. * The buffering cannot be disabled in that mode, so
  3414. * if the user has requested immediate mode, we don't
  3415. * use TPACKET_V3.
  3416. */
  3417. if (!handle->opt.immediate) {
  3418. ret = init_tpacket(handle, TPACKET_V3, "TPACKET_V3");
  3419. if (ret == 0) {
  3420. /*
  3421. * Success.
  3422. */
  3423. return 1;
  3424. }
  3425. if (ret == -1) {
  3426. /*
  3427. * We failed for some reason other than "the
  3428. * kernel doesn't support TPACKET_V3".
  3429. */
  3430. return -1;
  3431. }
  3432. }
  3433. #endif /* HAVE_TPACKET3 */
  3434. #ifdef HAVE_TPACKET2
  3435. /*
  3436. * Try setting the version to TPACKET_V2.
  3437. */
  3438. ret = init_tpacket(handle, TPACKET_V2, "TPACKET_V2");
  3439. if (ret == 0) {
  3440. /*
  3441. * Success.
  3442. */
  3443. return 1;
  3444. }
  3445. if (ret == -1) {
  3446. /*
  3447. * We failed for some reason other than "the
  3448. * kernel doesn't support TPACKET_V2".
  3449. */
  3450. return -1;
  3451. }
  3452. #endif /* HAVE_TPACKET2 */
  3453. /*
  3454. * OK, we're using TPACKET_V1, as that's all the kernel supports.
  3455. */
  3456. handlep->tp_version = TPACKET_V1;
  3457. handlep->tp_hdrlen = sizeof(struct tpacket_hdr);
  3458. #ifdef ISA_64_BIT
  3459. /*
  3460. * 32-bit userspace + 64-bit kernel + TPACKET_V1 are not compatible with
  3461. * each other due to platform-dependent data type size differences.
  3462. *
  3463. * If we have a 32-bit userland and a 64-bit kernel, use an
  3464. * internally-defined TPACKET_V1_64, with which we use a 64-bit
  3465. * version of the data structures.
  3466. */
  3467. if (sizeof(long) == 4) {
  3468. /*
  3469. * This is 32-bit code.
  3470. */
  3471. struct utsname utsname;
  3472. if (uname(&utsname) == -1) {
  3473. /*
  3474. * Failed.
  3475. */
  3476. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  3477. "uname failed: %s", pcap_strerror(errno));
  3478. return -1;
  3479. }
  3480. if (strcmp(utsname.machine, ISA_64_BIT) == 0) {
  3481. /*
  3482. * uname() tells us the machine is 64-bit,
  3483. * so we presumably have a 64-bit kernel.
  3484. *
  3485. * XXX - this presumes that uname() won't lie
  3486. * in 32-bit code and claim that the machine
  3487. * has the 32-bit version of the ISA.
  3488. */
  3489. handlep->tp_version = TPACKET_V1_64;
  3490. handlep->tp_hdrlen = sizeof(struct tpacket_hdr_64);
  3491. }
  3492. }
  3493. #endif
  3494. return 1;
  3495. }
  3496. /*
  3497. * Attempt to set up memory-mapped access.
  3498. *
  3499. * On success, returns 1, and sets *status to 0 if there are no warnings
  3500. * or to a PCAP_WARNING_ code if there is a warning.
  3501. *
  3502. * On failure due to lack of support for memory-mapped capture, returns
  3503. * 0.
  3504. *
  3505. * On error, returns -1, and sets *status to the appropriate error code;
  3506. * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
  3507. */
  3508. static int
  3509. create_ring(pcap_t *handle, int *status)
  3510. {
  3511. struct pcap_linux *handlep = handle->priv;
  3512. unsigned i, j, frames_per_block;
  3513. #ifdef HAVE_TPACKET3
  3514. /*
  3515. * For sockets using TPACKET_V1 or TPACKET_V2, the extra
  3516. * stuff at the end of a struct tpacket_req3 will be
  3517. * ignored, so this is OK even for those sockets.
  3518. */
  3519. struct tpacket_req3 req;
  3520. #else
  3521. struct tpacket_req req;
  3522. #endif
  3523. socklen_t len;
  3524. unsigned int sk_type, tp_reserve, maclen, tp_hdrlen, netoff, macoff;
  3525. unsigned int frame_size;
  3526. /*
  3527. * Start out assuming no warnings or errors.
  3528. */
  3529. *status = 0;
  3530. switch (handlep->tp_version) {
  3531. case TPACKET_V1:
  3532. case TPACKET_V1_64:
  3533. #ifdef HAVE_TPACKET2
  3534. case TPACKET_V2:
  3535. #endif
  3536. /* Note that with large snapshot length (say 64K, which is
  3537. * the default for recent versions of tcpdump, the value that
  3538. * "-s 0" has given for a long time with tcpdump, and the
  3539. * default in Wireshark/TShark/dumpcap), if we use the snapshot
  3540. * length to calculate the frame length, only a few frames
  3541. * will be available in the ring even with pretty
  3542. * large ring size (and a lot of memory will be unused).
  3543. *
  3544. * Ideally, we should choose a frame length based on the
  3545. * minimum of the specified snapshot length and the maximum
  3546. * packet size. That's not as easy as it sounds; consider,
  3547. * for example, an 802.11 interface in monitor mode, where
  3548. * the frame would include a radiotap header, where the
  3549. * maximum radiotap header length is device-dependent.
  3550. *
  3551. * So, for now, we just do this for Ethernet devices, where
  3552. * there's no metadata header, and the link-layer header is
  3553. * fixed length. We can get the maximum packet size by
  3554. * adding 18, the Ethernet header length plus the CRC length
  3555. * (just in case we happen to get the CRC in the packet), to
  3556. * the MTU of the interface; we fetch the MTU in the hopes
  3557. * that it reflects support for jumbo frames. (Even if the
  3558. * interface is just being used for passive snooping, the
  3559. * driver might set the size of buffers in the receive ring
  3560. * based on the MTU, so that the MTU limits the maximum size
  3561. * of packets that we can receive.)
  3562. *
  3563. * We don't do that if segmentation/fragmentation or receive
  3564. * offload are enabled, so we don't get rudely surprised by
  3565. * "packets" bigger than the MTU. */
  3566. frame_size = handle->snapshot;
  3567. if (handle->linktype == DLT_EN10MB) {
  3568. int mtu;
  3569. int offload;
  3570. offload = iface_get_offload(handle);
  3571. if (offload == -1) {
  3572. *status = PCAP_ERROR;
  3573. return -1;
  3574. }
  3575. if (!offload) {
  3576. mtu = iface_get_mtu(handle->fd, handle->opt.source,
  3577. handle->errbuf);
  3578. if (mtu == -1) {
  3579. *status = PCAP_ERROR;
  3580. return -1;
  3581. }
  3582. if (frame_size > mtu + 18)
  3583. frame_size = mtu + 18;
  3584. }
  3585. }
  3586. /* NOTE: calculus matching those in tpacket_rcv()
  3587. * in linux-2.6/net/packet/af_packet.c
  3588. */
  3589. len = sizeof(sk_type);
  3590. if (getsockopt(handle->fd, SOL_SOCKET, SO_TYPE, &sk_type,
  3591. &len) < 0) {
  3592. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  3593. "getsockopt: %s", pcap_strerror(errno));
  3594. *status = PCAP_ERROR;
  3595. return -1;
  3596. }
  3597. #ifdef PACKET_RESERVE
  3598. len = sizeof(tp_reserve);
  3599. if (getsockopt(handle->fd, SOL_PACKET, PACKET_RESERVE,
  3600. &tp_reserve, &len) < 0) {
  3601. if (errno != ENOPROTOOPT) {
  3602. /*
  3603. * ENOPROTOOPT means "kernel doesn't support
  3604. * PACKET_RESERVE", in which case we fall back
  3605. * as best we can.
  3606. */
  3607. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  3608. "getsockopt: %s", pcap_strerror(errno));
  3609. *status = PCAP_ERROR;
  3610. return -1;
  3611. }
  3612. tp_reserve = 0; /* older kernel, reserve not supported */
  3613. }
  3614. #else
  3615. tp_reserve = 0; /* older kernel, reserve not supported */
  3616. #endif
  3617. maclen = (sk_type == SOCK_DGRAM) ? 0 : MAX_LINKHEADER_SIZE;
  3618. /* XXX: in the kernel maclen is calculated from
  3619. * LL_ALLOCATED_SPACE(dev) and vnet_hdr.hdr_len
  3620. * in: packet_snd() in linux-2.6/net/packet/af_packet.c
  3621. * then packet_alloc_skb() in linux-2.6/net/packet/af_packet.c
  3622. * then sock_alloc_send_pskb() in linux-2.6/net/core/sock.c
  3623. * but I see no way to get those sizes in userspace,
  3624. * like for instance with an ifreq ioctl();
  3625. * the best thing I've found so far is MAX_HEADER in
  3626. * the kernel part of linux-2.6/include/linux/netdevice.h
  3627. * which goes up to 128+48=176; since pcap-linux.c
  3628. * defines a MAX_LINKHEADER_SIZE of 256 which is
  3629. * greater than that, let's use it.. maybe is it even
  3630. * large enough to directly replace macoff..
  3631. */
  3632. tp_hdrlen = TPACKET_ALIGN(handlep->tp_hdrlen) + sizeof(struct sockaddr_ll) ;
  3633. netoff = TPACKET_ALIGN(tp_hdrlen + (maclen < 16 ? 16 : maclen)) + tp_reserve;
  3634. /* NOTE: AFAICS tp_reserve may break the TPACKET_ALIGN
  3635. * of netoff, which contradicts
  3636. * linux-2.6/Documentation/networking/packet_mmap.txt
  3637. * documenting that:
  3638. * "- Gap, chosen so that packet data (Start+tp_net)
  3639. * aligns to TPACKET_ALIGNMENT=16"
  3640. */
  3641. /* NOTE: in linux-2.6/include/linux/skbuff.h:
  3642. * "CPUs often take a performance hit
  3643. * when accessing unaligned memory locations"
  3644. */
  3645. macoff = netoff - maclen;
  3646. req.tp_frame_size = TPACKET_ALIGN(macoff + frame_size);
  3647. req.tp_frame_nr = handle->opt.buffer_size/req.tp_frame_size;
  3648. break;
  3649. #ifdef HAVE_TPACKET3
  3650. case TPACKET_V3:
  3651. /* The "frames" for this are actually buffers that
  3652. * contain multiple variable-sized frames.
  3653. *
  3654. * We pick a "frame" size of 128K to leave enough
  3655. * room for at least one reasonably-sized packet
  3656. * in the "frame". */
  3657. req.tp_frame_size = MAXIMUM_SNAPLEN;
  3658. req.tp_frame_nr = handle->opt.buffer_size/req.tp_frame_size;
  3659. break;
  3660. #endif
  3661. default:
  3662. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  3663. "Internal error: unknown TPACKET_ value %u",
  3664. handlep->tp_version);
  3665. *status = PCAP_ERROR;
  3666. return -1;
  3667. }
  3668. /* compute the minumum block size that will handle this frame.
  3669. * The block has to be page size aligned.
  3670. * The max block size allowed by the kernel is arch-dependent and
  3671. * it's not explicitly checked here. */
  3672. req.tp_block_size = getpagesize();
  3673. while (req.tp_block_size < req.tp_frame_size)
  3674. req.tp_block_size <<= 1;
  3675. frames_per_block = req.tp_block_size/req.tp_frame_size;
  3676. /*
  3677. * PACKET_TIMESTAMP was added after linux/net_tstamp.h was,
  3678. * so we check for PACKET_TIMESTAMP. We check for
  3679. * linux/net_tstamp.h just in case a system somehow has
  3680. * PACKET_TIMESTAMP but not linux/net_tstamp.h; that might
  3681. * be unnecessary.
  3682. *
  3683. * SIOCSHWTSTAMP was introduced in the patch that introduced
  3684. * linux/net_tstamp.h, so we don't bother checking whether
  3685. * SIOCSHWTSTAMP is defined (if your Linux system has
  3686. * linux/net_tstamp.h but doesn't define SIOCSHWTSTAMP, your
  3687. * Linux system is badly broken).
  3688. */
  3689. #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
  3690. /*
  3691. * If we were told to do so, ask the kernel and the driver
  3692. * to use hardware timestamps.
  3693. *
  3694. * Hardware timestamps are only supported with mmapped
  3695. * captures.
  3696. */
  3697. if (handle->opt.tstamp_type == PCAP_TSTAMP_ADAPTER ||
  3698. handle->opt.tstamp_type == PCAP_TSTAMP_ADAPTER_UNSYNCED) {
  3699. struct hwtstamp_config hwconfig;
  3700. struct ifreq ifr;
  3701. int timesource;
  3702. /*
  3703. * Ask for hardware time stamps on all packets,
  3704. * including transmitted packets.
  3705. */
  3706. memset(&hwconfig, 0, sizeof(hwconfig));
  3707. hwconfig.tx_type = HWTSTAMP_TX_ON;
  3708. hwconfig.rx_filter = HWTSTAMP_FILTER_ALL;
  3709. memset(&ifr, 0, sizeof(ifr));
  3710. strlcpy(ifr.ifr_name, handle->opt.source, sizeof(ifr.ifr_name));
  3711. ifr.ifr_data = (void *)&hwconfig;
  3712. if (ioctl(handle->fd, SIOCSHWTSTAMP, &ifr) < 0) {
  3713. switch (errno) {
  3714. case EPERM:
  3715. /*
  3716. * Treat this as an error, as the
  3717. * user should try to run this
  3718. * with the appropriate privileges -
  3719. * and, if they can't, shouldn't
  3720. * try requesting hardware time stamps.
  3721. */
  3722. *status = PCAP_ERROR_PERM_DENIED;
  3723. return -1;
  3724. case EOPNOTSUPP:
  3725. /*
  3726. * Treat this as a warning, as the
  3727. * only way to fix the warning is to
  3728. * get an adapter that supports hardware
  3729. * time stamps. We'll just fall back
  3730. * on the standard host time stamps.
  3731. */
  3732. *status = PCAP_WARNING_TSTAMP_TYPE_NOTSUP;
  3733. break;
  3734. default:
  3735. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  3736. "SIOCSHWTSTAMP failed: %s",
  3737. pcap_strerror(errno));
  3738. *status = PCAP_ERROR;
  3739. return -1;
  3740. }
  3741. } else {
  3742. /*
  3743. * Well, that worked. Now specify the type of
  3744. * hardware time stamp we want for this
  3745. * socket.
  3746. */
  3747. if (handle->opt.tstamp_type == PCAP_TSTAMP_ADAPTER) {
  3748. /*
  3749. * Hardware timestamp, synchronized
  3750. * with the system clock.
  3751. */
  3752. timesource = SOF_TIMESTAMPING_SYS_HARDWARE;
  3753. } else {
  3754. /*
  3755. * PCAP_TSTAMP_ADAPTER_UNSYNCED - hardware
  3756. * timestamp, not synchronized with the
  3757. * system clock.
  3758. */
  3759. timesource = SOF_TIMESTAMPING_RAW_HARDWARE;
  3760. }
  3761. if (setsockopt(handle->fd, SOL_PACKET, PACKET_TIMESTAMP,
  3762. (void *)&timesource, sizeof(timesource))) {
  3763. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  3764. "can't set PACKET_TIMESTAMP: %s",
  3765. pcap_strerror(errno));
  3766. *status = PCAP_ERROR;
  3767. return -1;
  3768. }
  3769. }
  3770. }
  3771. #endif /* HAVE_LINUX_NET_TSTAMP_H && PACKET_TIMESTAMP */
  3772. /* ask the kernel to create the ring */
  3773. retry:
  3774. req.tp_block_nr = req.tp_frame_nr / frames_per_block;
  3775. /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
  3776. req.tp_frame_nr = req.tp_block_nr * frames_per_block;
  3777. #ifdef HAVE_TPACKET3
  3778. /* timeout value to retire block - use the configured buffering timeout, or default if <0. */
  3779. req.tp_retire_blk_tov = (handlep->timeout>=0)?handlep->timeout:0;
  3780. /* private data not used */
  3781. req.tp_sizeof_priv = 0;
  3782. /* Rx ring - feature request bits - none (rxhash will not be filled) */
  3783. req.tp_feature_req_word = 0;
  3784. #endif
  3785. if (setsockopt(handle->fd, SOL_PACKET, PACKET_RX_RING,
  3786. (void *) &req, sizeof(req))) {
  3787. if ((errno == ENOMEM) && (req.tp_block_nr > 1)) {
  3788. /*
  3789. * Memory failure; try to reduce the requested ring
  3790. * size.
  3791. *
  3792. * We used to reduce this by half -- do 5% instead.
  3793. * That may result in more iterations and a longer
  3794. * startup, but the user will be much happier with
  3795. * the resulting buffer size.
  3796. */
  3797. if (req.tp_frame_nr < 20)
  3798. req.tp_frame_nr -= 1;
  3799. else
  3800. req.tp_frame_nr -= req.tp_frame_nr/20;
  3801. goto retry;
  3802. }
  3803. if (errno == ENOPROTOOPT) {
  3804. /*
  3805. * We don't have ring buffer support in this kernel.
  3806. */
  3807. return 0;
  3808. }
  3809. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  3810. "can't create rx ring on packet socket: %s",
  3811. pcap_strerror(errno));
  3812. *status = PCAP_ERROR;
  3813. return -1;
  3814. }
  3815. /* memory map the rx ring */
  3816. handlep->mmapbuflen = req.tp_block_nr * req.tp_block_size;
  3817. handlep->mmapbuf = mmap(0, handlep->mmapbuflen,
  3818. PROT_READ|PROT_WRITE, MAP_SHARED, handle->fd, 0);
  3819. if (handlep->mmapbuf == MAP_FAILED) {
  3820. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  3821. "can't mmap rx ring: %s", pcap_strerror(errno));
  3822. /* clear the allocated ring on error*/
  3823. destroy_ring(handle);
  3824. *status = PCAP_ERROR;
  3825. return -1;
  3826. }
  3827. /* allocate a ring for each frame header pointer*/
  3828. handle->cc = req.tp_frame_nr;
  3829. handle->buffer = malloc(handle->cc * sizeof(union thdr *));
  3830. if (!handle->buffer) {
  3831. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  3832. "can't allocate ring of frame headers: %s",
  3833. pcap_strerror(errno));
  3834. destroy_ring(handle);
  3835. *status = PCAP_ERROR;
  3836. return -1;
  3837. }
  3838. /* fill the header ring with proper frame ptr*/
  3839. handle->offset = 0;
  3840. for (i=0; i<req.tp_block_nr; ++i) {
  3841. void *base = &handlep->mmapbuf[i*req.tp_block_size];
  3842. for (j=0; j<frames_per_block; ++j, ++handle->offset) {
  3843. RING_GET_FRAME(handle) = base;
  3844. base += req.tp_frame_size;
  3845. }
  3846. }
  3847. handle->bufsize = req.tp_frame_size;
  3848. handle->offset = 0;
  3849. return 1;
  3850. }
  3851. /* free all ring related resources*/
  3852. static void
  3853. destroy_ring(pcap_t *handle)
  3854. {
  3855. struct pcap_linux *handlep = handle->priv;
  3856. /* tell the kernel to destroy the ring*/
  3857. struct tpacket_req req;
  3858. memset(&req, 0, sizeof(req));
  3859. /* do not test for setsockopt failure, as we can't recover from any error */
  3860. (void)setsockopt(handle->fd, SOL_PACKET, PACKET_RX_RING,
  3861. (void *) &req, sizeof(req));
  3862. /* if ring is mapped, unmap it*/
  3863. if (handlep->mmapbuf) {
  3864. /* do not test for mmap failure, as we can't recover from any error */
  3865. (void)munmap(handlep->mmapbuf, handlep->mmapbuflen);
  3866. handlep->mmapbuf = NULL;
  3867. }
  3868. }
  3869. /*
  3870. * Special one-shot callback, used for pcap_next() and pcap_next_ex(),
  3871. * for Linux mmapped capture.
  3872. *
  3873. * The problem is that pcap_next() and pcap_next_ex() expect the packet
  3874. * data handed to the callback to be valid after the callback returns,
  3875. * but pcap_read_linux_mmap() has to release that packet as soon as
  3876. * the callback returns (otherwise, the kernel thinks there's still
  3877. * at least one unprocessed packet available in the ring, so a select()
  3878. * will immediately return indicating that there's data to process), so,
  3879. * in the callback, we have to make a copy of the packet.
  3880. *
  3881. * Yes, this means that, if the capture is using the ring buffer, using
  3882. * pcap_next() or pcap_next_ex() requires more copies than using
  3883. * pcap_loop() or pcap_dispatch(). If that bothers you, don't use
  3884. * pcap_next() or pcap_next_ex().
  3885. */
  3886. static void
  3887. pcap_oneshot_mmap(u_char *user, const struct pcap_pkthdr *h,
  3888. const u_char *bytes)
  3889. {
  3890. struct oneshot_userdata *sp = (struct oneshot_userdata *)user;
  3891. pcap_t *handle = sp->pd;
  3892. struct pcap_linux *handlep = handle->priv;
  3893. *sp->hdr = *h;
  3894. memcpy(handlep->oneshot_buffer, bytes, h->caplen);
  3895. *sp->pkt = handlep->oneshot_buffer;
  3896. }
  3897. static void
  3898. pcap_cleanup_linux_mmap( pcap_t *handle )
  3899. {
  3900. struct pcap_linux *handlep = handle->priv;
  3901. destroy_ring(handle);
  3902. if (handlep->oneshot_buffer != NULL) {
  3903. free(handlep->oneshot_buffer);
  3904. handlep->oneshot_buffer = NULL;
  3905. }
  3906. pcap_cleanup_linux(handle);
  3907. }
  3908. static int
  3909. pcap_getnonblock_mmap(pcap_t *p, char *errbuf)
  3910. {
  3911. struct pcap_linux *handlep = p->priv;
  3912. /* use negative value of timeout to indicate non blocking ops */
  3913. return (handlep->timeout<0);
  3914. }
  3915. static int
  3916. pcap_setnonblock_mmap(pcap_t *p, int nonblock, char *errbuf)
  3917. {
  3918. struct pcap_linux *handlep = p->priv;
  3919. /*
  3920. * Set the file descriptor to non-blocking mode, as we use
  3921. * it for sending packets.
  3922. */
  3923. if (pcap_setnonblock_fd(p, nonblock, errbuf) == -1)
  3924. return -1;
  3925. /*
  3926. * Map each value to their corresponding negation to
  3927. * preserve the timeout value provided with pcap_set_timeout.
  3928. */
  3929. if (nonblock) {
  3930. if (handlep->timeout >= 0) {
  3931. /*
  3932. * Indicate that we're switching to
  3933. * non-blocking mode.
  3934. */
  3935. handlep->timeout = ~handlep->timeout;
  3936. }
  3937. } else {
  3938. if (handlep->timeout < 0) {
  3939. handlep->timeout = ~handlep->timeout;
  3940. }
  3941. }
  3942. return 0;
  3943. }
  3944. static inline union thdr *
  3945. pcap_get_ring_frame(pcap_t *handle, int status)
  3946. {
  3947. struct pcap_linux *handlep = handle->priv;
  3948. union thdr h;
  3949. h.raw = RING_GET_FRAME(handle);
  3950. switch (handlep->tp_version) {
  3951. case TPACKET_V1:
  3952. if (status != (h.h1->tp_status ? TP_STATUS_USER :
  3953. TP_STATUS_KERNEL))
  3954. return NULL;
  3955. break;
  3956. case TPACKET_V1_64:
  3957. if (status != (h.h1_64->tp_status ? TP_STATUS_USER :
  3958. TP_STATUS_KERNEL))
  3959. return NULL;
  3960. break;
  3961. #ifdef HAVE_TPACKET2
  3962. case TPACKET_V2:
  3963. if (status != (h.h2->tp_status ? TP_STATUS_USER :
  3964. TP_STATUS_KERNEL))
  3965. return NULL;
  3966. break;
  3967. #endif
  3968. #ifdef HAVE_TPACKET3
  3969. case TPACKET_V3:
  3970. if (status != (h.h3->hdr.bh1.block_status ? TP_STATUS_USER :
  3971. TP_STATUS_KERNEL))
  3972. return NULL;
  3973. break;
  3974. #endif
  3975. }
  3976. return h.raw;
  3977. }
  3978. #ifndef POLLRDHUP
  3979. #define POLLRDHUP 0
  3980. #endif
  3981. /* wait for frames availability.*/
  3982. static int pcap_wait_for_frames_mmap(pcap_t *handle)
  3983. {
  3984. if (!pcap_get_ring_frame(handle, TP_STATUS_USER)) {
  3985. struct pcap_linux *handlep = handle->priv;
  3986. int timeout;
  3987. char c;
  3988. struct pollfd pollinfo;
  3989. int ret;
  3990. pollinfo.fd = handle->fd;
  3991. pollinfo.events = POLLIN;
  3992. if (handlep->timeout == 0) {
  3993. #ifdef HAVE_TPACKET3
  3994. /*
  3995. * XXX - due to a set of (mis)features in the
  3996. * TPACKET_V3 kernel code, blocking forever with
  3997. * a TPACKET_V3 socket can, if few packets
  3998. * are arriving and passing the socket filter,
  3999. * cause most packets to be dropped. See
  4000. * libpcap issue #335 for the full painful
  4001. * story. The workaround is to have poll()
  4002. * time out very quickly, so we grab the
  4003. * frames handed to us, and return them to
  4004. * the kernel, ASAP.
  4005. *
  4006. * If those issues are ever fixed, we might
  4007. * want to check the kernel version and block
  4008. * forever with TPACKET_V3 if we're running
  4009. * with a kernel that has the fix.
  4010. */
  4011. if (handlep->tp_version == TPACKET_V3)
  4012. timeout = 1; /* don't block for very long */
  4013. else
  4014. #endif
  4015. timeout = -1; /* block forever */
  4016. } else if (handlep->timeout > 0)
  4017. timeout = handlep->timeout; /* block for that amount of time */
  4018. else
  4019. timeout = 0; /* non-blocking mode - poll to pick up errors */
  4020. do {
  4021. ret = poll(&pollinfo, 1, timeout);
  4022. if (ret < 0 && errno != EINTR) {
  4023. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  4024. "can't poll on packet socket: %s",
  4025. pcap_strerror(errno));
  4026. return PCAP_ERROR;
  4027. } else if (ret > 0 &&
  4028. (pollinfo.revents & (POLLHUP|POLLRDHUP|POLLERR|POLLNVAL))) {
  4029. /*
  4030. * There's some indication other than
  4031. * "you can read on this descriptor" on
  4032. * the descriptor.
  4033. */
  4034. if (pollinfo.revents & (POLLHUP | POLLRDHUP)) {
  4035. snprintf(handle->errbuf,
  4036. PCAP_ERRBUF_SIZE,
  4037. "Hangup on packet socket");
  4038. return PCAP_ERROR;
  4039. }
  4040. if (pollinfo.revents & POLLERR) {
  4041. /*
  4042. * A recv() will give us the
  4043. * actual error code.
  4044. *
  4045. * XXX - make the socket non-blocking?
  4046. */
  4047. if (recv(handle->fd, &c, sizeof c,
  4048. MSG_PEEK) != -1)
  4049. continue; /* what, no error? */
  4050. if (errno == ENETDOWN) {
  4051. /*
  4052. * The device on which we're
  4053. * capturing went away.
  4054. *
  4055. * XXX - we should really return
  4056. * PCAP_ERROR_IFACE_NOT_UP,
  4057. * but pcap_dispatch() etc.
  4058. * aren't defined to return
  4059. * that.
  4060. */
  4061. snprintf(handle->errbuf,
  4062. PCAP_ERRBUF_SIZE,
  4063. "The interface went down");
  4064. } else {
  4065. snprintf(handle->errbuf,
  4066. PCAP_ERRBUF_SIZE,
  4067. "Error condition on packet socket: %s",
  4068. strerror(errno));
  4069. }
  4070. return PCAP_ERROR;
  4071. }
  4072. if (pollinfo.revents & POLLNVAL) {
  4073. snprintf(handle->errbuf,
  4074. PCAP_ERRBUF_SIZE,
  4075. "Invalid polling request on packet socket");
  4076. return PCAP_ERROR;
  4077. }
  4078. }
  4079. /* check for break loop condition on interrupted syscall*/
  4080. if (handle->break_loop) {
  4081. handle->break_loop = 0;
  4082. return PCAP_ERROR_BREAK;
  4083. }
  4084. } while (ret < 0);
  4085. }
  4086. return 0;
  4087. }
  4088. /* handle a single memory mapped packet */
  4089. static int pcap_handle_packet_mmap(
  4090. pcap_t *handle,
  4091. pcap_handler callback,
  4092. u_char *user,
  4093. unsigned char *frame,
  4094. unsigned int tp_len,
  4095. unsigned int tp_mac,
  4096. unsigned int tp_snaplen,
  4097. unsigned int tp_sec,
  4098. unsigned int tp_usec,
  4099. int tp_vlan_tci_valid,
  4100. __u16 tp_vlan_tci,
  4101. __u16 tp_vlan_tpid)
  4102. {
  4103. struct pcap_linux *handlep = handle->priv;
  4104. unsigned char *bp;
  4105. struct sockaddr_ll *sll;
  4106. struct pcap_pkthdr pcaphdr;
  4107. /* perform sanity check on internal offset. */
  4108. if (tp_mac + tp_snaplen > handle->bufsize) {
  4109. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  4110. "corrupted frame on kernel ring mac "
  4111. "offset %u + caplen %u > frame len %d",
  4112. tp_mac, tp_snaplen, handle->bufsize);
  4113. return -1;
  4114. }
  4115. /* run filter on received packet
  4116. * If the kernel filtering is enabled we need to run the
  4117. * filter until all the frames present into the ring
  4118. * at filter creation time are processed.
  4119. * In this case, blocks_to_filter_in_userland is used
  4120. * as a counter for the packet we need to filter.
  4121. * Note: alternatively it could be possible to stop applying
  4122. * the filter when the ring became empty, but it can possibly
  4123. * happen a lot later... */
  4124. bp = frame + tp_mac;
  4125. /* if required build in place the sll header*/
  4126. sll = (void *)frame + TPACKET_ALIGN(handlep->tp_hdrlen);
  4127. if (handlep->cooked) {
  4128. struct sll_header *hdrp;
  4129. /*
  4130. * The kernel should have left us with enough
  4131. * space for an sll header; back up the packet
  4132. * data pointer into that space, as that'll be
  4133. * the beginning of the packet we pass to the
  4134. * callback.
  4135. */
  4136. bp -= SLL_HDR_LEN;
  4137. /*
  4138. * Let's make sure that's past the end of
  4139. * the tpacket header, i.e. >=
  4140. * ((u_char *)thdr + TPACKET_HDRLEN), so we
  4141. * don't step on the header when we construct
  4142. * the sll header.
  4143. */
  4144. if (bp < (u_char *)frame +
  4145. TPACKET_ALIGN(handlep->tp_hdrlen) +
  4146. sizeof(struct sockaddr_ll)) {
  4147. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  4148. "cooked-mode frame doesn't have room for sll header");
  4149. return -1;
  4150. }
  4151. /*
  4152. * OK, that worked; construct the sll header.
  4153. */
  4154. hdrp = (struct sll_header *)bp;
  4155. hdrp->sll_pkttype = map_packet_type_to_sll_type(
  4156. sll->sll_pkttype);
  4157. hdrp->sll_hatype = htons(sll->sll_hatype);
  4158. hdrp->sll_halen = htons(sll->sll_halen);
  4159. memcpy(hdrp->sll_addr, sll->sll_addr, SLL_ADDRLEN);
  4160. hdrp->sll_protocol = sll->sll_protocol;
  4161. }
  4162. if (handlep->filter_in_userland && handle->fcode.bf_insns) {
  4163. struct bpf_aux_data aux_data;
  4164. aux_data.vlan_tag = tp_vlan_tci & 0x0fff;
  4165. aux_data.vlan_tag_present = tp_vlan_tci_valid;
  4166. if (bpf_filter_with_aux_data(handle->fcode.bf_insns, bp,
  4167. tp_len, tp_snaplen, &aux_data) == 0)
  4168. return 0;
  4169. }
  4170. if (!linux_check_direction(handle, sll))
  4171. return 0;
  4172. /* get required packet info from ring header */
  4173. pcaphdr.ts.tv_sec = tp_sec;
  4174. pcaphdr.ts.tv_usec = tp_usec;
  4175. pcaphdr.caplen = tp_snaplen;
  4176. pcaphdr.len = tp_len;
  4177. /* if required build in place the sll header*/
  4178. if (handlep->cooked) {
  4179. /* update packet len */
  4180. pcaphdr.caplen += SLL_HDR_LEN;
  4181. pcaphdr.len += SLL_HDR_LEN;
  4182. }
  4183. #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
  4184. if (tp_vlan_tci_valid &&
  4185. handlep->vlan_offset != -1 &&
  4186. tp_snaplen >= (unsigned int) handlep->vlan_offset)
  4187. {
  4188. struct vlan_tag *tag;
  4189. bp -= VLAN_TAG_LEN;
  4190. memmove(bp, bp + VLAN_TAG_LEN, handlep->vlan_offset);
  4191. tag = (struct vlan_tag *)(bp + handlep->vlan_offset);
  4192. tag->vlan_tpid = htons(tp_vlan_tpid);
  4193. tag->vlan_tci = htons(tp_vlan_tci);
  4194. pcaphdr.caplen += VLAN_TAG_LEN;
  4195. pcaphdr.len += VLAN_TAG_LEN;
  4196. }
  4197. #endif
  4198. /*
  4199. * The only way to tell the kernel to cut off the
  4200. * packet at a snapshot length is with a filter program;
  4201. * if there's no filter program, the kernel won't cut
  4202. * the packet off.
  4203. *
  4204. * Trim the snapshot length to be no longer than the
  4205. * specified snapshot length.
  4206. */
  4207. if (pcaphdr.caplen > handle->snapshot)
  4208. pcaphdr.caplen = handle->snapshot;
  4209. /* pass the packet to the user */
  4210. callback(user, &pcaphdr, bp);
  4211. return 1;
  4212. }
  4213. static int
  4214. pcap_read_linux_mmap_v1(pcap_t *handle, int max_packets, pcap_handler callback,
  4215. u_char *user)
  4216. {
  4217. struct pcap_linux *handlep = handle->priv;
  4218. int pkts = 0;
  4219. int ret;
  4220. /* wait for frames availability.*/
  4221. ret = pcap_wait_for_frames_mmap(handle);
  4222. if (ret) {
  4223. return ret;
  4224. }
  4225. /* non-positive values of max_packets are used to require all
  4226. * packets currently available in the ring */
  4227. while ((pkts < max_packets) || PACKET_COUNT_IS_UNLIMITED(max_packets)) {
  4228. union thdr h;
  4229. h.raw = pcap_get_ring_frame(handle, TP_STATUS_USER);
  4230. if (!h.raw)
  4231. break;
  4232. ret = pcap_handle_packet_mmap(
  4233. handle,
  4234. callback,
  4235. user,
  4236. h.raw,
  4237. h.h1->tp_len,
  4238. h.h1->tp_mac,
  4239. h.h1->tp_snaplen,
  4240. h.h1->tp_sec,
  4241. h.h1->tp_usec,
  4242. 0,
  4243. 0,
  4244. 0);
  4245. if (ret == 1) {
  4246. pkts++;
  4247. handlep->packets_read++;
  4248. } else if (ret < 0) {
  4249. return ret;
  4250. }
  4251. /*
  4252. * Hand this block back to the kernel, and, if we're
  4253. * counting blocks that need to be filtered in userland
  4254. * after having been filtered by the kernel, count
  4255. * the one we've just processed.
  4256. */
  4257. h.h1->tp_status = TP_STATUS_KERNEL;
  4258. if (handlep->blocks_to_filter_in_userland > 0) {
  4259. handlep->blocks_to_filter_in_userland--;
  4260. if (handlep->blocks_to_filter_in_userland == 0) {
  4261. /*
  4262. * No more blocks need to be filtered
  4263. * in userland.
  4264. */
  4265. handlep->filter_in_userland = 0;
  4266. }
  4267. }
  4268. /* next block */
  4269. if (++handle->offset >= handle->cc)
  4270. handle->offset = 0;
  4271. /* check for break loop condition*/
  4272. if (handle->break_loop) {
  4273. handle->break_loop = 0;
  4274. return PCAP_ERROR_BREAK;
  4275. }
  4276. }
  4277. return pkts;
  4278. }
  4279. static int
  4280. pcap_read_linux_mmap_v1_64(pcap_t *handle, int max_packets, pcap_handler callback,
  4281. u_char *user)
  4282. {
  4283. struct pcap_linux *handlep = handle->priv;
  4284. int pkts = 0;
  4285. int ret;
  4286. /* wait for frames availability.*/
  4287. ret = pcap_wait_for_frames_mmap(handle);
  4288. if (ret) {
  4289. return ret;
  4290. }
  4291. /* non-positive values of max_packets are used to require all
  4292. * packets currently available in the ring */
  4293. while ((pkts < max_packets) || PACKET_COUNT_IS_UNLIMITED(max_packets)) {
  4294. union thdr h;
  4295. h.raw = pcap_get_ring_frame(handle, TP_STATUS_USER);
  4296. if (!h.raw)
  4297. break;
  4298. ret = pcap_handle_packet_mmap(
  4299. handle,
  4300. callback,
  4301. user,
  4302. h.raw,
  4303. h.h1_64->tp_len,
  4304. h.h1_64->tp_mac,
  4305. h.h1_64->tp_snaplen,
  4306. h.h1_64->tp_sec,
  4307. h.h1_64->tp_usec,
  4308. 0,
  4309. 0,
  4310. 0);
  4311. if (ret == 1) {
  4312. pkts++;
  4313. handlep->packets_read++;
  4314. } else if (ret < 0) {
  4315. return ret;
  4316. }
  4317. /*
  4318. * Hand this block back to the kernel, and, if we're
  4319. * counting blocks that need to be filtered in userland
  4320. * after having been filtered by the kernel, count
  4321. * the one we've just processed.
  4322. */
  4323. h.h1_64->tp_status = TP_STATUS_KERNEL;
  4324. if (handlep->blocks_to_filter_in_userland > 0) {
  4325. handlep->blocks_to_filter_in_userland--;
  4326. if (handlep->blocks_to_filter_in_userland == 0) {
  4327. /*
  4328. * No more blocks need to be filtered
  4329. * in userland.
  4330. */
  4331. handlep->filter_in_userland = 0;
  4332. }
  4333. }
  4334. /* next block */
  4335. if (++handle->offset >= handle->cc)
  4336. handle->offset = 0;
  4337. /* check for break loop condition*/
  4338. if (handle->break_loop) {
  4339. handle->break_loop = 0;
  4340. return PCAP_ERROR_BREAK;
  4341. }
  4342. }
  4343. return pkts;
  4344. }
  4345. #ifdef HAVE_TPACKET2
  4346. static int
  4347. pcap_read_linux_mmap_v2(pcap_t *handle, int max_packets, pcap_handler callback,
  4348. u_char *user)
  4349. {
  4350. struct pcap_linux *handlep = handle->priv;
  4351. int pkts = 0;
  4352. int ret;
  4353. /* wait for frames availability.*/
  4354. ret = pcap_wait_for_frames_mmap(handle);
  4355. if (ret) {
  4356. return ret;
  4357. }
  4358. /* non-positive values of max_packets are used to require all
  4359. * packets currently available in the ring */
  4360. while ((pkts < max_packets) || PACKET_COUNT_IS_UNLIMITED(max_packets)) {
  4361. union thdr h;
  4362. h.raw = pcap_get_ring_frame(handle, TP_STATUS_USER);
  4363. if (!h.raw)
  4364. break;
  4365. ret = pcap_handle_packet_mmap(
  4366. handle,
  4367. callback,
  4368. user,
  4369. h.raw,
  4370. h.h2->tp_len,
  4371. h.h2->tp_mac,
  4372. h.h2->tp_snaplen,
  4373. h.h2->tp_sec,
  4374. handle->opt.tstamp_precision == PCAP_TSTAMP_PRECISION_NANO ? h.h2->tp_nsec : h.h2->tp_nsec / 1000,
  4375. #if defined(TP_STATUS_VLAN_VALID)
  4376. (h.h2->tp_vlan_tci || (h.h2->tp_status & TP_STATUS_VLAN_VALID)),
  4377. #else
  4378. h.h2->tp_vlan_tci != 0,
  4379. #endif
  4380. h.h2->tp_vlan_tci,
  4381. VLAN_TPID(h.h2, h.h2));
  4382. if (ret == 1) {
  4383. pkts++;
  4384. handlep->packets_read++;
  4385. } else if (ret < 0) {
  4386. return ret;
  4387. }
  4388. /*
  4389. * Hand this block back to the kernel, and, if we're
  4390. * counting blocks that need to be filtered in userland
  4391. * after having been filtered by the kernel, count
  4392. * the one we've just processed.
  4393. */
  4394. h.h2->tp_status = TP_STATUS_KERNEL;
  4395. if (handlep->blocks_to_filter_in_userland > 0) {
  4396. handlep->blocks_to_filter_in_userland--;
  4397. if (handlep->blocks_to_filter_in_userland == 0) {
  4398. /*
  4399. * No more blocks need to be filtered
  4400. * in userland.
  4401. */
  4402. handlep->filter_in_userland = 0;
  4403. }
  4404. }
  4405. /* next block */
  4406. if (++handle->offset >= handle->cc)
  4407. handle->offset = 0;
  4408. /* check for break loop condition*/
  4409. if (handle->break_loop) {
  4410. handle->break_loop = 0;
  4411. return PCAP_ERROR_BREAK;
  4412. }
  4413. }
  4414. return pkts;
  4415. }
  4416. #endif /* HAVE_TPACKET2 */
  4417. #ifdef HAVE_TPACKET3
  4418. static int
  4419. pcap_read_linux_mmap_v3(pcap_t *handle, int max_packets, pcap_handler callback,
  4420. u_char *user)
  4421. {
  4422. struct pcap_linux *handlep = handle->priv;
  4423. union thdr h;
  4424. int pkts = 0;
  4425. int ret;
  4426. again:
  4427. if (handlep->current_packet == NULL) {
  4428. /* wait for frames availability.*/
  4429. ret = pcap_wait_for_frames_mmap(handle);
  4430. if (ret) {
  4431. return ret;
  4432. }
  4433. }
  4434. h.raw = pcap_get_ring_frame(handle, TP_STATUS_USER);
  4435. if (!h.raw) {
  4436. if (pkts == 0 && handlep->timeout == 0) {
  4437. /* Block until we see a packet. */
  4438. goto again;
  4439. }
  4440. return pkts;
  4441. }
  4442. /* non-positive values of max_packets are used to require all
  4443. * packets currently available in the ring */
  4444. while ((pkts < max_packets) || PACKET_COUNT_IS_UNLIMITED(max_packets)) {
  4445. if (handlep->current_packet == NULL) {
  4446. h.raw = pcap_get_ring_frame(handle, TP_STATUS_USER);
  4447. if (!h.raw)
  4448. break;
  4449. handlep->current_packet = h.raw + h.h3->hdr.bh1.offset_to_first_pkt;
  4450. handlep->packets_left = h.h3->hdr.bh1.num_pkts;
  4451. }
  4452. int packets_to_read = handlep->packets_left;
  4453. if (!PACKET_COUNT_IS_UNLIMITED(max_packets) && packets_to_read > max_packets) {
  4454. packets_to_read = max_packets;
  4455. }
  4456. while(packets_to_read--) {
  4457. struct tpacket3_hdr* tp3_hdr = (struct tpacket3_hdr*) handlep->current_packet;
  4458. ret = pcap_handle_packet_mmap(
  4459. handle,
  4460. callback,
  4461. user,
  4462. handlep->current_packet,
  4463. tp3_hdr->tp_len,
  4464. tp3_hdr->tp_mac,
  4465. tp3_hdr->tp_snaplen,
  4466. tp3_hdr->tp_sec,
  4467. handle->opt.tstamp_precision == PCAP_TSTAMP_PRECISION_NANO ? tp3_hdr->tp_nsec : tp3_hdr->tp_nsec / 1000,
  4468. #if defined(TP_STATUS_VLAN_VALID)
  4469. (tp3_hdr->hv1.tp_vlan_tci || (tp3_hdr->tp_status & TP_STATUS_VLAN_VALID)),
  4470. #else
  4471. tp3_hdr->hv1.tp_vlan_tci != 0,
  4472. #endif
  4473. tp3_hdr->hv1.tp_vlan_tci,
  4474. VLAN_TPID(tp3_hdr, &tp3_hdr->hv1));
  4475. if (ret == 1) {
  4476. pkts++;
  4477. handlep->packets_read++;
  4478. } else if (ret < 0) {
  4479. handlep->current_packet = NULL;
  4480. return ret;
  4481. }
  4482. handlep->current_packet += tp3_hdr->tp_next_offset;
  4483. handlep->packets_left--;
  4484. }
  4485. if (handlep->packets_left <= 0) {
  4486. /*
  4487. * Hand this block back to the kernel, and, if
  4488. * we're counting blocks that need to be
  4489. * filtered in userland after having been
  4490. * filtered by the kernel, count the one we've
  4491. * just processed.
  4492. */
  4493. h.h3->hdr.bh1.block_status = TP_STATUS_KERNEL;
  4494. if (handlep->blocks_to_filter_in_userland > 0) {
  4495. handlep->blocks_to_filter_in_userland--;
  4496. if (handlep->blocks_to_filter_in_userland == 0) {
  4497. /*
  4498. * No more blocks need to be filtered
  4499. * in userland.
  4500. */
  4501. handlep->filter_in_userland = 0;
  4502. }
  4503. }
  4504. /* next block */
  4505. if (++handle->offset >= handle->cc)
  4506. handle->offset = 0;
  4507. handlep->current_packet = NULL;
  4508. }
  4509. /* check for break loop condition*/
  4510. if (handle->break_loop) {
  4511. handle->break_loop = 0;
  4512. return PCAP_ERROR_BREAK;
  4513. }
  4514. }
  4515. if (pkts == 0 && handlep->timeout == 0) {
  4516. /* Block until we see a packet. */
  4517. goto again;
  4518. }
  4519. return pkts;
  4520. }
  4521. #endif /* HAVE_TPACKET3 */
  4522. static int
  4523. pcap_setfilter_linux_mmap(pcap_t *handle, struct bpf_program *filter)
  4524. {
  4525. struct pcap_linux *handlep = handle->priv;
  4526. int n, offset;
  4527. int ret;
  4528. /*
  4529. * Don't rewrite "ret" instructions; we don't need to, as
  4530. * we're not reading packets with recvmsg(), and we don't
  4531. * want to, as, by not rewriting them, the kernel can avoid
  4532. * copying extra data.
  4533. */
  4534. ret = pcap_setfilter_linux_common(handle, filter, 1);
  4535. if (ret < 0)
  4536. return ret;
  4537. /*
  4538. * If we're filtering in userland, there's nothing to do;
  4539. * the new filter will be used for the next packet.
  4540. */
  4541. if (handlep->filter_in_userland)
  4542. return ret;
  4543. /*
  4544. * We're filtering in the kernel; the packets present in
  4545. * all blocks currently in the ring were already filtered
  4546. * by the old filter, and so will need to be filtered in
  4547. * userland by the new filter.
  4548. *
  4549. * Get an upper bound for the number of such blocks; first,
  4550. * walk the ring backward and count the free blocks.
  4551. */
  4552. offset = handle->offset;
  4553. if (--handle->offset < 0)
  4554. handle->offset = handle->cc - 1;
  4555. for (n=0; n < handle->cc; ++n) {
  4556. if (--handle->offset < 0)
  4557. handle->offset = handle->cc - 1;
  4558. if (!pcap_get_ring_frame(handle, TP_STATUS_KERNEL))
  4559. break;
  4560. }
  4561. /*
  4562. * If we found free blocks, decrement the count of free
  4563. * blocks by 1, just in case we lost a race with another
  4564. * thread of control that was adding a packet while
  4565. * we were counting and that had run the filter before
  4566. * we changed it.
  4567. *
  4568. * XXX - could there be more than one block added in
  4569. * this fashion?
  4570. *
  4571. * XXX - is there a way to avoid that race, e.g. somehow
  4572. * wait for all packets that passed the old filter to
  4573. * be added to the ring?
  4574. */
  4575. if (n != 0)
  4576. n--;
  4577. /* be careful to not change current ring position */
  4578. handle->offset = offset;
  4579. /*
  4580. * Set the count of blocks worth of packets to filter
  4581. * in userland to the total number of blocks in the
  4582. * ring minus the number of free blocks we found, and
  4583. * turn on userland filtering. (The count of blocks
  4584. * worth of packets to filter in userland is guaranteed
  4585. * not to be zero - n, above, couldn't be set to a
  4586. * value > handle->cc, and if it were equal to
  4587. * handle->cc, it wouldn't be zero, and thus would
  4588. * be decremented to handle->cc - 1.)
  4589. */
  4590. handlep->blocks_to_filter_in_userland = handle->cc - n;
  4591. handlep->filter_in_userland = 1;
  4592. return ret;
  4593. }
  4594. #endif /* HAVE_PACKET_RING */
  4595. #ifdef HAVE_PF_PACKET_SOCKETS
  4596. /*
  4597. * Return the index of the given device name. Fill ebuf and return
  4598. * -1 on failure.
  4599. */
  4600. static int
  4601. iface_get_id(int fd, const char *device, char *ebuf)
  4602. {
  4603. struct ifreq ifr;
  4604. memset(&ifr, 0, sizeof(ifr));
  4605. strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
  4606. if (ioctl(fd, SIOCGIFINDEX, &ifr) == -1) {
  4607. snprintf(ebuf, PCAP_ERRBUF_SIZE,
  4608. "SIOCGIFINDEX: %s", pcap_strerror(errno));
  4609. return -1;
  4610. }
  4611. return ifr.ifr_ifindex;
  4612. }
  4613. /*
  4614. * Bind the socket associated with FD to the given device.
  4615. * Return 1 on success, 0 if we should try a SOCK_PACKET socket,
  4616. * or a PCAP_ERROR_ value on a hard error.
  4617. */
  4618. static int
  4619. iface_bind(int fd, int ifindex, char *ebuf)
  4620. {
  4621. struct sockaddr_ll sll;
  4622. int err;
  4623. socklen_t errlen = sizeof(err);
  4624. memset(&sll, 0, sizeof(sll));
  4625. sll.sll_family = AF_PACKET;
  4626. sll.sll_ifindex = ifindex;
  4627. sll.sll_protocol = htons(ETH_P_ALL);
  4628. if (bind(fd, (struct sockaddr *) &sll, sizeof(sll)) == -1) {
  4629. if (errno == ENETDOWN) {
  4630. /*
  4631. * Return a "network down" indication, so that
  4632. * the application can report that rather than
  4633. * saying we had a mysterious failure and
  4634. * suggest that they report a problem to the
  4635. * libpcap developers.
  4636. */
  4637. return PCAP_ERROR_IFACE_NOT_UP;
  4638. } else {
  4639. snprintf(ebuf, PCAP_ERRBUF_SIZE,
  4640. "bind: %s", pcap_strerror(errno));
  4641. return PCAP_ERROR;
  4642. }
  4643. }
  4644. /* Any pending errors, e.g., network is down? */
  4645. if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen) == -1) {
  4646. snprintf(ebuf, PCAP_ERRBUF_SIZE,
  4647. "getsockopt: %s", pcap_strerror(errno));
  4648. return 0;
  4649. }
  4650. if (err == ENETDOWN) {
  4651. /*
  4652. * Return a "network down" indication, so that
  4653. * the application can report that rather than
  4654. * saying we had a mysterious failure and
  4655. * suggest that they report a problem to the
  4656. * libpcap developers.
  4657. */
  4658. return PCAP_ERROR_IFACE_NOT_UP;
  4659. } else if (err > 0) {
  4660. snprintf(ebuf, PCAP_ERRBUF_SIZE,
  4661. "bind: %s", pcap_strerror(err));
  4662. return 0;
  4663. }
  4664. return 1;
  4665. }
  4666. #ifdef IW_MODE_MONITOR
  4667. /*
  4668. * Check whether the device supports the Wireless Extensions.
  4669. * Returns 1 if it does, 0 if it doesn't, PCAP_ERROR_NO_SUCH_DEVICE
  4670. * if the device doesn't even exist.
  4671. */
  4672. static int
  4673. has_wext(int sock_fd, const char *device, char *ebuf)
  4674. {
  4675. struct iwreq ireq;
  4676. if (is_bonding_device(sock_fd, device))
  4677. return 0; /* bonding device, so don't even try */
  4678. strlcpy(ireq.ifr_ifrn.ifrn_name, device,
  4679. sizeof ireq.ifr_ifrn.ifrn_name);
  4680. if (ioctl(sock_fd, SIOCGIWNAME, &ireq) >= 0)
  4681. return 1; /* yes */
  4682. snprintf(ebuf, PCAP_ERRBUF_SIZE,
  4683. "%s: SIOCGIWNAME: %s", device, pcap_strerror(errno));
  4684. if (errno == ENODEV)
  4685. return PCAP_ERROR_NO_SUCH_DEVICE;
  4686. return 0;
  4687. }
  4688. /*
  4689. * Per me si va ne la citta dolente,
  4690. * Per me si va ne l'etterno dolore,
  4691. * ...
  4692. * Lasciate ogne speranza, voi ch'intrate.
  4693. *
  4694. * XXX - airmon-ng does special stuff with the Orinoco driver and the
  4695. * wlan-ng driver.
  4696. */
  4697. typedef enum {
  4698. MONITOR_WEXT,
  4699. MONITOR_HOSTAP,
  4700. MONITOR_PRISM,
  4701. MONITOR_PRISM54,
  4702. MONITOR_ACX100,
  4703. MONITOR_RT2500,
  4704. MONITOR_RT2570,
  4705. MONITOR_RT73,
  4706. MONITOR_RTL8XXX
  4707. } monitor_type;
  4708. /*
  4709. * Use the Wireless Extensions, if we have them, to try to turn monitor mode
  4710. * on if it's not already on.
  4711. *
  4712. * Returns 1 on success, 0 if we don't support the Wireless Extensions
  4713. * on this device, or a PCAP_ERROR_ value if we do support them but
  4714. * we weren't able to turn monitor mode on.
  4715. */
  4716. static int
  4717. enter_rfmon_mode_wext(pcap_t *handle, int sock_fd, const char *device)
  4718. {
  4719. /*
  4720. * XXX - at least some adapters require non-Wireless Extensions
  4721. * mechanisms to turn monitor mode on.
  4722. *
  4723. * Atheros cards might require that a separate "monitor virtual access
  4724. * point" be created, with later versions of the madwifi driver.
  4725. * airmon-ng does "wlanconfig ath create wlandev {if} wlanmode
  4726. * monitor -bssid", which apparently spits out a line "athN"
  4727. * where "athN" is the monitor mode device. To leave monitor
  4728. * mode, it destroys the monitor mode device.
  4729. *
  4730. * Some Intel Centrino adapters might require private ioctls to get
  4731. * radio headers; the ipw2200 and ipw3945 drivers allow you to
  4732. * configure a separate "rtapN" interface to capture in monitor
  4733. * mode without preventing the adapter from operating normally.
  4734. * (airmon-ng doesn't appear to use that, though.)
  4735. *
  4736. * It would be Truly Wonderful if mac80211 and nl80211 cleaned this
  4737. * up, and if all drivers were converted to mac80211 drivers.
  4738. *
  4739. * If interface {if} is a mac80211 driver, the file
  4740. * /sys/class/net/{if}/phy80211 is a symlink to
  4741. * /sys/class/ieee80211/{phydev}, for some {phydev}.
  4742. *
  4743. * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
  4744. * least, has a "wmaster0" device and a "wlan0" device; the
  4745. * latter is the one with the IP address. Both show up in
  4746. * "tcpdump -D" output. Capturing on the wmaster0 device
  4747. * captures with 802.11 headers.
  4748. *
  4749. * airmon-ng searches through /sys/class/net for devices named
  4750. * monN, starting with mon0; as soon as one *doesn't* exist,
  4751. * it chooses that as the monitor device name. If the "iw"
  4752. * command exists, it does "iw dev {if} interface add {monif}
  4753. * type monitor", where {monif} is the monitor device. It
  4754. * then (sigh) sleeps .1 second, and then configures the
  4755. * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
  4756. * is a file, it writes {mondev}, without a newline, to that file,
  4757. * and again (sigh) sleeps .1 second, and then iwconfig's that
  4758. * device into monitor mode and configures it up. Otherwise,
  4759. * you can't do monitor mode.
  4760. *
  4761. * All these devices are "glued" together by having the
  4762. * /sys/class/net/{device}/phy80211 links pointing to the same
  4763. * place, so, given a wmaster, wlan, or mon device, you can
  4764. * find the other devices by looking for devices with
  4765. * the same phy80211 link.
  4766. *
  4767. * To turn monitor mode off, delete the monitor interface,
  4768. * either with "iw dev {monif} interface del" or by sending
  4769. * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
  4770. *
  4771. * Note: if you try to create a monitor device named "monN", and
  4772. * there's already a "monN" device, it fails, as least with
  4773. * the netlink interface (which is what iw uses), with a return
  4774. * value of -ENFILE. (Return values are negative errnos.) We
  4775. * could probably use that to find an unused device.
  4776. */
  4777. struct pcap_linux *handlep = handle->priv;
  4778. int err;
  4779. struct iwreq ireq;
  4780. struct iw_priv_args *priv;
  4781. monitor_type montype;
  4782. int i;
  4783. __u32 cmd;
  4784. struct ifreq ifr;
  4785. int oldflags;
  4786. int args[2];
  4787. int channel;
  4788. /*
  4789. * Does this device *support* the Wireless Extensions?
  4790. */
  4791. err = has_wext(sock_fd, device, handle->errbuf);
  4792. if (err <= 0)
  4793. return err; /* either it doesn't or the device doesn't even exist */
  4794. /*
  4795. * Start out assuming we have no private extensions to control
  4796. * radio metadata.
  4797. */
  4798. montype = MONITOR_WEXT;
  4799. cmd = 0;
  4800. /*
  4801. * Try to get all the Wireless Extensions private ioctls
  4802. * supported by this device.
  4803. *
  4804. * First, get the size of the buffer we need, by supplying no
  4805. * buffer and a length of 0. If the device supports private
  4806. * ioctls, it should return E2BIG, with ireq.u.data.length set
  4807. * to the length we need. If it doesn't support them, it should
  4808. * return EOPNOTSUPP.
  4809. */
  4810. memset(&ireq, 0, sizeof ireq);
  4811. strlcpy(ireq.ifr_ifrn.ifrn_name, device,
  4812. sizeof ireq.ifr_ifrn.ifrn_name);
  4813. ireq.u.data.pointer = (void *)args;
  4814. ireq.u.data.length = 0;
  4815. ireq.u.data.flags = 0;
  4816. if (ioctl(sock_fd, SIOCGIWPRIV, &ireq) != -1) {
  4817. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  4818. "%s: SIOCGIWPRIV with a zero-length buffer didn't fail!",
  4819. device);
  4820. return PCAP_ERROR;
  4821. }
  4822. if (errno != EOPNOTSUPP) {
  4823. /*
  4824. * OK, it's not as if there are no private ioctls.
  4825. */
  4826. if (errno != E2BIG) {
  4827. /*
  4828. * Failed.
  4829. */
  4830. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  4831. "%s: SIOCGIWPRIV: %s", device,
  4832. pcap_strerror(errno));
  4833. return PCAP_ERROR;
  4834. }
  4835. /*
  4836. * OK, try to get the list of private ioctls.
  4837. */
  4838. priv = malloc(ireq.u.data.length * sizeof (struct iw_priv_args));
  4839. if (priv == NULL) {
  4840. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  4841. "malloc: %s", pcap_strerror(errno));
  4842. return PCAP_ERROR;
  4843. }
  4844. ireq.u.data.pointer = (void *)priv;
  4845. if (ioctl(sock_fd, SIOCGIWPRIV, &ireq) == -1) {
  4846. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  4847. "%s: SIOCGIWPRIV: %s", device,
  4848. pcap_strerror(errno));
  4849. free(priv);
  4850. return PCAP_ERROR;
  4851. }
  4852. /*
  4853. * Look for private ioctls to turn monitor mode on or, if
  4854. * monitor mode is on, to set the header type.
  4855. */
  4856. for (i = 0; i < ireq.u.data.length; i++) {
  4857. if (strcmp(priv[i].name, "monitor_type") == 0) {
  4858. /*
  4859. * Hostap driver, use this one.
  4860. * Set monitor mode first.
  4861. * You can set it to 0 to get DLT_IEEE80211,
  4862. * 1 to get DLT_PRISM, 2 to get
  4863. * DLT_IEEE80211_RADIO_AVS, and, with more
  4864. * recent versions of the driver, 3 to get
  4865. * DLT_IEEE80211_RADIO.
  4866. */
  4867. if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
  4868. break;
  4869. if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
  4870. break;
  4871. if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
  4872. break;
  4873. montype = MONITOR_HOSTAP;
  4874. cmd = priv[i].cmd;
  4875. break;
  4876. }
  4877. if (strcmp(priv[i].name, "set_prismhdr") == 0) {
  4878. /*
  4879. * Prism54 driver, use this one.
  4880. * Set monitor mode first.
  4881. * You can set it to 2 to get DLT_IEEE80211
  4882. * or 3 or get DLT_PRISM.
  4883. */
  4884. if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
  4885. break;
  4886. if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
  4887. break;
  4888. if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
  4889. break;
  4890. montype = MONITOR_PRISM54;
  4891. cmd = priv[i].cmd;
  4892. break;
  4893. }
  4894. if (strcmp(priv[i].name, "forceprismheader") == 0) {
  4895. /*
  4896. * RT2570 driver, use this one.
  4897. * Do this after turning monitor mode on.
  4898. * You can set it to 1 to get DLT_PRISM or 2
  4899. * to get DLT_IEEE80211.
  4900. */
  4901. if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
  4902. break;
  4903. if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
  4904. break;
  4905. if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
  4906. break;
  4907. montype = MONITOR_RT2570;
  4908. cmd = priv[i].cmd;
  4909. break;
  4910. }
  4911. if (strcmp(priv[i].name, "forceprism") == 0) {
  4912. /*
  4913. * RT73 driver, use this one.
  4914. * Do this after turning monitor mode on.
  4915. * Its argument is a *string*; you can
  4916. * set it to "1" to get DLT_PRISM or "2"
  4917. * to get DLT_IEEE80211.
  4918. */
  4919. if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_CHAR)
  4920. break;
  4921. if (priv[i].set_args & IW_PRIV_SIZE_FIXED)
  4922. break;
  4923. montype = MONITOR_RT73;
  4924. cmd = priv[i].cmd;
  4925. break;
  4926. }
  4927. if (strcmp(priv[i].name, "prismhdr") == 0) {
  4928. /*
  4929. * One of the RTL8xxx drivers, use this one.
  4930. * It can only be done after monitor mode
  4931. * has been turned on. You can set it to 1
  4932. * to get DLT_PRISM or 0 to get DLT_IEEE80211.
  4933. */
  4934. if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
  4935. break;
  4936. if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
  4937. break;
  4938. if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
  4939. break;
  4940. montype = MONITOR_RTL8XXX;
  4941. cmd = priv[i].cmd;
  4942. break;
  4943. }
  4944. if (strcmp(priv[i].name, "rfmontx") == 0) {
  4945. /*
  4946. * RT2500 or RT61 driver, use this one.
  4947. * It has one one-byte parameter; set
  4948. * u.data.length to 1 and u.data.pointer to
  4949. * point to the parameter.
  4950. * It doesn't itself turn monitor mode on.
  4951. * You can set it to 1 to allow transmitting
  4952. * in monitor mode(?) and get DLT_IEEE80211,
  4953. * or set it to 0 to disallow transmitting in
  4954. * monitor mode(?) and get DLT_PRISM.
  4955. */
  4956. if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
  4957. break;
  4958. if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 2)
  4959. break;
  4960. montype = MONITOR_RT2500;
  4961. cmd = priv[i].cmd;
  4962. break;
  4963. }
  4964. if (strcmp(priv[i].name, "monitor") == 0) {
  4965. /*
  4966. * Either ACX100 or hostap, use this one.
  4967. * It turns monitor mode on.
  4968. * If it takes two arguments, it's ACX100;
  4969. * the first argument is 1 for DLT_PRISM
  4970. * or 2 for DLT_IEEE80211, and the second
  4971. * argument is the channel on which to
  4972. * run. If it takes one argument, it's
  4973. * HostAP, and the argument is 2 for
  4974. * DLT_IEEE80211 and 3 for DLT_PRISM.
  4975. *
  4976. * If we see this, we don't quit, as this
  4977. * might be a version of the hostap driver
  4978. * that also supports "monitor_type".
  4979. */
  4980. if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
  4981. break;
  4982. if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
  4983. break;
  4984. switch (priv[i].set_args & IW_PRIV_SIZE_MASK) {
  4985. case 1:
  4986. montype = MONITOR_PRISM;
  4987. cmd = priv[i].cmd;
  4988. break;
  4989. case 2:
  4990. montype = MONITOR_ACX100;
  4991. cmd = priv[i].cmd;
  4992. break;
  4993. default:
  4994. break;
  4995. }
  4996. }
  4997. }
  4998. free(priv);
  4999. }
  5000. /*
  5001. * XXX - ipw3945? islism?
  5002. */
  5003. /*
  5004. * Get the old mode.
  5005. */
  5006. strlcpy(ireq.ifr_ifrn.ifrn_name, device,
  5007. sizeof ireq.ifr_ifrn.ifrn_name);
  5008. if (ioctl(sock_fd, SIOCGIWMODE, &ireq) == -1) {
  5009. /*
  5010. * We probably won't be able to set the mode, either.
  5011. */
  5012. return PCAP_ERROR_RFMON_NOTSUP;
  5013. }
  5014. /*
  5015. * Is it currently in monitor mode?
  5016. */
  5017. if (ireq.u.mode == IW_MODE_MONITOR) {
  5018. /*
  5019. * Yes. Just leave things as they are.
  5020. * We don't offer multiple link-layer types, as
  5021. * changing the link-layer type out from under
  5022. * somebody else capturing in monitor mode would
  5023. * be considered rude.
  5024. */
  5025. return 1;
  5026. }
  5027. /*
  5028. * No. We have to put the adapter into rfmon mode.
  5029. */
  5030. /*
  5031. * If we haven't already done so, arrange to have
  5032. * "pcap_close_all()" called when we exit.
  5033. */
  5034. if (!pcap_do_addexit(handle)) {
  5035. /*
  5036. * "atexit()" failed; don't put the interface
  5037. * in rfmon mode, just give up.
  5038. */
  5039. return PCAP_ERROR_RFMON_NOTSUP;
  5040. }
  5041. /*
  5042. * Save the old mode.
  5043. */
  5044. handlep->oldmode = ireq.u.mode;
  5045. /*
  5046. * Put the adapter in rfmon mode. How we do this depends
  5047. * on whether we have a special private ioctl or not.
  5048. */
  5049. if (montype == MONITOR_PRISM) {
  5050. /*
  5051. * We have the "monitor" private ioctl, but none of
  5052. * the other private ioctls. Use this, and select
  5053. * the Prism header.
  5054. *
  5055. * If it fails, just fall back on SIOCSIWMODE.
  5056. */
  5057. memset(&ireq, 0, sizeof ireq);
  5058. strlcpy(ireq.ifr_ifrn.ifrn_name, device,
  5059. sizeof ireq.ifr_ifrn.ifrn_name);
  5060. ireq.u.data.length = 1; /* 1 argument */
  5061. args[0] = 3; /* request Prism header */
  5062. memcpy(ireq.u.name, args, sizeof (int));
  5063. if (ioctl(sock_fd, cmd, &ireq) != -1) {
  5064. /*
  5065. * Success.
  5066. * Note that we have to put the old mode back
  5067. * when we close the device.
  5068. */
  5069. handlep->must_do_on_close |= MUST_CLEAR_RFMON;
  5070. /*
  5071. * Add this to the list of pcaps to close
  5072. * when we exit.
  5073. */
  5074. pcap_add_to_pcaps_to_close(handle);
  5075. return 1;
  5076. }
  5077. /*
  5078. * Failure. Fall back on SIOCSIWMODE.
  5079. */
  5080. }
  5081. /*
  5082. * First, take the interface down if it's up; otherwise, we
  5083. * might get EBUSY.
  5084. */
  5085. memset(&ifr, 0, sizeof(ifr));
  5086. strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
  5087. if (ioctl(sock_fd, SIOCGIFFLAGS, &ifr) == -1) {
  5088. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  5089. "%s: Can't get flags: %s", device, strerror(errno));
  5090. return PCAP_ERROR;
  5091. }
  5092. oldflags = 0;
  5093. if (ifr.ifr_flags & IFF_UP) {
  5094. oldflags = ifr.ifr_flags;
  5095. ifr.ifr_flags &= ~IFF_UP;
  5096. if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
  5097. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  5098. "%s: Can't set flags: %s", device, strerror(errno));
  5099. return PCAP_ERROR;
  5100. }
  5101. }
  5102. /*
  5103. * Then turn monitor mode on.
  5104. */
  5105. strlcpy(ireq.ifr_ifrn.ifrn_name, device,
  5106. sizeof ireq.ifr_ifrn.ifrn_name);
  5107. ireq.u.mode = IW_MODE_MONITOR;
  5108. if (ioctl(sock_fd, SIOCSIWMODE, &ireq) == -1) {
  5109. /*
  5110. * Scientist, you've failed.
  5111. * Bring the interface back up if we shut it down.
  5112. */
  5113. ifr.ifr_flags = oldflags;
  5114. if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
  5115. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  5116. "%s: Can't set flags: %s", device, strerror(errno));
  5117. return PCAP_ERROR;
  5118. }
  5119. return PCAP_ERROR_RFMON_NOTSUP;
  5120. }
  5121. /*
  5122. * XXX - airmon-ng does "iwconfig {if} key off" after setting
  5123. * monitor mode and setting the channel, and then does
  5124. * "iwconfig up".
  5125. */
  5126. /*
  5127. * Now select the appropriate radio header.
  5128. */
  5129. switch (montype) {
  5130. case MONITOR_WEXT:
  5131. /*
  5132. * We don't have any private ioctl to set the header.
  5133. */
  5134. break;
  5135. case MONITOR_HOSTAP:
  5136. /*
  5137. * Try to select the radiotap header.
  5138. */
  5139. memset(&ireq, 0, sizeof ireq);
  5140. strlcpy(ireq.ifr_ifrn.ifrn_name, device,
  5141. sizeof ireq.ifr_ifrn.ifrn_name);
  5142. args[0] = 3; /* request radiotap header */
  5143. memcpy(ireq.u.name, args, sizeof (int));
  5144. if (ioctl(sock_fd, cmd, &ireq) != -1)
  5145. break; /* success */
  5146. /*
  5147. * That failed. Try to select the AVS header.
  5148. */
  5149. memset(&ireq, 0, sizeof ireq);
  5150. strlcpy(ireq.ifr_ifrn.ifrn_name, device,
  5151. sizeof ireq.ifr_ifrn.ifrn_name);
  5152. args[0] = 2; /* request AVS header */
  5153. memcpy(ireq.u.name, args, sizeof (int));
  5154. if (ioctl(sock_fd, cmd, &ireq) != -1)
  5155. break; /* success */
  5156. /*
  5157. * That failed. Try to select the Prism header.
  5158. */
  5159. memset(&ireq, 0, sizeof ireq);
  5160. strlcpy(ireq.ifr_ifrn.ifrn_name, device,
  5161. sizeof ireq.ifr_ifrn.ifrn_name);
  5162. args[0] = 1; /* request Prism header */
  5163. memcpy(ireq.u.name, args, sizeof (int));
  5164. ioctl(sock_fd, cmd, &ireq);
  5165. break;
  5166. case MONITOR_PRISM:
  5167. /*
  5168. * The private ioctl failed.
  5169. */
  5170. break;
  5171. case MONITOR_PRISM54:
  5172. /*
  5173. * Select the Prism header.
  5174. */
  5175. memset(&ireq, 0, sizeof ireq);
  5176. strlcpy(ireq.ifr_ifrn.ifrn_name, device,
  5177. sizeof ireq.ifr_ifrn.ifrn_name);
  5178. args[0] = 3; /* request Prism header */
  5179. memcpy(ireq.u.name, args, sizeof (int));
  5180. ioctl(sock_fd, cmd, &ireq);
  5181. break;
  5182. case MONITOR_ACX100:
  5183. /*
  5184. * Get the current channel.
  5185. */
  5186. memset(&ireq, 0, sizeof ireq);
  5187. strlcpy(ireq.ifr_ifrn.ifrn_name, device,
  5188. sizeof ireq.ifr_ifrn.ifrn_name);
  5189. if (ioctl(sock_fd, SIOCGIWFREQ, &ireq) == -1) {
  5190. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  5191. "%s: SIOCGIWFREQ: %s", device,
  5192. pcap_strerror(errno));
  5193. return PCAP_ERROR;
  5194. }
  5195. channel = ireq.u.freq.m;
  5196. /*
  5197. * Select the Prism header, and set the channel to the
  5198. * current value.
  5199. */
  5200. memset(&ireq, 0, sizeof ireq);
  5201. strlcpy(ireq.ifr_ifrn.ifrn_name, device,
  5202. sizeof ireq.ifr_ifrn.ifrn_name);
  5203. args[0] = 1; /* request Prism header */
  5204. args[1] = channel; /* set channel */
  5205. memcpy(ireq.u.name, args, 2*sizeof (int));
  5206. ioctl(sock_fd, cmd, &ireq);
  5207. break;
  5208. case MONITOR_RT2500:
  5209. /*
  5210. * Disallow transmission - that turns on the
  5211. * Prism header.
  5212. */
  5213. memset(&ireq, 0, sizeof ireq);
  5214. strlcpy(ireq.ifr_ifrn.ifrn_name, device,
  5215. sizeof ireq.ifr_ifrn.ifrn_name);
  5216. args[0] = 0; /* disallow transmitting */
  5217. memcpy(ireq.u.name, args, sizeof (int));
  5218. ioctl(sock_fd, cmd, &ireq);
  5219. break;
  5220. case MONITOR_RT2570:
  5221. /*
  5222. * Force the Prism header.
  5223. */
  5224. memset(&ireq, 0, sizeof ireq);
  5225. strlcpy(ireq.ifr_ifrn.ifrn_name, device,
  5226. sizeof ireq.ifr_ifrn.ifrn_name);
  5227. args[0] = 1; /* request Prism header */
  5228. memcpy(ireq.u.name, args, sizeof (int));
  5229. ioctl(sock_fd, cmd, &ireq);
  5230. break;
  5231. case MONITOR_RT73:
  5232. /*
  5233. * Force the Prism header.
  5234. */
  5235. memset(&ireq, 0, sizeof ireq);
  5236. strlcpy(ireq.ifr_ifrn.ifrn_name, device,
  5237. sizeof ireq.ifr_ifrn.ifrn_name);
  5238. ireq.u.data.length = 1; /* 1 argument */
  5239. ireq.u.data.pointer = "1";
  5240. ireq.u.data.flags = 0;
  5241. ioctl(sock_fd, cmd, &ireq);
  5242. break;
  5243. case MONITOR_RTL8XXX:
  5244. /*
  5245. * Force the Prism header.
  5246. */
  5247. memset(&ireq, 0, sizeof ireq);
  5248. strlcpy(ireq.ifr_ifrn.ifrn_name, device,
  5249. sizeof ireq.ifr_ifrn.ifrn_name);
  5250. args[0] = 1; /* request Prism header */
  5251. memcpy(ireq.u.name, args, sizeof (int));
  5252. ioctl(sock_fd, cmd, &ireq);
  5253. break;
  5254. }
  5255. /*
  5256. * Now bring the interface back up if we brought it down.
  5257. */
  5258. if (oldflags != 0) {
  5259. ifr.ifr_flags = oldflags;
  5260. if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
  5261. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  5262. "%s: Can't set flags: %s", device, strerror(errno));
  5263. /*
  5264. * At least try to restore the old mode on the
  5265. * interface.
  5266. */
  5267. if (ioctl(handle->fd, SIOCSIWMODE, &ireq) == -1) {
  5268. /*
  5269. * Scientist, you've failed.
  5270. */
  5271. fprintf(stderr,
  5272. "Can't restore interface wireless mode (SIOCSIWMODE failed: %s).\n"
  5273. "Please adjust manually.\n",
  5274. strerror(errno));
  5275. }
  5276. return PCAP_ERROR;
  5277. }
  5278. }
  5279. /*
  5280. * Note that we have to put the old mode back when we
  5281. * close the device.
  5282. */
  5283. handlep->must_do_on_close |= MUST_CLEAR_RFMON;
  5284. /*
  5285. * Add this to the list of pcaps to close when we exit.
  5286. */
  5287. pcap_add_to_pcaps_to_close(handle);
  5288. return 1;
  5289. }
  5290. #endif /* IW_MODE_MONITOR */
  5291. /*
  5292. * Try various mechanisms to enter monitor mode.
  5293. */
  5294. static int
  5295. enter_rfmon_mode(pcap_t *handle, int sock_fd, const char *device)
  5296. {
  5297. #if defined(HAVE_LIBNL) || defined(IW_MODE_MONITOR)
  5298. int ret;
  5299. #endif
  5300. #ifdef HAVE_LIBNL
  5301. ret = enter_rfmon_mode_mac80211(handle, sock_fd, device);
  5302. if (ret < 0)
  5303. return ret; /* error attempting to do so */
  5304. if (ret == 1)
  5305. return 1; /* success */
  5306. #endif /* HAVE_LIBNL */
  5307. #ifdef IW_MODE_MONITOR
  5308. ret = enter_rfmon_mode_wext(handle, sock_fd, device);
  5309. if (ret < 0)
  5310. return ret; /* error attempting to do so */
  5311. if (ret == 1)
  5312. return 1; /* success */
  5313. #endif /* IW_MODE_MONITOR */
  5314. /*
  5315. * Either none of the mechanisms we know about work or none
  5316. * of those mechanisms are available, so we can't do monitor
  5317. * mode.
  5318. */
  5319. return 0;
  5320. }
  5321. #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
  5322. /*
  5323. * Map SOF_TIMESTAMPING_ values to PCAP_TSTAMP_ values.
  5324. */
  5325. static const struct {
  5326. int soft_timestamping_val;
  5327. int pcap_tstamp_val;
  5328. } sof_ts_type_map[3] = {
  5329. { SOF_TIMESTAMPING_SOFTWARE, PCAP_TSTAMP_HOST },
  5330. { SOF_TIMESTAMPING_SYS_HARDWARE, PCAP_TSTAMP_ADAPTER },
  5331. { SOF_TIMESTAMPING_RAW_HARDWARE, PCAP_TSTAMP_ADAPTER_UNSYNCED }
  5332. };
  5333. #define NUM_SOF_TIMESTAMPING_TYPES (sizeof sof_ts_type_map / sizeof sof_ts_type_map[0])
  5334. static void
  5335. iface_set_default_ts_types(pcap_t *handle)
  5336. {
  5337. int i;
  5338. handle->tstamp_type_count = NUM_SOF_TIMESTAMPING_TYPES;
  5339. handle->tstamp_type_list = malloc(NUM_SOF_TIMESTAMPING_TYPES * sizeof(u_int));
  5340. for (i = 0; i < NUM_SOF_TIMESTAMPING_TYPES; i++)
  5341. handle->tstamp_type_list[i] = sof_ts_type_map[i].pcap_tstamp_val;
  5342. }
  5343. #ifdef ETHTOOL_GET_TS_INFO
  5344. /*
  5345. * Get a list of time stamping capabilities.
  5346. */
  5347. static int
  5348. iface_ethtool_get_ts_info(pcap_t *handle, char *ebuf)
  5349. {
  5350. int fd;
  5351. struct ifreq ifr;
  5352. struct ethtool_ts_info info;
  5353. int num_ts_types;
  5354. int i, j;
  5355. /*
  5356. * This doesn't apply to the "any" device; you have to ask
  5357. * specific devices for their capabilities, so just default
  5358. * to saying we support all of them.
  5359. */
  5360. if (strcmp(handle->opt.source, "any") == 0) {
  5361. iface_set_default_ts_types(handle);
  5362. return 0;
  5363. }
  5364. /*
  5365. * Create a socket from which to fetch time stamping capabilities.
  5366. */
  5367. fd = socket(AF_INET, SOCK_DGRAM, 0);
  5368. if (fd < 0) {
  5369. (void)snprintf(ebuf, PCAP_ERRBUF_SIZE,
  5370. "socket for SIOCETHTOOL(ETHTOOL_GET_TS_INFO): %s", pcap_strerror(errno));
  5371. return -1;
  5372. }
  5373. memset(&ifr, 0, sizeof(ifr));
  5374. strlcpy(ifr.ifr_name, handle->opt.source, sizeof(ifr.ifr_name));
  5375. memset(&info, 0, sizeof(info));
  5376. info.cmd = ETHTOOL_GET_TS_INFO;
  5377. ifr.ifr_data = (caddr_t)&info;
  5378. if (ioctl(fd, SIOCETHTOOL, &ifr) == -1) {
  5379. close(fd);
  5380. if (errno == EOPNOTSUPP || errno == EINVAL) {
  5381. /*
  5382. * OK, let's just return all the possible time
  5383. * stamping types.
  5384. */
  5385. iface_set_default_ts_types(handle);
  5386. return 0;
  5387. }
  5388. snprintf(ebuf, PCAP_ERRBUF_SIZE,
  5389. "%s: SIOCETHTOOL(ETHTOOL_GET_TS_INFO) ioctl failed: %s", handle->opt.source,
  5390. strerror(errno));
  5391. return -1;
  5392. }
  5393. close(fd);
  5394. num_ts_types = 0;
  5395. for (i = 0; i < NUM_SOF_TIMESTAMPING_TYPES; i++) {
  5396. if (info.so_timestamping & sof_ts_type_map[i].soft_timestamping_val)
  5397. num_ts_types++;
  5398. }
  5399. handle->tstamp_type_count = num_ts_types;
  5400. if (num_ts_types != 0) {
  5401. handle->tstamp_type_list = malloc(num_ts_types * sizeof(u_int));
  5402. for (i = 0, j = 0; i < NUM_SOF_TIMESTAMPING_TYPES; i++) {
  5403. if (info.so_timestamping & sof_ts_type_map[i].soft_timestamping_val) {
  5404. handle->tstamp_type_list[j] = sof_ts_type_map[i].pcap_tstamp_val;
  5405. j++;
  5406. }
  5407. }
  5408. } else
  5409. handle->tstamp_type_list = NULL;
  5410. return 0;
  5411. }
  5412. #else /* ETHTOOL_GET_TS_INFO */
  5413. static int
  5414. iface_ethtool_get_ts_info(pcap_t *handle, char *ebuf _U_)
  5415. {
  5416. /*
  5417. * We don't have an ioctl to use to ask what's supported,
  5418. * so say we support everything.
  5419. */
  5420. iface_set_default_ts_types(handle);
  5421. return 0;
  5422. }
  5423. #endif /* ETHTOOL_GET_TS_INFO */
  5424. #endif /* defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP) */
  5425. #ifdef HAVE_PACKET_RING
  5426. /*
  5427. * Find out if we have any form of fragmentation/reassembly offloading.
  5428. *
  5429. * We do so using SIOCETHTOOL checking for various types of offloading;
  5430. * if SIOCETHTOOL isn't defined, or we don't have any #defines for any
  5431. * of the types of offloading, there's nothing we can do to check, so
  5432. * we just say "no, we don't".
  5433. */
  5434. #if defined(SIOCETHTOOL) && (defined(ETHTOOL_GTSO) || defined(ETHTOOL_GUFO) || defined(ETHTOOL_GGSO) || defined(ETHTOOL_GFLAGS) || defined(ETHTOOL_GGRO))
  5435. static int
  5436. iface_ethtool_flag_ioctl(pcap_t *handle, int cmd, const char *cmdname)
  5437. {
  5438. struct ifreq ifr;
  5439. struct ethtool_value eval;
  5440. memset(&ifr, 0, sizeof(ifr));
  5441. strlcpy(ifr.ifr_name, handle->opt.source, sizeof(ifr.ifr_name));
  5442. eval.cmd = cmd;
  5443. eval.data = 0;
  5444. ifr.ifr_data = (caddr_t)&eval;
  5445. if (ioctl(handle->fd, SIOCETHTOOL, &ifr) == -1) {
  5446. if (errno == EOPNOTSUPP || errno == EINVAL) {
  5447. /*
  5448. * OK, let's just return 0, which, in our
  5449. * case, either means "no, what we're asking
  5450. * about is not enabled" or "all the flags
  5451. * are clear (i.e., nothing is enabled)".
  5452. */
  5453. return 0;
  5454. }
  5455. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  5456. "%s: SIOCETHTOOL(%s) ioctl failed: %s", handle->opt.source,
  5457. cmdname, strerror(errno));
  5458. return -1;
  5459. }
  5460. return eval.data;
  5461. }
  5462. static int
  5463. iface_get_offload(pcap_t *handle)
  5464. {
  5465. int ret;
  5466. #ifdef ETHTOOL_GTSO
  5467. ret = iface_ethtool_flag_ioctl(handle, ETHTOOL_GTSO, "ETHTOOL_GTSO");
  5468. if (ret == -1)
  5469. return -1;
  5470. if (ret)
  5471. return 1; /* TCP segmentation offloading on */
  5472. #endif
  5473. #ifdef ETHTOOL_GUFO
  5474. ret = iface_ethtool_flag_ioctl(handle, ETHTOOL_GUFO, "ETHTOOL_GUFO");
  5475. if (ret == -1)
  5476. return -1;
  5477. if (ret)
  5478. return 1; /* UDP fragmentation offloading on */
  5479. #endif
  5480. #ifdef ETHTOOL_GGSO
  5481. /*
  5482. * XXX - will this cause large unsegmented packets to be
  5483. * handed to PF_PACKET sockets on transmission? If not,
  5484. * this need not be checked.
  5485. */
  5486. ret = iface_ethtool_flag_ioctl(handle, ETHTOOL_GGSO, "ETHTOOL_GGSO");
  5487. if (ret == -1)
  5488. return -1;
  5489. if (ret)
  5490. return 1; /* generic segmentation offloading on */
  5491. #endif
  5492. #ifdef ETHTOOL_GFLAGS
  5493. ret = iface_ethtool_flag_ioctl(handle, ETHTOOL_GFLAGS, "ETHTOOL_GFLAGS");
  5494. if (ret == -1)
  5495. return -1;
  5496. if (ret & ETH_FLAG_LRO)
  5497. return 1; /* large receive offloading on */
  5498. #endif
  5499. #ifdef ETHTOOL_GGRO
  5500. /*
  5501. * XXX - will this cause large reassembled packets to be
  5502. * handed to PF_PACKET sockets on receipt? If not,
  5503. * this need not be checked.
  5504. */
  5505. ret = iface_ethtool_flag_ioctl(handle, ETHTOOL_GGRO, "ETHTOOL_GGRO");
  5506. if (ret == -1)
  5507. return -1;
  5508. if (ret)
  5509. return 1; /* generic (large) receive offloading on */
  5510. #endif
  5511. return 0;
  5512. }
  5513. #else /* SIOCETHTOOL */
  5514. static int
  5515. iface_get_offload(pcap_t *handle _U_)
  5516. {
  5517. /*
  5518. * XXX - do we need to get this information if we don't
  5519. * have the ethtool ioctls? If so, how do we do that?
  5520. */
  5521. return 0;
  5522. }
  5523. #endif /* SIOCETHTOOL */
  5524. #endif /* HAVE_PACKET_RING */
  5525. #endif /* HAVE_PF_PACKET_SOCKETS */
  5526. /* ===== Functions to interface to the older kernels ================== */
  5527. /*
  5528. * Try to open a packet socket using the old kernel interface.
  5529. * Returns 1 on success and a PCAP_ERROR_ value on an error.
  5530. */
  5531. static int
  5532. activate_old(pcap_t *handle)
  5533. {
  5534. struct pcap_linux *handlep = handle->priv;
  5535. int arptype;
  5536. struct ifreq ifr;
  5537. const char *device = handle->opt.source;
  5538. struct utsname utsname;
  5539. int mtu;
  5540. /* Open the socket */
  5541. handle->fd = socket(PF_INET, SOCK_PACKET, htons(ETH_P_ALL));
  5542. if (handle->fd == -1) {
  5543. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  5544. "socket: %s", pcap_strerror(errno));
  5545. if (errno == EPERM || errno == EACCES) {
  5546. /*
  5547. * You don't have permission to open the
  5548. * socket.
  5549. */
  5550. return PCAP_ERROR_PERM_DENIED;
  5551. } else {
  5552. /*
  5553. * Other error.
  5554. */
  5555. return PCAP_ERROR;
  5556. }
  5557. }
  5558. /* It worked - we are using the old interface */
  5559. handlep->sock_packet = 1;
  5560. /* ...which means we get the link-layer header. */
  5561. handlep->cooked = 0;
  5562. /* Bind to the given device */
  5563. if (strcmp(device, "any") == 0) {
  5564. strlcpy(handle->errbuf, "pcap_activate: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
  5565. PCAP_ERRBUF_SIZE);
  5566. return PCAP_ERROR;
  5567. }
  5568. if (iface_bind_old(handle->fd, device, handle->errbuf) == -1)
  5569. return PCAP_ERROR;
  5570. /*
  5571. * Try to get the link-layer type.
  5572. */
  5573. arptype = iface_get_arptype(handle->fd, device, handle->errbuf);
  5574. if (arptype < 0)
  5575. return PCAP_ERROR;
  5576. /*
  5577. * Try to find the DLT_ type corresponding to that
  5578. * link-layer type.
  5579. */
  5580. map_arphrd_to_dlt(handle, handle->fd, arptype, device, 0);
  5581. if (handle->linktype == -1) {
  5582. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  5583. "unknown arptype %d", arptype);
  5584. return PCAP_ERROR;
  5585. }
  5586. /* Go to promisc mode if requested */
  5587. if (handle->opt.promisc) {
  5588. memset(&ifr, 0, sizeof(ifr));
  5589. strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
  5590. if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) == -1) {
  5591. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  5592. "SIOCGIFFLAGS: %s", pcap_strerror(errno));
  5593. return PCAP_ERROR;
  5594. }
  5595. if ((ifr.ifr_flags & IFF_PROMISC) == 0) {
  5596. /*
  5597. * Promiscuous mode isn't currently on,
  5598. * so turn it on, and remember that
  5599. * we should turn it off when the
  5600. * pcap_t is closed.
  5601. */
  5602. /*
  5603. * If we haven't already done so, arrange
  5604. * to have "pcap_close_all()" called when
  5605. * we exit.
  5606. */
  5607. if (!pcap_do_addexit(handle)) {
  5608. /*
  5609. * "atexit()" failed; don't put
  5610. * the interface in promiscuous
  5611. * mode, just give up.
  5612. */
  5613. return PCAP_ERROR;
  5614. }
  5615. ifr.ifr_flags |= IFF_PROMISC;
  5616. if (ioctl(handle->fd, SIOCSIFFLAGS, &ifr) == -1) {
  5617. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  5618. "SIOCSIFFLAGS: %s",
  5619. pcap_strerror(errno));
  5620. return PCAP_ERROR;
  5621. }
  5622. handlep->must_do_on_close |= MUST_CLEAR_PROMISC;
  5623. /*
  5624. * Add this to the list of pcaps
  5625. * to close when we exit.
  5626. */
  5627. pcap_add_to_pcaps_to_close(handle);
  5628. }
  5629. }
  5630. /*
  5631. * Compute the buffer size.
  5632. *
  5633. * We're using SOCK_PACKET, so this might be a 2.0[.x]
  5634. * kernel, and might require special handling - check.
  5635. */
  5636. if (uname(&utsname) < 0 ||
  5637. strncmp(utsname.release, "2.0", 3) == 0) {
  5638. /*
  5639. * Either we couldn't find out what kernel release
  5640. * this is, or it's a 2.0[.x] kernel.
  5641. *
  5642. * In the 2.0[.x] kernel, a "recvfrom()" on
  5643. * a SOCK_PACKET socket, with MSG_TRUNC set, will
  5644. * return the number of bytes read, so if we pass
  5645. * a length based on the snapshot length, it'll
  5646. * return the number of bytes from the packet
  5647. * copied to userland, not the actual length
  5648. * of the packet.
  5649. *
  5650. * This means that, for example, the IP dissector
  5651. * in tcpdump will get handed a packet length less
  5652. * than the length in the IP header, and will
  5653. * complain about "truncated-ip".
  5654. *
  5655. * So we don't bother trying to copy from the
  5656. * kernel only the bytes in which we're interested,
  5657. * but instead copy them all, just as the older
  5658. * versions of libpcap for Linux did.
  5659. *
  5660. * The buffer therefore needs to be big enough to
  5661. * hold the largest packet we can get from this
  5662. * device. Unfortunately, we can't get the MRU
  5663. * of the network; we can only get the MTU. The
  5664. * MTU may be too small, in which case a packet larger
  5665. * than the buffer size will be truncated *and* we
  5666. * won't get the actual packet size.
  5667. *
  5668. * However, if the snapshot length is larger than
  5669. * the buffer size based on the MTU, we use the
  5670. * snapshot length as the buffer size, instead;
  5671. * this means that with a sufficiently large snapshot
  5672. * length we won't artificially truncate packets
  5673. * to the MTU-based size.
  5674. *
  5675. * This mess just one of many problems with packet
  5676. * capture on 2.0[.x] kernels; you really want a
  5677. * 2.2[.x] or later kernel if you want packet capture
  5678. * to work well.
  5679. */
  5680. mtu = iface_get_mtu(handle->fd, device, handle->errbuf);
  5681. if (mtu == -1)
  5682. return PCAP_ERROR;
  5683. handle->bufsize = MAX_LINKHEADER_SIZE + mtu;
  5684. if (handle->bufsize < handle->snapshot)
  5685. handle->bufsize = handle->snapshot;
  5686. } else {
  5687. /*
  5688. * This is a 2.2[.x] or later kernel.
  5689. *
  5690. * We can safely pass "recvfrom()" a byte count
  5691. * based on the snapshot length.
  5692. */
  5693. handle->bufsize = handle->snapshot;
  5694. }
  5695. /*
  5696. * Default value for offset to align link-layer payload
  5697. * on a 4-byte boundary.
  5698. */
  5699. handle->offset = 0;
  5700. /*
  5701. * SOCK_PACKET sockets don't supply information from
  5702. * stripped VLAN tags.
  5703. */
  5704. handlep->vlan_offset = -1; /* unknown */
  5705. return 1;
  5706. }
  5707. /*
  5708. * Bind the socket associated with FD to the given device using the
  5709. * interface of the old kernels.
  5710. */
  5711. static int
  5712. iface_bind_old(int fd, const char *device, char *ebuf)
  5713. {
  5714. struct sockaddr saddr;
  5715. int err;
  5716. socklen_t errlen = sizeof(err);
  5717. memset(&saddr, 0, sizeof(saddr));
  5718. strlcpy(saddr.sa_data, device, sizeof(saddr.sa_data));
  5719. if (bind(fd, &saddr, sizeof(saddr)) == -1) {
  5720. snprintf(ebuf, PCAP_ERRBUF_SIZE,
  5721. "bind: %s", pcap_strerror(errno));
  5722. return -1;
  5723. }
  5724. /* Any pending errors, e.g., network is down? */
  5725. if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen) == -1) {
  5726. snprintf(ebuf, PCAP_ERRBUF_SIZE,
  5727. "getsockopt: %s", pcap_strerror(errno));
  5728. return -1;
  5729. }
  5730. if (err > 0) {
  5731. snprintf(ebuf, PCAP_ERRBUF_SIZE,
  5732. "bind: %s", pcap_strerror(err));
  5733. return -1;
  5734. }
  5735. return 0;
  5736. }
  5737. /* ===== System calls available on all supported kernels ============== */
  5738. /*
  5739. * Query the kernel for the MTU of the given interface.
  5740. */
  5741. static int
  5742. iface_get_mtu(int fd, const char *device, char *ebuf)
  5743. {
  5744. struct ifreq ifr;
  5745. if (!device)
  5746. return BIGGER_THAN_ALL_MTUS;
  5747. memset(&ifr, 0, sizeof(ifr));
  5748. strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
  5749. if (ioctl(fd, SIOCGIFMTU, &ifr) == -1) {
  5750. snprintf(ebuf, PCAP_ERRBUF_SIZE,
  5751. "SIOCGIFMTU: %s", pcap_strerror(errno));
  5752. return -1;
  5753. }
  5754. return ifr.ifr_mtu;
  5755. }
  5756. /*
  5757. * Get the hardware type of the given interface as ARPHRD_xxx constant.
  5758. */
  5759. static int
  5760. iface_get_arptype(int fd, const char *device, char *ebuf)
  5761. {
  5762. struct ifreq ifr;
  5763. memset(&ifr, 0, sizeof(ifr));
  5764. strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
  5765. if (ioctl(fd, SIOCGIFHWADDR, &ifr) == -1) {
  5766. snprintf(ebuf, PCAP_ERRBUF_SIZE,
  5767. "SIOCGIFHWADDR: %s", pcap_strerror(errno));
  5768. if (errno == ENODEV) {
  5769. /*
  5770. * No such device.
  5771. */
  5772. return PCAP_ERROR_NO_SUCH_DEVICE;
  5773. }
  5774. return PCAP_ERROR;
  5775. }
  5776. return ifr.ifr_hwaddr.sa_family;
  5777. }
  5778. #ifdef SO_ATTACH_FILTER
  5779. static int
  5780. fix_program(pcap_t *handle, struct sock_fprog *fcode, int is_mmapped)
  5781. {
  5782. struct pcap_linux *handlep = handle->priv;
  5783. size_t prog_size;
  5784. register int i;
  5785. register struct bpf_insn *p;
  5786. struct bpf_insn *f;
  5787. int len;
  5788. /*
  5789. * Make a copy of the filter, and modify that copy if
  5790. * necessary.
  5791. */
  5792. prog_size = sizeof(*handle->fcode.bf_insns) * handle->fcode.bf_len;
  5793. len = handle->fcode.bf_len;
  5794. f = (struct bpf_insn *)malloc(prog_size);
  5795. if (f == NULL) {
  5796. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  5797. "malloc: %s", pcap_strerror(errno));
  5798. return -1;
  5799. }
  5800. memcpy(f, handle->fcode.bf_insns, prog_size);
  5801. fcode->len = len;
  5802. fcode->filter = (struct sock_filter *) f;
  5803. for (i = 0; i < len; ++i) {
  5804. p = &f[i];
  5805. /*
  5806. * What type of instruction is this?
  5807. */
  5808. switch (BPF_CLASS(p->code)) {
  5809. case BPF_RET:
  5810. /*
  5811. * It's a return instruction; are we capturing
  5812. * in memory-mapped mode?
  5813. */
  5814. if (!is_mmapped) {
  5815. /*
  5816. * No; is the snapshot length a constant,
  5817. * rather than the contents of the
  5818. * accumulator?
  5819. */
  5820. if (BPF_MODE(p->code) == BPF_K) {
  5821. /*
  5822. * Yes - if the value to be returned,
  5823. * i.e. the snapshot length, is
  5824. * anything other than 0, make it
  5825. * MAXIMUM_SNAPLEN, so that the packet
  5826. * is truncated by "recvfrom()",
  5827. * not by the filter.
  5828. *
  5829. * XXX - there's nothing we can
  5830. * easily do if it's getting the
  5831. * value from the accumulator; we'd
  5832. * have to insert code to force
  5833. * non-zero values to be
  5834. * MAXIMUM_SNAPLEN.
  5835. */
  5836. if (p->k != 0)
  5837. p->k = MAXIMUM_SNAPLEN;
  5838. }
  5839. }
  5840. break;
  5841. case BPF_LD:
  5842. case BPF_LDX:
  5843. /*
  5844. * It's a load instruction; is it loading
  5845. * from the packet?
  5846. */
  5847. switch (BPF_MODE(p->code)) {
  5848. case BPF_ABS:
  5849. case BPF_IND:
  5850. case BPF_MSH:
  5851. /*
  5852. * Yes; are we in cooked mode?
  5853. */
  5854. if (handlep->cooked) {
  5855. /*
  5856. * Yes, so we need to fix this
  5857. * instruction.
  5858. */
  5859. if (fix_offset(p) < 0) {
  5860. /*
  5861. * We failed to do so.
  5862. * Return 0, so our caller
  5863. * knows to punt to userland.
  5864. */
  5865. return 0;
  5866. }
  5867. }
  5868. break;
  5869. }
  5870. break;
  5871. }
  5872. }
  5873. return 1; /* we succeeded */
  5874. }
  5875. static int
  5876. fix_offset(struct bpf_insn *p)
  5877. {
  5878. /*
  5879. * What's the offset?
  5880. */
  5881. if (p->k >= SLL_HDR_LEN) {
  5882. /*
  5883. * It's within the link-layer payload; that starts at an
  5884. * offset of 0, as far as the kernel packet filter is
  5885. * concerned, so subtract the length of the link-layer
  5886. * header.
  5887. */
  5888. p->k -= SLL_HDR_LEN;
  5889. } else if (p->k == 0) {
  5890. /*
  5891. * It's the packet type field; map it to the special magic
  5892. * kernel offset for that field.
  5893. */
  5894. p->k = SKF_AD_OFF + SKF_AD_PKTTYPE;
  5895. } else if (p->k == 14) {
  5896. /*
  5897. * It's the protocol field; map it to the special magic
  5898. * kernel offset for that field.
  5899. */
  5900. p->k = SKF_AD_OFF + SKF_AD_PROTOCOL;
  5901. } else if ((bpf_int32)(p->k) > 0) {
  5902. /*
  5903. * It's within the header, but it's not one of those
  5904. * fields; we can't do that in the kernel, so punt
  5905. * to userland.
  5906. */
  5907. return -1;
  5908. }
  5909. return 0;
  5910. }
  5911. static int
  5912. set_kernel_filter(pcap_t *handle, struct sock_fprog *fcode)
  5913. {
  5914. int total_filter_on = 0;
  5915. int save_mode;
  5916. int ret;
  5917. int save_errno;
  5918. /*
  5919. * The socket filter code doesn't discard all packets queued
  5920. * up on the socket when the filter is changed; this means
  5921. * that packets that don't match the new filter may show up
  5922. * after the new filter is put onto the socket, if those
  5923. * packets haven't yet been read.
  5924. *
  5925. * This means, for example, that if you do a tcpdump capture
  5926. * with a filter, the first few packets in the capture might
  5927. * be packets that wouldn't have passed the filter.
  5928. *
  5929. * We therefore discard all packets queued up on the socket
  5930. * when setting a kernel filter. (This isn't an issue for
  5931. * userland filters, as the userland filtering is done after
  5932. * packets are queued up.)
  5933. *
  5934. * To flush those packets, we put the socket in read-only mode,
  5935. * and read packets from the socket until there are no more to
  5936. * read.
  5937. *
  5938. * In order to keep that from being an infinite loop - i.e.,
  5939. * to keep more packets from arriving while we're draining
  5940. * the queue - we put the "total filter", which is a filter
  5941. * that rejects all packets, onto the socket before draining
  5942. * the queue.
  5943. *
  5944. * This code deliberately ignores any errors, so that you may
  5945. * get bogus packets if an error occurs, rather than having
  5946. * the filtering done in userland even if it could have been
  5947. * done in the kernel.
  5948. */
  5949. if (setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER,
  5950. &total_fcode, sizeof(total_fcode)) == 0) {
  5951. char drain[1];
  5952. /*
  5953. * Note that we've put the total filter onto the socket.
  5954. */
  5955. total_filter_on = 1;
  5956. /*
  5957. * Save the socket's current mode, and put it in
  5958. * non-blocking mode; we drain it by reading packets
  5959. * until we get an error (which is normally a
  5960. * "nothing more to be read" error).
  5961. */
  5962. save_mode = fcntl(handle->fd, F_GETFL, 0);
  5963. if (save_mode == -1) {
  5964. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  5965. "can't get FD flags when changing filter: %s",
  5966. pcap_strerror(errno));
  5967. return -2;
  5968. }
  5969. if (fcntl(handle->fd, F_SETFL, save_mode | O_NONBLOCK) < 0) {
  5970. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  5971. "can't set nonblocking mode when changing filter: %s",
  5972. pcap_strerror(errno));
  5973. return -2;
  5974. }
  5975. while (recv(handle->fd, &drain, sizeof drain, MSG_TRUNC) >= 0)
  5976. ;
  5977. save_errno = errno;
  5978. if (save_errno != EAGAIN) {
  5979. /*
  5980. * Fatal error.
  5981. *
  5982. * If we can't restore the mode or reset the
  5983. * kernel filter, there's nothing we can do.
  5984. */
  5985. (void)fcntl(handle->fd, F_SETFL, save_mode);
  5986. (void)reset_kernel_filter(handle);
  5987. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  5988. "recv failed when changing filter: %s",
  5989. pcap_strerror(save_errno));
  5990. return -2;
  5991. }
  5992. if (fcntl(handle->fd, F_SETFL, save_mode) == -1) {
  5993. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  5994. "can't restore FD flags when changing filter: %s",
  5995. pcap_strerror(save_errno));
  5996. return -2;
  5997. }
  5998. }
  5999. /*
  6000. * Now attach the new filter.
  6001. */
  6002. ret = setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER,
  6003. fcode, sizeof(*fcode));
  6004. if (ret == -1 && total_filter_on) {
  6005. /*
  6006. * Well, we couldn't set that filter on the socket,
  6007. * but we could set the total filter on the socket.
  6008. *
  6009. * This could, for example, mean that the filter was
  6010. * too big to put into the kernel, so we'll have to
  6011. * filter in userland; in any case, we'll be doing
  6012. * filtering in userland, so we need to remove the
  6013. * total filter so we see packets.
  6014. */
  6015. save_errno = errno;
  6016. /*
  6017. * If this fails, we're really screwed; we have the
  6018. * total filter on the socket, and it won't come off.
  6019. * Report it as a fatal error.
  6020. */
  6021. if (reset_kernel_filter(handle) == -1) {
  6022. snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  6023. "can't remove kernel total filter: %s",
  6024. pcap_strerror(errno));
  6025. return -2; /* fatal error */
  6026. }
  6027. errno = save_errno;
  6028. }
  6029. return ret;
  6030. }
  6031. static int
  6032. reset_kernel_filter(pcap_t *handle)
  6033. {
  6034. /*
  6035. * setsockopt() barfs unless it get a dummy parameter.
  6036. * valgrind whines unless the value is initialized,
  6037. * as it has no idea that setsockopt() ignores its
  6038. * parameter.
  6039. */
  6040. int dummy = 0;
  6041. return setsockopt(handle->fd, SOL_SOCKET, SO_DETACH_FILTER,
  6042. &dummy, sizeof(dummy));
  6043. }
  6044. #endif