2 * pcap-linux.c: Packet capture interface to the Linux kernel
4 * Copyright (c) 2000 Torsten Landschoff <torsten@debian.org>
5 * Sebastian Krahmer <krahmer@cs.uni-potsdam.de>
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
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
19 * 3. The names of the authors may not be used to endorse or promote
20 * products derived from this software without specific prior
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.
27 * Modifications: Added PACKET_MMAP support
28 * Paolo Abeni <paolo.abeni@email.it>
30 * based on previous works of:
31 * Simon Patarin <patarin@cs.unibo.it>
32 * Phil Wood <cpw@lanl.gov>
34 * Monitor-mode support for mac80211 includes code taken from the iw
35 * command; the copyright notice for that code is
37 * Copyright (c) 2007, 2008 Johannes Berg
38 * Copyright (c) 2007 Andy Lutomirski
39 * Copyright (c) 2007 Mike Kershaw
40 * Copyright (c) 2008 Gábor Stefanik
42 * All rights reserved.
44 * Redistribution and use in source and binary forms, with or without
45 * modification, are permitted provided that the following conditions
47 * 1. Redistributions of source code must retain the above copyright
48 * notice, this list of conditions and the following disclaimer.
49 * 2. Redistributions in binary form must reproduce the above copyright
50 * notice, this list of conditions and the following disclaimer in the
51 * documentation and/or other materials provided with the distribution.
52 * 3. The name of the author may not be used to endorse or promote products
53 * derived from this software without specific prior written permission.
55 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
56 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
57 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
58 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
59 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
60 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
61 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
62 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
63 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
64 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
69 static const char rcsid
[] _U_
=
70 "@(#) $Header: /tcpdump/master/libpcap/pcap-linux.c,v 1.164 2008-12-14 22:00:57 guy Exp $ (LBL)";
74 * Known problems with 2.0[.x] kernels:
76 * - The loopback device gives every packet twice; on 2.2[.x] kernels,
77 * if we use PF_PACKET, we can filter out the transmitted version
78 * of the packet by using data in the "sockaddr_ll" returned by
79 * "recvfrom()", but, on 2.0[.x] kernels, we have to use
80 * PF_INET/SOCK_PACKET, which means "recvfrom()" supplies a
81 * "sockaddr_pkt" which doesn't give us enough information to let
84 * - We have to set the interface's IFF_PROMISC flag ourselves, if
85 * we're to run in promiscuous mode, which means we have to turn
86 * it off ourselves when we're done; the kernel doesn't keep track
87 * of how many sockets are listening promiscuously, which means
88 * it won't get turned off automatically when no sockets are
89 * listening promiscuously. We catch "pcap_close()" and, for
90 * interfaces we put into promiscuous mode, take them out of
91 * promiscuous mode - which isn't necessarily the right thing to
92 * do, if another socket also requested promiscuous mode between
93 * the time when we opened the socket and the time when we close
96 * - MSG_TRUNC isn't supported, so you can't specify that "recvfrom()"
97 * return the amount of data that you could have read, rather than
98 * the amount that was returned, so we can't just allocate a buffer
99 * whose size is the snapshot length and pass the snapshot length
100 * as the byte count, and also pass MSG_TRUNC, so that the return
101 * value tells us how long the packet was on the wire.
103 * This means that, if we want to get the actual size of the packet,
104 * so we can return it in the "len" field of the packet header,
105 * we have to read the entire packet, not just the part that fits
106 * within the snapshot length, and thus waste CPU time copying data
107 * from the kernel that our caller won't see.
109 * We have to get the actual size, and supply it in "len", because
110 * otherwise, the IP dissector in tcpdump, for example, will complain
111 * about "truncated-ip", as the packet will appear to have been
112 * shorter, on the wire, than the IP header said it should have been.
129 #include <sys/socket.h>
130 #include <sys/ioctl.h>
131 #include <sys/utsname.h>
132 #include <sys/mman.h>
133 #include <linux/if.h>
134 #include <netinet/in.h>
135 #include <linux/if_ether.h>
136 #include <net/if_arp.h>
140 * Got Wireless Extensions?
142 #ifdef HAVE_LINUX_WIRELESS_H
143 #include <linux/wireless.h>
144 #endif /* HAVE_LINUX_WIRELESS_H */
150 #include <linux/nl80211.h>
152 #include <netlink/genl/genl.h>
153 #include <netlink/genl/family.h>
154 #include <netlink/genl/ctrl.h>
155 #include <netlink/msg.h>
156 #include <netlink/attr.h>
157 #endif /* HAVE_LIBNL */
159 #include "pcap-int.h"
160 #include "pcap/sll.h"
161 #include "pcap/vlan.h"
164 #include "pcap-dag.h"
165 #endif /* HAVE_DAG_API */
167 #ifdef HAVE_SEPTEL_API
168 #include "pcap-septel.h"
169 #endif /* HAVE_SEPTEL_API */
171 #ifdef PCAP_SUPPORT_USB
172 #include "pcap-usb-linux.h"
175 #ifdef PCAP_SUPPORT_BT
176 #include "pcap-bt-linux.h"
180 * If PF_PACKET is defined, we can use {SOCK_RAW,SOCK_DGRAM}/PF_PACKET
181 * sockets rather than SOCK_PACKET sockets.
183 * To use them, we include <linux/if_packet.h> rather than
184 * <netpacket/packet.h>; we do so because
186 * some Linux distributions (e.g., Slackware 4.0) have 2.2 or
187 * later kernels and libc5, and don't provide a <netpacket/packet.h>
190 * not all versions of glibc2 have a <netpacket/packet.h> file
191 * that defines stuff needed for some of the 2.4-or-later-kernel
192 * features, so if the system has a 2.4 or later kernel, we
193 * still can't use those features.
195 * We're already including a number of other <linux/XXX.h> headers, and
196 * this code is Linux-specific (no other OS has PF_PACKET sockets as
197 * a raw packet capture mechanism), so it's not as if you gain any
198 * useful portability by using <netpacket/packet.h>
200 * XXX - should we just include <linux/if_packet.h> even if PF_PACKET
201 * isn't defined? It only defines one data structure in 2.0.x, so
202 * it shouldn't cause any problems.
205 # include <linux/if_packet.h>
208 * On at least some Linux distributions (for example, Red Hat 5.2),
209 * there's no <netpacket/packet.h> file, but PF_PACKET is defined if
210 * you include <sys/socket.h>, but <linux/if_packet.h> doesn't define
211 * any of the PF_PACKET stuff such as "struct sockaddr_ll" or any of
212 * the PACKET_xxx stuff.
214 * So we check whether PACKET_HOST is defined, and assume that we have
215 * PF_PACKET sockets only if it is defined.
218 # define HAVE_PF_PACKET_SOCKETS
219 # ifdef PACKET_AUXDATA
220 # define HAVE_PACKET_AUXDATA
221 # endif /* PACKET_AUXDATA */
222 # endif /* PACKET_HOST */
225 /* check for memory mapped access avaibility. We assume every needed
226 * struct is defined if the macro TPACKET_HDRLEN is defined, because it
227 * uses many ring related structs and macros */
228 # ifdef TPACKET_HDRLEN
229 # define HAVE_PACKET_RING
230 # ifdef TPACKET2_HDRLEN
231 # define HAVE_TPACKET2
233 # define TPACKET_V1 0
234 # endif /* TPACKET2_HDRLEN */
235 # endif /* TPACKET_HDRLEN */
236 #endif /* PF_PACKET */
238 #ifdef SO_ATTACH_FILTER
239 #include <linux/types.h>
240 #include <linux/filter.h>
243 #ifndef HAVE_SOCKLEN_T
244 typedef int socklen_t
;
249 * This is being compiled on a system that lacks MSG_TRUNC; define it
250 * with the value it has in the 2.2 and later kernels, so that, on
251 * those kernels, when we pass it in the flags argument to "recvfrom()"
252 * we're passing the right value and thus get the MSG_TRUNC behavior
253 * we want. (We don't get that behavior on 2.0[.x] kernels, because
254 * they didn't support MSG_TRUNC.)
256 #define MSG_TRUNC 0x20
261 * This is being compiled on a system that lacks SOL_PACKET; define it
262 * with the value it has in the 2.2 and later kernels, so that we can
263 * set promiscuous mode in the good modern way rather than the old
264 * 2.0-kernel crappy way.
266 #define SOL_PACKET 263
269 #define MAX_LINKHEADER_SIZE 256
272 * When capturing on all interfaces we use this as the buffer size.
273 * Should be bigger then all MTUs that occur in real life.
274 * 64kB should be enough for now.
276 #define BIGGER_THAN_ALL_MTUS (64*1024)
279 * Prototypes for internal functions and methods.
281 static void map_arphrd_to_dlt(pcap_t
*, int, int);
282 #ifdef HAVE_PF_PACKET_SOCKETS
283 static short int map_packet_type_to_sll_type(short int);
285 static int pcap_activate_linux(pcap_t
*);
286 static int activate_old(pcap_t
*);
287 static int activate_new(pcap_t
*);
288 static int activate_mmap(pcap_t
*);
289 static int pcap_can_set_rfmon_linux(pcap_t
*);
290 static int pcap_read_linux(pcap_t
*, int, pcap_handler
, u_char
*);
291 static int pcap_read_packet(pcap_t
*, pcap_handler
, u_char
*);
292 static int pcap_inject_linux(pcap_t
*, const void *, size_t);
293 static int pcap_stats_linux(pcap_t
*, struct pcap_stat
*);
294 static int pcap_setfilter_linux(pcap_t
*, struct bpf_program
*);
295 static int pcap_setdirection_linux(pcap_t
*, pcap_direction_t
);
296 static void pcap_cleanup_linux(pcap_t
*);
299 struct tpacket_hdr
*h1
;
300 struct tpacket2_hdr
*h2
;
304 #ifdef HAVE_PACKET_RING
305 #define RING_GET_FRAME(h) (((union thdr **)h->buffer)[h->offset])
307 static void destroy_ring(pcap_t
*handle
);
308 static int create_ring(pcap_t
*handle
);
309 static int prepare_tpacket_socket(pcap_t
*handle
);
310 static void pcap_cleanup_linux_mmap(pcap_t
*);
311 static int pcap_read_linux_mmap(pcap_t
*, int, pcap_handler
, u_char
*);
312 static int pcap_setfilter_linux_mmap(pcap_t
*, struct bpf_program
*);
313 static int pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
, char *errbuf
);
314 static int pcap_getnonblock_mmap(pcap_t
*p
, char *errbuf
);
315 static void pcap_oneshot_mmap(u_char
*user
, const struct pcap_pkthdr
*h
,
316 const u_char
*bytes
);
320 * Wrap some ioctl calls
322 #ifdef HAVE_PF_PACKET_SOCKETS
323 static int iface_get_id(int fd
, const char *device
, char *ebuf
);
325 static int iface_get_mtu(int fd
, const char *device
, char *ebuf
);
326 static int iface_get_arptype(int fd
, const char *device
, char *ebuf
);
327 #ifdef HAVE_PF_PACKET_SOCKETS
328 static int iface_bind(int fd
, int ifindex
, char *ebuf
);
329 #ifdef IW_MODE_MONITOR
330 static int has_wext(int sock_fd
, const char *device
, char *ebuf
);
331 #endif /* IW_MODE_MONITOR */
332 static int enter_rfmon_mode(pcap_t
*handle
, int sock_fd
,
334 #endif /* HAVE_PF_PACKET_SOCKETS */
335 static int iface_bind_old(int fd
, const char *device
, char *ebuf
);
337 #ifdef SO_ATTACH_FILTER
338 static int fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
,
340 static int fix_offset(struct bpf_insn
*p
);
341 static int set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
);
342 static int reset_kernel_filter(pcap_t
*handle
);
344 static struct sock_filter total_insn
345 = BPF_STMT(BPF_RET
| BPF_K
, 0);
346 static struct sock_fprog total_fcode
347 = { 1, &total_insn
};
351 pcap_create(const char *device
, char *ebuf
)
356 * A null device name is equivalent to the "any" device.
362 if (strstr(device
, "dag")) {
363 return dag_create(device
, ebuf
);
365 #endif /* HAVE_DAG_API */
367 #ifdef HAVE_SEPTEL_API
368 if (strstr(device
, "septel")) {
369 return septel_create(device
, ebuf
);
371 #endif /* HAVE_SEPTEL_API */
373 #ifdef PCAP_SUPPORT_BT
374 if (strstr(device
, "bluetooth")) {
375 return bt_create(device
, ebuf
);
379 #ifdef PCAP_SUPPORT_USB
380 if (strstr(device
, "usbmon")) {
381 return usb_create(device
, ebuf
);
385 handle
= pcap_create_common(device
, ebuf
);
389 handle
->activate_op
= pcap_activate_linux
;
390 handle
->can_set_rfmon_op
= pcap_can_set_rfmon_linux
;
397 * If interface {if} is a mac80211 driver, the file
398 * /sys/class/net/{if}/phy80211 is a symlink to
399 * /sys/class/ieee80211/{phydev}, for some {phydev}.
401 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
402 * least, has a "wmaster0" device and a "wlan0" device; the
403 * latter is the one with the IP address. Both show up in
404 * "tcpdump -D" output. Capturing on the wmaster0 device
405 * captures with 802.11 headers.
407 * airmon-ng searches through /sys/class/net for devices named
408 * monN, starting with mon0; as soon as one *doesn't* exist,
409 * it chooses that as the monitor device name. If the "iw"
410 * command exists, it does "iw dev {if} interface add {monif}
411 * type monitor", where {monif} is the monitor device. It
412 * then (sigh) sleeps .1 second, and then configures the
413 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
414 * is a file, it writes {mondev}, without a newline, to that file,
415 * and again (sigh) sleeps .1 second, and then iwconfig's that
416 * device into monitor mode and configures it up. Otherwise,
417 * you can't do monitor mode.
419 * All these devices are "glued" together by having the
420 * /sys/class/net/{device}/phy80211 links pointing to the same
421 * place, so, given a wmaster, wlan, or mon device, you can
422 * find the other devices by looking for devices with
423 * the same phy80211 link.
425 * To turn monitor mode off, delete the monitor interface,
426 * either with "iw dev {monif} interface del" or by sending
427 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
429 * Note: if you try to create a monitor device named "monN", and
430 * there's already a "monN" device, it fails, as least with
431 * the netlink interface (which is what iw uses), with a return
432 * value of -ENFILE. (Return values are negative errnos.) We
433 * could probably use that to find an unused device.
435 * Yes, you can have multiple monitor devices for a given
440 * Is this a mac80211 device? If so, fill in the physical device path and
441 * return 1; if not, return 0. On an error, fill in handle->errbuf and
445 get_mac80211_phydev(pcap_t
*handle
, const char *device
, char *phydev_path
,
446 size_t phydev_max_pathlen
)
452 * Generate the path string for the symlink to the physical device.
454 if (asprintf(&pathstr
, "/sys/class/net/%s/phy80211", device
) == -1) {
455 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
456 "%s: Can't generate path name string for /sys/class/net device",
460 bytes_read
= readlink(pathstr
, phydev_path
, phydev_max_pathlen
);
461 if (bytes_read
== -1) {
462 if (errno
== ENOENT
|| errno
== EINVAL
) {
464 * Doesn't exist, or not a symlink; assume that
465 * means it's not a mac80211 device.
470 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
471 "%s: Can't readlink %s: %s", device
, pathstr
,
477 phydev_path
[bytes_read
] = '\0';
481 struct nl80211_state
{
482 struct nl_handle
*nl_handle
;
483 struct nl_cache
*nl_cache
;
484 struct genl_family
*nl80211
;
488 nl80211_init(pcap_t
*handle
, struct nl80211_state
*state
, const char *device
)
490 state
->nl_handle
= nl_handle_alloc();
491 if (!state
->nl_handle
) {
492 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
493 "%s: failed to allocate netlink handle", device
);
497 if (genl_connect(state
->nl_handle
)) {
498 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
499 "%s: failed to connect to generic netlink", device
);
500 goto out_handle_destroy
;
503 state
->nl_cache
= genl_ctrl_alloc_cache(state
->nl_handle
);
504 if (!state
->nl_cache
) {
505 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
506 "%s: failed to allocate generic netlink cache", device
);
507 goto out_handle_destroy
;
510 state
->nl80211
= genl_ctrl_search_by_name(state
->nl_cache
, "nl80211");
511 if (!state
->nl80211
) {
512 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
513 "%s: nl80211 not found", device
);
520 nl_cache_free(state
->nl_cache
);
522 nl_handle_destroy(state
->nl_handle
);
527 nl80211_cleanup(struct nl80211_state
*state
)
529 genl_family_put(state
->nl80211
);
530 nl_cache_free(state
->nl_cache
);
531 nl_handle_destroy(state
->nl_handle
);
535 add_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
536 const char *device
, const char *mondevice
)
542 ifindex
= iface_get_id(sock_fd
, device
, handle
->errbuf
);
548 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
549 "%s: failed to allocate netlink msg", device
);
553 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
554 0, NL80211_CMD_NEW_INTERFACE
, 0);
555 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
556 NLA_PUT_STRING(msg
, NL80211_ATTR_IFNAME
, mondevice
);
557 NLA_PUT_U32(msg
, NL80211_ATTR_IFTYPE
, NL80211_IFTYPE_MONITOR
);
559 err
= nl_send_auto_complete(state
->nl_handle
, msg
);
561 if (err
== -ENFILE
) {
563 * Device not available; our caller should just
570 * Real failure, not just "that device is not
573 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
574 "%s: nl_send_auto_complete failed adding %s interface: %s",
575 device
, mondevice
, strerror(-err
));
580 err
= nl_wait_for_ack(state
->nl_handle
);
582 if (err
== -ENFILE
) {
584 * Device not available; our caller should just
591 * Real failure, not just "that device is not
594 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
595 "%s: nl_wait_for_ack failed adding %s interface: %s",
596 device
, mondevice
, strerror(-err
));
609 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
610 "%s: nl_put failed adding %s interface",
617 del_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
618 const char *device
, const char *mondevice
)
624 ifindex
= iface_get_id(sock_fd
, mondevice
, handle
->errbuf
);
630 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
631 "%s: failed to allocate netlink msg", device
);
635 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
636 0, NL80211_CMD_DEL_INTERFACE
, 0);
637 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
639 err
= nl_send_auto_complete(state
->nl_handle
, msg
);
641 if (err
== -ENFILE
) {
643 * Device not available; our caller should just
650 * Real failure, not just "that device is not
653 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
654 "%s: nl_send_auto_complete failed deleting %s interface: %s",
655 device
, mondevice
, strerror(-err
));
660 err
= nl_wait_for_ack(state
->nl_handle
);
662 if (err
== -ENFILE
) {
664 * Device not available; our caller should just
671 * Real failure, not just "that device is not
674 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
675 "%s: nl_wait_for_ack failed adding %s interface: %s",
676 device
, mondevice
, strerror(-err
));
689 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
690 "%s: nl_put failed deleting %s interface",
697 enter_rfmon_mode_mac80211(pcap_t
*handle
, int sock_fd
, const char *device
)
700 char phydev_path
[PATH_MAX
+1];
701 struct nl80211_state nlstate
;
706 * Is this a mac80211 device?
708 ret
= get_mac80211_phydev(handle
, device
, phydev_path
, PATH_MAX
);
710 return ret
; /* error */
712 return 0; /* no error, but not mac80211 device */
715 * XXX - is this already a monN device?
717 * Is that determined by old Wireless Extensions ioctls?
721 * OK, it's apparently a mac80211 device.
722 * Try to find an unused monN device for it.
724 ret
= nl80211_init(handle
, &nlstate
, device
);
727 for (n
= 0; n
< UINT_MAX
; n
++) {
731 char mondevice
[3+10+1]; /* mon{UINT_MAX}\0 */
733 snprintf(mondevice
, sizeof mondevice
, "mon%u", n
);
734 ret
= add_mon_if(handle
, sock_fd
, &nlstate
, device
, mondevice
);
736 handle
->md
.mondevice
= strdup(mondevice
);
741 * Hard failure. Just return ret; handle->errbuf
742 * has already been set.
744 nl80211_cleanup(&nlstate
);
749 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
750 "%s: No free monN interfaces", device
);
751 nl80211_cleanup(&nlstate
);
758 * Sleep for .1 seconds.
761 delay
.tv_nsec
= 500000000;
762 nanosleep(&delay
, NULL
);
766 * Now configure the monitor interface up.
768 memset(&ifr
, 0, sizeof(ifr
));
769 strncpy(ifr
.ifr_name
, handle
->md
.mondevice
, sizeof(ifr
.ifr_name
));
770 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
771 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
772 "%s: Can't get flags for %s: %s", device
,
773 handle
->md
.mondevice
, strerror(errno
));
774 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
775 handle
->md
.mondevice
);
776 nl80211_cleanup(&nlstate
);
779 ifr
.ifr_flags
|= IFF_UP
|IFF_RUNNING
;
780 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
781 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
782 "%s: Can't set flags for %s: %s", device
,
783 handle
->md
.mondevice
, strerror(errno
));
784 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
785 handle
->md
.mondevice
);
786 nl80211_cleanup(&nlstate
);
791 * Success. Clean up the libnl state.
793 nl80211_cleanup(&nlstate
);
796 * Note that we have to delete the monitor device when we close
799 handle
->md
.must_do_on_close
|= MUST_DELETE_MONIF
;
802 * Add this to the list of pcaps to close when we exit.
804 pcap_add_to_pcaps_to_close(handle
);
808 #endif /* HAVE_LIBNL */
811 pcap_can_set_rfmon_linux(pcap_t
*handle
)
814 char phydev_path
[PATH_MAX
+1];
817 #ifdef IW_MODE_MONITOR
822 if (strcmp(handle
->opt
.source
, "any") == 0) {
824 * Monitor mode makes no sense on the "any" device.
831 * Bleah. There doesn't seem to be a way to ask a mac80211
832 * device, through libnl, whether it supports monitor mode;
833 * we'll just check whether the device appears to be a
834 * mac80211 device and, if so, assume the device supports
837 * wmaster devices don't appear to support the Wireless
838 * Extensions, but we can create a mon device for a
839 * wmaster device, so we don't bother checking whether
840 * a mac80211 device supports the Wireless Extensions.
842 ret
= get_mac80211_phydev(handle
, handle
->opt
.source
, phydev_path
,
845 return ret
; /* error */
847 return 1; /* mac80211 device */
850 #ifdef IW_MODE_MONITOR
852 * Bleah. There doesn't appear to be an ioctl to use to ask
853 * whether a device supports monitor mode; we'll just do
854 * SIOCGIWMODE and, if it succeeds, assume the device supports
857 * Open a socket on which to attempt to get the mode.
858 * (We assume that if we have Wireless Extensions support
859 * we also have PF_PACKET support.)
861 sock_fd
= socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
));
863 (void)snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
864 "socket: %s", pcap_strerror(errno
));
869 * Attempt to get the current mode.
871 strncpy(ireq
.ifr_ifrn
.ifrn_name
, handle
->opt
.source
,
872 sizeof ireq
.ifr_ifrn
.ifrn_name
);
873 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
874 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) != -1) {
876 * Well, we got the mode; assume we can set it.
881 if (errno
== ENODEV
) {
882 /* The device doesn't even exist. */
884 return PCAP_ERROR_NO_SUCH_DEVICE
;
892 * With older kernels promiscuous mode is kind of interesting because we
893 * have to reset the interface before exiting. The problem can't really
894 * be solved without some daemon taking care of managing usage counts.
895 * If we put the interface into promiscuous mode, we set a flag indicating
896 * that we must take it out of that mode when the interface is closed,
897 * and, when closing the interface, if that flag is set we take it out
898 * of promiscuous mode.
900 * Even with newer kernels, we have the same issue with rfmon mode.
903 static void pcap_cleanup_linux( pcap_t
*handle
)
907 struct nl80211_state nlstate
;
909 #endif /* HAVE_LIBNL */
910 #ifdef IW_MODE_MONITOR
912 #endif /* IW_MODE_MONITOR */
914 if (handle
->md
.must_do_on_close
!= 0) {
916 * There's something we have to do when closing this
919 if (handle
->md
.must_do_on_close
& MUST_CLEAR_PROMISC
) {
921 * We put the interface into promiscuous mode;
922 * take it out of promiscuous mode.
924 * XXX - if somebody else wants it in promiscuous
925 * mode, this code cannot know that, so it'll take
926 * it out of promiscuous mode. That's not fixable
927 * in 2.0[.x] kernels.
929 memset(&ifr
, 0, sizeof(ifr
));
930 strncpy(ifr
.ifr_name
, handle
->md
.device
,
931 sizeof(ifr
.ifr_name
));
932 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
934 "Can't restore interface flags (SIOCGIFFLAGS failed: %s).\n"
935 "Please adjust manually.\n"
936 "Hint: This can't happen with Linux >= 2.2.0.\n",
939 if (ifr
.ifr_flags
& IFF_PROMISC
) {
941 * Promiscuous mode is currently on;
944 ifr
.ifr_flags
&= ~IFF_PROMISC
;
945 if (ioctl(handle
->fd
, SIOCSIFFLAGS
,
948 "Can't restore interface flags (SIOCSIFFLAGS failed: %s).\n"
949 "Please adjust manually.\n"
950 "Hint: This can't happen with Linux >= 2.2.0.\n",
958 if (handle
->md
.must_do_on_close
& MUST_DELETE_MONIF
) {
959 ret
= nl80211_init(handle
, &nlstate
, handle
->md
.device
);
961 ret
= del_mon_if(handle
, handle
->fd
, &nlstate
,
962 handle
->md
.device
, handle
->md
.mondevice
);
963 nl80211_cleanup(&nlstate
);
967 "Can't delete monitor interface %s (%s).\n"
968 "Please delete manually.\n",
969 handle
->md
.mondevice
, handle
->errbuf
);
972 #endif /* HAVE_LIBNL */
974 #ifdef IW_MODE_MONITOR
975 if (handle
->md
.must_do_on_close
& MUST_CLEAR_RFMON
) {
977 * We put the interface into rfmon mode;
978 * take it out of rfmon mode.
980 * XXX - if somebody else wants it in rfmon
981 * mode, this code cannot know that, so it'll take
982 * it out of rfmon mode.
984 strncpy(ireq
.ifr_ifrn
.ifrn_name
, handle
->md
.device
,
985 sizeof ireq
.ifr_ifrn
.ifrn_name
);
986 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1]
988 ireq
.u
.mode
= handle
->md
.oldmode
;
989 if (ioctl(handle
->fd
, SIOCSIWMODE
, &ireq
) == -1) {
991 * Scientist, you've failed.
994 "Can't restore interface wireless mode (SIOCSIWMODE failed: %s).\n"
995 "Please adjust manually.\n",
999 #endif /* IW_MODE_MONITOR */
1002 * Take this pcap out of the list of pcaps for which we
1003 * have to take the interface out of some mode.
1005 pcap_remove_from_pcaps_to_close(handle
);
1008 if (handle
->md
.mondevice
!= NULL
) {
1009 free(handle
->md
.mondevice
);
1010 handle
->md
.mondevice
= NULL
;
1012 if (handle
->md
.device
!= NULL
) {
1013 free(handle
->md
.device
);
1014 handle
->md
.device
= NULL
;
1016 pcap_cleanup_live_common(handle
);
1020 * Get a handle for a live capture from the given device. You can
1021 * pass NULL as device to get all packages (without link level
1022 * information of course). If you pass 1 as promisc the interface
1023 * will be set to promiscous mode (XXX: I think this usage should
1024 * be deprecated and functions be added to select that later allow
1025 * modification of that values -- Torsten).
1028 pcap_activate_linux(pcap_t
*handle
)
1033 device
= handle
->opt
.source
;
1035 handle
->inject_op
= pcap_inject_linux
;
1036 handle
->setfilter_op
= pcap_setfilter_linux
;
1037 handle
->setdirection_op
= pcap_setdirection_linux
;
1038 handle
->set_datalink_op
= NULL
; /* can't change data link type */
1039 handle
->getnonblock_op
= pcap_getnonblock_fd
;
1040 handle
->setnonblock_op
= pcap_setnonblock_fd
;
1041 handle
->cleanup_op
= pcap_cleanup_linux
;
1042 handle
->read_op
= pcap_read_linux
;
1043 handle
->stats_op
= pcap_stats_linux
;
1046 * The "any" device is a special device which causes us not
1047 * to bind to a particular device and thus to look at all
1050 if (strcmp(device
, "any") == 0) {
1051 if (handle
->opt
.promisc
) {
1052 handle
->opt
.promisc
= 0;
1053 /* Just a warning. */
1054 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1055 "Promiscuous mode not supported on the \"any\" device");
1056 status
= PCAP_WARNING_PROMISC_NOTSUP
;
1060 handle
->md
.device
= strdup(device
);
1061 if (handle
->md
.device
== NULL
) {
1062 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "strdup: %s",
1063 pcap_strerror(errno
) );
1068 * Current Linux kernels use the protocol family PF_PACKET to
1069 * allow direct access to all packets on the network while
1070 * older kernels had a special socket type SOCK_PACKET to
1071 * implement this feature.
1072 * While this old implementation is kind of obsolete we need
1073 * to be compatible with older kernels for a while so we are
1074 * trying both methods with the newer method preferred.
1077 if ((status
= activate_new(handle
)) == 1) {
1080 * Try to use memory-mapped access.
1082 switch (activate_mmap(handle
)) {
1085 /* we succeeded; nothing more to do */
1090 * Kernel doesn't support it - just continue
1091 * with non-memory-mapped access.
1098 * We failed to set up to use it, or kernel
1099 * supports it, but we failed to enable it;
1100 * return an error. handle->errbuf contains
1103 status
= PCAP_ERROR
;
1107 else if (status
== 0) {
1108 /* Non-fatal error; try old way */
1109 if ((status
= activate_old(handle
)) != 1) {
1111 * Both methods to open the packet socket failed.
1112 * Tidy up and report our failure (handle->errbuf
1113 * is expected to be set by the functions above).
1119 * Fatal error with the new way; just fail.
1120 * status has the error return; if it's PCAP_ERROR,
1121 * handle->errbuf has been set appropriately.
1127 * We set up the socket, but not with memory-mapped access.
1129 if (handle
->opt
.buffer_size
!= 0) {
1131 * Set the socket buffer size to the specified value.
1133 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_RCVBUF
,
1134 &handle
->opt
.buffer_size
,
1135 sizeof(handle
->opt
.buffer_size
)) == -1) {
1136 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1137 "SO_RCVBUF: %s", pcap_strerror(errno
));
1138 status
= PCAP_ERROR
;
1143 /* Allocate the buffer */
1145 handle
->buffer
= malloc(handle
->bufsize
+ handle
->offset
);
1146 if (!handle
->buffer
) {
1147 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1148 "malloc: %s", pcap_strerror(errno
));
1149 status
= PCAP_ERROR
;
1154 * "handle->fd" is a socket, so "select()" and "poll()"
1155 * should work on it.
1157 handle
->selectable_fd
= handle
->fd
;
1162 pcap_cleanup_linux(handle
);
1167 * Read at most max_packets from the capture stream and call the callback
1168 * for each of them. Returns the number of packets handled or -1 if an
1172 pcap_read_linux(pcap_t
*handle
, int max_packets
, pcap_handler callback
, u_char
*user
)
1175 * Currently, on Linux only one packet is delivered per read,
1178 return pcap_read_packet(handle
, callback
, user
);
1182 * Read a packet from the socket calling the handler provided by
1183 * the user. Returns the number of packets received or -1 if an
1187 pcap_read_packet(pcap_t
*handle
, pcap_handler callback
, u_char
*userdata
)
1191 #ifdef HAVE_PF_PACKET_SOCKETS
1192 struct sockaddr_ll from
;
1193 struct sll_header
*hdrp
;
1195 struct sockaddr from
;
1197 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1200 struct cmsghdr
*cmsg
;
1202 struct cmsghdr cmsg
;
1203 char buf
[CMSG_SPACE(sizeof(struct tpacket_auxdata
))];
1205 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1207 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1208 int packet_len
, caplen
;
1209 struct pcap_pkthdr pcap_header
;
1211 #ifdef HAVE_PF_PACKET_SOCKETS
1213 * If this is a cooked device, leave extra room for a
1214 * fake packet header.
1216 if (handle
->md
.cooked
)
1217 offset
= SLL_HDR_LEN
;
1222 * This system doesn't have PF_PACKET sockets, so it doesn't
1223 * support cooked devices.
1229 * Receive a single packet from the kernel.
1230 * We ignore EINTR, as that might just be due to a signal
1231 * being delivered - if the signal should interrupt the
1232 * loop, the signal handler should call pcap_breakloop()
1233 * to set handle->break_loop (we ignore it on other
1234 * platforms as well).
1235 * We also ignore ENETDOWN, so that we can continue to
1236 * capture traffic if the interface goes down and comes
1237 * back up again; comments in the kernel indicate that
1238 * we'll just block waiting for packets if we try to
1239 * receive from a socket that delivered ENETDOWN, and,
1240 * if we're using a memory-mapped buffer, we won't even
1241 * get notified of "network down" events.
1243 bp
= handle
->buffer
+ handle
->offset
;
1245 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1246 msg
.msg_name
= &from
;
1247 msg
.msg_namelen
= sizeof(from
);
1250 msg
.msg_control
= &cmsg_buf
;
1251 msg
.msg_controllen
= sizeof(cmsg_buf
);
1254 iov
.iov_len
= handle
->bufsize
- offset
;
1255 iov
.iov_base
= bp
+ offset
;
1256 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1260 * Has "pcap_breakloop()" been called?
1262 if (handle
->break_loop
) {
1264 * Yes - clear the flag that indicates that it
1265 * has, and return -2 as an indication that we
1266 * were told to break out of the loop.
1268 handle
->break_loop
= 0;
1272 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1273 packet_len
= recvmsg(handle
->fd
, &msg
, MSG_TRUNC
);
1274 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1275 fromlen
= sizeof(from
);
1276 packet_len
= recvfrom(
1277 handle
->fd
, bp
+ offset
,
1278 handle
->bufsize
- offset
, MSG_TRUNC
,
1279 (struct sockaddr
*) &from
, &fromlen
);
1280 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1281 } while (packet_len
== -1 && (errno
== EINTR
|| errno
== ENETDOWN
));
1283 /* Check if an error occured */
1285 if (packet_len
== -1) {
1286 if (errno
== EAGAIN
)
1287 return 0; /* no packet there */
1289 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1290 "recvfrom: %s", pcap_strerror(errno
));
1295 #ifdef HAVE_PF_PACKET_SOCKETS
1296 if (!handle
->md
.sock_packet
) {
1298 * Unfortunately, there is a window between socket() and
1299 * bind() where the kernel may queue packets from any
1300 * interface. If we're bound to a particular interface,
1301 * discard packets not from that interface.
1303 * (If socket filters are supported, we could do the
1304 * same thing we do when changing the filter; however,
1305 * that won't handle packet sockets without socket
1306 * filter support, and it's a bit more complicated.
1307 * It would save some instructions per packet, however.)
1309 if (handle
->md
.ifindex
!= -1 &&
1310 from
.sll_ifindex
!= handle
->md
.ifindex
)
1314 * Do checks based on packet direction.
1315 * We can only do this if we're using PF_PACKET; the
1316 * address returned for SOCK_PACKET is a "sockaddr_pkt"
1317 * which lacks the relevant packet type information.
1319 if (from
.sll_pkttype
== PACKET_OUTGOING
) {
1322 * If this is from the loopback device, reject it;
1323 * we'll see the packet as an incoming packet as well,
1324 * and we don't want to see it twice.
1326 if (from
.sll_ifindex
== handle
->md
.lo_ifindex
)
1330 * If the user only wants incoming packets, reject it.
1332 if (handle
->direction
== PCAP_D_IN
)
1337 * If the user only wants outgoing packets, reject it.
1339 if (handle
->direction
== PCAP_D_OUT
)
1345 #ifdef HAVE_PF_PACKET_SOCKETS
1347 * If this is a cooked device, fill in the fake packet header.
1349 if (handle
->md
.cooked
) {
1351 * Add the length of the fake header to the length
1352 * of packet data we read.
1354 packet_len
+= SLL_HDR_LEN
;
1356 hdrp
= (struct sll_header
*)bp
;
1357 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(from
.sll_pkttype
);
1358 hdrp
->sll_hatype
= htons(from
.sll_hatype
);
1359 hdrp
->sll_halen
= htons(from
.sll_halen
);
1360 memcpy(hdrp
->sll_addr
, from
.sll_addr
,
1361 (from
.sll_halen
> SLL_ADDRLEN
) ?
1364 hdrp
->sll_protocol
= from
.sll_protocol
;
1367 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1368 for (cmsg
= CMSG_FIRSTHDR(&msg
); cmsg
; cmsg
= CMSG_NXTHDR(&msg
, cmsg
)) {
1369 struct tpacket_auxdata
*aux
;
1371 struct vlan_tag
*tag
;
1373 if (cmsg
->cmsg_len
< CMSG_LEN(sizeof(struct tpacket_auxdata
)) ||
1374 cmsg
->cmsg_level
!= SOL_PACKET
||
1375 cmsg
->cmsg_type
!= PACKET_AUXDATA
)
1378 aux
= (struct tpacket_auxdata
*)CMSG_DATA(cmsg
);
1379 if (aux
->tp_vlan_tci
== 0)
1382 len
= packet_len
> iov
.iov_len
? iov
.iov_len
: packet_len
;
1383 if (len
< 2 * ETH_ALEN
)
1387 memmove(bp
, bp
+ VLAN_TAG_LEN
, 2 * ETH_ALEN
);
1389 tag
= (struct vlan_tag
*)(bp
+ 2 * ETH_ALEN
);
1390 tag
->vlan_tpid
= htons(ETH_P_8021Q
);
1391 tag
->vlan_tci
= htons(aux
->tp_vlan_tci
);
1393 packet_len
+= VLAN_TAG_LEN
;
1395 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1396 #endif /* HAVE_PF_PACKET_SOCKETS */
1399 * XXX: According to the kernel source we should get the real
1400 * packet len if calling recvfrom with MSG_TRUNC set. It does
1401 * not seem to work here :(, but it is supported by this code
1403 * To be honest the code RELIES on that feature so this is really
1404 * broken with 2.2.x kernels.
1405 * I spend a day to figure out what's going on and I found out
1406 * that the following is happening:
1408 * The packet comes from a random interface and the packet_rcv
1409 * hook is called with a clone of the packet. That code inserts
1410 * the packet into the receive queue of the packet socket.
1411 * If a filter is attached to that socket that filter is run
1412 * first - and there lies the problem. The default filter always
1413 * cuts the packet at the snaplen:
1418 * So the packet filter cuts down the packet. The recvfrom call
1419 * says "hey, it's only 68 bytes, it fits into the buffer" with
1420 * the result that we don't get the real packet length. This
1421 * is valid at least until kernel 2.2.17pre6.
1423 * We currently handle this by making a copy of the filter
1424 * program, fixing all "ret" instructions with non-zero
1425 * operands to have an operand of 65535 so that the filter
1426 * doesn't truncate the packet, and supplying that modified
1427 * filter to the kernel.
1430 caplen
= packet_len
;
1431 if (caplen
> handle
->snapshot
)
1432 caplen
= handle
->snapshot
;
1434 /* Run the packet filter if not using kernel filter */
1435 if (!handle
->md
.use_bpf
&& handle
->fcode
.bf_insns
) {
1436 if (bpf_filter(handle
->fcode
.bf_insns
, bp
,
1437 packet_len
, caplen
) == 0)
1439 /* rejected by filter */
1444 /* Fill in our own header data */
1446 if (ioctl(handle
->fd
, SIOCGSTAMP
, &pcap_header
.ts
) == -1) {
1447 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1448 "SIOCGSTAMP: %s", pcap_strerror(errno
));
1451 pcap_header
.caplen
= caplen
;
1452 pcap_header
.len
= packet_len
;
1457 * Arguably, we should count them before we check the filter,
1458 * as on many other platforms "ps_recv" counts packets
1459 * handed to the filter rather than packets that passed
1460 * the filter, but if filtering is done in the kernel, we
1461 * can't get a count of packets that passed the filter,
1462 * and that would mean the meaning of "ps_recv" wouldn't
1463 * be the same on all Linux systems.
1465 * XXX - it's not the same on all systems in any case;
1466 * ideally, we should have a "get the statistics" call
1467 * that supplies more counts and indicates which of them
1468 * it supplies, so that we supply a count of packets
1469 * handed to the filter only on platforms where that
1470 * information is available.
1472 * We count them here even if we can get the packet count
1473 * from the kernel, as we can only determine at run time
1474 * whether we'll be able to get it from the kernel (if
1475 * HAVE_TPACKET_STATS isn't defined, we can't get it from
1476 * the kernel, but if it is defined, the library might
1477 * have been built with a 2.4 or later kernel, but we
1478 * might be running on a 2.2[.x] kernel without Alexey
1479 * Kuznetzov's turbopacket patches, and thus the kernel
1480 * might not be able to supply those statistics). We
1481 * could, I guess, try, when opening the socket, to get
1482 * the statistics, and if we can not increment the count
1483 * here, but it's not clear that always incrementing
1484 * the count is more expensive than always testing a flag
1487 * We keep the count in "md.packets_read", and use that for
1488 * "ps_recv" if we can't get the statistics from the kernel.
1489 * We do that because, if we *can* get the statistics from
1490 * the kernel, we use "md.stat.ps_recv" and "md.stat.ps_drop"
1491 * as running counts, as reading the statistics from the
1492 * kernel resets the kernel statistics, and if we directly
1493 * increment "md.stat.ps_recv" here, that means it will
1494 * count packets *twice* on systems where we can get kernel
1495 * statistics - once here, and once in pcap_stats_linux().
1497 handle
->md
.packets_read
++;
1499 /* Call the user supplied callback function */
1500 callback(userdata
, &pcap_header
, bp
);
1506 pcap_inject_linux(pcap_t
*handle
, const void *buf
, size_t size
)
1510 #ifdef HAVE_PF_PACKET_SOCKETS
1511 if (!handle
->md
.sock_packet
) {
1512 /* PF_PACKET socket */
1513 if (handle
->md
.ifindex
== -1) {
1515 * We don't support sending on the "any" device.
1517 strlcpy(handle
->errbuf
,
1518 "Sending packets isn't supported on the \"any\" device",
1523 if (handle
->md
.cooked
) {
1525 * We don't support sending on the "any" device.
1527 * XXX - how do you send on a bound cooked-mode
1529 * Is a "sendto()" required there?
1531 strlcpy(handle
->errbuf
,
1532 "Sending packets isn't supported in cooked mode",
1539 ret
= send(handle
->fd
, buf
, size
, 0);
1541 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "send: %s",
1542 pcap_strerror(errno
));
1549 * Get the statistics for the given packet capture handle.
1550 * Reports the number of dropped packets iff the kernel supports
1551 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
1552 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
1553 * patches); otherwise, that information isn't available, and we lie
1554 * and report 0 as the count of dropped packets.
1557 pcap_stats_linux(pcap_t
*handle
, struct pcap_stat
*stats
)
1559 #ifdef HAVE_TPACKET_STATS
1560 struct tpacket_stats kstats
;
1561 socklen_t len
= sizeof (struct tpacket_stats
);
1564 #ifdef HAVE_TPACKET_STATS
1566 * Try to get the packet counts from the kernel.
1568 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_STATISTICS
,
1569 &kstats
, &len
) > -1) {
1571 * On systems where the PACKET_STATISTICS "getsockopt()"
1572 * argument is supported on PF_PACKET sockets:
1574 * "ps_recv" counts only packets that *passed* the
1575 * filter, not packets that didn't pass the filter.
1576 * This includes packets later dropped because we
1577 * ran out of buffer space.
1579 * "ps_drop" counts packets dropped because we ran
1580 * out of buffer space. It doesn't count packets
1581 * dropped by the interface driver. It counts only
1582 * packets that passed the filter.
1584 * Both statistics include packets not yet read from
1585 * the kernel by libpcap, and thus not yet seen by
1588 * In "linux/net/packet/af_packet.c", at least in the
1589 * 2.4.9 kernel, "tp_packets" is incremented for every
1590 * packet that passes the packet filter *and* is
1591 * successfully queued on the socket; "tp_drops" is
1592 * incremented for every packet dropped because there's
1593 * not enough free space in the socket buffer.
1595 * When the statistics are returned for a PACKET_STATISTICS
1596 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
1597 * so that "tp_packets" counts all packets handed to
1598 * the PF_PACKET socket, including packets dropped because
1599 * there wasn't room on the socket buffer - but not
1600 * including packets that didn't pass the filter.
1602 * In the BSD BPF, the count of received packets is
1603 * incremented for every packet handed to BPF, regardless
1604 * of whether it passed the filter.
1606 * We can't make "pcap_stats()" work the same on both
1607 * platforms, but the best approximation is to return
1608 * "tp_packets" as the count of packets and "tp_drops"
1609 * as the count of drops.
1611 * Keep a running total because each call to
1612 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
1613 * resets the counters to zero.
1615 handle
->md
.stat
.ps_recv
+= kstats
.tp_packets
;
1616 handle
->md
.stat
.ps_drop
+= kstats
.tp_drops
;
1617 *stats
= handle
->md
.stat
;
1623 * If the error was EOPNOTSUPP, fall through, so that
1624 * if you build the library on a system with
1625 * "struct tpacket_stats" and run it on a system
1626 * that doesn't, it works as it does if the library
1627 * is built on a system without "struct tpacket_stats".
1629 if (errno
!= EOPNOTSUPP
) {
1630 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1631 "pcap_stats: %s", pcap_strerror(errno
));
1637 * On systems where the PACKET_STATISTICS "getsockopt()" argument
1638 * is not supported on PF_PACKET sockets:
1640 * "ps_recv" counts only packets that *passed* the filter,
1641 * not packets that didn't pass the filter. It does not
1642 * count packets dropped because we ran out of buffer
1645 * "ps_drop" is not supported.
1647 * "ps_recv" doesn't include packets not yet read from
1648 * the kernel by libpcap.
1650 * We maintain the count of packets processed by libpcap in
1651 * "md.packets_read", for reasons described in the comment
1652 * at the end of pcap_read_packet(). We have no idea how many
1653 * packets were dropped.
1655 stats
->ps_recv
= handle
->md
.packets_read
;
1661 * Description string for the "any" device.
1663 static const char any_descr
[] = "Pseudo-device that captures on all interfaces";
1666 pcap_platform_finddevs(pcap_if_t
**alldevsp
, char *errbuf
)
1668 if (pcap_add_if(alldevsp
, "any", 0, any_descr
, errbuf
) < 0)
1672 if (dag_platform_finddevs(alldevsp
, errbuf
) < 0)
1674 #endif /* HAVE_DAG_API */
1676 #ifdef HAVE_SEPTEL_API
1677 if (septel_platform_finddevs(alldevsp
, errbuf
) < 0)
1679 #endif /* HAVE_SEPTEL_API */
1681 #ifdef PCAP_SUPPORT_BT
1682 if (bt_platform_finddevs(alldevsp
, errbuf
) < 0)
1686 #ifdef PCAP_SUPPORT_USB
1687 if (usb_platform_finddevs(alldevsp
, errbuf
) < 0)
1695 * Attach the given BPF code to the packet capture device.
1698 pcap_setfilter_linux_common(pcap_t
*handle
, struct bpf_program
*filter
,
1701 #ifdef SO_ATTACH_FILTER
1702 struct sock_fprog fcode
;
1703 int can_filter_in_kernel
;
1710 strncpy(handle
->errbuf
, "setfilter: No filter specified",
1715 /* Make our private copy of the filter */
1717 if (install_bpf_program(handle
, filter
) < 0)
1718 /* install_bpf_program() filled in errbuf */
1722 * Run user level packet filter by default. Will be overriden if
1723 * installing a kernel filter succeeds.
1725 handle
->md
.use_bpf
= 0;
1727 /* Install kernel level filter if possible */
1729 #ifdef SO_ATTACH_FILTER
1731 if (handle
->fcode
.bf_len
> USHRT_MAX
) {
1733 * fcode.len is an unsigned short for current kernel.
1734 * I have yet to see BPF-Code with that much
1735 * instructions but still it is possible. So for the
1736 * sake of correctness I added this check.
1738 fprintf(stderr
, "Warning: Filter too complex for kernel\n");
1740 fcode
.filter
= NULL
;
1741 can_filter_in_kernel
= 0;
1743 #endif /* USHRT_MAX */
1746 * Oh joy, the Linux kernel uses struct sock_fprog instead
1747 * of struct bpf_program and of course the length field is
1748 * of different size. Pointed out by Sebastian
1750 * Oh, and we also need to fix it up so that all "ret"
1751 * instructions with non-zero operands have 65535 as the
1752 * operand if we're not capturing in memory-mapped modee,
1753 * and so that, if we're in cooked mode, all memory-reference
1754 * instructions use special magic offsets in references to
1755 * the link-layer header and assume that the link-layer
1756 * payload begins at 0; "fix_program()" will do that.
1758 switch (fix_program(handle
, &fcode
, is_mmapped
)) {
1763 * Fatal error; just quit.
1764 * (The "default" case shouldn't happen; we
1765 * return -1 for that reason.)
1771 * The program performed checks that we can't make
1772 * work in the kernel.
1774 can_filter_in_kernel
= 0;
1779 * We have a filter that'll work in the kernel.
1781 can_filter_in_kernel
= 1;
1786 if (can_filter_in_kernel
) {
1787 if ((err
= set_kernel_filter(handle
, &fcode
)) == 0)
1789 /* Installation succeded - using kernel filter. */
1790 handle
->md
.use_bpf
= 1;
1792 else if (err
== -1) /* Non-fatal error */
1795 * Print a warning if we weren't able to install
1796 * the filter for a reason other than "this kernel
1797 * isn't configured to support socket filters.
1799 if (errno
!= ENOPROTOOPT
&& errno
!= EOPNOTSUPP
) {
1801 "Warning: Kernel filter failed: %s\n",
1802 pcap_strerror(errno
));
1808 * If we're not using the kernel filter, get rid of any kernel
1809 * filter that might've been there before, e.g. because the
1810 * previous filter could work in the kernel, or because some other
1811 * code attached a filter to the socket by some means other than
1812 * calling "pcap_setfilter()". Otherwise, the kernel filter may
1813 * filter out packets that would pass the new userland filter.
1815 if (!handle
->md
.use_bpf
)
1816 reset_kernel_filter(handle
);
1819 * Free up the copy of the filter that was made by "fix_program()".
1821 if (fcode
.filter
!= NULL
)
1827 #endif /* SO_ATTACH_FILTER */
1833 pcap_setfilter_linux(pcap_t
*handle
, struct bpf_program
*filter
)
1835 return pcap_setfilter_linux_common(handle
, filter
, 0);
1840 * Set direction flag: Which packets do we accept on a forwarding
1841 * single device? IN, OUT or both?
1844 pcap_setdirection_linux(pcap_t
*handle
, pcap_direction_t d
)
1846 #ifdef HAVE_PF_PACKET_SOCKETS
1847 if (!handle
->md
.sock_packet
) {
1848 handle
->direction
= d
;
1853 * We're not using PF_PACKET sockets, so we can't determine
1854 * the direction of the packet.
1856 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1857 "Setting direction is not supported on SOCK_PACKET sockets");
1862 #ifdef HAVE_PF_PACKET_SOCKETS
1864 * Map the PACKET_ value to a LINUX_SLL_ value; we
1865 * want the same numerical value to be used in
1866 * the link-layer header even if the numerical values
1867 * for the PACKET_ #defines change, so that programs
1868 * that look at the packet type field will always be
1869 * able to handle DLT_LINUX_SLL captures.
1872 map_packet_type_to_sll_type(short int sll_pkttype
)
1874 switch (sll_pkttype
) {
1877 return htons(LINUX_SLL_HOST
);
1879 case PACKET_BROADCAST
:
1880 return htons(LINUX_SLL_BROADCAST
);
1882 case PACKET_MULTICAST
:
1883 return htons(LINUX_SLL_MULTICAST
);
1885 case PACKET_OTHERHOST
:
1886 return htons(LINUX_SLL_OTHERHOST
);
1888 case PACKET_OUTGOING
:
1889 return htons(LINUX_SLL_OUTGOING
);
1898 * Linux uses the ARP hardware type to identify the type of an
1899 * interface. pcap uses the DLT_xxx constants for this. This
1900 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
1901 * constant, as arguments, and sets "handle->linktype" to the
1902 * appropriate DLT_XXX constant and sets "handle->offset" to
1903 * the appropriate value (to make "handle->offset" plus link-layer
1904 * header length be a multiple of 4, so that the link-layer payload
1905 * will be aligned on a 4-byte boundary when capturing packets).
1906 * (If the offset isn't set here, it'll be 0; add code as appropriate
1907 * for cases where it shouldn't be 0.)
1909 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
1910 * in cooked mode; otherwise, we can't use cooked mode, so we have
1911 * to pick some type that works in raw mode, or fail.
1913 * Sets the link type to -1 if unable to map the type.
1915 static void map_arphrd_to_dlt(pcap_t
*handle
, int arptype
, int cooked_ok
)
1921 * This is (presumably) a real Ethernet capture; give it a
1922 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
1923 * that an application can let you choose it, in case you're
1924 * capturing DOCSIS traffic that a Cisco Cable Modem
1925 * Termination System is putting out onto an Ethernet (it
1926 * doesn't put an Ethernet header onto the wire, it puts raw
1927 * DOCSIS frames out on the wire inside the low-level
1928 * Ethernet framing).
1930 * XXX - are there any sorts of "fake Ethernet" that have
1931 * ARPHRD_ETHER but that *shouldn't offer DLT_DOCSIS as
1932 * a Cisco CMTS won't put traffic onto it or get traffic
1933 * bridged onto it? ISDN is handled in "activate_new()",
1934 * as we fall back on cooked mode there; are there any
1937 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
1939 * If that fails, just leave the list empty.
1941 if (handle
->dlt_list
!= NULL
) {
1942 handle
->dlt_list
[0] = DLT_EN10MB
;
1943 handle
->dlt_list
[1] = DLT_DOCSIS
;
1944 handle
->dlt_count
= 2;
1948 case ARPHRD_METRICOM
:
1949 case ARPHRD_LOOPBACK
:
1950 handle
->linktype
= DLT_EN10MB
;
1955 handle
->linktype
= DLT_EN3MB
;
1959 handle
->linktype
= DLT_AX25_KISS
;
1963 handle
->linktype
= DLT_PRONET
;
1967 handle
->linktype
= DLT_CHAOS
;
1970 #ifndef ARPHRD_IEEE802_TR
1971 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
1973 case ARPHRD_IEEE802_TR
:
1974 case ARPHRD_IEEE802
:
1975 handle
->linktype
= DLT_IEEE802
;
1980 handle
->linktype
= DLT_ARCNET_LINUX
;
1983 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
1984 #define ARPHRD_FDDI 774
1987 handle
->linktype
= DLT_FDDI
;
1991 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
1992 #define ARPHRD_ATM 19
1996 * The Classical IP implementation in ATM for Linux
1997 * supports both what RFC 1483 calls "LLC Encapsulation",
1998 * in which each packet has an LLC header, possibly
1999 * with a SNAP header as well, prepended to it, and
2000 * what RFC 1483 calls "VC Based Multiplexing", in which
2001 * different virtual circuits carry different network
2002 * layer protocols, and no header is prepended to packets.
2004 * They both have an ARPHRD_ type of ARPHRD_ATM, so
2005 * you can't use the ARPHRD_ type to find out whether
2006 * captured packets will have an LLC header, and,
2007 * while there's a socket ioctl to *set* the encapsulation
2008 * type, there's no ioctl to *get* the encapsulation type.
2012 * programs that dissect Linux Classical IP frames
2013 * would have to check for an LLC header and,
2014 * depending on whether they see one or not, dissect
2015 * the frame as LLC-encapsulated or as raw IP (I
2016 * don't know whether there's any traffic other than
2017 * IP that would show up on the socket, or whether
2018 * there's any support for IPv6 in the Linux
2019 * Classical IP code);
2021 * filter expressions would have to compile into
2022 * code that checks for an LLC header and does
2025 * Both of those are a nuisance - and, at least on systems
2026 * that support PF_PACKET sockets, we don't have to put
2027 * up with those nuisances; instead, we can just capture
2028 * in cooked mode. That's what we'll do, if we can.
2029 * Otherwise, we'll just fail.
2032 handle
->linktype
= DLT_LINUX_SLL
;
2034 handle
->linktype
= -1;
2037 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
2038 #define ARPHRD_IEEE80211 801
2040 case ARPHRD_IEEE80211
:
2041 handle
->linktype
= DLT_IEEE802_11
;
2044 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
2045 #define ARPHRD_IEEE80211_PRISM 802
2047 case ARPHRD_IEEE80211_PRISM
:
2048 handle
->linktype
= DLT_PRISM_HEADER
;
2051 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
2052 #define ARPHRD_IEEE80211_RADIOTAP 803
2054 case ARPHRD_IEEE80211_RADIOTAP
:
2055 handle
->linktype
= DLT_IEEE802_11_RADIO
;
2060 * Some PPP code in the kernel supplies no link-layer
2061 * header whatsoever to PF_PACKET sockets; other PPP
2062 * code supplies PPP link-layer headers ("syncppp.c");
2063 * some PPP code might supply random link-layer
2064 * headers (PPP over ISDN - there's code in Ethereal,
2065 * for example, to cope with PPP-over-ISDN captures
2066 * with which the Ethereal developers have had to cope,
2067 * heuristically trying to determine which of the
2068 * oddball link-layer headers particular packets have).
2070 * As such, we just punt, and run all PPP interfaces
2071 * in cooked mode, if we can; otherwise, we just treat
2072 * it as DLT_RAW, for now - if somebody needs to capture,
2073 * on a 2.0[.x] kernel, on PPP devices that supply a
2074 * link-layer header, they'll have to add code here to
2075 * map to the appropriate DLT_ type (possibly adding a
2076 * new DLT_ type, if necessary).
2079 handle
->linktype
= DLT_LINUX_SLL
;
2082 * XXX - handle ISDN types here? We can't fall
2083 * back on cooked sockets, so we'd have to
2084 * figure out from the device name what type of
2085 * link-layer encapsulation it's using, and map
2086 * that to an appropriate DLT_ value, meaning
2087 * we'd map "isdnN" devices to DLT_RAW (they
2088 * supply raw IP packets with no link-layer
2089 * header) and "isdY" devices to a new DLT_I4L_IP
2090 * type that has only an Ethernet packet type as
2091 * a link-layer header.
2093 * But sometimes we seem to get random crap
2094 * in the link-layer header when capturing on
2097 handle
->linktype
= DLT_RAW
;
2101 #ifndef ARPHRD_CISCO
2102 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
2105 handle
->linktype
= DLT_C_HDLC
;
2108 /* Not sure if this is correct for all tunnels, but it
2112 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
2120 #ifndef ARPHRD_RAWHDLC
2121 #define ARPHRD_RAWHDLC 518
2123 case ARPHRD_RAWHDLC
:
2125 #define ARPHRD_DLCI 15
2129 * XXX - should some of those be mapped to DLT_LINUX_SLL
2130 * instead? Should we just map all of them to DLT_LINUX_SLL?
2132 handle
->linktype
= DLT_RAW
;
2136 #define ARPHRD_FRAD 770
2139 handle
->linktype
= DLT_FRELAY
;
2142 case ARPHRD_LOCALTLK
:
2143 handle
->linktype
= DLT_LTALK
;
2147 #define ARPHRD_FCPP 784
2151 #define ARPHRD_FCAL 785
2155 #define ARPHRD_FCPL 786
2158 #ifndef ARPHRD_FCFABRIC
2159 #define ARPHRD_FCFABRIC 787
2161 case ARPHRD_FCFABRIC
:
2163 * We assume that those all mean RFC 2625 IP-over-
2164 * Fibre Channel, with the RFC 2625 header at
2165 * the beginning of the packet.
2167 handle
->linktype
= DLT_IP_OVER_FC
;
2171 #define ARPHRD_IRDA 783
2174 /* Don't expect IP packet out of this interfaces... */
2175 handle
->linktype
= DLT_LINUX_IRDA
;
2176 /* We need to save packet direction for IrDA decoding,
2177 * so let's use "Linux-cooked" mode. Jean II */
2178 //handle->md.cooked = 1;
2181 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
2182 * is needed, please report it to <daniele@orlandi.com> */
2184 #define ARPHRD_LAPD 8445
2187 /* Don't expect IP packet out of this interfaces... */
2188 handle
->linktype
= DLT_LINUX_LAPD
;
2192 #define ARPHRD_NONE 0xFFFE
2196 * No link-layer header; packets are just IP
2197 * packets, so use DLT_RAW.
2199 handle
->linktype
= DLT_RAW
;
2203 handle
->linktype
= -1;
2208 /* ===== Functions to interface to the newer kernels ================== */
2211 * Try to open a packet socket using the new kernel PF_PACKET interface.
2212 * Returns 1 on success, 0 on an error that means the new interface isn't
2213 * present (so the old SOCK_PACKET interface should be tried), and a
2214 * PCAP_ERROR_ value on an error that means that the old mechanism won't
2215 * work either (so it shouldn't be tried).
2218 activate_new(pcap_t
*handle
)
2220 #ifdef HAVE_PF_PACKET_SOCKETS
2221 const char *device
= handle
->opt
.source
;
2222 int is_any_device
= (strcmp(device
, "any") == 0);
2223 int sock_fd
= -1, arptype
;
2224 #ifdef HAVE_PACKET_AUXDATA
2228 struct packet_mreq mr
;
2231 * Open a socket with protocol family packet. If the
2232 * "any" device was specified, we open a SOCK_DGRAM
2233 * socket for the cooked interface, otherwise we first
2234 * try a SOCK_RAW socket for the raw interface.
2236 sock_fd
= is_any_device
?
2237 socket(PF_PACKET
, SOCK_DGRAM
, htons(ETH_P_ALL
)) :
2238 socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
));
2240 if (sock_fd
== -1) {
2241 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "socket: %s",
2242 pcap_strerror(errno
) );
2243 return 0; /* try old mechanism */
2246 /* It seems the kernel supports the new interface. */
2247 handle
->md
.sock_packet
= 0;
2250 * Get the interface index of the loopback device.
2251 * If the attempt fails, don't fail, just set the
2252 * "md.lo_ifindex" to -1.
2254 * XXX - can there be more than one device that loops
2255 * packets back, i.e. devices other than "lo"? If so,
2256 * we'd need to find them all, and have an array of
2257 * indices for them, and check all of them in
2258 * "pcap_read_packet()".
2260 handle
->md
.lo_ifindex
= iface_get_id(sock_fd
, "lo", handle
->errbuf
);
2263 * Default value for offset to align link-layer payload
2264 * on a 4-byte boundary.
2269 * What kind of frames do we have to deal with? Fall back
2270 * to cooked mode if we have an unknown interface type
2271 * or a type we know doesn't work well in raw mode.
2273 if (!is_any_device
) {
2274 /* Assume for now we don't need cooked mode. */
2275 handle
->md
.cooked
= 0;
2277 if (handle
->opt
.rfmon
) {
2279 * We were asked to turn on monitor mode.
2280 * Do so before we get the link-layer type,
2281 * because entering monitor mode could change
2282 * the link-layer type.
2284 err
= enter_rfmon_mode(handle
, sock_fd
, device
);
2292 * Nothing worked for turning monitor mode
2296 return PCAP_ERROR_RFMON_NOTSUP
;
2300 * Either monitor mode has been turned on for
2301 * the device, or we've been given a different
2302 * device to open for monitor mode. If we've
2303 * been given a different device, use it.
2305 if (handle
->md
.mondevice
!= NULL
)
2306 device
= handle
->md
.mondevice
;
2308 arptype
= iface_get_arptype(sock_fd
, device
, handle
->errbuf
);
2313 map_arphrd_to_dlt(handle
, arptype
, 1);
2314 if (handle
->linktype
== -1 ||
2315 handle
->linktype
== DLT_LINUX_SLL
||
2316 handle
->linktype
== DLT_LINUX_IRDA
||
2317 handle
->linktype
== DLT_LINUX_LAPD
||
2318 (handle
->linktype
== DLT_EN10MB
&&
2319 (strncmp("isdn", device
, 4) == 0 ||
2320 strncmp("isdY", device
, 4) == 0))) {
2322 * Unknown interface type (-1), or a
2323 * device we explicitly chose to run
2324 * in cooked mode (e.g., PPP devices),
2325 * or an ISDN device (whose link-layer
2326 * type we can only determine by using
2327 * APIs that may be different on different
2328 * kernels) - reopen in cooked mode.
2330 if (close(sock_fd
) == -1) {
2331 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2332 "close: %s", pcap_strerror(errno
));
2335 sock_fd
= socket(PF_PACKET
, SOCK_DGRAM
,
2337 if (sock_fd
== -1) {
2338 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2339 "socket: %s", pcap_strerror(errno
));
2342 handle
->md
.cooked
= 1;
2345 * Get rid of any link-layer type list
2346 * we allocated - this only supports cooked
2349 if (handle
->dlt_list
!= NULL
) {
2350 free(handle
->dlt_list
);
2351 handle
->dlt_list
= NULL
;
2352 handle
->dlt_count
= 0;
2355 if (handle
->linktype
== -1) {
2357 * Warn that we're falling back on
2358 * cooked mode; we may want to
2359 * update "map_arphrd_to_dlt()"
2360 * to handle the new type.
2362 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2364 "supported by libpcap - "
2365 "falling back to cooked "
2371 * IrDA capture is not a real "cooked" capture,
2372 * it's IrLAP frames, not IP packets. The
2373 * same applies to LAPD capture.
2375 if (handle
->linktype
!= DLT_LINUX_IRDA
&&
2376 handle
->linktype
!= DLT_LINUX_LAPD
)
2377 handle
->linktype
= DLT_LINUX_SLL
;
2380 handle
->md
.ifindex
= iface_get_id(sock_fd
, device
,
2382 if (handle
->md
.ifindex
== -1) {
2387 if ((err
= iface_bind(sock_fd
, handle
->md
.ifindex
,
2388 handle
->errbuf
)) != 1) {
2393 return 0; /* try old mechanism */
2399 if (handle
->opt
.rfmon
) {
2401 * It doesn't support monitor mode.
2403 return PCAP_ERROR_RFMON_NOTSUP
;
2407 * It uses cooked mode.
2409 handle
->md
.cooked
= 1;
2410 handle
->linktype
= DLT_LINUX_SLL
;
2413 * We're not bound to a device.
2414 * For now, we're using this as an indication
2415 * that we can't transmit; stop doing that only
2416 * if we figure out how to transmit in cooked
2419 handle
->md
.ifindex
= -1;
2423 * Select promiscuous mode on if "promisc" is set.
2425 * Do not turn allmulti mode on if we don't select
2426 * promiscuous mode - on some devices (e.g., Orinoco
2427 * wireless interfaces), allmulti mode isn't supported
2428 * and the driver implements it by turning promiscuous
2429 * mode on, and that screws up the operation of the
2430 * card as a normal networking interface, and on no
2431 * other platform I know of does starting a non-
2432 * promiscuous capture affect which multicast packets
2433 * are received by the interface.
2437 * Hmm, how can we set promiscuous mode on all interfaces?
2438 * I am not sure if that is possible at all. For now, we
2439 * silently ignore attempts to turn promiscuous mode on
2440 * for the "any" device (so you don't have to explicitly
2441 * disable it in programs such as tcpdump).
2444 if (!is_any_device
&& handle
->opt
.promisc
) {
2445 memset(&mr
, 0, sizeof(mr
));
2446 mr
.mr_ifindex
= handle
->md
.ifindex
;
2447 mr
.mr_type
= PACKET_MR_PROMISC
;
2448 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_ADD_MEMBERSHIP
,
2449 &mr
, sizeof(mr
)) == -1) {
2450 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2451 "setsockopt: %s", pcap_strerror(errno
));
2457 /* Enable auxillary data if supported and reserve room for
2458 * reconstructing VLAN headers. */
2459 #ifdef HAVE_PACKET_AUXDATA
2461 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_AUXDATA
, &val
,
2462 sizeof(val
)) == -1 && errno
!= ENOPROTOOPT
) {
2463 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2464 "setsockopt: %s", pcap_strerror(errno
));
2468 handle
->offset
+= VLAN_TAG_LEN
;
2469 #endif /* HAVE_PACKET_AUXDATA */
2472 * This is a 2.2[.x] or later kernel (we know that
2473 * because we're not using a SOCK_PACKET socket -
2474 * PF_PACKET is supported only in 2.2 and later
2477 * We can safely pass "recvfrom()" a byte count
2478 * based on the snapshot length.
2480 * If we're in cooked mode, make the snapshot length
2481 * large enough to hold a "cooked mode" header plus
2482 * 1 byte of packet data (so we don't pass a byte
2483 * count of 0 to "recvfrom()").
2485 if (handle
->md
.cooked
) {
2486 if (handle
->snapshot
< SLL_HDR_LEN
+ 1)
2487 handle
->snapshot
= SLL_HDR_LEN
+ 1;
2489 handle
->bufsize
= handle
->snapshot
;
2491 /* Save the socket FD in the pcap structure */
2492 handle
->fd
= sock_fd
;
2497 "New packet capturing interface not supported by build "
2498 "environment", PCAP_ERRBUF_SIZE
);
2504 activate_mmap(pcap_t
*handle
)
2506 #ifdef HAVE_PACKET_RING
2510 * Attempt to allocate a buffer to hold the contents of one
2511 * packet, for use by the oneshot callback.
2513 handle
->md
.oneshot_buffer
= malloc(handle
->snapshot
);
2514 if (handle
->md
.oneshot_buffer
== NULL
) {
2515 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2516 "can't allocate oneshot buffer: %s",
2517 pcap_strerror(errno
));
2521 if (handle
->opt
.buffer_size
== 0) {
2522 /* by default request 2M for the ring buffer */
2523 handle
->opt
.buffer_size
= 2*1024*1024;
2525 ret
= prepare_tpacket_socket(handle
);
2527 free(handle
->md
.oneshot_buffer
);
2530 ret
= create_ring(handle
);
2532 free(handle
->md
.oneshot_buffer
);
2536 /* override some defaults and inherit the other fields from
2538 * handle->offset is used to get the current position into the rx ring
2539 * handle->cc is used to store the ring size */
2540 handle
->read_op
= pcap_read_linux_mmap
;
2541 handle
->cleanup_op
= pcap_cleanup_linux_mmap
;
2542 handle
->setfilter_op
= pcap_setfilter_linux_mmap
;
2543 handle
->setnonblock_op
= pcap_setnonblock_mmap
;
2544 handle
->getnonblock_op
= pcap_getnonblock_mmap
;
2545 handle
->oneshot_callback
= pcap_oneshot_mmap
;
2546 handle
->selectable_fd
= handle
->fd
;
2548 #else /* HAVE_PACKET_RING */
2550 #endif /* HAVE_PACKET_RING */
2553 #ifdef HAVE_PACKET_RING
2555 prepare_tpacket_socket(pcap_t
*handle
)
2557 #ifdef HAVE_TPACKET2
2562 handle
->md
.tp_version
= TPACKET_V1
;
2563 handle
->md
.tp_hdrlen
= sizeof(struct tpacket_hdr
);
2565 #ifdef HAVE_TPACKET2
2566 /* Probe whether kernel supports TPACKET_V2 */
2569 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_HDRLEN
, &val
, &len
) < 0) {
2570 if (errno
== ENOPROTOOPT
)
2571 return 1; /* no - just drive on */
2573 /* Yes - treat as a failure. */
2574 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2575 "can't get TPACKET_V2 header len on packet socket: %s",
2576 pcap_strerror(errno
));
2579 handle
->md
.tp_hdrlen
= val
;
2582 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_VERSION
, &val
,
2584 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2585 "can't activate TPACKET_V2 on packet socket: %s",
2586 pcap_strerror(errno
));
2589 handle
->md
.tp_version
= TPACKET_V2
;
2591 /* Reserve space for VLAN tag reconstruction */
2593 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
, &val
,
2595 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2596 "can't set up reserve on packet socket: %s",
2597 pcap_strerror(errno
));
2601 #endif /* HAVE_TPACKET2 */
2606 create_ring(pcap_t
*handle
)
2608 unsigned i
, j
, frames_per_block
;
2609 struct tpacket_req req
;
2611 /* Note that with large snapshot (say 64K) only a few frames
2612 * will be available in the ring even with pretty large ring size
2613 * (and a lot of memory will be unused).
2614 * The snap len should be carefully chosen to achive best
2616 req
.tp_frame_size
= TPACKET_ALIGN(handle
->snapshot
+
2617 TPACKET_ALIGN(handle
->md
.tp_hdrlen
) +
2618 sizeof(struct sockaddr_ll
));
2619 req
.tp_frame_nr
= handle
->opt
.buffer_size
/req
.tp_frame_size
;
2621 /* compute the minumum block size that will handle this frame.
2622 * The block has to be page size aligned.
2623 * The max block size allowed by the kernel is arch-dependent and
2624 * it's not explicitly checked here. */
2625 req
.tp_block_size
= getpagesize();
2626 while (req
.tp_block_size
< req
.tp_frame_size
)
2627 req
.tp_block_size
<<= 1;
2629 frames_per_block
= req
.tp_block_size
/req
.tp_frame_size
;
2631 /* ask the kernel to create the ring */
2633 req
.tp_block_nr
= req
.tp_frame_nr
/ frames_per_block
;
2635 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
2636 req
.tp_frame_nr
= req
.tp_block_nr
* frames_per_block
;
2638 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
2639 (void *) &req
, sizeof(req
))) {
2640 if ((errno
== ENOMEM
) && (req
.tp_block_nr
> 1)) {
2642 * Memory failure; try to reduce the requested ring
2645 * We used to reduce this by half -- do 5% instead.
2646 * That may result in more iterations and a longer
2647 * startup, but the user will be much happier with
2648 * the resulting buffer size.
2650 if (req
.tp_frame_nr
< 20)
2651 req
.tp_frame_nr
-= 1;
2653 req
.tp_frame_nr
-= req
.tp_frame_nr
/20;
2656 if (errno
== ENOPROTOOPT
) {
2658 * We don't have ring buffer support in this kernel.
2662 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2663 "can't create rx ring on packet socket: %s",
2664 pcap_strerror(errno
));
2668 /* memory map the rx ring */
2669 handle
->md
.mmapbuflen
= req
.tp_block_nr
* req
.tp_block_size
;
2670 handle
->md
.mmapbuf
= mmap(0, handle
->md
.mmapbuflen
,
2671 PROT_READ
|PROT_WRITE
, MAP_SHARED
, handle
->fd
, 0);
2672 if (handle
->md
.mmapbuf
== MAP_FAILED
) {
2673 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2674 "can't mmap rx ring: %s", pcap_strerror(errno
));
2676 /* clear the allocated ring on error*/
2677 destroy_ring(handle
);
2681 /* allocate a ring for each frame header pointer*/
2682 handle
->cc
= req
.tp_frame_nr
;
2683 handle
->buffer
= malloc(handle
->cc
* sizeof(union thdr
*));
2684 if (!handle
->buffer
) {
2685 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2686 "can't allocate ring of frame headers: %s",
2687 pcap_strerror(errno
));
2689 destroy_ring(handle
);
2693 /* fill the header ring with proper frame ptr*/
2695 for (i
=0; i
<req
.tp_block_nr
; ++i
) {
2696 void *base
= &handle
->md
.mmapbuf
[i
*req
.tp_block_size
];
2697 for (j
=0; j
<frames_per_block
; ++j
, ++handle
->offset
) {
2698 RING_GET_FRAME(handle
) = base
;
2699 base
+= req
.tp_frame_size
;
2703 handle
->bufsize
= req
.tp_frame_size
;
2708 /* free all ring related resources*/
2710 destroy_ring(pcap_t
*handle
)
2712 /* tell the kernel to destroy the ring*/
2713 struct tpacket_req req
;
2714 memset(&req
, 0, sizeof(req
));
2715 setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
2716 (void *) &req
, sizeof(req
));
2718 /* if ring is mapped, unmap it*/
2719 if (handle
->md
.mmapbuf
) {
2720 /* do not test for mmap failure, as we can't recover from any error */
2721 munmap(handle
->md
.mmapbuf
, handle
->md
.mmapbuflen
);
2722 handle
->md
.mmapbuf
= NULL
;
2727 * Special one-shot callback, used for pcap_next() and pcap_next_ex(),
2728 * for Linux mmapped capture.
2730 * The problem is that pcap_next() and pcap_next_ex() expect the packet
2731 * data handed to the callback to be valid after the callback returns,
2732 * but pcap_read_linux_mmap() has to release that packet as soon as
2733 * the callback returns (otherwise, the kernel thinks there's still
2734 * at least one unprocessed packet available in the ring, so a select()
2735 * will immediately return indicating that there's data to process), so,
2736 * in the callback, we have to make a copy of the packet.
2738 * Yes, this means that, if the capture is using the ring buffer, using
2739 * pcap_next() or pcap_next_ex() requires more copies than using
2740 * pcap_loop() or pcap_dispatch(). If that bothers you, don't use
2741 * pcap_next() or pcap_next_ex().
2744 pcap_oneshot_mmap(u_char
*user
, const struct pcap_pkthdr
*h
,
2745 const u_char
*bytes
)
2747 struct pkt_for_oneshot
*sp
= (struct pkt_for_oneshot
*)user
;
2748 bpf_u_int32 copylen
;
2751 memcpy(sp
->pd
->md
.oneshot_buffer
, bytes
, h
->caplen
);
2752 *sp
->pkt
= sp
->pd
->md
.oneshot_buffer
;
2756 pcap_cleanup_linux_mmap( pcap_t
*handle
)
2758 destroy_ring(handle
);
2759 if (handle
->md
.oneshot_buffer
!= NULL
) {
2760 free(handle
->md
.oneshot_buffer
);
2761 handle
->md
.oneshot_buffer
= NULL
;
2763 pcap_cleanup_linux(handle
);
2768 pcap_getnonblock_mmap(pcap_t
*p
, char *errbuf
)
2770 /* use negative value of timeout to indicate non blocking ops */
2771 return (p
->md
.timeout
<0);
2775 pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
, char *errbuf
)
2777 /* map each value to the corresponding 2's complement, to
2778 * preserve the timeout value provided with pcap_set_timeout */
2780 if (p
->md
.timeout
>= 0) {
2782 * Timeout is non-negative, so we're not already
2783 * in non-blocking mode; set it to the 2's
2784 * complement, to make it negative, as an
2785 * indication that we're in non-blocking mode.
2787 p
->md
.timeout
= p
->md
.timeout
*-1 - 1;
2790 if (p
->md
.timeout
< 0) {
2792 * Timeout is negative, so we're not already
2793 * in blocking mode; reverse the previous
2794 * operation, to make the timeout non-negative
2797 p
->md
.timeout
= (p
->md
.timeout
+1)*-1;
2803 static inline union thdr
*
2804 pcap_get_ring_frame(pcap_t
*handle
, int status
)
2808 h
.raw
= RING_GET_FRAME(handle
);
2809 switch (handle
->md
.tp_version
) {
2811 if (status
!= (h
.h1
->tp_status
? TP_STATUS_USER
:
2815 #ifdef HAVE_TPACKET2
2817 if (status
!= (h
.h2
->tp_status
? TP_STATUS_USER
:
2827 pcap_read_linux_mmap(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
2832 /* wait for frames availability.*/
2833 if ((handle
->md
.timeout
>= 0) &&
2834 !pcap_get_ring_frame(handle
, TP_STATUS_USER
)) {
2835 struct pollfd pollinfo
;
2838 pollinfo
.fd
= handle
->fd
;
2839 pollinfo
.events
= POLLIN
;
2842 /* poll() requires a negative timeout to wait forever */
2843 ret
= poll(&pollinfo
, 1, (handle
->md
.timeout
> 0)?
2844 handle
->md
.timeout
: -1);
2845 if ((ret
< 0) && (errno
!= EINTR
)) {
2846 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2847 "can't poll on packet socket fd %d: %d-%s",
2848 handle
->fd
, errno
, pcap_strerror(errno
));
2851 /* check for break loop condition on interrupted syscall*/
2852 if (handle
->break_loop
) {
2853 handle
->break_loop
= 0;
2859 /* non-positive values of max_packets are used to require all
2860 * packets currently available in the ring */
2861 while ((pkts
< max_packets
) || (max_packets
<= 0)) {
2863 struct sockaddr_ll
*sll
;
2864 struct pcap_pkthdr pcaphdr
;
2867 unsigned int tp_len
;
2868 unsigned int tp_mac
;
2869 unsigned int tp_snaplen
;
2870 unsigned int tp_sec
;
2871 unsigned int tp_usec
;
2873 h
.raw
= pcap_get_ring_frame(handle
, TP_STATUS_USER
);
2877 switch (handle
->md
.tp_version
) {
2879 tp_len
= h
.h1
->tp_len
;
2880 tp_mac
= h
.h1
->tp_mac
;
2881 tp_snaplen
= h
.h1
->tp_snaplen
;
2882 tp_sec
= h
.h1
->tp_sec
;
2883 tp_usec
= h
.h1
->tp_usec
;
2885 #ifdef HAVE_TPACKET2
2887 tp_len
= h
.h2
->tp_len
;
2888 tp_mac
= h
.h2
->tp_mac
;
2889 tp_snaplen
= h
.h2
->tp_snaplen
;
2890 tp_sec
= h
.h2
->tp_sec
;
2891 tp_usec
= h
.h2
->tp_nsec
/ 1000;
2895 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2896 "unsupported tpacket version %d",
2897 handle
->md
.tp_version
);
2900 /* perform sanity check on internal offset. */
2901 if (tp_mac
+ tp_snaplen
> handle
->bufsize
) {
2902 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2903 "corrupted frame on kernel ring mac "
2904 "offset %d + caplen %d > frame len %d",
2905 tp_mac
, tp_snaplen
, handle
->bufsize
);
2909 /* run filter on received packet
2910 * If the kernel filtering is enabled we need to run the
2911 * filter until all the frames present into the ring
2912 * at filter creation time are processed.
2913 * In such case md.use_bpf is used as a counter for the
2914 * packet we need to filter.
2915 * Note: alternatively it could be possible to stop applying
2916 * the filter when the ring became empty, but it can possibly
2917 * happen a lot later... */
2918 bp
= (unsigned char*)h
.raw
+ tp_mac
;
2919 run_bpf
= (!handle
->md
.use_bpf
) ||
2920 ((handle
->md
.use_bpf
>1) && handle
->md
.use_bpf
--);
2921 if (run_bpf
&& handle
->fcode
.bf_insns
&&
2922 (bpf_filter(handle
->fcode
.bf_insns
, bp
,
2923 tp_len
, tp_snaplen
) == 0))
2927 * Do checks based on packet direction.
2929 sll
= (void *)h
.raw
+ TPACKET_ALIGN(handle
->md
.tp_hdrlen
);
2930 if (sll
->sll_pkttype
== PACKET_OUTGOING
) {
2933 * If this is from the loopback device, reject it;
2934 * we'll see the packet as an incoming packet as well,
2935 * and we don't want to see it twice.
2937 if (sll
->sll_ifindex
== handle
->md
.lo_ifindex
)
2941 * If the user only wants incoming packets, reject it.
2943 if (handle
->direction
== PCAP_D_IN
)
2948 * If the user only wants outgoing packets, reject it.
2950 if (handle
->direction
== PCAP_D_OUT
)
2954 /* get required packet info from ring header */
2955 pcaphdr
.ts
.tv_sec
= tp_sec
;
2956 pcaphdr
.ts
.tv_usec
= tp_usec
;
2957 pcaphdr
.caplen
= tp_snaplen
;
2958 pcaphdr
.len
= tp_len
;
2960 /* if required build in place the sll header*/
2961 if (handle
->md
.cooked
) {
2962 struct sll_header
*hdrp
;
2965 * The kernel should have left us with enough
2966 * space for an sll header; back up the packet
2967 * data pointer into that space, as that'll be
2968 * the beginning of the packet we pass to the
2974 * Let's make sure that's past the end of
2975 * the tpacket header, i.e. >=
2976 * ((u_char *)thdr + TPACKET_HDRLEN), so we
2977 * don't step on the header when we construct
2980 if (bp
< (u_char
*)h
.raw
+
2981 TPACKET_ALIGN(handle
->md
.tp_hdrlen
) +
2982 sizeof(struct sockaddr_ll
)) {
2983 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2984 "cooked-mode frame doesn't have room for sll header");
2989 * OK, that worked; construct the sll header.
2991 hdrp
= (struct sll_header
*)bp
;
2992 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(
2994 hdrp
->sll_hatype
= htons(sll
->sll_hatype
);
2995 hdrp
->sll_halen
= htons(sll
->sll_halen
);
2996 memcpy(hdrp
->sll_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
2997 hdrp
->sll_protocol
= sll
->sll_protocol
;
2999 /* update packet len */
3000 pcaphdr
.caplen
+= SLL_HDR_LEN
;
3001 pcaphdr
.len
+= SLL_HDR_LEN
;
3004 #ifdef HAVE_TPACKET2
3005 if (handle
->md
.tp_version
== TPACKET_V2
&& h
.h2
->tp_vlan_tci
&&
3006 tp_snaplen
>= 2 * ETH_ALEN
) {
3007 struct vlan_tag
*tag
;
3010 memmove(bp
, bp
+ VLAN_TAG_LEN
, 2 * ETH_ALEN
);
3012 tag
= (struct vlan_tag
*)(bp
+ 2 * ETH_ALEN
);
3013 tag
->vlan_tpid
= htons(ETH_P_8021Q
);
3014 tag
->vlan_tci
= htons(h
.h2
->tp_vlan_tci
);
3016 pcaphdr
.caplen
+= VLAN_TAG_LEN
;
3017 pcaphdr
.len
+= VLAN_TAG_LEN
;
3022 * The only way to tell the kernel to cut off the
3023 * packet at a snapshot length is with a filter program;
3024 * if there's no filter program, the kernel won't cut
3027 * Trim the snapshot length to be no longer than the
3028 * specified snapshot length.
3030 if (pcaphdr
.caplen
> handle
->snapshot
)
3031 pcaphdr
.caplen
= handle
->snapshot
;
3033 /* pass the packet to the user */
3035 callback(user
, &pcaphdr
, bp
);
3036 handle
->md
.packets_read
++;
3040 switch (handle
->md
.tp_version
) {
3042 h
.h1
->tp_status
= TP_STATUS_KERNEL
;
3044 #ifdef HAVE_TPACKET2
3046 h
.h2
->tp_status
= TP_STATUS_KERNEL
;
3050 if (++handle
->offset
>= handle
->cc
)
3053 /* check for break loop condition*/
3054 if (handle
->break_loop
) {
3055 handle
->break_loop
= 0;
3063 pcap_setfilter_linux_mmap(pcap_t
*handle
, struct bpf_program
*filter
)
3069 * Don't rewrite "ret" instructions; we don't need to, as
3070 * we're not reading packets with recvmsg(), and we don't
3071 * want to, as, by not rewriting them, the kernel can avoid
3072 * copying extra data.
3074 ret
= pcap_setfilter_linux_common(handle
, filter
, 1);
3078 /* if the kernel filter is enabled, we need to apply the filter on
3079 * all packets present into the ring. Get an upper bound of their number
3081 if (!handle
->md
.use_bpf
)
3084 /* walk the ring backward and count the free slot */
3085 offset
= handle
->offset
;
3086 if (--handle
->offset
< 0)
3087 handle
->offset
= handle
->cc
- 1;
3088 for (n
=0; n
< handle
->cc
; ++n
) {
3089 if (--handle
->offset
< 0)
3090 handle
->offset
= handle
->cc
- 1;
3091 if (!pcap_get_ring_frame(handle
, TP_STATUS_KERNEL
))
3095 /* be careful to not change current ring position */
3096 handle
->offset
= offset
;
3098 /* store the number of packets currently present in the ring */
3099 handle
->md
.use_bpf
= 1 + (handle
->cc
- n
);
3103 #endif /* HAVE_PACKET_RING */
3106 #ifdef HAVE_PF_PACKET_SOCKETS
3108 * Return the index of the given device name. Fill ebuf and return
3112 iface_get_id(int fd
, const char *device
, char *ebuf
)
3116 memset(&ifr
, 0, sizeof(ifr
));
3117 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
3119 if (ioctl(fd
, SIOCGIFINDEX
, &ifr
) == -1) {
3120 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3121 "SIOCGIFINDEX: %s", pcap_strerror(errno
));
3125 return ifr
.ifr_ifindex
;
3129 * Bind the socket associated with FD to the given device.
3130 * Return 1 on success, 0 if we should try a SOCK_PACKET socket,
3131 * or a PCAP_ERROR_ value on a hard error.
3134 iface_bind(int fd
, int ifindex
, char *ebuf
)
3136 struct sockaddr_ll sll
;
3138 socklen_t errlen
= sizeof(err
);
3140 memset(&sll
, 0, sizeof(sll
));
3141 sll
.sll_family
= AF_PACKET
;
3142 sll
.sll_ifindex
= ifindex
;
3143 sll
.sll_protocol
= htons(ETH_P_ALL
);
3145 if (bind(fd
, (struct sockaddr
*) &sll
, sizeof(sll
)) == -1) {
3146 if (errno
== ENETDOWN
) {
3148 * Return a "network down" indication, so that
3149 * the application can report that rather than
3150 * saying we had a mysterious failure and
3151 * suggest that they report a problem to the
3152 * libpcap developers.
3154 return PCAP_ERROR_IFACE_NOT_UP
;
3156 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3157 "bind: %s", pcap_strerror(errno
));
3162 /* Any pending errors, e.g., network is down? */
3164 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
3165 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3166 "getsockopt: %s", pcap_strerror(errno
));
3170 if (err
== ENETDOWN
) {
3172 * Return a "network down" indication, so that
3173 * the application can report that rather than
3174 * saying we had a mysterious failure and
3175 * suggest that they report a problem to the
3176 * libpcap developers.
3178 return PCAP_ERROR_IFACE_NOT_UP
;
3179 } else if (err
> 0) {
3180 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3181 "bind: %s", pcap_strerror(err
));
3188 #ifdef IW_MODE_MONITOR
3190 * Check whether the device supports the Wireless Extensions.
3191 * Returns 1 if it does, 0 if it doesn't, PCAP_ERROR_NO_SUCH_DEVICE
3192 * if the device doesn't even exist.
3195 has_wext(int sock_fd
, const char *device
, char *ebuf
)
3199 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3200 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3201 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3202 if (ioctl(sock_fd
, SIOCGIWNAME
, &ireq
) >= 0)
3204 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3205 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
3206 if (errno
== ENODEV
)
3207 return PCAP_ERROR_NO_SUCH_DEVICE
;
3212 * Per me si va ne la citta dolente,
3213 * Per me si va ne l'etterno dolore,
3215 * Lasciate ogne speranza, voi ch'intrate.
3217 * XXX - airmon-ng does special stuff with the Orinoco driver and the
3233 * Use the Wireless Extensions, if we have them, to try to turn monitor mode
3234 * on if it's not already on.
3236 * Returns 1 on success, 0 if we don't support the Wireless Extensions
3237 * on this device, or a PCAP_ERROR_ value if we do support them but
3238 * we weren't able to turn monitor mode on.
3241 enter_rfmon_mode_wext(pcap_t
*handle
, int sock_fd
, const char *device
)
3244 * XXX - at least some adapters require non-Wireless Extensions
3245 * mechanisms to turn monitor mode on.
3247 * Atheros cards might require that a separate "monitor virtual access
3248 * point" be created, with later versions of the madwifi driver.
3249 * airmon-ng does "wlanconfig ath create wlandev {if} wlanmode
3250 * monitor -bssid", which apparently spits out a line "athN"
3251 * where "athN" is the monitor mode device. To leave monitor
3252 * mode, it destroys the monitor mode device.
3254 * Some Intel Centrino adapters might require private ioctls to get
3255 * radio headers; the ipw2200 and ipw3945 drivers allow you to
3256 * configure a separate "rtapN" interface to capture in monitor
3257 * mode without preventing the adapter from operating normally.
3258 * (airmon-ng doesn't appear to use that, though.)
3260 * It would be Truly Wonderful if mac80211 and nl80211 cleaned this
3261 * up, and if all drivers were converted to mac80211 drivers.
3263 * If interface {if} is a mac80211 driver, the file
3264 * /sys/class/net/{if}/phy80211 is a symlink to
3265 * /sys/class/ieee80211/{phydev}, for some {phydev}.
3267 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
3268 * least, has a "wmaster0" device and a "wlan0" device; the
3269 * latter is the one with the IP address. Both show up in
3270 * "tcpdump -D" output. Capturing on the wmaster0 device
3271 * captures with 802.11 headers.
3273 * airmon-ng searches through /sys/class/net for devices named
3274 * monN, starting with mon0; as soon as one *doesn't* exist,
3275 * it chooses that as the monitor device name. If the "iw"
3276 * command exists, it does "iw dev {if} interface add {monif}
3277 * type monitor", where {monif} is the monitor device. It
3278 * then (sigh) sleeps .1 second, and then configures the
3279 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
3280 * is a file, it writes {mondev}, without a newline, to that file,
3281 * and again (sigh) sleeps .1 second, and then iwconfig's that
3282 * device into monitor mode and configures it up. Otherwise,
3283 * you can't do monitor mode.
3285 * All these devices are "glued" together by having the
3286 * /sys/class/net/{device}/phy80211 links pointing to the same
3287 * place, so, given a wmaster, wlan, or mon device, you can
3288 * find the other devices by looking for devices with
3289 * the same phy80211 link.
3291 * To turn monitor mode off, delete the monitor interface,
3292 * either with "iw dev {monif} interface del" or by sending
3293 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
3295 * Note: if you try to create a monitor device named "monN", and
3296 * there's already a "monN" device, it fails, as least with
3297 * the netlink interface (which is what iw uses), with a return
3298 * value of -ENFILE. (Return values are negative errnos.) We
3299 * could probably use that to find an unused device.
3303 struct iw_priv_args
*priv
;
3304 monitor_type montype
;
3311 * Does this device *support* the Wireless Extensions?
3313 err
= has_wext(sock_fd
, device
, handle
->errbuf
);
3315 return err
; /* either it doesn't or the device doesn't even exist */
3317 * Try to get all the Wireless Extensions private ioctls
3318 * supported by this device.
3320 * First, get the size of the buffer we need, by supplying no
3321 * buffer and a length of 0. If the device supports private
3322 * ioctls, it should return E2BIG, with ireq.u.data.length set
3323 * to the length we need. If it doesn't support them, it should
3324 * return EOPNOTSUPP.
3326 memset(&ireq
, 0, sizeof ireq
);
3327 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3328 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3329 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3330 ireq
.u
.data
.pointer
= (void *)args
;
3331 ireq
.u
.data
.length
= 0;
3332 ireq
.u
.data
.flags
= 0;
3333 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) != -1) {
3334 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3335 "%s: SIOCGIWPRIV with a zero-length buffer didn't fail!",
3339 if (errno
== EOPNOTSUPP
) {
3341 * No private ioctls, so we assume that there's only one
3342 * DLT_ for monitor mode.
3346 if (errno
!= E2BIG
) {
3350 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3351 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
3354 priv
= malloc(ireq
.u
.data
.length
* sizeof (struct iw_priv_args
));
3356 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3357 "malloc: %s", pcap_strerror(errno
));
3360 ireq
.u
.data
.pointer
= (void *)priv
;
3361 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) == -1) {
3362 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3363 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
3369 * Look for private ioctls to turn monitor mode on or, if
3370 * monitor mode is on, to set the header type.
3372 montype
= MONITOR_WEXT
;
3374 for (i
= 0; i
< ireq
.u
.data
.length
; i
++) {
3375 if (strcmp(priv
[i
].name
, "monitor_type") == 0) {
3377 * Hostap driver, use this one.
3378 * Set monitor mode first.
3379 * You can set it to 0 to get DLT_IEEE80211,
3380 * 1 to get DLT_PRISM, 2 to get
3381 * DLT_IEEE80211_RADIO_AVS, and, with more
3382 * recent versions of the driver, 3 to get
3383 * DLT_IEEE80211_RADIO.
3385 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
3387 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
3389 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
3391 montype
= MONITOR_HOSTAP
;
3395 if (strcmp(priv
[i
].name
, "set_prismhdr") == 0) {
3397 * Prism54 driver, use this one.
3398 * Set monitor mode first.
3399 * You can set it to 2 to get DLT_IEEE80211
3400 * or 3 or get DLT_PRISM.
3402 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
3404 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
3406 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
3408 montype
= MONITOR_PRISM54
;
3412 if (strcmp(priv
[i
].name
, "forceprismheader") == 0) {
3414 * RT2570 driver, use this one.
3415 * Do this after turning monitor mode on.
3416 * You can set it to 1 to get DLT_PRISM or 2
3417 * to get DLT_IEEE80211.
3419 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
3421 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
3423 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
3425 montype
= MONITOR_RT2570
;
3429 if (strcmp(priv
[i
].name
, "forceprism") == 0) {
3431 * RT73 driver, use this one.
3432 * Do this after turning monitor mode on.
3433 * Its argument is a *string*; you can
3434 * set it to "1" to get DLT_PRISM or "2"
3435 * to get DLT_IEEE80211.
3437 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_CHAR
)
3439 if (priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
)
3441 montype
= MONITOR_RT73
;
3445 if (strcmp(priv
[i
].name
, "prismhdr") == 0) {
3447 * One of the RTL8xxx drivers, use this one.
3448 * It can only be done after monitor mode
3449 * has been turned on. You can set it to 1
3450 * to get DLT_PRISM or 0 to get DLT_IEEE80211.
3452 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
3454 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
3456 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
3458 montype
= MONITOR_RTL8XXX
;
3462 if (strcmp(priv
[i
].name
, "rfmontx") == 0) {
3464 * RT2500 or RT61 driver, use this one.
3465 * It has one one-byte parameter; set
3466 * u.data.length to 1 and u.data.pointer to
3467 * point to the parameter.
3468 * It doesn't itself turn monitor mode on.
3469 * You can set it to 1 to allow transmitting
3470 * in monitor mode(?) and get DLT_IEEE80211,
3471 * or set it to 0 to disallow transmitting in
3472 * monitor mode(?) and get DLT_PRISM.
3474 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
3476 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 2)
3478 montype
= MONITOR_RT2500
;
3482 if (strcmp(priv
[i
].name
, "monitor") == 0) {
3484 * Either ACX100 or hostap, use this one.
3485 * It turns monitor mode on.
3486 * If it takes two arguments, it's ACX100;
3487 * the first argument is 1 for DLT_PRISM
3488 * or 2 for DLT_IEEE80211, and the second
3489 * argument is the channel on which to
3490 * run. If it takes one argument, it's
3491 * HostAP, and the argument is 2 for
3492 * DLT_IEEE80211 and 3 for DLT_PRISM.
3494 * If we see this, we don't quit, as this
3495 * might be a version of the hostap driver
3496 * that also supports "monitor_type".
3498 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
3500 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
3502 switch (priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) {
3505 montype
= MONITOR_PRISM
;
3510 montype
= MONITOR_ACX100
;
3522 * XXX - ipw3945? islism?
3528 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3529 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3530 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3531 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) == -1) {
3533 * We probably won't be able to set the mode, either.
3535 return PCAP_ERROR_RFMON_NOTSUP
;
3539 * Is it currently in monitor mode?
3541 if (ireq
.u
.mode
== IW_MODE_MONITOR
) {
3543 * Yes. Just leave things as they are.
3544 * We don't offer multiple link-layer types, as
3545 * changing the link-layer type out from under
3546 * somebody else capturing in monitor mode would
3547 * be considered rude.
3552 * No. We have to put the adapter into rfmon mode.
3556 * If we haven't already done so, arrange to have
3557 * "pcap_close_all()" called when we exit.
3559 if (!pcap_do_addexit(handle
)) {
3561 * "atexit()" failed; don't put the interface
3562 * in rfmon mode, just give up.
3564 return PCAP_ERROR_RFMON_NOTSUP
;
3568 * Save the old mode.
3570 handle
->md
.oldmode
= ireq
.u
.mode
;
3573 * Put the adapter in rfmon mode. How we do this depends
3574 * on whether we have a special private ioctl or not.
3576 if (montype
== MONITOR_PRISM
) {
3578 * We have the "monitor" private ioctl, but none of
3579 * the other private ioctls. Use this, and select
3582 * If it fails, just fall back on SIOCSIWMODE.
3584 memset(&ireq
, 0, sizeof ireq
);
3585 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3586 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3587 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3588 ireq
.u
.data
.length
= 1; /* 1 argument */
3589 args
[0] = 3; /* request Prism header */
3590 memcpy(ireq
.u
.name
, args
, IFNAMSIZ
);
3591 if (ioctl(sock_fd
, cmd
, &ireq
) != -1) {
3594 * Note that we have to put the old mode back
3595 * when we close the device.
3597 handle
->md
.must_do_on_close
|= MUST_CLEAR_RFMON
;
3600 * Add this to the list of pcaps to close
3603 pcap_add_to_pcaps_to_close(handle
);
3609 * Failure. Fall back on SIOCSIWMODE.
3614 * First, turn monitor mode on.
3616 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3617 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3618 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3619 ireq
.u
.mode
= IW_MODE_MONITOR
;
3620 if (ioctl(sock_fd
, SIOCSIWMODE
, &ireq
) == -1) {
3622 * Scientist, you've failed.
3624 return PCAP_ERROR_RFMON_NOTSUP
;
3628 * XXX - airmon-ng does "iwconfig {if} key off" after setting
3629 * monitor mode and setting the channel, and then does
3634 * Now select the appropriate radio header.
3640 * We don't have any private ioctl to set the header.
3644 case MONITOR_HOSTAP
:
3646 * Try to select the radiotap header.
3648 memset(&ireq
, 0, sizeof ireq
);
3649 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3650 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3651 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3652 args
[0] = 3; /* request radiotap header */
3653 memcpy(ireq
.u
.name
, args
, sizeof (int));
3654 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
3655 break; /* success */
3658 * That failed. Try to select the AVS header.
3660 memset(&ireq
, 0, sizeof ireq
);
3661 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3662 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3663 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3664 args
[0] = 2; /* request AVS header */
3665 memcpy(ireq
.u
.name
, args
, sizeof (int));
3666 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
3667 break; /* success */
3670 * That failed. Try to select the Prism header.
3672 memset(&ireq
, 0, sizeof ireq
);
3673 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3674 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3675 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3676 args
[0] = 1; /* request Prism header */
3677 memcpy(ireq
.u
.name
, args
, sizeof (int));
3678 ioctl(sock_fd
, cmd
, &ireq
);
3683 * The private ioctl failed.
3687 case MONITOR_PRISM54
:
3689 * Select the Prism header.
3691 memset(&ireq
, 0, sizeof ireq
);
3692 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3693 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3694 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3695 args
[0] = 3; /* request Prism header */
3696 memcpy(ireq
.u
.name
, args
, sizeof (int));
3697 ioctl(sock_fd
, cmd
, &ireq
);
3700 case MONITOR_ACX100
:
3702 * Get the current channel.
3704 memset(&ireq
, 0, sizeof ireq
);
3705 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3706 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3707 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3708 if (ioctl(sock_fd
, SIOCGIWFREQ
, &ireq
) == -1) {
3709 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3710 "%s: SIOCGIWFREQ: %s", device
,
3711 pcap_strerror(errno
));
3714 channel
= ireq
.u
.freq
.m
;
3717 * Select the Prism header, and set the channel to the
3720 memset(&ireq
, 0, sizeof ireq
);
3721 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3722 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3723 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3724 args
[0] = 1; /* request Prism header */
3725 args
[1] = channel
; /* set channel */
3726 memcpy(ireq
.u
.name
, args
, 2*sizeof (int));
3727 ioctl(sock_fd
, cmd
, &ireq
);
3730 case MONITOR_RT2500
:
3732 * Disallow transmission - that turns on the
3735 memset(&ireq
, 0, sizeof ireq
);
3736 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3737 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3738 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3739 args
[0] = 0; /* disallow transmitting */
3740 memcpy(ireq
.u
.name
, args
, sizeof (int));
3741 ioctl(sock_fd
, cmd
, &ireq
);
3744 case MONITOR_RT2570
:
3746 * Force the Prism header.
3748 memset(&ireq
, 0, sizeof ireq
);
3749 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3750 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3751 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3752 args
[0] = 1; /* request Prism header */
3753 memcpy(ireq
.u
.name
, args
, sizeof (int));
3754 ioctl(sock_fd
, cmd
, &ireq
);
3759 * Force the Prism header.
3761 memset(&ireq
, 0, sizeof ireq
);
3762 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3763 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3764 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3765 ireq
.u
.data
.length
= 1; /* 1 argument */
3766 ireq
.u
.data
.pointer
= "1";
3767 ireq
.u
.data
.flags
= 0;
3768 ioctl(sock_fd
, cmd
, &ireq
);
3771 case MONITOR_RTL8XXX
:
3773 * Force the Prism header.
3775 memset(&ireq
, 0, sizeof ireq
);
3776 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3777 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3778 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3779 args
[0] = 1; /* request Prism header */
3780 memcpy(ireq
.u
.name
, args
, sizeof (int));
3781 ioctl(sock_fd
, cmd
, &ireq
);
3786 * Note that we have to put the old mode back when we
3789 handle
->md
.must_do_on_close
|= MUST_CLEAR_RFMON
;
3792 * Add this to the list of pcaps to close when we exit.
3794 pcap_add_to_pcaps_to_close(handle
);
3798 #endif /* IW_MODE_MONITOR */
3801 * Try various mechanisms to enter monitor mode.
3804 enter_rfmon_mode(pcap_t
*handle
, int sock_fd
, const char *device
)
3806 #if defined(HAVE_LIBNL) || defined(IW_MODE_MONITOR)
3811 ret
= enter_rfmon_mode_mac80211(handle
, sock_fd
, device
);
3813 return ret
; /* error attempting to do so */
3815 return 1; /* success */
3816 #endif /* HAVE_LIBNL */
3818 #ifdef IW_MODE_MONITOR
3819 ret
= enter_rfmon_mode_wext(handle
, sock_fd
, device
);
3821 return ret
; /* error attempting to do so */
3823 return 1; /* success */
3824 #endif /* IW_MODE_MONITOR */
3827 * Either none of the mechanisms we know about work or none
3828 * of those mechanisms are available, so we can't do monitor
3834 #endif /* HAVE_PF_PACKET_SOCKETS */
3836 /* ===== Functions to interface to the older kernels ================== */
3839 * Try to open a packet socket using the old kernel interface.
3840 * Returns 1 on success and a PCAP_ERROR_ value on an error.
3843 activate_old(pcap_t
*handle
)
3847 const char *device
= handle
->opt
.source
;
3848 struct utsname utsname
;
3851 /* Open the socket */
3853 handle
->fd
= socket(PF_INET
, SOCK_PACKET
, htons(ETH_P_ALL
));
3854 if (handle
->fd
== -1) {
3855 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3856 "socket: %s", pcap_strerror(errno
));
3857 return PCAP_ERROR_PERM_DENIED
;
3860 /* It worked - we are using the old interface */
3861 handle
->md
.sock_packet
= 1;
3863 /* ...which means we get the link-layer header. */
3864 handle
->md
.cooked
= 0;
3866 /* Bind to the given device */
3868 if (strcmp(device
, "any") == 0) {
3869 strncpy(handle
->errbuf
, "pcap_activate: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
3873 if (iface_bind_old(handle
->fd
, device
, handle
->errbuf
) == -1)
3877 * Try to get the link-layer type.
3879 arptype
= iface_get_arptype(handle
->fd
, device
, handle
->errbuf
);
3884 * Try to find the DLT_ type corresponding to that
3887 map_arphrd_to_dlt(handle
, arptype
, 0);
3888 if (handle
->linktype
== -1) {
3889 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3890 "unknown arptype %d", arptype
);
3894 /* Go to promisc mode if requested */
3896 if (handle
->opt
.promisc
) {
3897 memset(&ifr
, 0, sizeof(ifr
));
3898 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
3899 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
3900 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3901 "SIOCGIFFLAGS: %s", pcap_strerror(errno
));
3904 if ((ifr
.ifr_flags
& IFF_PROMISC
) == 0) {
3906 * Promiscuous mode isn't currently on,
3907 * so turn it on, and remember that
3908 * we should turn it off when the
3913 * If we haven't already done so, arrange
3914 * to have "pcap_close_all()" called when
3917 if (!pcap_do_addexit(handle
)) {
3919 * "atexit()" failed; don't put
3920 * the interface in promiscuous
3921 * mode, just give up.
3926 ifr
.ifr_flags
|= IFF_PROMISC
;
3927 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
3928 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3930 pcap_strerror(errno
));
3933 handle
->md
.must_do_on_close
|= MUST_CLEAR_PROMISC
;
3936 * Add this to the list of pcaps
3937 * to close when we exit.
3939 pcap_add_to_pcaps_to_close(handle
);
3944 * Compute the buffer size.
3946 * We're using SOCK_PACKET, so this might be a 2.0[.x]
3947 * kernel, and might require special handling - check.
3949 if (uname(&utsname
) < 0 ||
3950 strncmp(utsname
.release
, "2.0", 3) == 0) {
3952 * Either we couldn't find out what kernel release
3953 * this is, or it's a 2.0[.x] kernel.
3955 * In the 2.0[.x] kernel, a "recvfrom()" on
3956 * a SOCK_PACKET socket, with MSG_TRUNC set, will
3957 * return the number of bytes read, so if we pass
3958 * a length based on the snapshot length, it'll
3959 * return the number of bytes from the packet
3960 * copied to userland, not the actual length
3963 * This means that, for example, the IP dissector
3964 * in tcpdump will get handed a packet length less
3965 * than the length in the IP header, and will
3966 * complain about "truncated-ip".
3968 * So we don't bother trying to copy from the
3969 * kernel only the bytes in which we're interested,
3970 * but instead copy them all, just as the older
3971 * versions of libpcap for Linux did.
3973 * The buffer therefore needs to be big enough to
3974 * hold the largest packet we can get from this
3975 * device. Unfortunately, we can't get the MRU
3976 * of the network; we can only get the MTU. The
3977 * MTU may be too small, in which case a packet larger
3978 * than the buffer size will be truncated *and* we
3979 * won't get the actual packet size.
3981 * However, if the snapshot length is larger than
3982 * the buffer size based on the MTU, we use the
3983 * snapshot length as the buffer size, instead;
3984 * this means that with a sufficiently large snapshot
3985 * length we won't artificially truncate packets
3986 * to the MTU-based size.
3988 * This mess just one of many problems with packet
3989 * capture on 2.0[.x] kernels; you really want a
3990 * 2.2[.x] or later kernel if you want packet capture
3993 mtu
= iface_get_mtu(handle
->fd
, device
, handle
->errbuf
);
3996 handle
->bufsize
= MAX_LINKHEADER_SIZE
+ mtu
;
3997 if (handle
->bufsize
< handle
->snapshot
)
3998 handle
->bufsize
= handle
->snapshot
;
4001 * This is a 2.2[.x] or later kernel.
4003 * We can safely pass "recvfrom()" a byte count
4004 * based on the snapshot length.
4006 handle
->bufsize
= handle
->snapshot
;
4010 * Default value for offset to align link-layer payload
4011 * on a 4-byte boundary.
4019 * Bind the socket associated with FD to the given device using the
4020 * interface of the old kernels.
4023 iface_bind_old(int fd
, const char *device
, char *ebuf
)
4025 struct sockaddr saddr
;
4027 socklen_t errlen
= sizeof(err
);
4029 memset(&saddr
, 0, sizeof(saddr
));
4030 strncpy(saddr
.sa_data
, device
, sizeof(saddr
.sa_data
));
4031 if (bind(fd
, &saddr
, sizeof(saddr
)) == -1) {
4032 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4033 "bind: %s", pcap_strerror(errno
));
4037 /* Any pending errors, e.g., network is down? */
4039 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
4040 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4041 "getsockopt: %s", pcap_strerror(errno
));
4046 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4047 "bind: %s", pcap_strerror(err
));
4055 /* ===== System calls available on all supported kernels ============== */
4058 * Query the kernel for the MTU of the given interface.
4061 iface_get_mtu(int fd
, const char *device
, char *ebuf
)
4066 return BIGGER_THAN_ALL_MTUS
;
4068 memset(&ifr
, 0, sizeof(ifr
));
4069 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4071 if (ioctl(fd
, SIOCGIFMTU
, &ifr
) == -1) {
4072 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4073 "SIOCGIFMTU: %s", pcap_strerror(errno
));
4081 * Get the hardware type of the given interface as ARPHRD_xxx constant.
4084 iface_get_arptype(int fd
, const char *device
, char *ebuf
)
4088 memset(&ifr
, 0, sizeof(ifr
));
4089 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4091 if (ioctl(fd
, SIOCGIFHWADDR
, &ifr
) == -1) {
4092 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4093 "SIOCGIFHWADDR: %s", pcap_strerror(errno
));
4094 if (errno
== ENODEV
) {
4098 return PCAP_ERROR_NO_SUCH_DEVICE
;
4103 return ifr
.ifr_hwaddr
.sa_family
;
4106 #ifdef SO_ATTACH_FILTER
4108 fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
, int is_mmapped
)
4112 register struct bpf_insn
*p
;
4117 * Make a copy of the filter, and modify that copy if
4120 prog_size
= sizeof(*handle
->fcode
.bf_insns
) * handle
->fcode
.bf_len
;
4121 len
= handle
->fcode
.bf_len
;
4122 f
= (struct bpf_insn
*)malloc(prog_size
);
4124 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4125 "malloc: %s", pcap_strerror(errno
));
4128 memcpy(f
, handle
->fcode
.bf_insns
, prog_size
);
4130 fcode
->filter
= (struct sock_filter
*) f
;
4132 for (i
= 0; i
< len
; ++i
) {
4135 * What type of instruction is this?
4137 switch (BPF_CLASS(p
->code
)) {
4141 * It's a return instruction; are we capturing
4142 * in memory-mapped mode?
4146 * No; is the snapshot length a constant,
4147 * rather than the contents of the
4150 if (BPF_MODE(p
->code
) == BPF_K
) {
4152 * Yes - if the value to be returned,
4153 * i.e. the snapshot length, is
4154 * anything other than 0, make it
4155 * 65535, so that the packet is
4156 * truncated by "recvfrom()",
4157 * not by the filter.
4159 * XXX - there's nothing we can
4160 * easily do if it's getting the
4161 * value from the accumulator; we'd
4162 * have to insert code to force
4163 * non-zero values to be 65535.
4174 * It's a load instruction; is it loading
4177 switch (BPF_MODE(p
->code
)) {
4183 * Yes; are we in cooked mode?
4185 if (handle
->md
.cooked
) {
4187 * Yes, so we need to fix this
4190 if (fix_offset(p
) < 0) {
4192 * We failed to do so.
4193 * Return 0, so our caller
4194 * knows to punt to userland.
4204 return 1; /* we succeeded */
4208 fix_offset(struct bpf_insn
*p
)
4211 * What's the offset?
4213 if (p
->k
>= SLL_HDR_LEN
) {
4215 * It's within the link-layer payload; that starts at an
4216 * offset of 0, as far as the kernel packet filter is
4217 * concerned, so subtract the length of the link-layer
4220 p
->k
-= SLL_HDR_LEN
;
4221 } else if (p
->k
== 14) {
4223 * It's the protocol field; map it to the special magic
4224 * kernel offset for that field.
4226 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
4229 * It's within the header, but it's not one of those
4230 * fields; we can't do that in the kernel, so punt
4239 set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
)
4241 int total_filter_on
= 0;
4247 * The socket filter code doesn't discard all packets queued
4248 * up on the socket when the filter is changed; this means
4249 * that packets that don't match the new filter may show up
4250 * after the new filter is put onto the socket, if those
4251 * packets haven't yet been read.
4253 * This means, for example, that if you do a tcpdump capture
4254 * with a filter, the first few packets in the capture might
4255 * be packets that wouldn't have passed the filter.
4257 * We therefore discard all packets queued up on the socket
4258 * when setting a kernel filter. (This isn't an issue for
4259 * userland filters, as the userland filtering is done after
4260 * packets are queued up.)
4262 * To flush those packets, we put the socket in read-only mode,
4263 * and read packets from the socket until there are no more to
4266 * In order to keep that from being an infinite loop - i.e.,
4267 * to keep more packets from arriving while we're draining
4268 * the queue - we put the "total filter", which is a filter
4269 * that rejects all packets, onto the socket before draining
4272 * This code deliberately ignores any errors, so that you may
4273 * get bogus packets if an error occurs, rather than having
4274 * the filtering done in userland even if it could have been
4275 * done in the kernel.
4277 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
4278 &total_fcode
, sizeof(total_fcode
)) == 0) {
4282 * Note that we've put the total filter onto the socket.
4284 total_filter_on
= 1;
4287 * Save the socket's current mode, and put it in
4288 * non-blocking mode; we drain it by reading packets
4289 * until we get an error (which is normally a
4290 * "nothing more to be read" error).
4292 save_mode
= fcntl(handle
->fd
, F_GETFL
, 0);
4293 if (save_mode
!= -1 &&
4294 fcntl(handle
->fd
, F_SETFL
, save_mode
| O_NONBLOCK
) >= 0) {
4295 while (recv(handle
->fd
, &drain
, sizeof drain
,
4299 fcntl(handle
->fd
, F_SETFL
, save_mode
);
4300 if (save_errno
!= EAGAIN
) {
4302 reset_kernel_filter(handle
);
4303 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4304 "recv: %s", pcap_strerror(save_errno
));
4311 * Now attach the new filter.
4313 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
4314 fcode
, sizeof(*fcode
));
4315 if (ret
== -1 && total_filter_on
) {
4317 * Well, we couldn't set that filter on the socket,
4318 * but we could set the total filter on the socket.
4320 * This could, for example, mean that the filter was
4321 * too big to put into the kernel, so we'll have to
4322 * filter in userland; in any case, we'll be doing
4323 * filtering in userland, so we need to remove the
4324 * total filter so we see packets.
4329 * XXX - if this fails, we're really screwed;
4330 * we have the total filter on the socket,
4331 * and it won't come off. What do we do then?
4333 reset_kernel_filter(handle
);
4341 reset_kernel_filter(pcap_t
*handle
)
4344 * setsockopt() barfs unless it get a dummy parameter.
4345 * valgrind whines unless the value is initialized,
4346 * as it has no idea that setsockopt() ignores its
4351 return setsockopt(handle
->fd
, SOL_SOCKET
, SO_DETACH_FILTER
,
4352 &dummy
, sizeof(dummy
));