PageRenderTime 60ms CodeModel.GetById 16ms 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

Large files files are truncated, but you can click here to view the full file

  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

Large files files are truncated, but you can click here to view the full file