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>
149 #include <linux/nl80211.h>
151 #include <netlink/genl/genl.h>
152 #include <netlink/genl/family.h>
153 #include <netlink/genl/ctrl.h>
154 #include <netlink/msg.h>
155 #include <netlink/attr.h>
156 #endif /* HAVE_LIBNL */
158 #endif /* HAVE_LINUX_WIRELESS_H */
160 #include "pcap-int.h"
161 #include "pcap/sll.h"
162 #include "pcap/vlan.h"
165 #include "pcap-dag.h"
166 #endif /* HAVE_DAG_API */
168 #ifdef HAVE_SEPTEL_API
169 #include "pcap-septel.h"
170 #endif /* HAVE_SEPTEL_API */
172 #ifdef PCAP_SUPPORT_USB
173 #include "pcap-usb-linux.h"
176 #ifdef PCAP_SUPPORT_BT
177 #include "pcap-bt-linux.h"
181 * If PF_PACKET is defined, we can use {SOCK_RAW,SOCK_DGRAM}/PF_PACKET
182 * sockets rather than SOCK_PACKET sockets.
184 * To use them, we include <linux/if_packet.h> rather than
185 * <netpacket/packet.h>; we do so because
187 * some Linux distributions (e.g., Slackware 4.0) have 2.2 or
188 * later kernels and libc5, and don't provide a <netpacket/packet.h>
191 * not all versions of glibc2 have a <netpacket/packet.h> file
192 * that defines stuff needed for some of the 2.4-or-later-kernel
193 * features, so if the system has a 2.4 or later kernel, we
194 * still can't use those features.
196 * We're already including a number of other <linux/XXX.h> headers, and
197 * this code is Linux-specific (no other OS has PF_PACKET sockets as
198 * a raw packet capture mechanism), so it's not as if you gain any
199 * useful portability by using <netpacket/packet.h>
201 * XXX - should we just include <linux/if_packet.h> even if PF_PACKET
202 * isn't defined? It only defines one data structure in 2.0.x, so
203 * it shouldn't cause any problems.
206 # include <linux/if_packet.h>
209 * On at least some Linux distributions (for example, Red Hat 5.2),
210 * there's no <netpacket/packet.h> file, but PF_PACKET is defined if
211 * you include <sys/socket.h>, but <linux/if_packet.h> doesn't define
212 * any of the PF_PACKET stuff such as "struct sockaddr_ll" or any of
213 * the PACKET_xxx stuff.
215 * So we check whether PACKET_HOST is defined, and assume that we have
216 * PF_PACKET sockets only if it is defined.
219 # define HAVE_PF_PACKET_SOCKETS
220 # ifdef PACKET_AUXDATA
221 # define HAVE_PACKET_AUXDATA
222 # endif /* PACKET_AUXDATA */
223 # endif /* PACKET_HOST */
226 /* check for memory mapped access avaibility. We assume every needed
227 * struct is defined if the macro TPACKET_HDRLEN is defined, because it
228 * uses many ring related structs and macros */
229 # ifdef TPACKET_HDRLEN
230 # define HAVE_PACKET_RING
231 # ifdef TPACKET2_HDRLEN
232 # define HAVE_TPACKET2
234 # define TPACKET_V1 0
235 # endif /* TPACKET2_HDRLEN */
236 # endif /* TPACKET_HDRLEN */
237 #endif /* PF_PACKET */
239 #ifdef SO_ATTACH_FILTER
240 #include <linux/types.h>
241 #include <linux/filter.h>
244 #ifndef HAVE_SOCKLEN_T
245 typedef int socklen_t
;
250 * This is being compiled on a system that lacks MSG_TRUNC; define it
251 * with the value it has in the 2.2 and later kernels, so that, on
252 * those kernels, when we pass it in the flags argument to "recvfrom()"
253 * we're passing the right value and thus get the MSG_TRUNC behavior
254 * we want. (We don't get that behavior on 2.0[.x] kernels, because
255 * they didn't support MSG_TRUNC.)
257 #define MSG_TRUNC 0x20
262 * This is being compiled on a system that lacks SOL_PACKET; define it
263 * with the value it has in the 2.2 and later kernels, so that we can
264 * set promiscuous mode in the good modern way rather than the old
265 * 2.0-kernel crappy way.
267 #define SOL_PACKET 263
270 #define MAX_LINKHEADER_SIZE 256
273 * When capturing on all interfaces we use this as the buffer size.
274 * Should be bigger then all MTUs that occur in real life.
275 * 64kB should be enough for now.
277 #define BIGGER_THAN_ALL_MTUS (64*1024)
280 * Prototypes for internal functions and methods.
282 static void map_arphrd_to_dlt(pcap_t
*, int, int);
283 #ifdef HAVE_PF_PACKET_SOCKETS
284 static short int map_packet_type_to_sll_type(short int);
286 static int pcap_activate_linux(pcap_t
*);
287 static int activate_old(pcap_t
*);
288 static int activate_new(pcap_t
*);
289 static int activate_mmap(pcap_t
*);
290 static int pcap_can_set_rfmon_linux(pcap_t
*);
291 static int pcap_read_linux(pcap_t
*, int, pcap_handler
, u_char
*);
292 static int pcap_read_packet(pcap_t
*, pcap_handler
, u_char
*);
293 static int pcap_inject_linux(pcap_t
*, const void *, size_t);
294 static int pcap_stats_linux(pcap_t
*, struct pcap_stat
*);
295 static int pcap_setfilter_linux(pcap_t
*, struct bpf_program
*);
296 static int pcap_setdirection_linux(pcap_t
*, pcap_direction_t
);
297 static void pcap_cleanup_linux(pcap_t
*);
299 #ifdef HAVE_PACKET_RING
300 #define RING_GET_FRAME(h) (((union thdr **)h->buffer)[h->offset])
302 static void destroy_ring(pcap_t
*handle
);
303 static int create_ring(pcap_t
*handle
);
304 static int prepare_tpacket_socket(pcap_t
*handle
);
305 static void pcap_cleanup_linux_mmap(pcap_t
*);
306 static int pcap_read_linux_mmap(pcap_t
*, int, pcap_handler
, u_char
*);
307 static int pcap_setfilter_linux_mmap(pcap_t
*, struct bpf_program
*);
308 static int pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
, char *errbuf
);
309 static int pcap_getnonblock_mmap(pcap_t
*p
, char *errbuf
);
313 * Wrap some ioctl calls
315 #ifdef HAVE_PF_PACKET_SOCKETS
316 static int iface_get_id(int fd
, const char *device
, char *ebuf
);
318 static int iface_get_mtu(int fd
, const char *device
, char *ebuf
);
319 static int iface_get_arptype(int fd
, const char *device
, char *ebuf
);
320 #ifdef HAVE_PF_PACKET_SOCKETS
321 static int iface_bind(int fd
, int ifindex
, char *ebuf
);
322 #ifdef IW_MODE_MONITOR
323 static int has_wext(int sock_fd
, const char *device
, char *ebuf
);
324 #endif /* IW_MODE_MONITOR */
325 static int enter_rfmon_mode(pcap_t
*handle
, int sock_fd
,
327 #endif /* HAVE_PF_PACKET_SOCKETS */
328 static int iface_bind_old(int fd
, const char *device
, char *ebuf
);
330 #ifdef SO_ATTACH_FILTER
331 static int fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
);
332 static int fix_offset(struct bpf_insn
*p
);
333 static int set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
);
334 static int reset_kernel_filter(pcap_t
*handle
);
336 static struct sock_filter total_insn
337 = BPF_STMT(BPF_RET
| BPF_K
, 0);
338 static struct sock_fprog total_fcode
339 = { 1, &total_insn
};
343 pcap_create(const char *device
, char *ebuf
)
348 * A null device name is equivalent to the "any" device.
354 if (strstr(device
, "dag")) {
355 return dag_create(device
, ebuf
);
357 #endif /* HAVE_DAG_API */
359 #ifdef HAVE_SEPTEL_API
360 if (strstr(device
, "septel")) {
361 return septel_create(device
, ebuf
);
363 #endif /* HAVE_SEPTEL_API */
365 #ifdef PCAP_SUPPORT_BT
366 if (strstr(device
, "bluetooth")) {
367 return bt_create(device
, ebuf
);
371 #ifdef PCAP_SUPPORT_USB
372 if (strstr(device
, "usbmon")) {
373 return usb_create(device
, ebuf
);
377 handle
= pcap_create_common(device
, ebuf
);
381 handle
->activate_op
= pcap_activate_linux
;
382 handle
->can_set_rfmon_op
= pcap_can_set_rfmon_linux
;
387 pcap_can_set_rfmon_linux(pcap_t
*p
)
389 #ifdef IW_MODE_MONITOR
394 if (strcmp(p
->opt
.source
, "any") == 0) {
396 * Monitor mode makes no sense on the "any" device.
401 #ifdef IW_MODE_MONITOR
403 * Bleah. There doesn't appear to be an ioctl to use to ask
404 * whether a device supports monitor mode; we'll just do
405 * SIOCGIWMODE and, if it succeeds, assume the device supports
408 * Open a socket on which to attempt to get the mode.
409 * (We assume that if we have Wireless Extensions support
410 * we also have PF_PACKET support.)
412 * This also presumes that the mac80211 framework supports the
413 * Wireless Extensions, which appears to be the case at least
414 * as far back as the 2.6.22.6 kernel.
416 sock_fd
= socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
));
418 (void)snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
419 "socket: %s", pcap_strerror(errno
));
424 * Attempt to get the current mode.
426 strncpy(ireq
.ifr_ifrn
.ifrn_name
, p
->opt
.source
,
427 sizeof ireq
.ifr_ifrn
.ifrn_name
);
428 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
429 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) != -1) {
431 * Well, we got the mode; assume we can set it.
436 if (errno
== ENODEV
) {
437 /* The device doesn't even exist. */
439 return PCAP_ERROR_NO_SUCH_DEVICE
;
446 #if defined(IW_MODE_MONITOR) && defined(HAVE_LIBNL)
448 struct nl80211_state
{
449 struct nl_handle
*nl_handle
;
450 struct nl_cache
*nl_cache
;
451 struct genl_family
*nl80211
;
455 nl80211_init(pcap_t
*handle
, struct nl80211_state
*state
, const char *device
)
457 state
->nl_handle
= nl_handle_alloc();
458 if (!state
->nl_handle
) {
459 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
460 "%s: failed to allocate netlink handle", device
);
464 if (genl_connect(state
->nl_handle
)) {
465 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
466 "%s: failed to connect to generic netlink", device
);
467 goto out_handle_destroy
;
470 state
->nl_cache
= genl_ctrl_alloc_cache(state
->nl_handle
);
471 if (!state
->nl_cache
) {
472 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
473 "%s: failed to allocate generic netlink cache", device
);
474 goto out_handle_destroy
;
477 state
->nl80211
= genl_ctrl_search_by_name(state
->nl_cache
, "nl80211");
478 if (!state
->nl80211
) {
479 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
480 "%s: nl80211 not found", device
);
487 nl_cache_free(state
->nl_cache
);
489 nl_handle_destroy(state
->nl_handle
);
494 nl80211_cleanup(struct nl80211_state
*state
)
496 genl_family_put(state
->nl80211
);
497 nl_cache_free(state
->nl_cache
);
498 nl_handle_destroy(state
->nl_handle
);
502 add_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
503 const char *device
, const char *mondevice
)
509 ifindex
= iface_get_id(sock_fd
, device
, handle
->errbuf
);
515 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
516 "%s: failed to allocate netlink msg", device
);
520 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
521 0, NL80211_CMD_NEW_INTERFACE
, 0);
522 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
523 NLA_PUT_STRING(msg
, NL80211_ATTR_IFNAME
, mondevice
);
524 NLA_PUT_U32(msg
, NL80211_ATTR_IFTYPE
, NL80211_IFTYPE_MONITOR
);
526 err
= nl_send_auto_complete(state
->nl_handle
, msg
);
528 if (err
== -ENFILE
) {
530 * Device not available; our caller should just
537 * Real failure, not just "that device is not
540 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
541 "%s: nl_send_auto_complete failed adding %s interface: %s",
542 device
, mondevice
, strerror(-err
));
547 err
= nl_wait_for_ack(state
->nl_handle
);
549 if (err
== -ENFILE
) {
551 * Device not available; our caller should just
558 * Real failure, not just "that device is not
561 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
562 "%s: nl_wait_for_ack failed adding %s interface: %s",
563 device
, mondevice
, strerror(-err
));
576 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
577 "%s: nl_put failed adding %s interface",
584 del_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
585 const char *device
, const char *mondevice
)
591 ifindex
= iface_get_id(sock_fd
, mondevice
, handle
->errbuf
);
597 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
598 "%s: failed to allocate netlink msg", device
);
602 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
603 0, NL80211_CMD_DEL_INTERFACE
, 0);
604 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
606 err
= nl_send_auto_complete(state
->nl_handle
, msg
);
608 if (err
== -ENFILE
) {
610 * Device not available; our caller should just
617 * Real failure, not just "that device is not
620 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
621 "%s: nl_send_auto_complete failed deleting %s interface: %s",
622 device
, mondevice
, strerror(-err
));
627 err
= nl_wait_for_ack(state
->nl_handle
);
629 if (err
== -ENFILE
) {
631 * Device not available; our caller should just
638 * Real failure, not just "that device is not
641 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
642 "%s: nl_wait_for_ack failed adding %s interface: %s",
643 device
, mondevice
, strerror(-err
));
656 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
657 "%s: nl_put failed deleting %s interface",
663 #endif /* defined(IW_MODE_MONITOR) && defined(HAVE_LIBNL) */
666 * With older kernels promiscuous mode is kind of interesting because we
667 * have to reset the interface before exiting. The problem can't really
668 * be solved without some daemon taking care of managing usage counts.
669 * If we put the interface into promiscuous mode, we set a flag indicating
670 * that we must take it out of that mode when the interface is closed,
671 * and, when closing the interface, if that flag is set we take it out
672 * of promiscuous mode.
674 * Even with newer kernels, we have the same issue with rfmon mode.
677 static void pcap_cleanup_linux( pcap_t
*handle
)
680 #ifdef IW_MODE_MONITOR
682 struct nl80211_state nlstate
;
684 #endif /* HAVE_LIBNL */
686 #endif /* IW_MODE_MONITOR */
688 if (handle
->md
.must_do_on_close
!= 0) {
690 * There's something we have to do when closing this
693 if (handle
->md
.must_do_on_close
& MUST_CLEAR_PROMISC
) {
695 * We put the interface into promiscuous mode;
696 * take it out of promiscuous mode.
698 * XXX - if somebody else wants it in promiscuous
699 * mode, this code cannot know that, so it'll take
700 * it out of promiscuous mode. That's not fixable
701 * in 2.0[.x] kernels.
703 memset(&ifr
, 0, sizeof(ifr
));
704 strncpy(ifr
.ifr_name
, handle
->md
.device
,
705 sizeof(ifr
.ifr_name
));
706 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
708 "Can't restore interface flags (SIOCGIFFLAGS failed: %s).\n"
709 "Please adjust manually.\n"
710 "Hint: This can't happen with Linux >= 2.2.0.\n",
713 if (ifr
.ifr_flags
& IFF_PROMISC
) {
715 * Promiscuous mode is currently on;
718 ifr
.ifr_flags
&= ~IFF_PROMISC
;
719 if (ioctl(handle
->fd
, SIOCSIFFLAGS
,
722 "Can't restore interface flags (SIOCSIFFLAGS failed: %s).\n"
723 "Please adjust manually.\n"
724 "Hint: This can't happen with Linux >= 2.2.0.\n",
731 #ifdef IW_MODE_MONITOR
733 if (handle
->md
.must_do_on_close
& MUST_DELETE_MONIF
) {
734 ret
= nl80211_init(handle
, &nlstate
, handle
->md
.device
);
736 ret
= del_mon_if(handle
, handle
->fd
, &nlstate
,
737 handle
->md
.device
, handle
->md
.mondevice
);
738 nl80211_cleanup(&nlstate
);
742 "Can't delete monitor interface %s (%s).\n"
743 "Please delete manually.\n",
744 handle
->md
.mondevice
, handle
->errbuf
);
747 #endif /* HAVE_LIBNL */
749 if (handle
->md
.must_do_on_close
& MUST_CLEAR_RFMON
) {
751 * We put the interface into rfmon mode;
752 * take it out of rfmon mode.
754 * XXX - if somebody else wants it in rfmon
755 * mode, this code cannot know that, so it'll take
756 * it out of rfmon mode.
758 strncpy(ireq
.ifr_ifrn
.ifrn_name
, handle
->md
.device
,
759 sizeof ireq
.ifr_ifrn
.ifrn_name
);
760 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1]
762 ireq
.u
.mode
= handle
->md
.oldmode
;
763 if (ioctl(handle
->fd
, SIOCSIWMODE
, &ireq
) == -1) {
765 * Scientist, you've failed.
768 "Can't restore interface wireless mode (SIOCSIWMODE failed: %s).\n"
769 "Please adjust manually.\n",
773 #endif /* IW_MODE_MONITOR */
776 * Take this pcap out of the list of pcaps for which we
777 * have to take the interface out of some mode.
779 pcap_remove_from_pcaps_to_close(handle
);
782 if (handle
->md
.mondevice
!= NULL
) {
783 free(handle
->md
.mondevice
);
784 handle
->md
.mondevice
= NULL
;
786 if (handle
->md
.device
!= NULL
) {
787 free(handle
->md
.device
);
788 handle
->md
.device
= NULL
;
790 pcap_cleanup_live_common(handle
);
794 * Get a handle for a live capture from the given device. You can
795 * pass NULL as device to get all packages (without link level
796 * information of course). If you pass 1 as promisc the interface
797 * will be set to promiscous mode (XXX: I think this usage should
798 * be deprecated and functions be added to select that later allow
799 * modification of that values -- Torsten).
802 pcap_activate_linux(pcap_t
*handle
)
807 device
= handle
->opt
.source
;
809 handle
->inject_op
= pcap_inject_linux
;
810 handle
->setfilter_op
= pcap_setfilter_linux
;
811 handle
->setdirection_op
= pcap_setdirection_linux
;
812 handle
->set_datalink_op
= NULL
; /* can't change data link type */
813 handle
->getnonblock_op
= pcap_getnonblock_fd
;
814 handle
->setnonblock_op
= pcap_setnonblock_fd
;
815 handle
->cleanup_op
= pcap_cleanup_linux
;
816 handle
->read_op
= pcap_read_linux
;
817 handle
->stats_op
= pcap_stats_linux
;
820 * The "any" device is a special device which causes us not
821 * to bind to a particular device and thus to look at all
824 if (strcmp(device
, "any") == 0) {
825 if (handle
->opt
.promisc
) {
826 handle
->opt
.promisc
= 0;
827 /* Just a warning. */
828 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
829 "Promiscuous mode not supported on the \"any\" device");
830 status
= PCAP_WARNING_PROMISC_NOTSUP
;
834 handle
->md
.device
= strdup(device
);
835 if (handle
->md
.device
== NULL
) {
836 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "strdup: %s",
837 pcap_strerror(errno
) );
842 * Current Linux kernels use the protocol family PF_PACKET to
843 * allow direct access to all packets on the network while
844 * older kernels had a special socket type SOCK_PACKET to
845 * implement this feature.
846 * While this old implementation is kind of obsolete we need
847 * to be compatible with older kernels for a while so we are
848 * trying both methods with the newer method preferred.
851 if ((status
= activate_new(handle
)) == 1) {
854 * Try to use memory-mapped access.
856 switch (activate_mmap(handle
)) {
859 /* we succeeded; nothing more to do */
864 * Kernel doesn't support it - just continue
865 * with non-memory-mapped access.
872 * We failed to set up to use it, or kernel
873 * supports it, but we failed to enable it;
874 * return an error. handle->errbuf contains
881 else if (status
== 0) {
882 /* Non-fatal error; try old way */
883 if ((status
= activate_old(handle
)) != 1) {
885 * Both methods to open the packet socket failed.
886 * Tidy up and report our failure (handle->errbuf
887 * is expected to be set by the functions above).
893 * Fatal error with the new way; just fail.
894 * status has the error return; if it's PCAP_ERROR,
895 * handle->errbuf has been set appropriately.
901 * We set up the socket, but not with memory-mapped access.
903 if (handle
->opt
.buffer_size
!= 0) {
905 * Set the socket buffer size to the specified value.
907 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_RCVBUF
,
908 &handle
->opt
.buffer_size
,
909 sizeof(handle
->opt
.buffer_size
)) == -1) {
910 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
911 "SO_RCVBUF: %s", pcap_strerror(errno
));
917 /* Allocate the buffer */
919 handle
->buffer
= malloc(handle
->bufsize
+ handle
->offset
);
920 if (!handle
->buffer
) {
921 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
922 "malloc: %s", pcap_strerror(errno
));
928 * "handle->fd" is a socket, so "select()" and "poll()"
931 handle
->selectable_fd
= handle
->fd
;
936 pcap_cleanup_linux(handle
);
941 * Read at most max_packets from the capture stream and call the callback
942 * for each of them. Returns the number of packets handled or -1 if an
946 pcap_read_linux(pcap_t
*handle
, int max_packets
, pcap_handler callback
, u_char
*user
)
949 * Currently, on Linux only one packet is delivered per read,
952 return pcap_read_packet(handle
, callback
, user
);
956 * Read a packet from the socket calling the handler provided by
957 * the user. Returns the number of packets received or -1 if an
961 pcap_read_packet(pcap_t
*handle
, pcap_handler callback
, u_char
*userdata
)
965 #ifdef HAVE_PF_PACKET_SOCKETS
966 struct sockaddr_ll from
;
967 struct sll_header
*hdrp
;
969 struct sockaddr from
;
971 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
974 struct cmsghdr
*cmsg
;
977 char buf
[CMSG_SPACE(sizeof(struct tpacket_auxdata
))];
979 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
981 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
982 int packet_len
, caplen
;
983 struct pcap_pkthdr pcap_header
;
985 #ifdef HAVE_PF_PACKET_SOCKETS
987 * If this is a cooked device, leave extra room for a
988 * fake packet header.
990 if (handle
->md
.cooked
)
991 offset
= SLL_HDR_LEN
;
996 * This system doesn't have PF_PACKET sockets, so it doesn't
997 * support cooked devices.
1003 * Receive a single packet from the kernel.
1004 * We ignore EINTR, as that might just be due to a signal
1005 * being delivered - if the signal should interrupt the
1006 * loop, the signal handler should call pcap_breakloop()
1007 * to set handle->break_loop (we ignore it on other
1008 * platforms as well).
1009 * We also ignore ENETDOWN, so that we can continue to
1010 * capture traffic if the interface goes down and comes
1011 * back up again; comments in the kernel indicate that
1012 * we'll just block waiting for packets if we try to
1013 * receive from a socket that delivered ENETDOWN, and,
1014 * if we're using a memory-mapped buffer, we won't even
1015 * get notified of "network down" events.
1017 bp
= handle
->buffer
+ handle
->offset
;
1019 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1020 msg
.msg_name
= &from
;
1021 msg
.msg_namelen
= sizeof(from
);
1024 msg
.msg_control
= &cmsg_buf
;
1025 msg
.msg_controllen
= sizeof(cmsg_buf
);
1028 iov
.iov_len
= handle
->bufsize
- offset
;
1029 iov
.iov_base
= bp
+ offset
;
1030 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1034 * Has "pcap_breakloop()" been called?
1036 if (handle
->break_loop
) {
1038 * Yes - clear the flag that indicates that it
1039 * has, and return -2 as an indication that we
1040 * were told to break out of the loop.
1042 handle
->break_loop
= 0;
1046 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1047 packet_len
= recvmsg(handle
->fd
, &msg
, MSG_TRUNC
);
1048 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1049 fromlen
= sizeof(from
);
1050 packet_len
= recvfrom(
1051 handle
->fd
, bp
+ offset
,
1052 handle
->bufsize
- offset
, MSG_TRUNC
,
1053 (struct sockaddr
*) &from
, &fromlen
);
1054 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1055 } while (packet_len
== -1 && (errno
== EINTR
|| errno
== ENETDOWN
));
1057 /* Check if an error occured */
1059 if (packet_len
== -1) {
1060 if (errno
== EAGAIN
)
1061 return 0; /* no packet there */
1063 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1064 "recvfrom: %s", pcap_strerror(errno
));
1069 #ifdef HAVE_PF_PACKET_SOCKETS
1070 if (!handle
->md
.sock_packet
) {
1072 * Unfortunately, there is a window between socket() and
1073 * bind() where the kernel may queue packets from any
1074 * interface. If we're bound to a particular interface,
1075 * discard packets not from that interface.
1077 * (If socket filters are supported, we could do the
1078 * same thing we do when changing the filter; however,
1079 * that won't handle packet sockets without socket
1080 * filter support, and it's a bit more complicated.
1081 * It would save some instructions per packet, however.)
1083 if (handle
->md
.ifindex
!= -1 &&
1084 from
.sll_ifindex
!= handle
->md
.ifindex
)
1088 * Do checks based on packet direction.
1089 * We can only do this if we're using PF_PACKET; the
1090 * address returned for SOCK_PACKET is a "sockaddr_pkt"
1091 * which lacks the relevant packet type information.
1093 if (from
.sll_pkttype
== PACKET_OUTGOING
) {
1096 * If this is from the loopback device, reject it;
1097 * we'll see the packet as an incoming packet as well,
1098 * and we don't want to see it twice.
1100 if (from
.sll_ifindex
== handle
->md
.lo_ifindex
)
1104 * If the user only wants incoming packets, reject it.
1106 if (handle
->direction
== PCAP_D_IN
)
1111 * If the user only wants outgoing packets, reject it.
1113 if (handle
->direction
== PCAP_D_OUT
)
1119 #ifdef HAVE_PF_PACKET_SOCKETS
1121 * If this is a cooked device, fill in the fake packet header.
1123 if (handle
->md
.cooked
) {
1125 * Add the length of the fake header to the length
1126 * of packet data we read.
1128 packet_len
+= SLL_HDR_LEN
;
1130 hdrp
= (struct sll_header
*)bp
;
1131 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(from
.sll_pkttype
);
1132 hdrp
->sll_hatype
= htons(from
.sll_hatype
);
1133 hdrp
->sll_halen
= htons(from
.sll_halen
);
1134 memcpy(hdrp
->sll_addr
, from
.sll_addr
,
1135 (from
.sll_halen
> SLL_ADDRLEN
) ?
1138 hdrp
->sll_protocol
= from
.sll_protocol
;
1141 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1142 for (cmsg
= CMSG_FIRSTHDR(&msg
); cmsg
; cmsg
= CMSG_NXTHDR(&msg
, cmsg
)) {
1143 struct tpacket_auxdata
*aux
;
1145 struct vlan_tag
*tag
;
1147 if (cmsg
->cmsg_len
< CMSG_LEN(sizeof(struct tpacket_auxdata
)) ||
1148 cmsg
->cmsg_level
!= SOL_PACKET
||
1149 cmsg
->cmsg_type
!= PACKET_AUXDATA
)
1152 aux
= (struct tpacket_auxdata
*)CMSG_DATA(cmsg
);
1153 if (aux
->tp_vlan_tci
== 0)
1156 len
= packet_len
> iov
.iov_len
? iov
.iov_len
: packet_len
;
1157 if (len
< 2 * ETH_ALEN
)
1161 memmove(bp
, bp
+ VLAN_TAG_LEN
, 2 * ETH_ALEN
);
1163 tag
= (struct vlan_tag
*)(bp
+ 2 * ETH_ALEN
);
1164 tag
->vlan_tpid
= htons(ETH_P_8021Q
);
1165 tag
->vlan_tci
= htons(aux
->tp_vlan_tci
);
1167 packet_len
+= VLAN_TAG_LEN
;
1169 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1170 #endif /* HAVE_PF_PACKET_SOCKETS */
1173 * XXX: According to the kernel source we should get the real
1174 * packet len if calling recvfrom with MSG_TRUNC set. It does
1175 * not seem to work here :(, but it is supported by this code
1177 * To be honest the code RELIES on that feature so this is really
1178 * broken with 2.2.x kernels.
1179 * I spend a day to figure out what's going on and I found out
1180 * that the following is happening:
1182 * The packet comes from a random interface and the packet_rcv
1183 * hook is called with a clone of the packet. That code inserts
1184 * the packet into the receive queue of the packet socket.
1185 * If a filter is attached to that socket that filter is run
1186 * first - and there lies the problem. The default filter always
1187 * cuts the packet at the snaplen:
1192 * So the packet filter cuts down the packet. The recvfrom call
1193 * says "hey, it's only 68 bytes, it fits into the buffer" with
1194 * the result that we don't get the real packet length. This
1195 * is valid at least until kernel 2.2.17pre6.
1197 * We currently handle this by making a copy of the filter
1198 * program, fixing all "ret" instructions with non-zero
1199 * operands to have an operand of 65535 so that the filter
1200 * doesn't truncate the packet, and supplying that modified
1201 * filter to the kernel.
1204 caplen
= packet_len
;
1205 if (caplen
> handle
->snapshot
)
1206 caplen
= handle
->snapshot
;
1208 /* Run the packet filter if not using kernel filter */
1209 if (!handle
->md
.use_bpf
&& handle
->fcode
.bf_insns
) {
1210 if (bpf_filter(handle
->fcode
.bf_insns
, bp
,
1211 packet_len
, caplen
) == 0)
1213 /* rejected by filter */
1218 /* Fill in our own header data */
1220 if (ioctl(handle
->fd
, SIOCGSTAMP
, &pcap_header
.ts
) == -1) {
1221 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1222 "SIOCGSTAMP: %s", pcap_strerror(errno
));
1225 pcap_header
.caplen
= caplen
;
1226 pcap_header
.len
= packet_len
;
1231 * Arguably, we should count them before we check the filter,
1232 * as on many other platforms "ps_recv" counts packets
1233 * handed to the filter rather than packets that passed
1234 * the filter, but if filtering is done in the kernel, we
1235 * can't get a count of packets that passed the filter,
1236 * and that would mean the meaning of "ps_recv" wouldn't
1237 * be the same on all Linux systems.
1239 * XXX - it's not the same on all systems in any case;
1240 * ideally, we should have a "get the statistics" call
1241 * that supplies more counts and indicates which of them
1242 * it supplies, so that we supply a count of packets
1243 * handed to the filter only on platforms where that
1244 * information is available.
1246 * We count them here even if we can get the packet count
1247 * from the kernel, as we can only determine at run time
1248 * whether we'll be able to get it from the kernel (if
1249 * HAVE_TPACKET_STATS isn't defined, we can't get it from
1250 * the kernel, but if it is defined, the library might
1251 * have been built with a 2.4 or later kernel, but we
1252 * might be running on a 2.2[.x] kernel without Alexey
1253 * Kuznetzov's turbopacket patches, and thus the kernel
1254 * might not be able to supply those statistics). We
1255 * could, I guess, try, when opening the socket, to get
1256 * the statistics, and if we can not increment the count
1257 * here, but it's not clear that always incrementing
1258 * the count is more expensive than always testing a flag
1261 * We keep the count in "md.packets_read", and use that for
1262 * "ps_recv" if we can't get the statistics from the kernel.
1263 * We do that because, if we *can* get the statistics from
1264 * the kernel, we use "md.stat.ps_recv" and "md.stat.ps_drop"
1265 * as running counts, as reading the statistics from the
1266 * kernel resets the kernel statistics, and if we directly
1267 * increment "md.stat.ps_recv" here, that means it will
1268 * count packets *twice* on systems where we can get kernel
1269 * statistics - once here, and once in pcap_stats_linux().
1271 handle
->md
.packets_read
++;
1273 /* Call the user supplied callback function */
1274 callback(userdata
, &pcap_header
, bp
);
1280 pcap_inject_linux(pcap_t
*handle
, const void *buf
, size_t size
)
1284 #ifdef HAVE_PF_PACKET_SOCKETS
1285 if (!handle
->md
.sock_packet
) {
1286 /* PF_PACKET socket */
1287 if (handle
->md
.ifindex
== -1) {
1289 * We don't support sending on the "any" device.
1291 strlcpy(handle
->errbuf
,
1292 "Sending packets isn't supported on the \"any\" device",
1297 if (handle
->md
.cooked
) {
1299 * We don't support sending on the "any" device.
1301 * XXX - how do you send on a bound cooked-mode
1303 * Is a "sendto()" required there?
1305 strlcpy(handle
->errbuf
,
1306 "Sending packets isn't supported in cooked mode",
1313 ret
= send(handle
->fd
, buf
, size
, 0);
1315 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "send: %s",
1316 pcap_strerror(errno
));
1323 * Get the statistics for the given packet capture handle.
1324 * Reports the number of dropped packets iff the kernel supports
1325 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
1326 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
1327 * patches); otherwise, that information isn't available, and we lie
1328 * and report 0 as the count of dropped packets.
1331 pcap_stats_linux(pcap_t
*handle
, struct pcap_stat
*stats
)
1333 #ifdef HAVE_TPACKET_STATS
1334 struct tpacket_stats kstats
;
1335 socklen_t len
= sizeof (struct tpacket_stats
);
1338 #ifdef HAVE_TPACKET_STATS
1340 * Try to get the packet counts from the kernel.
1342 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_STATISTICS
,
1343 &kstats
, &len
) > -1) {
1345 * On systems where the PACKET_STATISTICS "getsockopt()"
1346 * argument is supported on PF_PACKET sockets:
1348 * "ps_recv" counts only packets that *passed* the
1349 * filter, not packets that didn't pass the filter.
1350 * This includes packets later dropped because we
1351 * ran out of buffer space.
1353 * "ps_drop" counts packets dropped because we ran
1354 * out of buffer space. It doesn't count packets
1355 * dropped by the interface driver. It counts only
1356 * packets that passed the filter.
1358 * Both statistics include packets not yet read from
1359 * the kernel by libpcap, and thus not yet seen by
1362 * In "linux/net/packet/af_packet.c", at least in the
1363 * 2.4.9 kernel, "tp_packets" is incremented for every
1364 * packet that passes the packet filter *and* is
1365 * successfully queued on the socket; "tp_drops" is
1366 * incremented for every packet dropped because there's
1367 * not enough free space in the socket buffer.
1369 * When the statistics are returned for a PACKET_STATISTICS
1370 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
1371 * so that "tp_packets" counts all packets handed to
1372 * the PF_PACKET socket, including packets dropped because
1373 * there wasn't room on the socket buffer - but not
1374 * including packets that didn't pass the filter.
1376 * In the BSD BPF, the count of received packets is
1377 * incremented for every packet handed to BPF, regardless
1378 * of whether it passed the filter.
1380 * We can't make "pcap_stats()" work the same on both
1381 * platforms, but the best approximation is to return
1382 * "tp_packets" as the count of packets and "tp_drops"
1383 * as the count of drops.
1385 * Keep a running total because each call to
1386 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
1387 * resets the counters to zero.
1389 handle
->md
.stat
.ps_recv
+= kstats
.tp_packets
;
1390 handle
->md
.stat
.ps_drop
+= kstats
.tp_drops
;
1391 *stats
= handle
->md
.stat
;
1397 * If the error was EOPNOTSUPP, fall through, so that
1398 * if you build the library on a system with
1399 * "struct tpacket_stats" and run it on a system
1400 * that doesn't, it works as it does if the library
1401 * is built on a system without "struct tpacket_stats".
1403 if (errno
!= EOPNOTSUPP
) {
1404 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1405 "pcap_stats: %s", pcap_strerror(errno
));
1411 * On systems where the PACKET_STATISTICS "getsockopt()" argument
1412 * is not supported on PF_PACKET sockets:
1414 * "ps_recv" counts only packets that *passed* the filter,
1415 * not packets that didn't pass the filter. It does not
1416 * count packets dropped because we ran out of buffer
1419 * "ps_drop" is not supported.
1421 * "ps_recv" doesn't include packets not yet read from
1422 * the kernel by libpcap.
1424 * We maintain the count of packets processed by libpcap in
1425 * "md.packets_read", for reasons described in the comment
1426 * at the end of pcap_read_packet(). We have no idea how many
1427 * packets were dropped.
1429 stats
->ps_recv
= handle
->md
.packets_read
;
1435 * Description string for the "any" device.
1437 static const char any_descr
[] = "Pseudo-device that captures on all interfaces";
1440 pcap_platform_finddevs(pcap_if_t
**alldevsp
, char *errbuf
)
1442 if (pcap_add_if(alldevsp
, "any", 0, any_descr
, errbuf
) < 0)
1446 if (dag_platform_finddevs(alldevsp
, errbuf
) < 0)
1448 #endif /* HAVE_DAG_API */
1450 #ifdef HAVE_SEPTEL_API
1451 if (septel_platform_finddevs(alldevsp
, errbuf
) < 0)
1453 #endif /* HAVE_SEPTEL_API */
1455 #ifdef PCAP_SUPPORT_BT
1456 if (bt_platform_finddevs(alldevsp
, errbuf
) < 0)
1460 #ifdef PCAP_SUPPORT_USB
1461 if (usb_platform_finddevs(alldevsp
, errbuf
) < 0)
1469 * Attach the given BPF code to the packet capture device.
1472 pcap_setfilter_linux(pcap_t
*handle
, struct bpf_program
*filter
)
1474 #ifdef SO_ATTACH_FILTER
1475 struct sock_fprog fcode
;
1476 int can_filter_in_kernel
;
1483 strncpy(handle
->errbuf
, "setfilter: No filter specified",
1488 /* Make our private copy of the filter */
1490 if (install_bpf_program(handle
, filter
) < 0)
1491 /* install_bpf_program() filled in errbuf */
1495 * Run user level packet filter by default. Will be overriden if
1496 * installing a kernel filter succeeds.
1498 handle
->md
.use_bpf
= 0;
1500 /* Install kernel level filter if possible */
1502 #ifdef SO_ATTACH_FILTER
1504 if (handle
->fcode
.bf_len
> USHRT_MAX
) {
1506 * fcode.len is an unsigned short for current kernel.
1507 * I have yet to see BPF-Code with that much
1508 * instructions but still it is possible. So for the
1509 * sake of correctness I added this check.
1511 fprintf(stderr
, "Warning: Filter too complex for kernel\n");
1513 fcode
.filter
= NULL
;
1514 can_filter_in_kernel
= 0;
1516 #endif /* USHRT_MAX */
1519 * Oh joy, the Linux kernel uses struct sock_fprog instead
1520 * of struct bpf_program and of course the length field is
1521 * of different size. Pointed out by Sebastian
1523 * Oh, and we also need to fix it up so that all "ret"
1524 * instructions with non-zero operands have 65535 as the
1525 * operand, and so that, if we're in cooked mode, all
1526 * memory-reference instructions use special magic offsets
1527 * in references to the link-layer header and assume that
1528 * the link-layer payload begins at 0; "fix_program()"
1531 switch (fix_program(handle
, &fcode
)) {
1536 * Fatal error; just quit.
1537 * (The "default" case shouldn't happen; we
1538 * return -1 for that reason.)
1544 * The program performed checks that we can't make
1545 * work in the kernel.
1547 can_filter_in_kernel
= 0;
1552 * We have a filter that'll work in the kernel.
1554 can_filter_in_kernel
= 1;
1559 if (can_filter_in_kernel
) {
1560 if ((err
= set_kernel_filter(handle
, &fcode
)) == 0)
1562 /* Installation succeded - using kernel filter. */
1563 handle
->md
.use_bpf
= 1;
1565 else if (err
== -1) /* Non-fatal error */
1568 * Print a warning if we weren't able to install
1569 * the filter for a reason other than "this kernel
1570 * isn't configured to support socket filters.
1572 if (errno
!= ENOPROTOOPT
&& errno
!= EOPNOTSUPP
) {
1574 "Warning: Kernel filter failed: %s\n",
1575 pcap_strerror(errno
));
1581 * If we're not using the kernel filter, get rid of any kernel
1582 * filter that might've been there before, e.g. because the
1583 * previous filter could work in the kernel, or because some other
1584 * code attached a filter to the socket by some means other than
1585 * calling "pcap_setfilter()". Otherwise, the kernel filter may
1586 * filter out packets that would pass the new userland filter.
1588 if (!handle
->md
.use_bpf
)
1589 reset_kernel_filter(handle
);
1592 * Free up the copy of the filter that was made by "fix_program()".
1594 if (fcode
.filter
!= NULL
)
1600 #endif /* SO_ATTACH_FILTER */
1606 * Set direction flag: Which packets do we accept on a forwarding
1607 * single device? IN, OUT or both?
1610 pcap_setdirection_linux(pcap_t
*handle
, pcap_direction_t d
)
1612 #ifdef HAVE_PF_PACKET_SOCKETS
1613 if (!handle
->md
.sock_packet
) {
1614 handle
->direction
= d
;
1619 * We're not using PF_PACKET sockets, so we can't determine
1620 * the direction of the packet.
1622 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1623 "Setting direction is not supported on SOCK_PACKET sockets");
1628 #ifdef HAVE_PF_PACKET_SOCKETS
1630 * Map the PACKET_ value to a LINUX_SLL_ value; we
1631 * want the same numerical value to be used in
1632 * the link-layer header even if the numerical values
1633 * for the PACKET_ #defines change, so that programs
1634 * that look at the packet type field will always be
1635 * able to handle DLT_LINUX_SLL captures.
1638 map_packet_type_to_sll_type(short int sll_pkttype
)
1640 switch (sll_pkttype
) {
1643 return htons(LINUX_SLL_HOST
);
1645 case PACKET_BROADCAST
:
1646 return htons(LINUX_SLL_BROADCAST
);
1648 case PACKET_MULTICAST
:
1649 return htons(LINUX_SLL_MULTICAST
);
1651 case PACKET_OTHERHOST
:
1652 return htons(LINUX_SLL_OTHERHOST
);
1654 case PACKET_OUTGOING
:
1655 return htons(LINUX_SLL_OUTGOING
);
1664 * Linux uses the ARP hardware type to identify the type of an
1665 * interface. pcap uses the DLT_xxx constants for this. This
1666 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
1667 * constant, as arguments, and sets "handle->linktype" to the
1668 * appropriate DLT_XXX constant and sets "handle->offset" to
1669 * the appropriate value (to make "handle->offset" plus link-layer
1670 * header length be a multiple of 4, so that the link-layer payload
1671 * will be aligned on a 4-byte boundary when capturing packets).
1672 * (If the offset isn't set here, it'll be 0; add code as appropriate
1673 * for cases where it shouldn't be 0.)
1675 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
1676 * in cooked mode; otherwise, we can't use cooked mode, so we have
1677 * to pick some type that works in raw mode, or fail.
1679 * Sets the link type to -1 if unable to map the type.
1681 static void map_arphrd_to_dlt(pcap_t
*handle
, int arptype
, int cooked_ok
)
1687 * This is (presumably) a real Ethernet capture; give it a
1688 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
1689 * that an application can let you choose it, in case you're
1690 * capturing DOCSIS traffic that a Cisco Cable Modem
1691 * Termination System is putting out onto an Ethernet (it
1692 * doesn't put an Ethernet header onto the wire, it puts raw
1693 * DOCSIS frames out on the wire inside the low-level
1694 * Ethernet framing).
1696 * XXX - are there any sorts of "fake Ethernet" that have
1697 * ARPHRD_ETHER but that *shouldn't offer DLT_DOCSIS as
1698 * a Cisco CMTS won't put traffic onto it or get traffic
1699 * bridged onto it? ISDN is handled in "activate_new()",
1700 * as we fall back on cooked mode there; are there any
1703 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
1705 * If that fails, just leave the list empty.
1707 if (handle
->dlt_list
!= NULL
) {
1708 handle
->dlt_list
[0] = DLT_EN10MB
;
1709 handle
->dlt_list
[1] = DLT_DOCSIS
;
1710 handle
->dlt_count
= 2;
1714 case ARPHRD_METRICOM
:
1715 case ARPHRD_LOOPBACK
:
1716 handle
->linktype
= DLT_EN10MB
;
1721 handle
->linktype
= DLT_EN3MB
;
1725 handle
->linktype
= DLT_AX25_KISS
;
1729 handle
->linktype
= DLT_PRONET
;
1733 handle
->linktype
= DLT_CHAOS
;
1736 #ifndef ARPHRD_IEEE802_TR
1737 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
1739 case ARPHRD_IEEE802_TR
:
1740 case ARPHRD_IEEE802
:
1741 handle
->linktype
= DLT_IEEE802
;
1746 handle
->linktype
= DLT_ARCNET_LINUX
;
1749 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
1750 #define ARPHRD_FDDI 774
1753 handle
->linktype
= DLT_FDDI
;
1757 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
1758 #define ARPHRD_ATM 19
1762 * The Classical IP implementation in ATM for Linux
1763 * supports both what RFC 1483 calls "LLC Encapsulation",
1764 * in which each packet has an LLC header, possibly
1765 * with a SNAP header as well, prepended to it, and
1766 * what RFC 1483 calls "VC Based Multiplexing", in which
1767 * different virtual circuits carry different network
1768 * layer protocols, and no header is prepended to packets.
1770 * They both have an ARPHRD_ type of ARPHRD_ATM, so
1771 * you can't use the ARPHRD_ type to find out whether
1772 * captured packets will have an LLC header, and,
1773 * while there's a socket ioctl to *set* the encapsulation
1774 * type, there's no ioctl to *get* the encapsulation type.
1778 * programs that dissect Linux Classical IP frames
1779 * would have to check for an LLC header and,
1780 * depending on whether they see one or not, dissect
1781 * the frame as LLC-encapsulated or as raw IP (I
1782 * don't know whether there's any traffic other than
1783 * IP that would show up on the socket, or whether
1784 * there's any support for IPv6 in the Linux
1785 * Classical IP code);
1787 * filter expressions would have to compile into
1788 * code that checks for an LLC header and does
1791 * Both of those are a nuisance - and, at least on systems
1792 * that support PF_PACKET sockets, we don't have to put
1793 * up with those nuisances; instead, we can just capture
1794 * in cooked mode. That's what we'll do, if we can.
1795 * Otherwise, we'll just fail.
1798 handle
->linktype
= DLT_LINUX_SLL
;
1800 handle
->linktype
= -1;
1803 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
1804 #define ARPHRD_IEEE80211 801
1806 case ARPHRD_IEEE80211
:
1807 handle
->linktype
= DLT_IEEE802_11
;
1810 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
1811 #define ARPHRD_IEEE80211_PRISM 802
1813 case ARPHRD_IEEE80211_PRISM
:
1814 handle
->linktype
= DLT_PRISM_HEADER
;
1817 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
1818 #define ARPHRD_IEEE80211_RADIOTAP 803
1820 case ARPHRD_IEEE80211_RADIOTAP
:
1821 handle
->linktype
= DLT_IEEE802_11_RADIO
;
1826 * Some PPP code in the kernel supplies no link-layer
1827 * header whatsoever to PF_PACKET sockets; other PPP
1828 * code supplies PPP link-layer headers ("syncppp.c");
1829 * some PPP code might supply random link-layer
1830 * headers (PPP over ISDN - there's code in Ethereal,
1831 * for example, to cope with PPP-over-ISDN captures
1832 * with which the Ethereal developers have had to cope,
1833 * heuristically trying to determine which of the
1834 * oddball link-layer headers particular packets have).
1836 * As such, we just punt, and run all PPP interfaces
1837 * in cooked mode, if we can; otherwise, we just treat
1838 * it as DLT_RAW, for now - if somebody needs to capture,
1839 * on a 2.0[.x] kernel, on PPP devices that supply a
1840 * link-layer header, they'll have to add code here to
1841 * map to the appropriate DLT_ type (possibly adding a
1842 * new DLT_ type, if necessary).
1845 handle
->linktype
= DLT_LINUX_SLL
;
1848 * XXX - handle ISDN types here? We can't fall
1849 * back on cooked sockets, so we'd have to
1850 * figure out from the device name what type of
1851 * link-layer encapsulation it's using, and map
1852 * that to an appropriate DLT_ value, meaning
1853 * we'd map "isdnN" devices to DLT_RAW (they
1854 * supply raw IP packets with no link-layer
1855 * header) and "isdY" devices to a new DLT_I4L_IP
1856 * type that has only an Ethernet packet type as
1857 * a link-layer header.
1859 * But sometimes we seem to get random crap
1860 * in the link-layer header when capturing on
1863 handle
->linktype
= DLT_RAW
;
1867 #ifndef ARPHRD_CISCO
1868 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
1871 handle
->linktype
= DLT_C_HDLC
;
1874 /* Not sure if this is correct for all tunnels, but it
1878 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
1886 #ifndef ARPHRD_RAWHDLC
1887 #define ARPHRD_RAWHDLC 518
1889 case ARPHRD_RAWHDLC
:
1891 #define ARPHRD_DLCI 15
1895 * XXX - should some of those be mapped to DLT_LINUX_SLL
1896 * instead? Should we just map all of them to DLT_LINUX_SLL?
1898 handle
->linktype
= DLT_RAW
;
1902 #define ARPHRD_FRAD 770
1905 handle
->linktype
= DLT_FRELAY
;
1908 case ARPHRD_LOCALTLK
:
1909 handle
->linktype
= DLT_LTALK
;
1913 #define ARPHRD_FCPP 784
1917 #define ARPHRD_FCAL 785
1921 #define ARPHRD_FCPL 786
1924 #ifndef ARPHRD_FCFABRIC
1925 #define ARPHRD_FCFABRIC 787
1927 case ARPHRD_FCFABRIC
:
1929 * We assume that those all mean RFC 2625 IP-over-
1930 * Fibre Channel, with the RFC 2625 header at
1931 * the beginning of the packet.
1933 handle
->linktype
= DLT_IP_OVER_FC
;
1937 #define ARPHRD_IRDA 783
1940 /* Don't expect IP packet out of this interfaces... */
1941 handle
->linktype
= DLT_LINUX_IRDA
;
1942 /* We need to save packet direction for IrDA decoding,
1943 * so let's use "Linux-cooked" mode. Jean II */
1944 //handle->md.cooked = 1;
1947 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
1948 * is needed, please report it to <daniele@orlandi.com> */
1950 #define ARPHRD_LAPD 8445
1953 /* Don't expect IP packet out of this interfaces... */
1954 handle
->linktype
= DLT_LINUX_LAPD
;
1958 #define ARPHRD_NONE 0xFFFE
1962 * No link-layer header; packets are just IP
1963 * packets, so use DLT_RAW.
1965 handle
->linktype
= DLT_RAW
;
1969 handle
->linktype
= -1;
1974 /* ===== Functions to interface to the newer kernels ================== */
1977 * Try to open a packet socket using the new kernel PF_PACKET interface.
1978 * Returns 1 on success, 0 on an error that means the new interface isn't
1979 * present (so the old SOCK_PACKET interface should be tried), and a
1980 * PCAP_ERROR_ value on an error that means that the old mechanism won't
1981 * work either (so it shouldn't be tried).
1984 activate_new(pcap_t
*handle
)
1986 #ifdef HAVE_PF_PACKET_SOCKETS
1987 const char *device
= handle
->opt
.source
;
1988 int is_any_device
= (strcmp(device
, "any") == 0);
1989 int sock_fd
= -1, arptype
, val
;
1991 struct packet_mreq mr
;
1994 * Open a socket with protocol family packet. If the
1995 * "any" device was specified, we open a SOCK_DGRAM
1996 * socket for the cooked interface, otherwise we first
1997 * try a SOCK_RAW socket for the raw interface.
1999 sock_fd
= is_any_device
?
2000 socket(PF_PACKET
, SOCK_DGRAM
, htons(ETH_P_ALL
)) :
2001 socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
));
2003 if (sock_fd
== -1) {
2004 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "socket: %s",
2005 pcap_strerror(errno
) );
2006 return 0; /* try old mechanism */
2009 /* It seems the kernel supports the new interface. */
2010 handle
->md
.sock_packet
= 0;
2013 * Get the interface index of the loopback device.
2014 * If the attempt fails, don't fail, just set the
2015 * "md.lo_ifindex" to -1.
2017 * XXX - can there be more than one device that loops
2018 * packets back, i.e. devices other than "lo"? If so,
2019 * we'd need to find them all, and have an array of
2020 * indices for them, and check all of them in
2021 * "pcap_read_packet()".
2023 handle
->md
.lo_ifindex
= iface_get_id(sock_fd
, "lo", handle
->errbuf
);
2026 * Default value for offset to align link-layer payload
2027 * on a 4-byte boundary.
2032 * What kind of frames do we have to deal with? Fall back
2033 * to cooked mode if we have an unknown interface type
2034 * or a type we know doesn't work well in raw mode.
2036 if (!is_any_device
) {
2037 /* Assume for now we don't need cooked mode. */
2038 handle
->md
.cooked
= 0;
2040 if (handle
->opt
.rfmon
) {
2042 * We were asked to turn on monitor mode.
2043 * Do so before we get the link-layer type,
2044 * because entering monitor mode could change
2045 * the link-layer type.
2047 err
= enter_rfmon_mode(handle
, sock_fd
, device
);
2055 * Nothing worked for turning monitor mode
2059 return PCAP_ERROR_RFMON_NOTSUP
;
2063 * Either monitor mode has been turned on for
2064 * the device, or we've been given a different
2065 * device to open for monitor mode. If we've
2066 * been given a different device, use it.
2068 if (handle
->md
.mondevice
!= NULL
)
2069 device
= handle
->md
.mondevice
;
2071 arptype
= iface_get_arptype(sock_fd
, device
, handle
->errbuf
);
2076 map_arphrd_to_dlt(handle
, arptype
, 1);
2077 if (handle
->linktype
== -1 ||
2078 handle
->linktype
== DLT_LINUX_SLL
||
2079 handle
->linktype
== DLT_LINUX_IRDA
||
2080 handle
->linktype
== DLT_LINUX_LAPD
||
2081 (handle
->linktype
== DLT_EN10MB
&&
2082 (strncmp("isdn", device
, 4) == 0 ||
2083 strncmp("isdY", device
, 4) == 0))) {
2085 * Unknown interface type (-1), or a
2086 * device we explicitly chose to run
2087 * in cooked mode (e.g., PPP devices),
2088 * or an ISDN device (whose link-layer
2089 * type we can only determine by using
2090 * APIs that may be different on different
2091 * kernels) - reopen in cooked mode.
2093 if (close(sock_fd
) == -1) {
2094 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2095 "close: %s", pcap_strerror(errno
));
2098 sock_fd
= socket(PF_PACKET
, SOCK_DGRAM
,
2100 if (sock_fd
== -1) {
2101 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2102 "socket: %s", pcap_strerror(errno
));
2105 handle
->md
.cooked
= 1;
2108 * Get rid of any link-layer type list
2109 * we allocated - this only supports cooked
2112 if (handle
->dlt_list
!= NULL
) {
2113 free(handle
->dlt_list
);
2114 handle
->dlt_list
= NULL
;
2115 handle
->dlt_count
= 0;
2118 if (handle
->linktype
== -1) {
2120 * Warn that we're falling back on
2121 * cooked mode; we may want to
2122 * update "map_arphrd_to_dlt()"
2123 * to handle the new type.
2125 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2127 "supported by libpcap - "
2128 "falling back to cooked "
2134 * IrDA capture is not a real "cooked" capture,
2135 * it's IrLAP frames, not IP packets. The
2136 * same applies to LAPD capture.
2138 if (handle
->linktype
!= DLT_LINUX_IRDA
&&
2139 handle
->linktype
!= DLT_LINUX_LAPD
)
2140 handle
->linktype
= DLT_LINUX_SLL
;
2143 handle
->md
.ifindex
= iface_get_id(sock_fd
, device
,
2145 if (handle
->md
.ifindex
== -1) {
2150 if ((err
= iface_bind(sock_fd
, handle
->md
.ifindex
,
2151 handle
->errbuf
)) != 1) {
2156 return 0; /* try old mechanism */
2162 if (handle
->opt
.rfmon
) {
2164 * It doesn't support monitor mode.
2166 return PCAP_ERROR_RFMON_NOTSUP
;
2170 * It uses cooked mode.
2172 handle
->md
.cooked
= 1;
2173 handle
->linktype
= DLT_LINUX_SLL
;
2176 * We're not bound to a device.
2177 * For now, we're using this as an indication
2178 * that we can't transmit; stop doing that only
2179 * if we figure out how to transmit in cooked
2182 handle
->md
.ifindex
= -1;
2186 * Select promiscuous mode on if "promisc" is set.
2188 * Do not turn allmulti mode on if we don't select
2189 * promiscuous mode - on some devices (e.g., Orinoco
2190 * wireless interfaces), allmulti mode isn't supported
2191 * and the driver implements it by turning promiscuous
2192 * mode on, and that screws up the operation of the
2193 * card as a normal networking interface, and on no
2194 * other platform I know of does starting a non-
2195 * promiscuous capture affect which multicast packets
2196 * are received by the interface.
2200 * Hmm, how can we set promiscuous mode on all interfaces?
2201 * I am not sure if that is possible at all. For now, we
2202 * silently ignore attempts to turn promiscuous mode on
2203 * for the "any" device (so you don't have to explicitly
2204 * disable it in programs such as tcpdump).
2207 if (!is_any_device
&& handle
->opt
.promisc
) {
2208 memset(&mr
, 0, sizeof(mr
));
2209 mr
.mr_ifindex
= handle
->md
.ifindex
;
2210 mr
.mr_type
= PACKET_MR_PROMISC
;
2211 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_ADD_MEMBERSHIP
,
2212 &mr
, sizeof(mr
)) == -1) {
2213 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2214 "setsockopt: %s", pcap_strerror(errno
));
2220 /* Enable auxillary data if supported and reserve room for
2221 * reconstructing VLAN headers. */
2222 #ifdef HAVE_PACKET_AUXDATA
2224 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_AUXDATA
, &val
,
2225 sizeof(val
)) == -1 && errno
!= ENOPROTOOPT
) {
2226 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2227 "setsockopt: %s", pcap_strerror(errno
));
2231 handle
->offset
+= VLAN_TAG_LEN
;
2232 #endif /* HAVE_PACKET_AUXDATA */
2235 * This is a 2.2[.x] or later kernel (we know that
2236 * because we're not using a SOCK_PACKET socket -
2237 * PF_PACKET is supported only in 2.2 and later
2240 * We can safely pass "recvfrom()" a byte count
2241 * based on the snapshot length.
2243 * If we're in cooked mode, make the snapshot length
2244 * large enough to hold a "cooked mode" header plus
2245 * 1 byte of packet data (so we don't pass a byte
2246 * count of 0 to "recvfrom()").
2248 if (handle
->md
.cooked
) {
2249 if (handle
->snapshot
< SLL_HDR_LEN
+ 1)
2250 handle
->snapshot
= SLL_HDR_LEN
+ 1;
2252 handle
->bufsize
= handle
->snapshot
;
2254 /* Save the socket FD in the pcap structure */
2255 handle
->fd
= sock_fd
;
2260 "New packet capturing interface not supported by build "
2261 "environment", PCAP_ERRBUF_SIZE
);
2267 activate_mmap(pcap_t
*handle
)
2269 #ifdef HAVE_PACKET_RING
2272 if (handle
->opt
.buffer_size
== 0) {
2273 /* by default request 2M for the ring buffer */
2274 handle
->opt
.buffer_size
= 2*1024*1024;
2276 ret
= prepare_tpacket_socket(handle
);
2279 ret
= create_ring(handle
);
2283 /* override some defaults and inherit the other fields from
2285 * handle->offset is used to get the current position into the rx ring
2286 * handle->cc is used to store the ring size */
2287 handle
->read_op
= pcap_read_linux_mmap
;
2288 handle
->cleanup_op
= pcap_cleanup_linux_mmap
;
2289 handle
->setfilter_op
= pcap_setfilter_linux_mmap
;
2290 handle
->setnonblock_op
= pcap_setnonblock_mmap
;
2291 handle
->getnonblock_op
= pcap_getnonblock_mmap
;
2292 handle
->selectable_fd
= handle
->fd
;
2294 #else /* HAVE_PACKET_RING */
2296 #endif /* HAVE_PACKET_RING */
2299 #ifdef HAVE_PACKET_RING
2301 prepare_tpacket_socket(pcap_t
*handle
)
2303 #ifdef HAVE_TPACKET2
2308 handle
->md
.tp_version
= TPACKET_V1
;
2309 handle
->md
.tp_hdrlen
= sizeof(struct tpacket_hdr
);
2311 #ifdef HAVE_TPACKET2
2312 /* Probe whether kernel supports TPACKET_V2 */
2315 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_HDRLEN
, &val
, &len
) < 0) {
2316 if (errno
== ENOPROTOOPT
)
2317 return 1; /* no - just drive on */
2319 /* Yes - treat as a failure. */
2320 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2321 "can't get TPACKET_V2 header len on packet socket: %s",
2322 pcap_strerror(errno
));
2325 handle
->md
.tp_hdrlen
= val
;
2328 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_VERSION
, &val
,
2330 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2331 "can't activate TPACKET_V2 on packet socket: %s",
2332 pcap_strerror(errno
));
2335 handle
->md
.tp_version
= TPACKET_V2
;
2337 /* Reserve space for VLAN tag reconstruction */
2339 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
, &val
,
2341 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2342 "can't set up reserve on packet socket: %s",
2343 pcap_strerror(errno
));
2347 #endif /* HAVE_TPACKET2 */
2352 compute_ring_block(int frame_size
, unsigned *block_size
, unsigned *frames_per_block
)
2354 /* compute the minumum block size that will handle this frame.
2355 * The block has to be page size aligned.
2356 * The max block size allowed by the kernel is arch-dependent and
2357 * it's not explicitly checked here. */
2358 *block_size
= getpagesize();
2359 while (*block_size
< frame_size
)
2362 *frames_per_block
= *block_size
/frame_size
;
2366 create_ring(pcap_t
*handle
)
2368 unsigned i
, j
, ringsize
, frames_per_block
;
2369 struct tpacket_req req
;
2371 /* Note that with large snapshot (say 64K) only a few frames
2372 * will be available in the ring even with pretty large ring size
2373 * (and a lot of memory will be unused).
2374 * The snap len should be carefully chosen to achive best
2376 req
.tp_frame_size
= TPACKET_ALIGN(handle
->snapshot
+
2377 TPACKET_ALIGN(handle
->md
.tp_hdrlen
) +
2378 sizeof(struct sockaddr_ll
));
2379 req
.tp_frame_nr
= handle
->opt
.buffer_size
/req
.tp_frame_size
;
2380 compute_ring_block(req
.tp_frame_size
, &req
.tp_block_size
, &frames_per_block
);
2381 req
.tp_block_nr
= req
.tp_frame_nr
/ frames_per_block
;
2383 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
2384 req
.tp_frame_nr
= req
.tp_block_nr
* frames_per_block
;
2386 /* ask the kernel to create the ring */
2388 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
2389 (void *) &req
, sizeof(req
))) {
2390 /* try to reduce requested ring size to prevent memory failure */
2391 if ((errno
== ENOMEM
) && (req
.tp_block_nr
> 1)) {
2392 req
.tp_frame_nr
>>= 1;
2393 req
.tp_block_nr
= req
.tp_frame_nr
/frames_per_block
;
2396 if (errno
== ENOPROTOOPT
) {
2398 * We don't have ring buffer support in this kernel.
2402 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2403 "can't create rx ring on packet socket: %s",
2404 pcap_strerror(errno
));
2408 /* memory map the rx ring */
2409 ringsize
= req
.tp_block_nr
* req
.tp_block_size
;
2410 handle
->bp
= mmap(0, ringsize
, PROT_READ
| PROT_WRITE
, MAP_SHARED
,
2412 if (handle
->bp
== MAP_FAILED
) {
2413 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2414 "can't mmap rx ring: %s", pcap_strerror(errno
));
2416 /* clear the allocated ring on error*/
2417 destroy_ring(handle
);
2421 /* allocate a ring for each frame header pointer*/
2422 handle
->cc
= req
.tp_frame_nr
;
2423 handle
->buffer
= malloc(handle
->cc
* sizeof(union thdr
*));
2424 if (!handle
->buffer
) {
2425 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2426 "can't allocate ring of frame headers: %s",
2427 pcap_strerror(errno
));
2429 destroy_ring(handle
);
2433 /* fill the header ring with proper frame ptr*/
2435 for (i
=0; i
<req
.tp_block_nr
; ++i
) {
2436 void *base
= &handle
->bp
[i
*req
.tp_block_size
];
2437 for (j
=0; j
<frames_per_block
; ++j
, ++handle
->offset
) {
2438 RING_GET_FRAME(handle
) = base
;
2439 base
+= req
.tp_frame_size
;
2443 handle
->bufsize
= req
.tp_frame_size
;
2448 /* free all ring related resources*/
2450 destroy_ring(pcap_t
*handle
)
2452 /* tell the kernel to destroy the ring*/
2453 struct tpacket_req req
;
2454 memset(&req
, 0, sizeof(req
));
2455 setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
2456 (void *) &req
, sizeof(req
));
2458 /* if ring is mapped, unmap it*/
2460 /* need to re-compute the ring size */
2461 unsigned frames_per_block
, block_size
;
2462 compute_ring_block(handle
->bufsize
, &block_size
, &frames_per_block
);
2464 /* do not perform sanity check here: we can't recover any error */
2465 munmap(handle
->bp
, block_size
* handle
->cc
/ frames_per_block
);
2471 pcap_cleanup_linux_mmap( pcap_t
*handle
)
2473 destroy_ring(handle
);
2474 pcap_cleanup_linux(handle
);
2479 pcap_getnonblock_mmap(pcap_t
*p
, char *errbuf
)
2481 /* use negative value of timeout to indicate non blocking ops */
2482 return (p
->md
.timeout
<0);
2486 pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
, char *errbuf
)
2488 /* map each value to the corresponding 2's complement, to
2489 * preserve the timeout value provided with pcap_set_timeout */
2491 if (p
->md
.timeout
> 0)
2492 p
->md
.timeout
= p
->md
.timeout
*-1 - 1;
2494 if (p
->md
.timeout
< 0)
2495 p
->md
.timeout
= (p
->md
.timeout
+1)*-1;
2499 static inline union thdr
*
2500 pcap_get_ring_frame(pcap_t
*handle
, int status
)
2504 h
.raw
= RING_GET_FRAME(handle
);
2505 switch (handle
->md
.tp_version
) {
2507 if (status
!= (h
.h1
->tp_status
? TP_STATUS_USER
:
2511 #ifdef HAVE_TPACKET2
2513 if (status
!= (h
.h2
->tp_status
? TP_STATUS_USER
:
2523 pcap_release_previous_ring_frame(pcap_t
*handle
)
2525 if (handle
->md
.prev_pkt
.raw
!= NULL
) {
2526 switch (handle
->md
.tp_version
) {
2528 handle
->md
.prev_pkt
.h1
->tp_status
= TP_STATUS_KERNEL
;
2530 #ifdef HAVE_TPACKET2
2532 handle
->md
.prev_pkt
.h2
->tp_status
= TP_STATUS_KERNEL
;
2536 handle
->md
.prev_pkt
.raw
= NULL
;
2541 pcap_read_linux_mmap(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
2546 /* wait for frames availability.*/
2547 if ((handle
->md
.timeout
>= 0) &&
2548 !pcap_get_ring_frame(handle
, TP_STATUS_USER
)) {
2549 struct pollfd pollinfo
;
2552 pollinfo
.fd
= handle
->fd
;
2553 pollinfo
.events
= POLLIN
;
2556 /* poll() requires a negative timeout to wait forever */
2557 ret
= poll(&pollinfo
, 1, (handle
->md
.timeout
> 0)?
2558 handle
->md
.timeout
: -1);
2559 if ((ret
< 0) && (errno
!= EINTR
)) {
2560 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2561 "can't poll on packet socket fd %d: %d-%s",
2562 handle
->fd
, errno
, pcap_strerror(errno
));
2565 /* check for break loop condition on interrupted syscall*/
2566 if (handle
->break_loop
) {
2567 handle
->break_loop
= 0;
2573 /* non-positive values of max_packets are used to require all
2574 * packets currently available in the ring */
2575 while ((pkts
< max_packets
) || (max_packets
<= 0)) {
2577 struct sockaddr_ll
*sll
;
2578 struct pcap_pkthdr pcaphdr
;
2581 unsigned int tp_len
;
2582 unsigned int tp_mac
;
2583 unsigned int tp_snaplen
;
2584 unsigned int tp_sec
;
2585 unsigned int tp_usec
;
2588 * Check for break loop condition; a callback might have
2591 if (handle
->break_loop
) {
2592 handle
->break_loop
= 0;
2596 h
.raw
= pcap_get_ring_frame(handle
, TP_STATUS_USER
);
2601 * We have a packet; release the previous packet,
2604 * Libpcap has never guaranteed that, if we get a
2605 * packet from the underlying packet capture
2606 * mechanism, the data passed to callbacks for
2607 * any previous packets is still valid. It did
2608 * implicitly guarantee that the data will still
2609 * be available after the callback returns, by
2610 * virtue of implementing pcap_next() by calling
2611 * pcap_dispatch() with a count of 1 and a callback
2612 * that fills in a structure with a pointer to
2613 * the packet data, meaning that pointer is
2614 * expected to point to valid data after the
2615 * callback returns and pcap_next() returns,
2616 * so we can't release the packet when the
2619 * Therefore, we remember the packet that
2620 * needs to be released after handing it
2621 * to the callback, and release it up here.
2623 pcap_release_previous_ring_frame(handle
);
2625 switch (handle
->md
.tp_version
) {
2627 tp_len
= h
.h1
->tp_len
;
2628 tp_mac
= h
.h1
->tp_mac
;
2629 tp_snaplen
= h
.h1
->tp_snaplen
;
2630 tp_sec
= h
.h1
->tp_sec
;
2631 tp_usec
= h
.h1
->tp_usec
;
2633 #ifdef HAVE_TPACKET2
2635 tp_len
= h
.h2
->tp_len
;
2636 tp_mac
= h
.h2
->tp_mac
;
2637 tp_snaplen
= h
.h2
->tp_snaplen
;
2638 tp_sec
= h
.h2
->tp_sec
;
2639 tp_usec
= h
.h2
->tp_nsec
/ 1000;
2643 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2644 "unsupported tpacket version %d",
2645 handle
->md
.tp_version
);
2648 /* perform sanity check on internal offset. */
2649 if (tp_mac
+ tp_snaplen
> handle
->bufsize
) {
2650 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2651 "corrupted frame on kernel ring mac "
2652 "offset %d + caplen %d > frame len %d",
2653 tp_mac
, tp_snaplen
, handle
->bufsize
);
2657 /* run filter on received packet
2658 * If the kernel filtering is enabled we need to run the
2659 * filter until all the frames present into the ring
2660 * at filter creation time are processed.
2661 * In such case md.use_bpf is used as a counter for the
2662 * packet we need to filter.
2663 * Note: alternatively it could be possible to stop applying
2664 * the filter when the ring became empty, but it can possibly
2665 * happen a lot later... */
2666 bp
= (unsigned char*)h
.raw
+ tp_mac
;
2667 run_bpf
= (!handle
->md
.use_bpf
) ||
2668 ((handle
->md
.use_bpf
>1) && handle
->md
.use_bpf
--);
2669 if (run_bpf
&& handle
->fcode
.bf_insns
&&
2670 (bpf_filter(handle
->fcode
.bf_insns
, bp
,
2671 tp_len
, tp_snaplen
) == 0))
2675 * Do checks based on packet direction.
2677 sll
= (void *)h
.raw
+ TPACKET_ALIGN(handle
->md
.tp_hdrlen
);
2678 if (sll
->sll_pkttype
== PACKET_OUTGOING
) {
2681 * If this is from the loopback device, reject it;
2682 * we'll see the packet as an incoming packet as well,
2683 * and we don't want to see it twice.
2685 if (sll
->sll_ifindex
== handle
->md
.lo_ifindex
)
2689 * If the user only wants incoming packets, reject it.
2691 if (handle
->direction
== PCAP_D_IN
)
2696 * If the user only wants outgoing packets, reject it.
2698 if (handle
->direction
== PCAP_D_OUT
)
2702 /* get required packet info from ring header */
2703 pcaphdr
.ts
.tv_sec
= tp_sec
;
2704 pcaphdr
.ts
.tv_usec
= tp_usec
;
2705 pcaphdr
.caplen
= tp_snaplen
;
2706 pcaphdr
.len
= tp_len
;
2708 /* if required build in place the sll header*/
2709 if (handle
->md
.cooked
) {
2710 struct sll_header
*hdrp
;
2713 * The kernel should have left us with enough
2714 * space for an sll header; back up the packet
2715 * data pointer into that space, as that'll be
2716 * the beginning of the packet we pass to the
2722 * Let's make sure that's past the end of
2723 * the tpacket header, i.e. >=
2724 * ((u_char *)thdr + TPACKET_HDRLEN), so we
2725 * don't step on the header when we construct
2728 if (bp
< (u_char
*)h
.raw
+
2729 TPACKET_ALIGN(handle
->md
.tp_hdrlen
) +
2730 sizeof(struct sockaddr_ll
)) {
2731 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2732 "cooked-mode frame doesn't have room for sll header");
2737 * OK, that worked; construct the sll header.
2739 hdrp
= (struct sll_header
*)bp
;
2740 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(
2742 hdrp
->sll_hatype
= htons(sll
->sll_hatype
);
2743 hdrp
->sll_halen
= htons(sll
->sll_halen
);
2744 memcpy(hdrp
->sll_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
2745 hdrp
->sll_protocol
= sll
->sll_protocol
;
2747 /* update packet len */
2748 pcaphdr
.caplen
+= SLL_HDR_LEN
;
2749 pcaphdr
.len
+= SLL_HDR_LEN
;
2752 #ifdef HAVE_TPACKET2
2753 if (handle
->md
.tp_version
== TPACKET_V2
&& h
.h2
->tp_vlan_tci
&&
2754 tp_snaplen
>= 2 * ETH_ALEN
) {
2755 struct vlan_tag
*tag
;
2758 memmove(bp
, bp
+ VLAN_TAG_LEN
, 2 * ETH_ALEN
);
2760 tag
= (struct vlan_tag
*)(bp
+ 2 * ETH_ALEN
);
2761 tag
->vlan_tpid
= htons(ETH_P_8021Q
);
2762 tag
->vlan_tci
= htons(h
.h2
->tp_vlan_tci
);
2764 pcaphdr
.caplen
+= VLAN_TAG_LEN
;
2765 pcaphdr
.len
+= VLAN_TAG_LEN
;
2769 /* pass the packet to the user */
2771 callback(user
, &pcaphdr
, bp
);
2772 handle
->md
.packets_read
++;
2776 * As per the comment above, we can't yet release this
2777 * packet, even though the callback has returned, as
2778 * some users of pcap_loop() and pcap_dispatch() - such
2779 * as pcap_next() and pcap_next_ex() - expect the packet
2780 * to be available until the next pcap_dispatch() call.
2782 handle
->md
.prev_pkt
= h
;
2783 if (++handle
->offset
>= handle
->cc
)
2786 /* check for break loop condition*/
2787 if (handle
->break_loop
) {
2788 handle
->break_loop
= 0;
2796 pcap_setfilter_linux_mmap(pcap_t
*handle
, struct bpf_program
*filter
)
2799 int ret
= pcap_setfilter_linux(handle
, filter
);
2803 /* if the kernel filter is enabled, we need to apply the filter on
2804 * all packets present into the ring. Get an upper bound of their number
2806 if (!handle
->md
.use_bpf
)
2809 /* walk the ring backward and count the free slot */
2810 offset
= handle
->offset
;
2811 if (--handle
->offset
< 0)
2812 handle
->offset
= handle
->cc
- 1;
2813 for (n
=0; n
< handle
->cc
; ++n
) {
2814 if (--handle
->offset
< 0)
2815 handle
->offset
= handle
->cc
- 1;
2816 if (!pcap_get_ring_frame(handle
, TP_STATUS_KERNEL
))
2820 /* be careful to not change current ring position */
2821 handle
->offset
= offset
;
2823 /* store the number of packets currently present in the ring */
2824 handle
->md
.use_bpf
= 1 + (handle
->cc
- n
);
2828 #endif /* HAVE_PACKET_RING */
2831 #ifdef HAVE_PF_PACKET_SOCKETS
2833 * Return the index of the given device name. Fill ebuf and return
2837 iface_get_id(int fd
, const char *device
, char *ebuf
)
2841 memset(&ifr
, 0, sizeof(ifr
));
2842 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
2844 if (ioctl(fd
, SIOCGIFINDEX
, &ifr
) == -1) {
2845 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2846 "SIOCGIFINDEX: %s", pcap_strerror(errno
));
2850 return ifr
.ifr_ifindex
;
2854 * Bind the socket associated with FD to the given device.
2855 * Return 1 on success, 0 if we should try a SOCK_PACKET socket,
2856 * or a PCAP_ERROR_ value on a hard error.
2859 iface_bind(int fd
, int ifindex
, char *ebuf
)
2861 struct sockaddr_ll sll
;
2863 socklen_t errlen
= sizeof(err
);
2865 memset(&sll
, 0, sizeof(sll
));
2866 sll
.sll_family
= AF_PACKET
;
2867 sll
.sll_ifindex
= ifindex
;
2868 sll
.sll_protocol
= htons(ETH_P_ALL
);
2870 if (bind(fd
, (struct sockaddr
*) &sll
, sizeof(sll
)) == -1) {
2871 if (errno
== ENETDOWN
) {
2873 * Return a "network down" indication, so that
2874 * the application can report that rather than
2875 * saying we had a mysterious failure and
2876 * suggest that they report a problem to the
2877 * libpcap developers.
2879 return PCAP_ERROR_IFACE_NOT_UP
;
2881 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2882 "bind: %s", pcap_strerror(errno
));
2887 /* Any pending errors, e.g., network is down? */
2889 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
2890 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2891 "getsockopt: %s", pcap_strerror(errno
));
2895 if (err
== ENETDOWN
) {
2897 * Return a "network down" indication, so that
2898 * the application can report that rather than
2899 * saying we had a mysterious failure and
2900 * suggest that they report a problem to the
2901 * libpcap developers.
2903 return PCAP_ERROR_IFACE_NOT_UP
;
2904 } else if (err
> 0) {
2905 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2906 "bind: %s", pcap_strerror(err
));
2913 #ifdef IW_MODE_MONITOR
2915 * Check whether the device supports the Wireless Extensions.
2916 * Returns 1 if it does, 0 if it doesn't, PCAP_ERROR_NO_SUCH_DEVICE
2917 * if the device doesn't even exist.
2920 has_wext(int sock_fd
, const char *device
, char *ebuf
)
2924 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
2925 sizeof ireq
.ifr_ifrn
.ifrn_name
);
2926 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
2927 if (ioctl(sock_fd
, SIOCGIWNAME
, &ireq
) >= 0)
2929 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2930 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
2931 if (errno
== ENODEV
)
2932 return PCAP_ERROR_NO_SUCH_DEVICE
;
2937 * Per me si va ne la citta dolente,
2938 * Per me si va ne l'etterno dolore,
2940 * Lasciate ogne speranza, voi ch'intrate.
2942 * XXX - airmon-ng does special stuff with the Orinoco driver and the
2959 * If interface {if} is a mac80211 driver, the file
2960 * /sys/class/net/{if}/phy80211 is a symlink to
2961 * /sys/class/ieee80211/{phydev}, for some {phydev}.
2963 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
2964 * least, has a "wmaster0" device and a "wlan0" device; the
2965 * latter is the one with the IP address. Both show up in
2966 * "tcpdump -D" output. Capturing on the wmaster0 device
2967 * captures with 802.11 headers.
2969 * airmon-ng searches through /sys/class/net for devices named
2970 * monN, starting with mon0; as soon as one *doesn't* exist,
2971 * it chooses that as the monitor device name. If the "iw"
2972 * command exists, it does "iw dev {if} interface add {monif}
2973 * type monitor", where {monif} is the monitor device. It
2974 * then (sigh) sleeps .1 second, and then configures the
2975 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
2976 * is a file, it writes {mondev}, without a newline, to that file,
2977 * and again (sigh) sleeps .1 second, and then iwconfig's that
2978 * device into monitor mode and configures it up. Otherwise,
2979 * you can't do monitor mode.
2981 * All these devices are "glued" together by having the
2982 * /sys/class/net/{device}/phy80211 links pointing to the same
2983 * place, so, given a wmaster, wlan, or mon device, you can
2984 * find the other devices by looking for devices with
2985 * the same phy80211 link.
2987 * To turn monitor mode off, delete the monitor interface,
2988 * either with "iw dev {monif} interface del" or by sending
2989 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
2991 * Note: if you try to create a monitor device named "monN", and
2992 * there's already a "monN" device, it fails, as least with
2993 * the netlink interface (which is what iw uses), with a return
2994 * value of -ENFILE. (Return values are negative errnos.) We
2995 * could probably use that to find an unused device.
2997 * Yes, you can have multiple monitor devices for a given
3003 * Is this a mac80211 device? If so, fill in the physical device path and
3004 * return 1; if not, return 0. On an error, fill in handle->errbuf and
3005 * return PCAP_ERROR.
3008 get_mac80211_phydev(pcap_t
*handle
, const char *device
, char *phydev_path
,
3009 size_t phydev_max_pathlen
)
3015 * Generate the path string for the symlink to the physical device.
3017 if (asprintf(&pathstr
, "/sys/class/net/%s/phy80211", device
) == -1) {
3018 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3019 "%s: Can't generate path name string for /sys/class/net device",
3023 bytes_read
= readlink(pathstr
, phydev_path
, phydev_max_pathlen
);
3024 if (bytes_read
== -1) {
3025 if (errno
== ENOENT
|| errno
== EINVAL
) {
3027 * Doesn't exist, or not a symlink; assume that
3028 * means it's not a mac80211 device.
3033 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3034 "%s: Can't readlink %s: %s", device
, pathstr
,
3040 phydev_path
[bytes_read
] = '\0';
3045 enter_rfmon_mode_mac80211(pcap_t
*handle
, int sock_fd
, const char *device
)
3048 char phydev_path
[PATH_MAX
+1];
3049 struct nl80211_state nlstate
;
3054 * Is this a mac80211 device?
3056 ret
= get_mac80211_phydev(handle
, device
, phydev_path
, PATH_MAX
);
3058 return ret
; /* error */
3060 return 0; /* no error, but not mac80211 device */
3063 * XXX - is this already a monN device?
3064 * If so, we're done.
3065 * Is that determined by old Wireless Extensions ioctls?
3069 * OK, it's apparently a mac80211 device.
3070 * Try to find an unused monN device for it.
3072 ret
= nl80211_init(handle
, &nlstate
, device
);
3075 for (n
= 0; n
< UINT_MAX
; n
++) {
3079 char mondevice
[3+10+1]; /* mon{UINT_MAX}\0 */
3081 snprintf(mondevice
, sizeof mondevice
, "mon%u", n
);
3082 ret
= add_mon_if(handle
, sock_fd
, &nlstate
, device
, mondevice
);
3084 handle
->md
.mondevice
= strdup(mondevice
);
3089 * Hard failure. Just return ret; handle->errbuf
3090 * has already been set.
3092 nl80211_cleanup(&nlstate
);
3097 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3098 "%s: No free monN interfaces", device
);
3099 nl80211_cleanup(&nlstate
);
3106 * Sleep for .1 seconds.
3109 delay
.tv_nsec
= 500000000;
3110 nanosleep(&delay
, NULL
);
3114 * Now configure the monitor interface up.
3116 memset(&ifr
, 0, sizeof(ifr
));
3117 strncpy(ifr
.ifr_name
, handle
->md
.mondevice
, sizeof(ifr
.ifr_name
));
3118 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
3119 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3120 "%s: Can't get flags for %s: %s", device
,
3121 handle
->md
.mondevice
, strerror(errno
));
3122 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
3123 handle
->md
.mondevice
);
3124 nl80211_cleanup(&nlstate
);
3127 ifr
.ifr_flags
|= IFF_UP
|IFF_RUNNING
;
3128 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
3129 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3130 "%s: Can't set flags for %s: %s", device
,
3131 handle
->md
.mondevice
, strerror(errno
));
3132 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
3133 handle
->md
.mondevice
);
3134 nl80211_cleanup(&nlstate
);
3139 * Success. Clean up the libnl state.
3141 nl80211_cleanup(&nlstate
);
3144 * Note that we have to delete the monitor device when we close
3147 handle
->md
.must_do_on_close
|= MUST_DELETE_MONIF
;
3150 * Add this to the list of pcaps to close when we exit.
3152 pcap_add_to_pcaps_to_close(handle
);
3156 #endif /* HAVE_LIBNL */
3159 * Use the Wireless Extensions, if we have them, to try to turn monitor mode
3160 * on if it's not already on.
3162 * Returns 1 on success, 0 if we don't support the Wireless Extensions
3163 * on this device, or a PCAP_ERROR_ value if we do support them but
3164 * we weren't able to turn monitor mode on.
3167 enter_rfmon_mode_wext(pcap_t
*handle
, int sock_fd
, const char *device
)
3170 * XXX - at least some adapters require non-Wireless Extensions
3171 * mechanisms to turn monitor mode on.
3173 * Atheros cards might require that a separate "monitor virtual access
3174 * point" be created, with later versions of the madwifi driver.
3175 * airmon-ng does "wlanconfig ath create wlandev {if} wlanmode
3176 * monitor -bssid", which apparently spits out a line "athN"
3177 * where "athN" is the monitor mode device. To leave monitor
3178 * mode, it destroys the monitor mode device.
3180 * Some Intel Centrino adapters might require private ioctls to get
3181 * radio headers; the ipw2200 and ipw3945 drivers allow you to
3182 * configure a separate "rtapN" interface to capture in monitor
3183 * mode without preventing the adapter from operating normally.
3184 * (airmon-ng doesn't appear to use that, though.)
3186 * It would be Truly Wonderful if mac80211 and nl80211 cleaned this
3187 * up, and if all drivers were converted to mac80211 drivers.
3189 * If interface {if} is a mac80211 driver, the file
3190 * /sys/class/net/{if}/phy80211 is a symlink to
3191 * /sys/class/ieee80211/{phydev}, for some {phydev}.
3193 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
3194 * least, has a "wmaster0" device and a "wlan0" device; the
3195 * latter is the one with the IP address. Both show up in
3196 * "tcpdump -D" output. Capturing on the wmaster0 device
3197 * captures with 802.11 headers.
3199 * airmon-ng searches through /sys/class/net for devices named
3200 * monN, starting with mon0; as soon as one *doesn't* exist,
3201 * it chooses that as the monitor device name. If the "iw"
3202 * command exists, it does "iw dev {if} interface add {monif}
3203 * type monitor", where {monif} is the monitor device. It
3204 * then (sigh) sleeps .1 second, and then configures the
3205 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
3206 * is a file, it writes {mondev}, without a newline, to that file,
3207 * and again (sigh) sleeps .1 second, and then iwconfig's that
3208 * device into monitor mode and configures it up. Otherwise,
3209 * you can't do monitor mode.
3211 * All these devices are "glued" together by having the
3212 * /sys/class/net/{device}/phy80211 links pointing to the same
3213 * place, so, given a wmaster, wlan, or mon device, you can
3214 * find the other devices by looking for devices with
3215 * the same phy80211 link.
3217 * To turn monitor mode off, delete the monitor interface,
3218 * either with "iw dev {monif} interface del" or by sending
3219 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
3221 * Note: if you try to create a monitor device named "monN", and
3222 * there's already a "monN" device, it fails, as least with
3223 * the netlink interface (which is what iw uses), with a return
3224 * value of -ENFILE. (Return values are negative errnos.) We
3225 * could probably use that to find an unused device.
3229 struct iw_priv_args
*priv
;
3230 monitor_type montype
;
3237 * Does this device *support* the Wireless Extensions?
3239 err
= has_wext(sock_fd
, device
, handle
->errbuf
);
3241 return err
; /* either it doesn't or the device doesn't even exist */
3243 * Try to get all the Wireless Extensions private ioctls
3244 * supported by this device.
3246 * First, get the size of the buffer we need, by supplying no
3247 * buffer and a length of 0. If the device supports private
3248 * ioctls, it should return E2BIG, with ireq.u.data.length set
3249 * to the length we need. If it doesn't support them, it should
3250 * return EOPNOTSUPP.
3252 memset(&ireq
, 0, sizeof ireq
);
3253 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3254 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3255 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3256 ireq
.u
.data
.pointer
= args
;
3257 ireq
.u
.data
.length
= 0;
3258 ireq
.u
.data
.flags
= 0;
3259 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) != -1) {
3260 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3261 "%s: SIOCGIWPRIV with a zero-length buffer didn't fail!",
3265 if (errno
== EOPNOTSUPP
) {
3267 * No private ioctls, so we assume that there's only one
3268 * DLT_ for monitor mode.
3272 if (errno
!= E2BIG
) {
3276 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3277 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
3280 priv
= malloc(ireq
.u
.data
.length
* sizeof (struct iw_priv_args
));
3282 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3283 "malloc: %s", pcap_strerror(errno
));
3286 ireq
.u
.data
.pointer
= priv
;
3287 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) == -1) {
3288 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3289 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
3295 * Look for private ioctls to turn monitor mode on or, if
3296 * monitor mode is on, to set the header type.
3298 montype
= MONITOR_WEXT
;
3300 for (i
= 0; i
< ireq
.u
.data
.length
; i
++) {
3301 if (strcmp(priv
[i
].name
, "monitor_type") == 0) {
3303 * Hostap driver, use this one.
3304 * Set monitor mode first.
3305 * You can set it to 0 to get DLT_IEEE80211,
3306 * 1 to get DLT_PRISM, 2 to get
3307 * DLT_IEEE80211_RADIO_AVS, and, with more
3308 * recent versions of the driver, 3 to get
3309 * DLT_IEEE80211_RADIO.
3311 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
3313 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
3315 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
3317 montype
= MONITOR_HOSTAP
;
3321 if (strcmp(priv
[i
].name
, "set_prismhdr") == 0) {
3323 * Prism54 driver, use this one.
3324 * Set monitor mode first.
3325 * You can set it to 2 to get DLT_IEEE80211
3326 * or 3 or get DLT_PRISM.
3328 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
3330 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
3332 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
3334 montype
= MONITOR_PRISM54
;
3338 if (strcmp(priv
[i
].name
, "forceprismheader") == 0) {
3340 * RT2570 driver, use this one.
3341 * Do this after turning monitor mode on.
3342 * You can set it to 1 to get DLT_PRISM or 2
3343 * to get DLT_IEEE80211.
3345 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
3347 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
3349 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
3351 montype
= MONITOR_RT2570
;
3355 if (strcmp(priv
[i
].name
, "forceprism") == 0) {
3357 * RT73 driver, use this one.
3358 * Do this after turning monitor mode on.
3359 * Its argument is a *string*; you can
3360 * set it to "1" to get DLT_PRISM or "2"
3361 * to get DLT_IEEE80211.
3363 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_CHAR
)
3365 if (priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
)
3367 montype
= MONITOR_RT73
;
3371 if (strcmp(priv
[i
].name
, "prismhdr") == 0) {
3373 * One of the RTL8xxx drivers, use this one.
3374 * It can only be done after monitor mode
3375 * has been turned on. You can set it to 1
3376 * to get DLT_PRISM or 0 to get DLT_IEEE80211.
3378 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
3380 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
3382 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
3384 montype
= MONITOR_RTL8XXX
;
3388 if (strcmp(priv
[i
].name
, "rfmontx") == 0) {
3390 * RT2500 or RT61 driver, use this one.
3391 * It has one one-byte parameter; set
3392 * u.data.length to 1 and u.data.pointer to
3393 * point to the parameter.
3394 * It doesn't itself turn monitor mode on.
3395 * You can set it to 1 to allow transmitting
3396 * in monitor mode(?) and get DLT_IEEE80211,
3397 * or set it to 0 to disallow transmitting in
3398 * monitor mode(?) and get DLT_PRISM.
3400 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
3402 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 2)
3404 montype
= MONITOR_RT2500
;
3408 if (strcmp(priv
[i
].name
, "monitor") == 0) {
3410 * Either ACX100 or hostap, use this one.
3411 * It turns monitor mode on.
3412 * If it takes two arguments, it's ACX100;
3413 * the first argument is 1 for DLT_PRISM
3414 * or 2 for DLT_IEEE80211, and the second
3415 * argument is the channel on which to
3416 * run. If it takes one argument, it's
3417 * HostAP, and the argument is 2 for
3418 * DLT_IEEE80211 and 3 for DLT_PRISM.
3420 * If we see this, we don't quit, as this
3421 * might be a version of the hostap driver
3422 * that also supports "monitor_type".
3424 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
3426 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
3428 switch (priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) {
3431 montype
= MONITOR_PRISM
;
3436 montype
= MONITOR_ACX100
;
3448 * XXX - ipw3945? islism?
3454 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3455 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3456 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3457 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) == -1) {
3459 * We probably won't be able to set the mode, either.
3461 return PCAP_ERROR_RFMON_NOTSUP
;
3465 * Is it currently in monitor mode?
3467 if (ireq
.u
.mode
== IW_MODE_MONITOR
) {
3469 * Yes. Just leave things as they are.
3470 * We don't offer multiple link-layer types, as
3471 * changing the link-layer type out from under
3472 * somebody else capturing in monitor mode would
3473 * be considered rude.
3478 * No. We have to put the adapter into rfmon mode.
3482 * If we haven't already done so, arrange to have
3483 * "pcap_close_all()" called when we exit.
3485 if (!pcap_do_addexit(handle
)) {
3487 * "atexit()" failed; don't put the interface
3488 * in rfmon mode, just give up.
3490 return PCAP_ERROR_RFMON_NOTSUP
;
3494 * Save the old mode.
3496 handle
->md
.oldmode
= ireq
.u
.mode
;
3499 * Put the adapter in rfmon mode. How we do this depends
3500 * on whether we have a special private ioctl or not.
3502 if (montype
== MONITOR_PRISM
) {
3504 * We have the "monitor" private ioctl, but none of
3505 * the other private ioctls. Use this, and select
3508 * If it fails, just fall back on SIOCSIWMODE.
3510 memset(&ireq
, 0, sizeof ireq
);
3511 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3512 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3513 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3514 ireq
.u
.data
.length
= 1; /* 1 argument */
3515 args
[0] = 3; /* request Prism header */
3516 memcpy(ireq
.u
.name
, args
, IFNAMSIZ
);
3517 if (ioctl(sock_fd
, cmd
, &ireq
) != -1) {
3520 * Note that we have to put the old mode back
3521 * when we close the device.
3523 handle
->md
.must_do_on_close
|= MUST_CLEAR_RFMON
;
3526 * Add this to the list of pcaps to close
3529 pcap_add_to_pcaps_to_close(handle
);
3535 * Failure. Fall back on SIOCSIWMODE.
3540 * First, turn monitor mode on.
3542 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3543 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3544 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3545 ireq
.u
.mode
= IW_MODE_MONITOR
;
3546 if (ioctl(sock_fd
, SIOCSIWMODE
, &ireq
) == -1) {
3548 * Scientist, you've failed.
3550 return PCAP_ERROR_RFMON_NOTSUP
;
3554 * XXX - airmon-ng does "iwconfig {if} key off" after setting
3555 * monitor mode and setting the channel, and then does
3560 * Now select the appropriate radio header.
3566 * We don't have any private ioctl to set the header.
3570 case MONITOR_HOSTAP
:
3572 * Try to select the radiotap header.
3574 memset(&ireq
, 0, sizeof ireq
);
3575 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3576 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3577 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3578 args
[0] = 3; /* request radiotap header */
3579 memcpy(ireq
.u
.name
, args
, sizeof (int));
3580 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
3581 break; /* success */
3584 * That failed. Try to select the AVS header.
3586 memset(&ireq
, 0, sizeof ireq
);
3587 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3588 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3589 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3590 args
[0] = 2; /* request AVS header */
3591 memcpy(ireq
.u
.name
, args
, sizeof (int));
3592 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
3593 break; /* success */
3596 * That failed. Try to select the Prism header.
3598 memset(&ireq
, 0, sizeof ireq
);
3599 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3600 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3601 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3602 args
[0] = 1; /* request Prism header */
3603 memcpy(ireq
.u
.name
, args
, sizeof (int));
3604 ioctl(sock_fd
, cmd
, &ireq
);
3609 * The private ioctl failed.
3613 case MONITOR_PRISM54
:
3615 * Select the Prism header.
3617 memset(&ireq
, 0, sizeof ireq
);
3618 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3619 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3620 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3621 args
[0] = 3; /* request Prism header */
3622 memcpy(ireq
.u
.name
, args
, sizeof (int));
3623 ioctl(sock_fd
, cmd
, &ireq
);
3626 case MONITOR_ACX100
:
3628 * Get the current channel.
3630 memset(&ireq
, 0, sizeof ireq
);
3631 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3632 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3633 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3634 if (ioctl(sock_fd
, SIOCGIWFREQ
, &ireq
) == -1) {
3635 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3636 "%s: SIOCGIWFREQ: %s", device
,
3637 pcap_strerror(errno
));
3640 channel
= ireq
.u
.freq
.m
;
3643 * Select the Prism header, and set the channel to the
3646 memset(&ireq
, 0, sizeof ireq
);
3647 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3648 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3649 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3650 args
[0] = 1; /* request Prism header */
3651 args
[1] = channel
; /* set channel */
3652 memcpy(ireq
.u
.name
, args
, 2*sizeof (int));
3653 ioctl(sock_fd
, cmd
, &ireq
);
3656 case MONITOR_RT2500
:
3658 * Disallow transmission - that turns on the
3661 memset(&ireq
, 0, sizeof ireq
);
3662 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3663 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3664 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3665 args
[0] = 0; /* disallow transmitting */
3666 memcpy(ireq
.u
.name
, args
, sizeof (int));
3667 ioctl(sock_fd
, cmd
, &ireq
);
3670 case MONITOR_RT2570
:
3672 * Force the Prism header.
3674 memset(&ireq
, 0, sizeof ireq
);
3675 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3676 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3677 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3678 args
[0] = 1; /* request Prism header */
3679 memcpy(ireq
.u
.name
, args
, sizeof (int));
3680 ioctl(sock_fd
, cmd
, &ireq
);
3685 * Force the Prism header.
3687 memset(&ireq
, 0, sizeof ireq
);
3688 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3689 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3690 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3691 ireq
.u
.data
.length
= 1; /* 1 argument */
3692 ireq
.u
.data
.pointer
= "1";
3693 ireq
.u
.data
.flags
= 0;
3694 ioctl(sock_fd
, cmd
, &ireq
);
3697 case MONITOR_RTL8XXX
:
3699 * Force the Prism header.
3701 memset(&ireq
, 0, sizeof ireq
);
3702 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3703 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3704 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3705 args
[0] = 1; /* request Prism header */
3706 memcpy(ireq
.u
.name
, args
, sizeof (int));
3707 ioctl(sock_fd
, cmd
, &ireq
);
3712 * Note that we have to put the old mode back when we
3715 handle
->md
.must_do_on_close
|= MUST_CLEAR_RFMON
;
3718 * Add this to the list of pcaps to close when we exit.
3720 pcap_add_to_pcaps_to_close(handle
);
3724 #endif /* IW_MODE_MONITOR */
3727 * Try various mechanisms to enter monitor mode.
3730 enter_rfmon_mode(pcap_t
*handle
, int sock_fd
, const char *device
)
3732 #ifdef IW_MODE_MONITOR
3736 ret
= enter_rfmon_mode_mac80211(handle
, sock_fd
, device
);
3738 return ret
; /* error attempting to do so */
3740 return 1; /* success */
3741 #endif /* HAVE_LIBNL */
3743 ret
= enter_rfmon_mode_wext(handle
, sock_fd
, device
);
3745 return ret
; /* error attempting to do so */
3747 return 1; /* success */
3748 #endif /* IW_MODE_MONITOR */
3751 * Either none of the mechanisms we know about work or none
3752 * of those mechanisms are available, so we can't do monitor
3758 #endif /* HAVE_PF_PACKET_SOCKETS */
3760 /* ===== Functions to interface to the older kernels ================== */
3763 * Try to open a packet socket using the old kernel interface.
3764 * Returns 1 on success and a PCAP_ERROR_ value on an error.
3767 activate_old(pcap_t
*handle
)
3771 const char *device
= handle
->opt
.source
;
3772 struct utsname utsname
;
3775 /* Open the socket */
3777 handle
->fd
= socket(PF_INET
, SOCK_PACKET
, htons(ETH_P_ALL
));
3778 if (handle
->fd
== -1) {
3779 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3780 "socket: %s", pcap_strerror(errno
));
3781 return PCAP_ERROR_PERM_DENIED
;
3784 /* It worked - we are using the old interface */
3785 handle
->md
.sock_packet
= 1;
3787 /* ...which means we get the link-layer header. */
3788 handle
->md
.cooked
= 0;
3790 /* Bind to the given device */
3792 if (strcmp(device
, "any") == 0) {
3793 strncpy(handle
->errbuf
, "pcap_activate: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
3797 if (iface_bind_old(handle
->fd
, device
, handle
->errbuf
) == -1)
3801 * Try to get the link-layer type.
3803 arptype
= iface_get_arptype(handle
->fd
, device
, handle
->errbuf
);
3808 * Try to find the DLT_ type corresponding to that
3811 map_arphrd_to_dlt(handle
, arptype
, 0);
3812 if (handle
->linktype
== -1) {
3813 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3814 "unknown arptype %d", arptype
);
3818 /* Go to promisc mode if requested */
3820 if (handle
->opt
.promisc
) {
3821 memset(&ifr
, 0, sizeof(ifr
));
3822 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
3823 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
3824 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3825 "SIOCGIFFLAGS: %s", pcap_strerror(errno
));
3828 if ((ifr
.ifr_flags
& IFF_PROMISC
) == 0) {
3830 * Promiscuous mode isn't currently on,
3831 * so turn it on, and remember that
3832 * we should turn it off when the
3837 * If we haven't already done so, arrange
3838 * to have "pcap_close_all()" called when
3841 if (!pcap_do_addexit(handle
)) {
3843 * "atexit()" failed; don't put
3844 * the interface in promiscuous
3845 * mode, just give up.
3850 ifr
.ifr_flags
|= IFF_PROMISC
;
3851 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
3852 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3854 pcap_strerror(errno
));
3857 handle
->md
.must_do_on_close
|= MUST_CLEAR_PROMISC
;
3860 * Add this to the list of pcaps
3861 * to close when we exit.
3863 pcap_add_to_pcaps_to_close(handle
);
3868 * Compute the buffer size.
3870 * We're using SOCK_PACKET, so this might be a 2.0[.x]
3871 * kernel, and might require special handling - check.
3873 if (uname(&utsname
) < 0 ||
3874 strncmp(utsname
.release
, "2.0", 3) == 0) {
3876 * Either we couldn't find out what kernel release
3877 * this is, or it's a 2.0[.x] kernel.
3879 * In the 2.0[.x] kernel, a "recvfrom()" on
3880 * a SOCK_PACKET socket, with MSG_TRUNC set, will
3881 * return the number of bytes read, so if we pass
3882 * a length based on the snapshot length, it'll
3883 * return the number of bytes from the packet
3884 * copied to userland, not the actual length
3887 * This means that, for example, the IP dissector
3888 * in tcpdump will get handed a packet length less
3889 * than the length in the IP header, and will
3890 * complain about "truncated-ip".
3892 * So we don't bother trying to copy from the
3893 * kernel only the bytes in which we're interested,
3894 * but instead copy them all, just as the older
3895 * versions of libpcap for Linux did.
3897 * The buffer therefore needs to be big enough to
3898 * hold the largest packet we can get from this
3899 * device. Unfortunately, we can't get the MRU
3900 * of the network; we can only get the MTU. The
3901 * MTU may be too small, in which case a packet larger
3902 * than the buffer size will be truncated *and* we
3903 * won't get the actual packet size.
3905 * However, if the snapshot length is larger than
3906 * the buffer size based on the MTU, we use the
3907 * snapshot length as the buffer size, instead;
3908 * this means that with a sufficiently large snapshot
3909 * length we won't artificially truncate packets
3910 * to the MTU-based size.
3912 * This mess just one of many problems with packet
3913 * capture on 2.0[.x] kernels; you really want a
3914 * 2.2[.x] or later kernel if you want packet capture
3917 mtu
= iface_get_mtu(handle
->fd
, device
, handle
->errbuf
);
3920 handle
->bufsize
= MAX_LINKHEADER_SIZE
+ mtu
;
3921 if (handle
->bufsize
< handle
->snapshot
)
3922 handle
->bufsize
= handle
->snapshot
;
3925 * This is a 2.2[.x] or later kernel.
3927 * We can safely pass "recvfrom()" a byte count
3928 * based on the snapshot length.
3930 handle
->bufsize
= handle
->snapshot
;
3934 * Default value for offset to align link-layer payload
3935 * on a 4-byte boundary.
3943 * Bind the socket associated with FD to the given device using the
3944 * interface of the old kernels.
3947 iface_bind_old(int fd
, const char *device
, char *ebuf
)
3949 struct sockaddr saddr
;
3951 socklen_t errlen
= sizeof(err
);
3953 memset(&saddr
, 0, sizeof(saddr
));
3954 strncpy(saddr
.sa_data
, device
, sizeof(saddr
.sa_data
));
3955 if (bind(fd
, &saddr
, sizeof(saddr
)) == -1) {
3956 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3957 "bind: %s", pcap_strerror(errno
));
3961 /* Any pending errors, e.g., network is down? */
3963 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
3964 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3965 "getsockopt: %s", pcap_strerror(errno
));
3970 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3971 "bind: %s", pcap_strerror(err
));
3979 /* ===== System calls available on all supported kernels ============== */
3982 * Query the kernel for the MTU of the given interface.
3985 iface_get_mtu(int fd
, const char *device
, char *ebuf
)
3990 return BIGGER_THAN_ALL_MTUS
;
3992 memset(&ifr
, 0, sizeof(ifr
));
3993 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
3995 if (ioctl(fd
, SIOCGIFMTU
, &ifr
) == -1) {
3996 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3997 "SIOCGIFMTU: %s", pcap_strerror(errno
));
4005 * Get the hardware type of the given interface as ARPHRD_xxx constant.
4008 iface_get_arptype(int fd
, const char *device
, char *ebuf
)
4012 memset(&ifr
, 0, sizeof(ifr
));
4013 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4015 if (ioctl(fd
, SIOCGIFHWADDR
, &ifr
) == -1) {
4016 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4017 "SIOCGIFHWADDR: %s", pcap_strerror(errno
));
4018 if (errno
== ENODEV
) {
4022 return PCAP_ERROR_NO_SUCH_DEVICE
;
4027 return ifr
.ifr_hwaddr
.sa_family
;
4030 #ifdef SO_ATTACH_FILTER
4032 fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
)
4036 register struct bpf_insn
*p
;
4041 * Make a copy of the filter, and modify that copy if
4044 prog_size
= sizeof(*handle
->fcode
.bf_insns
) * handle
->fcode
.bf_len
;
4045 len
= handle
->fcode
.bf_len
;
4046 f
= (struct bpf_insn
*)malloc(prog_size
);
4048 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4049 "malloc: %s", pcap_strerror(errno
));
4052 memcpy(f
, handle
->fcode
.bf_insns
, prog_size
);
4054 fcode
->filter
= (struct sock_filter
*) f
;
4056 for (i
= 0; i
< len
; ++i
) {
4059 * What type of instruction is this?
4061 switch (BPF_CLASS(p
->code
)) {
4065 * It's a return instruction; is the snapshot
4066 * length a constant, rather than the contents
4067 * of the accumulator?
4069 if (BPF_MODE(p
->code
) == BPF_K
) {
4071 * Yes - if the value to be returned,
4072 * i.e. the snapshot length, is anything
4073 * other than 0, make it 65535, so that
4074 * the packet is truncated by "recvfrom()",
4075 * not by the filter.
4077 * XXX - there's nothing we can easily do
4078 * if it's getting the value from the
4079 * accumulator; we'd have to insert
4080 * code to force non-zero values to be
4091 * It's a load instruction; is it loading
4094 switch (BPF_MODE(p
->code
)) {
4100 * Yes; are we in cooked mode?
4102 if (handle
->md
.cooked
) {
4104 * Yes, so we need to fix this
4107 if (fix_offset(p
) < 0) {
4109 * We failed to do so.
4110 * Return 0, so our caller
4111 * knows to punt to userland.
4121 return 1; /* we succeeded */
4125 fix_offset(struct bpf_insn
*p
)
4128 * What's the offset?
4130 if (p
->k
>= SLL_HDR_LEN
) {
4132 * It's within the link-layer payload; that starts at an
4133 * offset of 0, as far as the kernel packet filter is
4134 * concerned, so subtract the length of the link-layer
4137 p
->k
-= SLL_HDR_LEN
;
4138 } else if (p
->k
== 14) {
4140 * It's the protocol field; map it to the special magic
4141 * kernel offset for that field.
4143 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
4146 * It's within the header, but it's not one of those
4147 * fields; we can't do that in the kernel, so punt
4156 set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
)
4158 int total_filter_on
= 0;
4164 * The socket filter code doesn't discard all packets queued
4165 * up on the socket when the filter is changed; this means
4166 * that packets that don't match the new filter may show up
4167 * after the new filter is put onto the socket, if those
4168 * packets haven't yet been read.
4170 * This means, for example, that if you do a tcpdump capture
4171 * with a filter, the first few packets in the capture might
4172 * be packets that wouldn't have passed the filter.
4174 * We therefore discard all packets queued up on the socket
4175 * when setting a kernel filter. (This isn't an issue for
4176 * userland filters, as the userland filtering is done after
4177 * packets are queued up.)
4179 * To flush those packets, we put the socket in read-only mode,
4180 * and read packets from the socket until there are no more to
4183 * In order to keep that from being an infinite loop - i.e.,
4184 * to keep more packets from arriving while we're draining
4185 * the queue - we put the "total filter", which is a filter
4186 * that rejects all packets, onto the socket before draining
4189 * This code deliberately ignores any errors, so that you may
4190 * get bogus packets if an error occurs, rather than having
4191 * the filtering done in userland even if it could have been
4192 * done in the kernel.
4194 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
4195 &total_fcode
, sizeof(total_fcode
)) == 0) {
4199 * Note that we've put the total filter onto the socket.
4201 total_filter_on
= 1;
4204 * Save the socket's current mode, and put it in
4205 * non-blocking mode; we drain it by reading packets
4206 * until we get an error (which is normally a
4207 * "nothing more to be read" error).
4209 save_mode
= fcntl(handle
->fd
, F_GETFL
, 0);
4210 if (save_mode
!= -1 &&
4211 fcntl(handle
->fd
, F_SETFL
, save_mode
| O_NONBLOCK
) >= 0) {
4212 while (recv(handle
->fd
, &drain
, sizeof drain
,
4216 fcntl(handle
->fd
, F_SETFL
, save_mode
);
4217 if (save_errno
!= EAGAIN
) {
4219 reset_kernel_filter(handle
);
4220 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4221 "recv: %s", pcap_strerror(save_errno
));
4228 * Now attach the new filter.
4230 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
4231 fcode
, sizeof(*fcode
));
4232 if (ret
== -1 && total_filter_on
) {
4234 * Well, we couldn't set that filter on the socket,
4235 * but we could set the total filter on the socket.
4237 * This could, for example, mean that the filter was
4238 * too big to put into the kernel, so we'll have to
4239 * filter in userland; in any case, we'll be doing
4240 * filtering in userland, so we need to remove the
4241 * total filter so we see packets.
4246 * XXX - if this fails, we're really screwed;
4247 * we have the total filter on the socket,
4248 * and it won't come off. What do we do then?
4250 reset_kernel_filter(handle
);
4258 reset_kernel_filter(pcap_t
*handle
)
4261 * setsockopt() barfs unless it get a dummy parameter.
4262 * valgrind whines unless the value is initialized,
4263 * as it has no idea that setsockopt() ignores its
4268 return setsockopt(handle
->fd
, SOL_SOCKET
, SO_DETACH_FILTER
,
4269 &dummy
, sizeof(dummy
));