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.
130 #include <sys/socket.h>
131 #include <sys/ioctl.h>
132 #include <sys/utsname.h>
133 #include <sys/mman.h>
134 #include <linux/if.h>
135 #include <netinet/in.h>
136 #include <linux/if_ether.h>
137 #include <net/if_arp.h>
142 * Got Wireless Extensions?
144 #ifdef HAVE_LINUX_WIRELESS_H
145 #include <linux/wireless.h>
146 #endif /* HAVE_LINUX_WIRELESS_H */
152 #include <linux/nl80211.h>
154 #include <netlink/genl/genl.h>
155 #include <netlink/genl/family.h>
156 #include <netlink/genl/ctrl.h>
157 #include <netlink/msg.h>
158 #include <netlink/attr.h>
159 #endif /* HAVE_LIBNL */
161 #include "pcap-int.h"
162 #include "pcap/sll.h"
163 #include "pcap/vlan.h"
166 #include "pcap-dag.h"
167 #endif /* HAVE_DAG_API */
169 #ifdef HAVE_SEPTEL_API
170 #include "pcap-septel.h"
171 #endif /* HAVE_SEPTEL_API */
174 #include "pcap-snf.h"
175 #endif /* HAVE_SNF_API */
177 #ifdef PCAP_SUPPORT_USB
178 #include "pcap-usb-linux.h"
181 #ifdef PCAP_SUPPORT_BT
182 #include "pcap-bt-linux.h"
185 #ifdef PCAP_SUPPORT_CAN
186 #include "pcap-can-linux.h"
190 * If PF_PACKET is defined, we can use {SOCK_RAW,SOCK_DGRAM}/PF_PACKET
191 * sockets rather than SOCK_PACKET sockets.
193 * To use them, we include <linux/if_packet.h> rather than
194 * <netpacket/packet.h>; we do so because
196 * some Linux distributions (e.g., Slackware 4.0) have 2.2 or
197 * later kernels and libc5, and don't provide a <netpacket/packet.h>
200 * not all versions of glibc2 have a <netpacket/packet.h> file
201 * that defines stuff needed for some of the 2.4-or-later-kernel
202 * features, so if the system has a 2.4 or later kernel, we
203 * still can't use those features.
205 * We're already including a number of other <linux/XXX.h> headers, and
206 * this code is Linux-specific (no other OS has PF_PACKET sockets as
207 * a raw packet capture mechanism), so it's not as if you gain any
208 * useful portability by using <netpacket/packet.h>
210 * XXX - should we just include <linux/if_packet.h> even if PF_PACKET
211 * isn't defined? It only defines one data structure in 2.0.x, so
212 * it shouldn't cause any problems.
215 # include <linux/if_packet.h>
218 * On at least some Linux distributions (for example, Red Hat 5.2),
219 * there's no <netpacket/packet.h> file, but PF_PACKET is defined if
220 * you include <sys/socket.h>, but <linux/if_packet.h> doesn't define
221 * any of the PF_PACKET stuff such as "struct sockaddr_ll" or any of
222 * the PACKET_xxx stuff.
224 * So we check whether PACKET_HOST is defined, and assume that we have
225 * PF_PACKET sockets only if it is defined.
228 # define HAVE_PF_PACKET_SOCKETS
229 # ifdef PACKET_AUXDATA
230 # define HAVE_PACKET_AUXDATA
231 # endif /* PACKET_AUXDATA */
232 # endif /* PACKET_HOST */
235 /* check for memory mapped access avaibility. We assume every needed
236 * struct is defined if the macro TPACKET_HDRLEN is defined, because it
237 * uses many ring related structs and macros */
238 # ifdef TPACKET_HDRLEN
239 # define HAVE_PACKET_RING
240 # ifdef TPACKET2_HDRLEN
241 # define HAVE_TPACKET2
243 # define TPACKET_V1 0
244 # endif /* TPACKET2_HDRLEN */
245 # endif /* TPACKET_HDRLEN */
246 #endif /* PF_PACKET */
248 #ifdef SO_ATTACH_FILTER
249 #include <linux/types.h>
250 #include <linux/filter.h>
253 #ifndef HAVE_SOCKLEN_T
254 typedef int socklen_t
;
259 * This is being compiled on a system that lacks MSG_TRUNC; define it
260 * with the value it has in the 2.2 and later kernels, so that, on
261 * those kernels, when we pass it in the flags argument to "recvfrom()"
262 * we're passing the right value and thus get the MSG_TRUNC behavior
263 * we want. (We don't get that behavior on 2.0[.x] kernels, because
264 * they didn't support MSG_TRUNC.)
266 #define MSG_TRUNC 0x20
271 * This is being compiled on a system that lacks SOL_PACKET; define it
272 * with the value it has in the 2.2 and later kernels, so that we can
273 * set promiscuous mode in the good modern way rather than the old
274 * 2.0-kernel crappy way.
276 #define SOL_PACKET 263
279 #define MAX_LINKHEADER_SIZE 256
282 * When capturing on all interfaces we use this as the buffer size.
283 * Should be bigger then all MTUs that occur in real life.
284 * 64kB should be enough for now.
286 #define BIGGER_THAN_ALL_MTUS (64*1024)
289 * Prototypes for internal functions and methods.
291 static void map_arphrd_to_dlt(pcap_t
*, int, int);
292 #ifdef HAVE_PF_PACKET_SOCKETS
293 static short int map_packet_type_to_sll_type(short int);
295 static int pcap_activate_linux(pcap_t
*);
296 static int activate_old(pcap_t
*);
297 static int activate_new(pcap_t
*);
298 static int activate_mmap(pcap_t
*);
299 static int pcap_can_set_rfmon_linux(pcap_t
*);
300 static int pcap_read_linux(pcap_t
*, int, pcap_handler
, u_char
*);
301 static int pcap_read_packet(pcap_t
*, pcap_handler
, u_char
*);
302 static int pcap_inject_linux(pcap_t
*, const void *, size_t);
303 static int pcap_stats_linux(pcap_t
*, struct pcap_stat
*);
304 static int pcap_setfilter_linux(pcap_t
*, struct bpf_program
*);
305 static int pcap_setdirection_linux(pcap_t
*, pcap_direction_t
);
306 static void pcap_cleanup_linux(pcap_t
*);
309 struct tpacket_hdr
*h1
;
310 struct tpacket2_hdr
*h2
;
314 #ifdef HAVE_PACKET_RING
315 #define RING_GET_FRAME(h) (((union thdr **)h->buffer)[h->offset])
317 static void destroy_ring(pcap_t
*handle
);
318 static int create_ring(pcap_t
*handle
);
319 static int prepare_tpacket_socket(pcap_t
*handle
);
320 static void pcap_cleanup_linux_mmap(pcap_t
*);
321 static int pcap_read_linux_mmap(pcap_t
*, int, pcap_handler
, u_char
*);
322 static int pcap_setfilter_linux_mmap(pcap_t
*, struct bpf_program
*);
323 static int pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
, char *errbuf
);
324 static int pcap_getnonblock_mmap(pcap_t
*p
, char *errbuf
);
325 static void pcap_oneshot_mmap(u_char
*user
, const struct pcap_pkthdr
*h
,
326 const u_char
*bytes
);
330 * Wrap some ioctl calls
332 #ifdef HAVE_PF_PACKET_SOCKETS
333 static int iface_get_id(int fd
, const char *device
, char *ebuf
);
335 static int iface_get_mtu(int fd
, const char *device
, char *ebuf
);
336 static int iface_get_arptype(int fd
, const char *device
, char *ebuf
);
337 #ifdef HAVE_PF_PACKET_SOCKETS
338 static int iface_bind(int fd
, int ifindex
, char *ebuf
);
339 #ifdef IW_MODE_MONITOR
340 static int has_wext(int sock_fd
, const char *device
, char *ebuf
);
341 #endif /* IW_MODE_MONITOR */
342 static int enter_rfmon_mode(pcap_t
*handle
, int sock_fd
,
344 #endif /* HAVE_PF_PACKET_SOCKETS */
345 static int iface_bind_old(int fd
, const char *device
, char *ebuf
);
347 #ifdef SO_ATTACH_FILTER
348 static int fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
,
350 static int fix_offset(struct bpf_insn
*p
);
351 static int set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
);
352 static int reset_kernel_filter(pcap_t
*handle
);
354 static struct sock_filter total_insn
355 = BPF_STMT(BPF_RET
| BPF_K
, 0);
356 static struct sock_fprog total_fcode
357 = { 1, &total_insn
};
361 pcap_create(const char *device
, char *ebuf
)
366 * A null device name is equivalent to the "any" device.
372 if (strstr(device
, "dag")) {
373 return dag_create(device
, ebuf
);
375 #endif /* HAVE_DAG_API */
377 #ifdef HAVE_SEPTEL_API
378 if (strstr(device
, "septel")) {
379 return septel_create(device
, ebuf
);
381 #endif /* HAVE_SEPTEL_API */
384 handle
= snf_create(device
, ebuf
);
385 if (strstr(device
, "snf") || handle
!= NULL
)
388 #endif /* HAVE_SNF_API */
390 #ifdef PCAP_SUPPORT_BT
391 if (strstr(device
, "bluetooth")) {
392 return bt_create(device
, ebuf
);
396 #ifdef PCAP_SUPPORT_CAN
397 if (strstr(device
, "can") || strstr(device
, "vcan")) {
398 return can_create(device
, ebuf
);
402 #ifdef PCAP_SUPPORT_USB
403 if (strstr(device
, "usbmon")) {
404 return usb_create(device
, ebuf
);
408 handle
= pcap_create_common(device
, ebuf
);
412 handle
->activate_op
= pcap_activate_linux
;
413 handle
->can_set_rfmon_op
= pcap_can_set_rfmon_linux
;
419 * If interface {if} is a mac80211 driver, the file
420 * /sys/class/net/{if}/phy80211 is a symlink to
421 * /sys/class/ieee80211/{phydev}, for some {phydev}.
423 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
424 * least, has a "wmaster0" device and a "wlan0" device; the
425 * latter is the one with the IP address. Both show up in
426 * "tcpdump -D" output. Capturing on the wmaster0 device
427 * captures with 802.11 headers.
429 * airmon-ng searches through /sys/class/net for devices named
430 * monN, starting with mon0; as soon as one *doesn't* exist,
431 * it chooses that as the monitor device name. If the "iw"
432 * command exists, it does "iw dev {if} interface add {monif}
433 * type monitor", where {monif} is the monitor device. It
434 * then (sigh) sleeps .1 second, and then configures the
435 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
436 * is a file, it writes {mondev}, without a newline, to that file,
437 * and again (sigh) sleeps .1 second, and then iwconfig's that
438 * device into monitor mode and configures it up. Otherwise,
439 * you can't do monitor mode.
441 * All these devices are "glued" together by having the
442 * /sys/class/net/{device}/phy80211 links pointing to the same
443 * place, so, given a wmaster, wlan, or mon device, you can
444 * find the other devices by looking for devices with
445 * the same phy80211 link.
447 * To turn monitor mode off, delete the monitor interface,
448 * either with "iw dev {monif} interface del" or by sending
449 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
451 * Note: if you try to create a monitor device named "monN", and
452 * there's already a "monN" device, it fails, as least with
453 * the netlink interface (which is what iw uses), with a return
454 * value of -ENFILE. (Return values are negative errnos.) We
455 * could probably use that to find an unused device.
457 * Yes, you can have multiple monitor devices for a given
462 * Is this a mac80211 device? If so, fill in the physical device path and
463 * return 1; if not, return 0. On an error, fill in handle->errbuf and
467 get_mac80211_phydev(pcap_t
*handle
, const char *device
, char *phydev_path
,
468 size_t phydev_max_pathlen
)
474 * Generate the path string for the symlink to the physical device.
476 if (asprintf(&pathstr
, "/sys/class/net/%s/phy80211", device
) == -1) {
477 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
478 "%s: Can't generate path name string for /sys/class/net device",
482 bytes_read
= readlink(pathstr
, phydev_path
, phydev_max_pathlen
);
483 if (bytes_read
== -1) {
484 if (errno
== ENOENT
|| errno
== EINVAL
) {
486 * Doesn't exist, or not a symlink; assume that
487 * means it's not a mac80211 device.
492 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
493 "%s: Can't readlink %s: %s", device
, pathstr
,
499 phydev_path
[bytes_read
] = '\0';
503 struct nl80211_state
{
504 struct nl_handle
*nl_handle
;
505 struct nl_cache
*nl_cache
;
506 struct genl_family
*nl80211
;
510 nl80211_init(pcap_t
*handle
, struct nl80211_state
*state
, const char *device
)
512 state
->nl_handle
= nl_handle_alloc();
513 if (!state
->nl_handle
) {
514 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
515 "%s: failed to allocate netlink handle", device
);
519 if (genl_connect(state
->nl_handle
)) {
520 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
521 "%s: failed to connect to generic netlink", device
);
522 goto out_handle_destroy
;
525 state
->nl_cache
= genl_ctrl_alloc_cache(state
->nl_handle
);
526 if (!state
->nl_cache
) {
527 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
528 "%s: failed to allocate generic netlink cache", device
);
529 goto out_handle_destroy
;
532 state
->nl80211
= genl_ctrl_search_by_name(state
->nl_cache
, "nl80211");
533 if (!state
->nl80211
) {
534 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
535 "%s: nl80211 not found", device
);
542 nl_cache_free(state
->nl_cache
);
544 nl_handle_destroy(state
->nl_handle
);
549 nl80211_cleanup(struct nl80211_state
*state
)
551 genl_family_put(state
->nl80211
);
552 nl_cache_free(state
->nl_cache
);
553 nl_handle_destroy(state
->nl_handle
);
557 add_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
558 const char *device
, const char *mondevice
)
564 ifindex
= iface_get_id(sock_fd
, device
, handle
->errbuf
);
570 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
571 "%s: failed to allocate netlink msg", device
);
575 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
576 0, NL80211_CMD_NEW_INTERFACE
, 0);
577 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
578 NLA_PUT_STRING(msg
, NL80211_ATTR_IFNAME
, mondevice
);
579 NLA_PUT_U32(msg
, NL80211_ATTR_IFTYPE
, NL80211_IFTYPE_MONITOR
);
581 err
= nl_send_auto_complete(state
->nl_handle
, msg
);
583 if (err
== -ENFILE
) {
585 * Device not available; our caller should just
592 * Real failure, not just "that device is not
595 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
596 "%s: nl_send_auto_complete failed adding %s interface: %s",
597 device
, mondevice
, strerror(-err
));
602 err
= nl_wait_for_ack(state
->nl_handle
);
604 if (err
== -ENFILE
) {
606 * Device not available; our caller should just
613 * Real failure, not just "that device is not
616 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
617 "%s: nl_wait_for_ack failed adding %s interface: %s",
618 device
, mondevice
, strerror(-err
));
631 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
632 "%s: nl_put failed adding %s interface",
639 del_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
640 const char *device
, const char *mondevice
)
646 ifindex
= iface_get_id(sock_fd
, mondevice
, handle
->errbuf
);
652 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
653 "%s: failed to allocate netlink msg", device
);
657 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
658 0, NL80211_CMD_DEL_INTERFACE
, 0);
659 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
661 err
= nl_send_auto_complete(state
->nl_handle
, msg
);
663 if (err
== -ENFILE
) {
665 * Device not available; our caller should just
672 * Real failure, not just "that device is not
675 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
676 "%s: nl_send_auto_complete failed deleting %s interface: %s",
677 device
, mondevice
, strerror(-err
));
682 err
= nl_wait_for_ack(state
->nl_handle
);
684 if (err
== -ENFILE
) {
686 * Device not available; our caller should just
693 * Real failure, not just "that device is not
696 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
697 "%s: nl_wait_for_ack failed adding %s interface: %s",
698 device
, mondevice
, strerror(-err
));
711 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
712 "%s: nl_put failed deleting %s interface",
719 enter_rfmon_mode_mac80211(pcap_t
*handle
, int sock_fd
, const char *device
)
722 char phydev_path
[PATH_MAX
+1];
723 struct nl80211_state nlstate
;
728 * Is this a mac80211 device?
730 ret
= get_mac80211_phydev(handle
, device
, phydev_path
, PATH_MAX
);
732 return ret
; /* error */
734 return 0; /* no error, but not mac80211 device */
737 * XXX - is this already a monN device?
739 * Is that determined by old Wireless Extensions ioctls?
743 * OK, it's apparently a mac80211 device.
744 * Try to find an unused monN device for it.
746 ret
= nl80211_init(handle
, &nlstate
, device
);
749 for (n
= 0; n
< UINT_MAX
; n
++) {
753 char mondevice
[3+10+1]; /* mon{UINT_MAX}\0 */
755 snprintf(mondevice
, sizeof mondevice
, "mon%u", n
);
756 ret
= add_mon_if(handle
, sock_fd
, &nlstate
, device
, mondevice
);
758 handle
->md
.mondevice
= strdup(mondevice
);
763 * Hard failure. Just return ret; handle->errbuf
764 * has already been set.
766 nl80211_cleanup(&nlstate
);
771 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
772 "%s: No free monN interfaces", device
);
773 nl80211_cleanup(&nlstate
);
780 * Sleep for .1 seconds.
783 delay
.tv_nsec
= 500000000;
784 nanosleep(&delay
, NULL
);
788 * Now configure the monitor interface up.
790 memset(&ifr
, 0, sizeof(ifr
));
791 strncpy(ifr
.ifr_name
, handle
->md
.mondevice
, sizeof(ifr
.ifr_name
));
792 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
793 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
794 "%s: Can't get flags for %s: %s", device
,
795 handle
->md
.mondevice
, strerror(errno
));
796 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
797 handle
->md
.mondevice
);
798 nl80211_cleanup(&nlstate
);
801 ifr
.ifr_flags
|= IFF_UP
|IFF_RUNNING
;
802 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
803 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
804 "%s: Can't set flags for %s: %s", device
,
805 handle
->md
.mondevice
, strerror(errno
));
806 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
807 handle
->md
.mondevice
);
808 nl80211_cleanup(&nlstate
);
813 * Success. Clean up the libnl state.
815 nl80211_cleanup(&nlstate
);
818 * Note that we have to delete the monitor device when we close
821 handle
->md
.must_do_on_close
|= MUST_DELETE_MONIF
;
824 * Add this to the list of pcaps to close when we exit.
826 pcap_add_to_pcaps_to_close(handle
);
830 #endif /* HAVE_LIBNL */
833 pcap_can_set_rfmon_linux(pcap_t
*handle
)
836 char phydev_path
[PATH_MAX
+1];
839 #ifdef IW_MODE_MONITOR
844 if (strcmp(handle
->opt
.source
, "any") == 0) {
846 * Monitor mode makes no sense on the "any" device.
853 * Bleah. There doesn't seem to be a way to ask a mac80211
854 * device, through libnl, whether it supports monitor mode;
855 * we'll just check whether the device appears to be a
856 * mac80211 device and, if so, assume the device supports
859 * wmaster devices don't appear to support the Wireless
860 * Extensions, but we can create a mon device for a
861 * wmaster device, so we don't bother checking whether
862 * a mac80211 device supports the Wireless Extensions.
864 ret
= get_mac80211_phydev(handle
, handle
->opt
.source
, phydev_path
,
867 return ret
; /* error */
869 return 1; /* mac80211 device */
872 #ifdef IW_MODE_MONITOR
874 * Bleah. There doesn't appear to be an ioctl to use to ask
875 * whether a device supports monitor mode; we'll just do
876 * SIOCGIWMODE and, if it succeeds, assume the device supports
879 * Open a socket on which to attempt to get the mode.
880 * (We assume that if we have Wireless Extensions support
881 * we also have PF_PACKET support.)
883 sock_fd
= socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
));
885 (void)snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
886 "socket: %s", pcap_strerror(errno
));
891 * Attempt to get the current mode.
893 strncpy(ireq
.ifr_ifrn
.ifrn_name
, handle
->opt
.source
,
894 sizeof ireq
.ifr_ifrn
.ifrn_name
);
895 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
896 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) != -1) {
898 * Well, we got the mode; assume we can set it.
903 if (errno
== ENODEV
) {
904 /* The device doesn't even exist. */
905 (void)snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
906 "SIOCGIWMODE failed: %s", pcap_strerror(errno
));
908 return PCAP_ERROR_NO_SUCH_DEVICE
;
916 * Grabs the number of dropped packets by the interface from /proc/net/dev.
918 * XXX - what about /sys/class/net/{interface name}/rx_*? There are
919 * individual devices giving, in ASCII, various rx_ and tx_ statistics.
921 * Or can we get them in binary form from netlink?
924 linux_if_drops(const char * if_name
)
929 int field_to_convert
= 3, if_name_sz
= strlen(if_name
);
930 long int dropped_pkts
= 0;
932 file
= fopen("/proc/net/dev", "r");
936 while (!dropped_pkts
&& fgets( buffer
, sizeof(buffer
), file
))
938 /* search for 'bytes' -- if its in there, then
939 that means we need to grab the fourth field. otherwise
940 grab the third field. */
941 if (field_to_convert
!= 4 && strstr(buffer
, "bytes"))
943 field_to_convert
= 4;
947 /* find iface and make sure it actually matches -- space before the name and : after it */
948 if ((bufptr
= strstr(buffer
, if_name
)) &&
949 (bufptr
== buffer
|| *(bufptr
-1) == ' ') &&
950 *(bufptr
+ if_name_sz
) == ':')
952 bufptr
= bufptr
+ if_name_sz
+ 1;
954 /* grab the nth field from it */
955 while( --field_to_convert
&& *bufptr
!= '\0')
957 while (*bufptr
!= '\0' && *(bufptr
++) == ' ');
958 while (*bufptr
!= '\0' && *(bufptr
++) != ' ');
961 /* get rid of any final spaces */
962 while (*bufptr
!= '\0' && *bufptr
== ' ') bufptr
++;
965 dropped_pkts
= strtol(bufptr
, NULL
, 10);
977 * With older kernels promiscuous mode is kind of interesting because we
978 * have to reset the interface before exiting. The problem can't really
979 * be solved without some daemon taking care of managing usage counts.
980 * If we put the interface into promiscuous mode, we set a flag indicating
981 * that we must take it out of that mode when the interface is closed,
982 * and, when closing the interface, if that flag is set we take it out
983 * of promiscuous mode.
985 * Even with newer kernels, we have the same issue with rfmon mode.
988 static void pcap_cleanup_linux( pcap_t
*handle
)
992 struct nl80211_state nlstate
;
994 #endif /* HAVE_LIBNL */
995 #ifdef IW_MODE_MONITOR
997 #endif /* IW_MODE_MONITOR */
999 if (handle
->md
.must_do_on_close
!= 0) {
1001 * There's something we have to do when closing this
1004 if (handle
->md
.must_do_on_close
& MUST_CLEAR_PROMISC
) {
1006 * We put the interface into promiscuous mode;
1007 * take it out of promiscuous mode.
1009 * XXX - if somebody else wants it in promiscuous
1010 * mode, this code cannot know that, so it'll take
1011 * it out of promiscuous mode. That's not fixable
1012 * in 2.0[.x] kernels.
1014 memset(&ifr
, 0, sizeof(ifr
));
1015 strncpy(ifr
.ifr_name
, handle
->md
.device
,
1016 sizeof(ifr
.ifr_name
));
1017 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
1019 "Can't restore interface flags (SIOCGIFFLAGS failed: %s).\n"
1020 "Please adjust manually.\n"
1021 "Hint: This can't happen with Linux >= 2.2.0.\n",
1024 if (ifr
.ifr_flags
& IFF_PROMISC
) {
1026 * Promiscuous mode is currently on;
1029 ifr
.ifr_flags
&= ~IFF_PROMISC
;
1030 if (ioctl(handle
->fd
, SIOCSIFFLAGS
,
1033 "Can't restore interface flags (SIOCSIFFLAGS failed: %s).\n"
1034 "Please adjust manually.\n"
1035 "Hint: This can't happen with Linux >= 2.2.0.\n",
1043 if (handle
->md
.must_do_on_close
& MUST_DELETE_MONIF
) {
1044 ret
= nl80211_init(handle
, &nlstate
, handle
->md
.device
);
1046 ret
= del_mon_if(handle
, handle
->fd
, &nlstate
,
1047 handle
->md
.device
, handle
->md
.mondevice
);
1048 nl80211_cleanup(&nlstate
);
1052 "Can't delete monitor interface %s (%s).\n"
1053 "Please delete manually.\n",
1054 handle
->md
.mondevice
, handle
->errbuf
);
1057 #endif /* HAVE_LIBNL */
1059 #ifdef IW_MODE_MONITOR
1060 if (handle
->md
.must_do_on_close
& MUST_CLEAR_RFMON
) {
1062 * We put the interface into rfmon mode;
1063 * take it out of rfmon mode.
1065 * XXX - if somebody else wants it in rfmon
1066 * mode, this code cannot know that, so it'll take
1067 * it out of rfmon mode.
1069 strncpy(ireq
.ifr_ifrn
.ifrn_name
, handle
->md
.device
,
1070 sizeof ireq
.ifr_ifrn
.ifrn_name
);
1071 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1]
1073 ireq
.u
.mode
= handle
->md
.oldmode
;
1074 if (ioctl(handle
->fd
, SIOCSIWMODE
, &ireq
) == -1) {
1076 * Scientist, you've failed.
1079 "Can't restore interface wireless mode (SIOCSIWMODE failed: %s).\n"
1080 "Please adjust manually.\n",
1084 #endif /* IW_MODE_MONITOR */
1087 * Take this pcap out of the list of pcaps for which we
1088 * have to take the interface out of some mode.
1090 pcap_remove_from_pcaps_to_close(handle
);
1093 if (handle
->md
.mondevice
!= NULL
) {
1094 free(handle
->md
.mondevice
);
1095 handle
->md
.mondevice
= NULL
;
1097 if (handle
->md
.device
!= NULL
) {
1098 free(handle
->md
.device
);
1099 handle
->md
.device
= NULL
;
1101 pcap_cleanup_live_common(handle
);
1105 * Get a handle for a live capture from the given device. You can
1106 * pass NULL as device to get all packages (without link level
1107 * information of course). If you pass 1 as promisc the interface
1108 * will be set to promiscous mode (XXX: I think this usage should
1109 * be deprecated and functions be added to select that later allow
1110 * modification of that values -- Torsten).
1113 pcap_activate_linux(pcap_t
*handle
)
1118 device
= handle
->opt
.source
;
1120 handle
->inject_op
= pcap_inject_linux
;
1121 handle
->setfilter_op
= pcap_setfilter_linux
;
1122 handle
->setdirection_op
= pcap_setdirection_linux
;
1123 handle
->set_datalink_op
= NULL
; /* can't change data link type */
1124 handle
->getnonblock_op
= pcap_getnonblock_fd
;
1125 handle
->setnonblock_op
= pcap_setnonblock_fd
;
1126 handle
->cleanup_op
= pcap_cleanup_linux
;
1127 handle
->read_op
= pcap_read_linux
;
1128 handle
->stats_op
= pcap_stats_linux
;
1131 * The "any" device is a special device which causes us not
1132 * to bind to a particular device and thus to look at all
1135 if (strcmp(device
, "any") == 0) {
1136 if (handle
->opt
.promisc
) {
1137 handle
->opt
.promisc
= 0;
1138 /* Just a warning. */
1139 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1140 "Promiscuous mode not supported on the \"any\" device");
1141 status
= PCAP_WARNING_PROMISC_NOTSUP
;
1145 handle
->md
.device
= strdup(device
);
1146 if (handle
->md
.device
== NULL
) {
1147 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "strdup: %s",
1148 pcap_strerror(errno
) );
1153 * If we're in promiscuous mode, then we probably want
1154 * to see when the interface drops packets too, so get an
1155 * initial count from /proc/net/dev
1157 if (handle
->opt
.promisc
)
1158 handle
->md
.proc_dropped
= linux_if_drops(handle
->md
.device
);
1161 * Current Linux kernels use the protocol family PF_PACKET to
1162 * allow direct access to all packets on the network while
1163 * older kernels had a special socket type SOCK_PACKET to
1164 * implement this feature.
1165 * While this old implementation is kind of obsolete we need
1166 * to be compatible with older kernels for a while so we are
1167 * trying both methods with the newer method preferred.
1170 if ((status
= activate_new(handle
)) == 1) {
1173 * Try to use memory-mapped access.
1175 switch (activate_mmap(handle
)) {
1178 /* we succeeded; nothing more to do */
1183 * Kernel doesn't support it - just continue
1184 * with non-memory-mapped access.
1191 * We failed to set up to use it, or kernel
1192 * supports it, but we failed to enable it;
1193 * return an error. handle->errbuf contains
1196 status
= PCAP_ERROR
;
1200 else if (status
== 0) {
1201 /* Non-fatal error; try old way */
1202 if ((status
= activate_old(handle
)) != 1) {
1204 * Both methods to open the packet socket failed.
1205 * Tidy up and report our failure (handle->errbuf
1206 * is expected to be set by the functions above).
1212 * Fatal error with the new way; just fail.
1213 * status has the error return; if it's PCAP_ERROR,
1214 * handle->errbuf has been set appropriately.
1220 * We set up the socket, but not with memory-mapped access.
1222 if (handle
->opt
.buffer_size
!= 0) {
1224 * Set the socket buffer size to the specified value.
1226 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_RCVBUF
,
1227 &handle
->opt
.buffer_size
,
1228 sizeof(handle
->opt
.buffer_size
)) == -1) {
1229 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1230 "SO_RCVBUF: %s", pcap_strerror(errno
));
1231 status
= PCAP_ERROR
;
1236 /* Allocate the buffer */
1238 handle
->buffer
= malloc(handle
->bufsize
+ handle
->offset
);
1239 if (!handle
->buffer
) {
1240 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1241 "malloc: %s", pcap_strerror(errno
));
1242 status
= PCAP_ERROR
;
1247 * "handle->fd" is a socket, so "select()" and "poll()"
1248 * should work on it.
1250 handle
->selectable_fd
= handle
->fd
;
1255 pcap_cleanup_linux(handle
);
1260 * Read at most max_packets from the capture stream and call the callback
1261 * for each of them. Returns the number of packets handled or -1 if an
1265 pcap_read_linux(pcap_t
*handle
, int max_packets
, pcap_handler callback
, u_char
*user
)
1268 * Currently, on Linux only one packet is delivered per read,
1271 return pcap_read_packet(handle
, callback
, user
);
1275 * Read a packet from the socket calling the handler provided by
1276 * the user. Returns the number of packets received or -1 if an
1280 pcap_read_packet(pcap_t
*handle
, pcap_handler callback
, u_char
*userdata
)
1284 #ifdef HAVE_PF_PACKET_SOCKETS
1285 struct sockaddr_ll from
;
1286 struct sll_header
*hdrp
;
1288 struct sockaddr from
;
1290 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1293 struct cmsghdr
*cmsg
;
1295 struct cmsghdr cmsg
;
1296 char buf
[CMSG_SPACE(sizeof(struct tpacket_auxdata
))];
1298 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1300 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1301 int packet_len
, caplen
;
1302 struct pcap_pkthdr pcap_header
;
1304 #ifdef HAVE_PF_PACKET_SOCKETS
1306 * If this is a cooked device, leave extra room for a
1307 * fake packet header.
1309 if (handle
->md
.cooked
)
1310 offset
= SLL_HDR_LEN
;
1315 * This system doesn't have PF_PACKET sockets, so it doesn't
1316 * support cooked devices.
1322 * Receive a single packet from the kernel.
1323 * We ignore EINTR, as that might just be due to a signal
1324 * being delivered - if the signal should interrupt the
1325 * loop, the signal handler should call pcap_breakloop()
1326 * to set handle->break_loop (we ignore it on other
1327 * platforms as well).
1328 * We also ignore ENETDOWN, so that we can continue to
1329 * capture traffic if the interface goes down and comes
1330 * back up again; comments in the kernel indicate that
1331 * we'll just block waiting for packets if we try to
1332 * receive from a socket that delivered ENETDOWN, and,
1333 * if we're using a memory-mapped buffer, we won't even
1334 * get notified of "network down" events.
1336 bp
= handle
->buffer
+ handle
->offset
;
1338 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1339 msg
.msg_name
= &from
;
1340 msg
.msg_namelen
= sizeof(from
);
1343 msg
.msg_control
= &cmsg_buf
;
1344 msg
.msg_controllen
= sizeof(cmsg_buf
);
1347 iov
.iov_len
= handle
->bufsize
- offset
;
1348 iov
.iov_base
= bp
+ offset
;
1349 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1353 * Has "pcap_breakloop()" been called?
1355 if (handle
->break_loop
) {
1357 * Yes - clear the flag that indicates that it has,
1358 * and return PCAP_ERROR_BREAK as an indication that
1359 * we were told to break out of the loop.
1361 handle
->break_loop
= 0;
1362 return PCAP_ERROR_BREAK
;
1365 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1366 packet_len
= recvmsg(handle
->fd
, &msg
, MSG_TRUNC
);
1367 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1368 fromlen
= sizeof(from
);
1369 packet_len
= recvfrom(
1370 handle
->fd
, bp
+ offset
,
1371 handle
->bufsize
- offset
, MSG_TRUNC
,
1372 (struct sockaddr
*) &from
, &fromlen
);
1373 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1374 } while (packet_len
== -1 && errno
== EINTR
);
1376 /* Check if an error occured */
1378 if (packet_len
== -1) {
1382 return 0; /* no packet there */
1386 * The device on which we're capturing went away.
1388 * XXX - we should really return
1389 * PCAP_ERROR_IFACE_NOT_UP, but pcap_dispatch()
1390 * etc. aren't defined to return that.
1392 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1393 "The interface went down");
1397 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1398 "recvfrom: %s", pcap_strerror(errno
));
1403 #ifdef HAVE_PF_PACKET_SOCKETS
1404 if (!handle
->md
.sock_packet
) {
1406 * Unfortunately, there is a window between socket() and
1407 * bind() where the kernel may queue packets from any
1408 * interface. If we're bound to a particular interface,
1409 * discard packets not from that interface.
1411 * (If socket filters are supported, we could do the
1412 * same thing we do when changing the filter; however,
1413 * that won't handle packet sockets without socket
1414 * filter support, and it's a bit more complicated.
1415 * It would save some instructions per packet, however.)
1417 if (handle
->md
.ifindex
!= -1 &&
1418 from
.sll_ifindex
!= handle
->md
.ifindex
)
1422 * Do checks based on packet direction.
1423 * We can only do this if we're using PF_PACKET; the
1424 * address returned for SOCK_PACKET is a "sockaddr_pkt"
1425 * which lacks the relevant packet type information.
1427 if (from
.sll_pkttype
== PACKET_OUTGOING
) {
1430 * If this is from the loopback device, reject it;
1431 * we'll see the packet as an incoming packet as well,
1432 * and we don't want to see it twice.
1434 if (from
.sll_ifindex
== handle
->md
.lo_ifindex
)
1438 * If the user only wants incoming packets, reject it.
1440 if (handle
->direction
== PCAP_D_IN
)
1445 * If the user only wants outgoing packets, reject it.
1447 if (handle
->direction
== PCAP_D_OUT
)
1453 #ifdef HAVE_PF_PACKET_SOCKETS
1455 * If this is a cooked device, fill in the fake packet header.
1457 if (handle
->md
.cooked
) {
1459 * Add the length of the fake header to the length
1460 * of packet data we read.
1462 packet_len
+= SLL_HDR_LEN
;
1464 hdrp
= (struct sll_header
*)bp
;
1465 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(from
.sll_pkttype
);
1466 hdrp
->sll_hatype
= htons(from
.sll_hatype
);
1467 hdrp
->sll_halen
= htons(from
.sll_halen
);
1468 memcpy(hdrp
->sll_addr
, from
.sll_addr
,
1469 (from
.sll_halen
> SLL_ADDRLEN
) ?
1472 hdrp
->sll_protocol
= from
.sll_protocol
;
1475 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1476 for (cmsg
= CMSG_FIRSTHDR(&msg
); cmsg
; cmsg
= CMSG_NXTHDR(&msg
, cmsg
)) {
1477 struct tpacket_auxdata
*aux
;
1479 struct vlan_tag
*tag
;
1481 if (cmsg
->cmsg_len
< CMSG_LEN(sizeof(struct tpacket_auxdata
)) ||
1482 cmsg
->cmsg_level
!= SOL_PACKET
||
1483 cmsg
->cmsg_type
!= PACKET_AUXDATA
)
1486 aux
= (struct tpacket_auxdata
*)CMSG_DATA(cmsg
);
1487 if (aux
->tp_vlan_tci
== 0)
1490 len
= packet_len
> iov
.iov_len
? iov
.iov_len
: packet_len
;
1491 if (len
< 2 * ETH_ALEN
)
1495 memmove(bp
, bp
+ VLAN_TAG_LEN
, 2 * ETH_ALEN
);
1497 tag
= (struct vlan_tag
*)(bp
+ 2 * ETH_ALEN
);
1498 tag
->vlan_tpid
= htons(ETH_P_8021Q
);
1499 tag
->vlan_tci
= htons(aux
->tp_vlan_tci
);
1501 packet_len
+= VLAN_TAG_LEN
;
1503 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1504 #endif /* HAVE_PF_PACKET_SOCKETS */
1507 * XXX: According to the kernel source we should get the real
1508 * packet len if calling recvfrom with MSG_TRUNC set. It does
1509 * not seem to work here :(, but it is supported by this code
1511 * To be honest the code RELIES on that feature so this is really
1512 * broken with 2.2.x kernels.
1513 * I spend a day to figure out what's going on and I found out
1514 * that the following is happening:
1516 * The packet comes from a random interface and the packet_rcv
1517 * hook is called with a clone of the packet. That code inserts
1518 * the packet into the receive queue of the packet socket.
1519 * If a filter is attached to that socket that filter is run
1520 * first - and there lies the problem. The default filter always
1521 * cuts the packet at the snaplen:
1526 * So the packet filter cuts down the packet. The recvfrom call
1527 * says "hey, it's only 68 bytes, it fits into the buffer" with
1528 * the result that we don't get the real packet length. This
1529 * is valid at least until kernel 2.2.17pre6.
1531 * We currently handle this by making a copy of the filter
1532 * program, fixing all "ret" instructions with non-zero
1533 * operands to have an operand of 65535 so that the filter
1534 * doesn't truncate the packet, and supplying that modified
1535 * filter to the kernel.
1538 caplen
= packet_len
;
1539 if (caplen
> handle
->snapshot
)
1540 caplen
= handle
->snapshot
;
1542 /* Run the packet filter if not using kernel filter */
1543 if (!handle
->md
.use_bpf
&& handle
->fcode
.bf_insns
) {
1544 if (bpf_filter(handle
->fcode
.bf_insns
, bp
,
1545 packet_len
, caplen
) == 0)
1547 /* rejected by filter */
1552 /* Fill in our own header data */
1554 if (ioctl(handle
->fd
, SIOCGSTAMP
, &pcap_header
.ts
) == -1) {
1555 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1556 "SIOCGSTAMP: %s", pcap_strerror(errno
));
1559 pcap_header
.caplen
= caplen
;
1560 pcap_header
.len
= packet_len
;
1565 * Arguably, we should count them before we check the filter,
1566 * as on many other platforms "ps_recv" counts packets
1567 * handed to the filter rather than packets that passed
1568 * the filter, but if filtering is done in the kernel, we
1569 * can't get a count of packets that passed the filter,
1570 * and that would mean the meaning of "ps_recv" wouldn't
1571 * be the same on all Linux systems.
1573 * XXX - it's not the same on all systems in any case;
1574 * ideally, we should have a "get the statistics" call
1575 * that supplies more counts and indicates which of them
1576 * it supplies, so that we supply a count of packets
1577 * handed to the filter only on platforms where that
1578 * information is available.
1580 * We count them here even if we can get the packet count
1581 * from the kernel, as we can only determine at run time
1582 * whether we'll be able to get it from the kernel (if
1583 * HAVE_TPACKET_STATS isn't defined, we can't get it from
1584 * the kernel, but if it is defined, the library might
1585 * have been built with a 2.4 or later kernel, but we
1586 * might be running on a 2.2[.x] kernel without Alexey
1587 * Kuznetzov's turbopacket patches, and thus the kernel
1588 * might not be able to supply those statistics). We
1589 * could, I guess, try, when opening the socket, to get
1590 * the statistics, and if we can not increment the count
1591 * here, but it's not clear that always incrementing
1592 * the count is more expensive than always testing a flag
1595 * We keep the count in "md.packets_read", and use that for
1596 * "ps_recv" if we can't get the statistics from the kernel.
1597 * We do that because, if we *can* get the statistics from
1598 * the kernel, we use "md.stat.ps_recv" and "md.stat.ps_drop"
1599 * as running counts, as reading the statistics from the
1600 * kernel resets the kernel statistics, and if we directly
1601 * increment "md.stat.ps_recv" here, that means it will
1602 * count packets *twice* on systems where we can get kernel
1603 * statistics - once here, and once in pcap_stats_linux().
1605 handle
->md
.packets_read
++;
1607 /* Call the user supplied callback function */
1608 callback(userdata
, &pcap_header
, bp
);
1614 pcap_inject_linux(pcap_t
*handle
, const void *buf
, size_t size
)
1618 #ifdef HAVE_PF_PACKET_SOCKETS
1619 if (!handle
->md
.sock_packet
) {
1620 /* PF_PACKET socket */
1621 if (handle
->md
.ifindex
== -1) {
1623 * We don't support sending on the "any" device.
1625 strlcpy(handle
->errbuf
,
1626 "Sending packets isn't supported on the \"any\" device",
1631 if (handle
->md
.cooked
) {
1633 * We don't support sending on the "any" device.
1635 * XXX - how do you send on a bound cooked-mode
1637 * Is a "sendto()" required there?
1639 strlcpy(handle
->errbuf
,
1640 "Sending packets isn't supported in cooked mode",
1647 ret
= send(handle
->fd
, buf
, size
, 0);
1649 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "send: %s",
1650 pcap_strerror(errno
));
1657 * Get the statistics for the given packet capture handle.
1658 * Reports the number of dropped packets iff the kernel supports
1659 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
1660 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
1661 * patches); otherwise, that information isn't available, and we lie
1662 * and report 0 as the count of dropped packets.
1665 pcap_stats_linux(pcap_t
*handle
, struct pcap_stat
*stats
)
1667 #ifdef HAVE_TPACKET_STATS
1668 struct tpacket_stats kstats
;
1669 socklen_t len
= sizeof (struct tpacket_stats
);
1672 long if_dropped
= 0;
1675 * To fill in ps_ifdrop, we parse /proc/net/dev for the number
1677 if (handle
->opt
.promisc
)
1679 if_dropped
= handle
->md
.proc_dropped
;
1680 handle
->md
.proc_dropped
= linux_if_drops(handle
->md
.device
);
1681 handle
->md
.stat
.ps_ifdrop
+= (handle
->md
.proc_dropped
- if_dropped
);
1684 #ifdef HAVE_TPACKET_STATS
1686 * Try to get the packet counts from the kernel.
1688 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_STATISTICS
,
1689 &kstats
, &len
) > -1) {
1691 * On systems where the PACKET_STATISTICS "getsockopt()"
1692 * argument is supported on PF_PACKET sockets:
1694 * "ps_recv" counts only packets that *passed* the
1695 * filter, not packets that didn't pass the filter.
1696 * This includes packets later dropped because we
1697 * ran out of buffer space.
1699 * "ps_drop" counts packets dropped because we ran
1700 * out of buffer space. It doesn't count packets
1701 * dropped by the interface driver. It counts only
1702 * packets that passed the filter.
1704 * See above for ps_ifdrop.
1706 * Both statistics include packets not yet read from
1707 * the kernel by libpcap, and thus not yet seen by
1710 * In "linux/net/packet/af_packet.c", at least in the
1711 * 2.4.9 kernel, "tp_packets" is incremented for every
1712 * packet that passes the packet filter *and* is
1713 * successfully queued on the socket; "tp_drops" is
1714 * incremented for every packet dropped because there's
1715 * not enough free space in the socket buffer.
1717 * When the statistics are returned for a PACKET_STATISTICS
1718 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
1719 * so that "tp_packets" counts all packets handed to
1720 * the PF_PACKET socket, including packets dropped because
1721 * there wasn't room on the socket buffer - but not
1722 * including packets that didn't pass the filter.
1724 * In the BSD BPF, the count of received packets is
1725 * incremented for every packet handed to BPF, regardless
1726 * of whether it passed the filter.
1728 * We can't make "pcap_stats()" work the same on both
1729 * platforms, but the best approximation is to return
1730 * "tp_packets" as the count of packets and "tp_drops"
1731 * as the count of drops.
1733 * Keep a running total because each call to
1734 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
1735 * resets the counters to zero.
1737 handle
->md
.stat
.ps_recv
+= kstats
.tp_packets
;
1738 handle
->md
.stat
.ps_drop
+= kstats
.tp_drops
;
1739 *stats
= handle
->md
.stat
;
1745 * If the error was EOPNOTSUPP, fall through, so that
1746 * if you build the library on a system with
1747 * "struct tpacket_stats" and run it on a system
1748 * that doesn't, it works as it does if the library
1749 * is built on a system without "struct tpacket_stats".
1751 if (errno
!= EOPNOTSUPP
) {
1752 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1753 "pcap_stats: %s", pcap_strerror(errno
));
1759 * On systems where the PACKET_STATISTICS "getsockopt()" argument
1760 * is not supported on PF_PACKET sockets:
1762 * "ps_recv" counts only packets that *passed* the filter,
1763 * not packets that didn't pass the filter. It does not
1764 * count packets dropped because we ran out of buffer
1767 * "ps_drop" is not supported.
1769 * "ps_ifdrop" is supported. It will return the number
1770 * of drops the interface reports in /proc/net/dev,
1771 * if that is available.
1773 * "ps_recv" doesn't include packets not yet read from
1774 * the kernel by libpcap.
1776 * We maintain the count of packets processed by libpcap in
1777 * "md.packets_read", for reasons described in the comment
1778 * at the end of pcap_read_packet(). We have no idea how many
1779 * packets were dropped by the kernel buffers -- but we know
1780 * how many the interface dropped, so we can return that.
1783 stats
->ps_recv
= handle
->md
.packets_read
;
1785 stats
->ps_ifdrop
= handle
->md
.stat
.ps_ifdrop
;
1790 * Get from "/sys/class/net" all interfaces listed there; if they're
1791 * already in the list of interfaces we have, that won't add another
1792 * instance, but if they're not, that'll add them.
1794 * We don't bother getting any addresses for them; it appears you can't
1795 * use SIOCGIFADDR on Linux to get IPv6 addresses for interfaces, and,
1796 * although some other types of addresses can be fetched with SIOCGIFADDR,
1797 * we don't bother with them for now.
1799 * We also don't fail if we couldn't open "/sys/class/net"; we just leave
1800 * the list of interfaces as is, and return 0, so that we can try
1801 * scanning /proc/net/dev.
1804 scan_sys_class_net(pcap_if_t
**devlistp
, char *errbuf
)
1806 DIR *sys_class_net_d
;
1810 char name
[512]; /* XXX - pick a size */
1812 struct ifreq ifrflags
;
1815 sys_class_net_d
= opendir("/sys/class/net");
1816 if (sys_class_net_d
== NULL
&& errno
== ENOENT
)
1820 * Create a socket from which to fetch interface information.
1822 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
1824 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1825 "socket: %s", pcap_strerror(errno
));
1831 ent
= readdir(sys_class_net_d
);
1834 * Error or EOF; if errno != 0, it's an error.
1840 * Ignore directories (".", "..", and any subdirectories).
1842 if (ent
->d_type
== DT_DIR
)
1846 * Get the interface name.
1848 p
= &ent
->d_name
[0];
1850 while (*p
!= '\0' && isascii(*p
) && !isspace(*p
)) {
1853 * This could be the separator between a
1854 * name and an alias number, or it could be
1855 * the separator between a name with no
1856 * alias number and the next field.
1858 * If there's a colon after digits, it
1859 * separates the name and the alias number,
1860 * otherwise it separates the name and the
1864 while (isascii(*p
) && isdigit(*p
))
1868 * That was the next field,
1869 * not the alias number.
1880 * Get the flags for this interface, and skip it if
1883 strncpy(ifrflags
.ifr_name
, name
, sizeof(ifrflags
.ifr_name
));
1884 if (ioctl(fd
, SIOCGIFFLAGS
, (char *)&ifrflags
) < 0) {
1885 if (errno
== ENXIO
|| errno
== ENODEV
)
1887 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1888 "SIOCGIFFLAGS: %.*s: %s",
1889 (int)sizeof(ifrflags
.ifr_name
),
1891 pcap_strerror(errno
));
1895 if (!(ifrflags
.ifr_flags
& IFF_UP
))
1899 * Add an entry for this interface, with no addresses.
1901 if (pcap_add_if(devlistp
, name
, ifrflags
.ifr_flags
, NULL
,
1912 * Well, we didn't fail for any other reason; did we
1913 * fail due to an error reading the directory?
1916 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1917 "Error reading /sys/class/net: %s",
1918 pcap_strerror(errno
));
1924 (void)closedir(sys_class_net_d
);
1929 * Get from "/proc/net/dev" all interfaces listed there; if they're
1930 * already in the list of interfaces we have, that won't add another
1931 * instance, but if they're not, that'll add them.
1933 * See comments from scan_sys_class_net().
1936 scan_proc_net_dev(pcap_if_t
**devlistp
, char *errbuf
)
1943 char name
[512]; /* XXX - pick a size */
1945 struct ifreq ifrflags
;
1948 proc_net_f
= fopen("/proc/net/dev", "r");
1949 if (proc_net_f
== NULL
&& errno
== ENOENT
)
1953 * Create a socket from which to fetch interface information.
1955 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
1957 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1958 "socket: %s", pcap_strerror(errno
));
1963 fgets(linebuf
, sizeof linebuf
, proc_net_f
) != NULL
; linenum
++) {
1965 * Skip the first two lines - they're headers.
1973 * Skip leading white space.
1975 while (*p
!= '\0' && isascii(*p
) && isspace(*p
))
1977 if (*p
== '\0' || *p
== '\n')
1978 continue; /* blank line */
1981 * Get the interface name.
1984 while (*p
!= '\0' && isascii(*p
) && !isspace(*p
)) {
1987 * This could be the separator between a
1988 * name and an alias number, or it could be
1989 * the separator between a name with no
1990 * alias number and the next field.
1992 * If there's a colon after digits, it
1993 * separates the name and the alias number,
1994 * otherwise it separates the name and the
1998 while (isascii(*p
) && isdigit(*p
))
2002 * That was the next field,
2003 * not the alias number.
2014 * Get the flags for this interface, and skip it if
2017 strncpy(ifrflags
.ifr_name
, name
, sizeof(ifrflags
.ifr_name
));
2018 if (ioctl(fd
, SIOCGIFFLAGS
, (char *)&ifrflags
) < 0) {
2021 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2022 "SIOCGIFFLAGS: %.*s: %s",
2023 (int)sizeof(ifrflags
.ifr_name
),
2025 pcap_strerror(errno
));
2029 if (!(ifrflags
.ifr_flags
& IFF_UP
))
2033 * Add an entry for this interface, with no addresses.
2035 if (pcap_add_if(devlistp
, name
, ifrflags
.ifr_flags
, NULL
,
2046 * Well, we didn't fail for any other reason; did we
2047 * fail due to an error reading the file?
2049 if (ferror(proc_net_f
)) {
2050 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2051 "Error reading /proc/net/dev: %s",
2052 pcap_strerror(errno
));
2058 (void)fclose(proc_net_f
);
2063 * Description string for the "any" device.
2065 static const char any_descr
[] = "Pseudo-device that captures on all interfaces";
2068 pcap_platform_finddevs(pcap_if_t
**alldevsp
, char *errbuf
)
2073 * Read "/sys/class/net", and add to the list of interfaces all
2074 * interfaces listed there that we don't already have, because,
2075 * on Linux, SIOCGIFCONF reports only interfaces with IPv4 addresses,
2076 * and even getifaddrs() won't return information about
2077 * interfaces with no addresses, so you need to read "/sys/class/net"
2078 * to get the names of the rest of the interfaces.
2080 ret
= scan_sys_class_net(alldevsp
, errbuf
);
2082 return (-1); /* failed */
2085 * No /sys/class/net; try reading /proc/net/dev instead.
2087 if (scan_proc_net_dev(alldevsp
, errbuf
) == -1)
2092 * Add the "any" device.
2094 if (pcap_add_if(alldevsp
, "any", 0, any_descr
, errbuf
) < 0)
2101 if (dag_platform_finddevs(alldevsp
, errbuf
) < 0)
2103 #endif /* HAVE_DAG_API */
2105 #ifdef HAVE_SEPTEL_API
2107 * Add Septel devices.
2109 if (septel_platform_finddevs(alldevsp
, errbuf
) < 0)
2111 #endif /* HAVE_SEPTEL_API */
2114 if (snf_platform_finddevs(alldevsp
, errbuf
) < 0)
2116 #endif /* HAVE_SNF_API */
2118 #ifdef PCAP_SUPPORT_BT
2120 * Add Bluetooth devices.
2122 if (bt_platform_finddevs(alldevsp
, errbuf
) < 0)
2126 #ifdef PCAP_SUPPORT_USB
2130 if (usb_platform_finddevs(alldevsp
, errbuf
) < 0)
2138 * Attach the given BPF code to the packet capture device.
2141 pcap_setfilter_linux_common(pcap_t
*handle
, struct bpf_program
*filter
,
2144 #ifdef SO_ATTACH_FILTER
2145 struct sock_fprog fcode
;
2146 int can_filter_in_kernel
;
2153 strncpy(handle
->errbuf
, "setfilter: No filter specified",
2158 /* Make our private copy of the filter */
2160 if (install_bpf_program(handle
, filter
) < 0)
2161 /* install_bpf_program() filled in errbuf */
2165 * Run user level packet filter by default. Will be overriden if
2166 * installing a kernel filter succeeds.
2168 handle
->md
.use_bpf
= 0;
2170 /* Install kernel level filter if possible */
2172 #ifdef SO_ATTACH_FILTER
2174 if (handle
->fcode
.bf_len
> USHRT_MAX
) {
2176 * fcode.len is an unsigned short for current kernel.
2177 * I have yet to see BPF-Code with that much
2178 * instructions but still it is possible. So for the
2179 * sake of correctness I added this check.
2181 fprintf(stderr
, "Warning: Filter too complex for kernel\n");
2183 fcode
.filter
= NULL
;
2184 can_filter_in_kernel
= 0;
2186 #endif /* USHRT_MAX */
2189 * Oh joy, the Linux kernel uses struct sock_fprog instead
2190 * of struct bpf_program and of course the length field is
2191 * of different size. Pointed out by Sebastian
2193 * Oh, and we also need to fix it up so that all "ret"
2194 * instructions with non-zero operands have 65535 as the
2195 * operand if we're not capturing in memory-mapped modee,
2196 * and so that, if we're in cooked mode, all memory-reference
2197 * instructions use special magic offsets in references to
2198 * the link-layer header and assume that the link-layer
2199 * payload begins at 0; "fix_program()" will do that.
2201 switch (fix_program(handle
, &fcode
, is_mmapped
)) {
2206 * Fatal error; just quit.
2207 * (The "default" case shouldn't happen; we
2208 * return -1 for that reason.)
2214 * The program performed checks that we can't make
2215 * work in the kernel.
2217 can_filter_in_kernel
= 0;
2222 * We have a filter that'll work in the kernel.
2224 can_filter_in_kernel
= 1;
2229 if (can_filter_in_kernel
) {
2230 if ((err
= set_kernel_filter(handle
, &fcode
)) == 0)
2232 /* Installation succeded - using kernel filter. */
2233 handle
->md
.use_bpf
= 1;
2235 else if (err
== -1) /* Non-fatal error */
2238 * Print a warning if we weren't able to install
2239 * the filter for a reason other than "this kernel
2240 * isn't configured to support socket filters.
2242 if (errno
!= ENOPROTOOPT
&& errno
!= EOPNOTSUPP
) {
2244 "Warning: Kernel filter failed: %s\n",
2245 pcap_strerror(errno
));
2251 * If we're not using the kernel filter, get rid of any kernel
2252 * filter that might've been there before, e.g. because the
2253 * previous filter could work in the kernel, or because some other
2254 * code attached a filter to the socket by some means other than
2255 * calling "pcap_setfilter()". Otherwise, the kernel filter may
2256 * filter out packets that would pass the new userland filter.
2258 if (!handle
->md
.use_bpf
)
2259 reset_kernel_filter(handle
);
2262 * Free up the copy of the filter that was made by "fix_program()".
2264 if (fcode
.filter
!= NULL
)
2270 #endif /* SO_ATTACH_FILTER */
2276 pcap_setfilter_linux(pcap_t
*handle
, struct bpf_program
*filter
)
2278 return pcap_setfilter_linux_common(handle
, filter
, 0);
2283 * Set direction flag: Which packets do we accept on a forwarding
2284 * single device? IN, OUT or both?
2287 pcap_setdirection_linux(pcap_t
*handle
, pcap_direction_t d
)
2289 #ifdef HAVE_PF_PACKET_SOCKETS
2290 if (!handle
->md
.sock_packet
) {
2291 handle
->direction
= d
;
2296 * We're not using PF_PACKET sockets, so we can't determine
2297 * the direction of the packet.
2299 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2300 "Setting direction is not supported on SOCK_PACKET sockets");
2304 #ifdef HAVE_PF_PACKET_SOCKETS
2306 * Map the PACKET_ value to a LINUX_SLL_ value; we
2307 * want the same numerical value to be used in
2308 * the link-layer header even if the numerical values
2309 * for the PACKET_ #defines change, so that programs
2310 * that look at the packet type field will always be
2311 * able to handle DLT_LINUX_SLL captures.
2314 map_packet_type_to_sll_type(short int sll_pkttype
)
2316 switch (sll_pkttype
) {
2319 return htons(LINUX_SLL_HOST
);
2321 case PACKET_BROADCAST
:
2322 return htons(LINUX_SLL_BROADCAST
);
2324 case PACKET_MULTICAST
:
2325 return htons(LINUX_SLL_MULTICAST
);
2327 case PACKET_OTHERHOST
:
2328 return htons(LINUX_SLL_OTHERHOST
);
2330 case PACKET_OUTGOING
:
2331 return htons(LINUX_SLL_OUTGOING
);
2340 * Linux uses the ARP hardware type to identify the type of an
2341 * interface. pcap uses the DLT_xxx constants for this. This
2342 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
2343 * constant, as arguments, and sets "handle->linktype" to the
2344 * appropriate DLT_XXX constant and sets "handle->offset" to
2345 * the appropriate value (to make "handle->offset" plus link-layer
2346 * header length be a multiple of 4, so that the link-layer payload
2347 * will be aligned on a 4-byte boundary when capturing packets).
2348 * (If the offset isn't set here, it'll be 0; add code as appropriate
2349 * for cases where it shouldn't be 0.)
2351 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
2352 * in cooked mode; otherwise, we can't use cooked mode, so we have
2353 * to pick some type that works in raw mode, or fail.
2355 * Sets the link type to -1 if unable to map the type.
2357 static void map_arphrd_to_dlt(pcap_t
*handle
, int arptype
, int cooked_ok
)
2363 * This is (presumably) a real Ethernet capture; give it a
2364 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
2365 * that an application can let you choose it, in case you're
2366 * capturing DOCSIS traffic that a Cisco Cable Modem
2367 * Termination System is putting out onto an Ethernet (it
2368 * doesn't put an Ethernet header onto the wire, it puts raw
2369 * DOCSIS frames out on the wire inside the low-level
2370 * Ethernet framing).
2372 * XXX - are there any sorts of "fake Ethernet" that have
2373 * ARPHRD_ETHER but that *shouldn't offer DLT_DOCSIS as
2374 * a Cisco CMTS won't put traffic onto it or get traffic
2375 * bridged onto it? ISDN is handled in "activate_new()",
2376 * as we fall back on cooked mode there; are there any
2379 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
2381 * If that fails, just leave the list empty.
2383 if (handle
->dlt_list
!= NULL
) {
2384 handle
->dlt_list
[0] = DLT_EN10MB
;
2385 handle
->dlt_list
[1] = DLT_DOCSIS
;
2386 handle
->dlt_count
= 2;
2390 case ARPHRD_METRICOM
:
2391 case ARPHRD_LOOPBACK
:
2392 handle
->linktype
= DLT_EN10MB
;
2397 handle
->linktype
= DLT_EN3MB
;
2401 handle
->linktype
= DLT_AX25_KISS
;
2405 handle
->linktype
= DLT_PRONET
;
2409 handle
->linktype
= DLT_CHAOS
;
2412 #define ARPHRD_CAN 280
2415 handle
->linktype
= DLT_CAN_SOCKETCAN
;
2418 #ifndef ARPHRD_IEEE802_TR
2419 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
2421 case ARPHRD_IEEE802_TR
:
2422 case ARPHRD_IEEE802
:
2423 handle
->linktype
= DLT_IEEE802
;
2428 handle
->linktype
= DLT_ARCNET_LINUX
;
2431 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
2432 #define ARPHRD_FDDI 774
2435 handle
->linktype
= DLT_FDDI
;
2439 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
2440 #define ARPHRD_ATM 19
2444 * The Classical IP implementation in ATM for Linux
2445 * supports both what RFC 1483 calls "LLC Encapsulation",
2446 * in which each packet has an LLC header, possibly
2447 * with a SNAP header as well, prepended to it, and
2448 * what RFC 1483 calls "VC Based Multiplexing", in which
2449 * different virtual circuits carry different network
2450 * layer protocols, and no header is prepended to packets.
2452 * They both have an ARPHRD_ type of ARPHRD_ATM, so
2453 * you can't use the ARPHRD_ type to find out whether
2454 * captured packets will have an LLC header, and,
2455 * while there's a socket ioctl to *set* the encapsulation
2456 * type, there's no ioctl to *get* the encapsulation type.
2460 * programs that dissect Linux Classical IP frames
2461 * would have to check for an LLC header and,
2462 * depending on whether they see one or not, dissect
2463 * the frame as LLC-encapsulated or as raw IP (I
2464 * don't know whether there's any traffic other than
2465 * IP that would show up on the socket, or whether
2466 * there's any support for IPv6 in the Linux
2467 * Classical IP code);
2469 * filter expressions would have to compile into
2470 * code that checks for an LLC header and does
2473 * Both of those are a nuisance - and, at least on systems
2474 * that support PF_PACKET sockets, we don't have to put
2475 * up with those nuisances; instead, we can just capture
2476 * in cooked mode. That's what we'll do, if we can.
2477 * Otherwise, we'll just fail.
2480 handle
->linktype
= DLT_LINUX_SLL
;
2482 handle
->linktype
= -1;
2485 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
2486 #define ARPHRD_IEEE80211 801
2488 case ARPHRD_IEEE80211
:
2489 handle
->linktype
= DLT_IEEE802_11
;
2492 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
2493 #define ARPHRD_IEEE80211_PRISM 802
2495 case ARPHRD_IEEE80211_PRISM
:
2496 handle
->linktype
= DLT_PRISM_HEADER
;
2499 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
2500 #define ARPHRD_IEEE80211_RADIOTAP 803
2502 case ARPHRD_IEEE80211_RADIOTAP
:
2503 handle
->linktype
= DLT_IEEE802_11_RADIO
;
2508 * Some PPP code in the kernel supplies no link-layer
2509 * header whatsoever to PF_PACKET sockets; other PPP
2510 * code supplies PPP link-layer headers ("syncppp.c");
2511 * some PPP code might supply random link-layer
2512 * headers (PPP over ISDN - there's code in Ethereal,
2513 * for example, to cope with PPP-over-ISDN captures
2514 * with which the Ethereal developers have had to cope,
2515 * heuristically trying to determine which of the
2516 * oddball link-layer headers particular packets have).
2518 * As such, we just punt, and run all PPP interfaces
2519 * in cooked mode, if we can; otherwise, we just treat
2520 * it as DLT_RAW, for now - if somebody needs to capture,
2521 * on a 2.0[.x] kernel, on PPP devices that supply a
2522 * link-layer header, they'll have to add code here to
2523 * map to the appropriate DLT_ type (possibly adding a
2524 * new DLT_ type, if necessary).
2527 handle
->linktype
= DLT_LINUX_SLL
;
2530 * XXX - handle ISDN types here? We can't fall
2531 * back on cooked sockets, so we'd have to
2532 * figure out from the device name what type of
2533 * link-layer encapsulation it's using, and map
2534 * that to an appropriate DLT_ value, meaning
2535 * we'd map "isdnN" devices to DLT_RAW (they
2536 * supply raw IP packets with no link-layer
2537 * header) and "isdY" devices to a new DLT_I4L_IP
2538 * type that has only an Ethernet packet type as
2539 * a link-layer header.
2541 * But sometimes we seem to get random crap
2542 * in the link-layer header when capturing on
2545 handle
->linktype
= DLT_RAW
;
2549 #ifndef ARPHRD_CISCO
2550 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
2553 handle
->linktype
= DLT_C_HDLC
;
2556 /* Not sure if this is correct for all tunnels, but it
2560 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
2568 #ifndef ARPHRD_RAWHDLC
2569 #define ARPHRD_RAWHDLC 518
2571 case ARPHRD_RAWHDLC
:
2573 #define ARPHRD_DLCI 15
2577 * XXX - should some of those be mapped to DLT_LINUX_SLL
2578 * instead? Should we just map all of them to DLT_LINUX_SLL?
2580 handle
->linktype
= DLT_RAW
;
2584 #define ARPHRD_FRAD 770
2587 handle
->linktype
= DLT_FRELAY
;
2590 case ARPHRD_LOCALTLK
:
2591 handle
->linktype
= DLT_LTALK
;
2595 #define ARPHRD_FCPP 784
2599 #define ARPHRD_FCAL 785
2603 #define ARPHRD_FCPL 786
2606 #ifndef ARPHRD_FCFABRIC
2607 #define ARPHRD_FCFABRIC 787
2609 case ARPHRD_FCFABRIC
:
2611 * We assume that those all mean RFC 2625 IP-over-
2612 * Fibre Channel, with the RFC 2625 header at
2613 * the beginning of the packet.
2615 handle
->linktype
= DLT_IP_OVER_FC
;
2619 #define ARPHRD_IRDA 783
2622 /* Don't expect IP packet out of this interfaces... */
2623 handle
->linktype
= DLT_LINUX_IRDA
;
2624 /* We need to save packet direction for IrDA decoding,
2625 * so let's use "Linux-cooked" mode. Jean II */
2626 //handle->md.cooked = 1;
2629 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
2630 * is needed, please report it to <daniele@orlandi.com> */
2632 #define ARPHRD_LAPD 8445
2635 /* Don't expect IP packet out of this interfaces... */
2636 handle
->linktype
= DLT_LINUX_LAPD
;
2640 #define ARPHRD_NONE 0xFFFE
2644 * No link-layer header; packets are just IP
2645 * packets, so use DLT_RAW.
2647 handle
->linktype
= DLT_RAW
;
2650 #ifndef ARPHRD_IEEE802154
2651 #define ARPHRD_IEEE802154 804
2653 case ARPHRD_IEEE802154
:
2654 handle
->linktype
= DLT_IEEE802_15_4_NOFCS
;
2658 handle
->linktype
= -1;
2663 /* ===== Functions to interface to the newer kernels ================== */
2666 * Try to open a packet socket using the new kernel PF_PACKET interface.
2667 * Returns 1 on success, 0 on an error that means the new interface isn't
2668 * present (so the old SOCK_PACKET interface should be tried), and a
2669 * PCAP_ERROR_ value on an error that means that the old mechanism won't
2670 * work either (so it shouldn't be tried).
2673 activate_new(pcap_t
*handle
)
2675 #ifdef HAVE_PF_PACKET_SOCKETS
2676 const char *device
= handle
->opt
.source
;
2677 int is_any_device
= (strcmp(device
, "any") == 0);
2678 int sock_fd
= -1, arptype
;
2679 #ifdef HAVE_PACKET_AUXDATA
2683 struct packet_mreq mr
;
2686 * Open a socket with protocol family packet. If the
2687 * "any" device was specified, we open a SOCK_DGRAM
2688 * socket for the cooked interface, otherwise we first
2689 * try a SOCK_RAW socket for the raw interface.
2691 sock_fd
= is_any_device
?
2692 socket(PF_PACKET
, SOCK_DGRAM
, htons(ETH_P_ALL
)) :
2693 socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
));
2695 if (sock_fd
== -1) {
2696 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "socket: %s",
2697 pcap_strerror(errno
) );
2698 return 0; /* try old mechanism */
2701 /* It seems the kernel supports the new interface. */
2702 handle
->md
.sock_packet
= 0;
2705 * Get the interface index of the loopback device.
2706 * If the attempt fails, don't fail, just set the
2707 * "md.lo_ifindex" to -1.
2709 * XXX - can there be more than one device that loops
2710 * packets back, i.e. devices other than "lo"? If so,
2711 * we'd need to find them all, and have an array of
2712 * indices for them, and check all of them in
2713 * "pcap_read_packet()".
2715 handle
->md
.lo_ifindex
= iface_get_id(sock_fd
, "lo", handle
->errbuf
);
2718 * Default value for offset to align link-layer payload
2719 * on a 4-byte boundary.
2724 * What kind of frames do we have to deal with? Fall back
2725 * to cooked mode if we have an unknown interface type
2726 * or a type we know doesn't work well in raw mode.
2728 if (!is_any_device
) {
2729 /* Assume for now we don't need cooked mode. */
2730 handle
->md
.cooked
= 0;
2732 if (handle
->opt
.rfmon
) {
2734 * We were asked to turn on monitor mode.
2735 * Do so before we get the link-layer type,
2736 * because entering monitor mode could change
2737 * the link-layer type.
2739 err
= enter_rfmon_mode(handle
, sock_fd
, device
);
2747 * Nothing worked for turning monitor mode
2751 return PCAP_ERROR_RFMON_NOTSUP
;
2755 * Either monitor mode has been turned on for
2756 * the device, or we've been given a different
2757 * device to open for monitor mode. If we've
2758 * been given a different device, use it.
2760 if (handle
->md
.mondevice
!= NULL
)
2761 device
= handle
->md
.mondevice
;
2763 arptype
= iface_get_arptype(sock_fd
, device
, handle
->errbuf
);
2768 map_arphrd_to_dlt(handle
, arptype
, 1);
2769 if (handle
->linktype
== -1 ||
2770 handle
->linktype
== DLT_LINUX_SLL
||
2771 handle
->linktype
== DLT_LINUX_IRDA
||
2772 handle
->linktype
== DLT_LINUX_LAPD
||
2773 (handle
->linktype
== DLT_EN10MB
&&
2774 (strncmp("isdn", device
, 4) == 0 ||
2775 strncmp("isdY", device
, 4) == 0))) {
2777 * Unknown interface type (-1), or a
2778 * device we explicitly chose to run
2779 * in cooked mode (e.g., PPP devices),
2780 * or an ISDN device (whose link-layer
2781 * type we can only determine by using
2782 * APIs that may be different on different
2783 * kernels) - reopen in cooked mode.
2785 if (close(sock_fd
) == -1) {
2786 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2787 "close: %s", pcap_strerror(errno
));
2790 sock_fd
= socket(PF_PACKET
, SOCK_DGRAM
,
2792 if (sock_fd
== -1) {
2793 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2794 "socket: %s", pcap_strerror(errno
));
2797 handle
->md
.cooked
= 1;
2800 * Get rid of any link-layer type list
2801 * we allocated - this only supports cooked
2804 if (handle
->dlt_list
!= NULL
) {
2805 free(handle
->dlt_list
);
2806 handle
->dlt_list
= NULL
;
2807 handle
->dlt_count
= 0;
2810 if (handle
->linktype
== -1) {
2812 * Warn that we're falling back on
2813 * cooked mode; we may want to
2814 * update "map_arphrd_to_dlt()"
2815 * to handle the new type.
2817 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2819 "supported by libpcap - "
2820 "falling back to cooked "
2826 * IrDA capture is not a real "cooked" capture,
2827 * it's IrLAP frames, not IP packets. The
2828 * same applies to LAPD capture.
2830 if (handle
->linktype
!= DLT_LINUX_IRDA
&&
2831 handle
->linktype
!= DLT_LINUX_LAPD
)
2832 handle
->linktype
= DLT_LINUX_SLL
;
2835 handle
->md
.ifindex
= iface_get_id(sock_fd
, device
,
2837 if (handle
->md
.ifindex
== -1) {
2842 if ((err
= iface_bind(sock_fd
, handle
->md
.ifindex
,
2843 handle
->errbuf
)) != 1) {
2848 return 0; /* try old mechanism */
2854 if (handle
->opt
.rfmon
) {
2856 * It doesn't support monitor mode.
2858 return PCAP_ERROR_RFMON_NOTSUP
;
2862 * It uses cooked mode.
2864 handle
->md
.cooked
= 1;
2865 handle
->linktype
= DLT_LINUX_SLL
;
2868 * We're not bound to a device.
2869 * For now, we're using this as an indication
2870 * that we can't transmit; stop doing that only
2871 * if we figure out how to transmit in cooked
2874 handle
->md
.ifindex
= -1;
2878 * Select promiscuous mode on if "promisc" is set.
2880 * Do not turn allmulti mode on if we don't select
2881 * promiscuous mode - on some devices (e.g., Orinoco
2882 * wireless interfaces), allmulti mode isn't supported
2883 * and the driver implements it by turning promiscuous
2884 * mode on, and that screws up the operation of the
2885 * card as a normal networking interface, and on no
2886 * other platform I know of does starting a non-
2887 * promiscuous capture affect which multicast packets
2888 * are received by the interface.
2892 * Hmm, how can we set promiscuous mode on all interfaces?
2893 * I am not sure if that is possible at all. For now, we
2894 * silently ignore attempts to turn promiscuous mode on
2895 * for the "any" device (so you don't have to explicitly
2896 * disable it in programs such as tcpdump).
2899 if (!is_any_device
&& handle
->opt
.promisc
) {
2900 memset(&mr
, 0, sizeof(mr
));
2901 mr
.mr_ifindex
= handle
->md
.ifindex
;
2902 mr
.mr_type
= PACKET_MR_PROMISC
;
2903 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_ADD_MEMBERSHIP
,
2904 &mr
, sizeof(mr
)) == -1) {
2905 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2906 "setsockopt: %s", pcap_strerror(errno
));
2912 /* Enable auxillary data if supported and reserve room for
2913 * reconstructing VLAN headers. */
2914 #ifdef HAVE_PACKET_AUXDATA
2916 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_AUXDATA
, &val
,
2917 sizeof(val
)) == -1 && errno
!= ENOPROTOOPT
) {
2918 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2919 "setsockopt: %s", pcap_strerror(errno
));
2923 handle
->offset
+= VLAN_TAG_LEN
;
2924 #endif /* HAVE_PACKET_AUXDATA */
2927 * This is a 2.2[.x] or later kernel (we know that
2928 * because we're not using a SOCK_PACKET socket -
2929 * PF_PACKET is supported only in 2.2 and later
2932 * We can safely pass "recvfrom()" a byte count
2933 * based on the snapshot length.
2935 * If we're in cooked mode, make the snapshot length
2936 * large enough to hold a "cooked mode" header plus
2937 * 1 byte of packet data (so we don't pass a byte
2938 * count of 0 to "recvfrom()").
2940 if (handle
->md
.cooked
) {
2941 if (handle
->snapshot
< SLL_HDR_LEN
+ 1)
2942 handle
->snapshot
= SLL_HDR_LEN
+ 1;
2944 handle
->bufsize
= handle
->snapshot
;
2946 /* Save the socket FD in the pcap structure */
2947 handle
->fd
= sock_fd
;
2952 "New packet capturing interface not supported by build "
2953 "environment", PCAP_ERRBUF_SIZE
);
2959 activate_mmap(pcap_t
*handle
)
2961 #ifdef HAVE_PACKET_RING
2965 * Attempt to allocate a buffer to hold the contents of one
2966 * packet, for use by the oneshot callback.
2968 handle
->md
.oneshot_buffer
= malloc(handle
->snapshot
);
2969 if (handle
->md
.oneshot_buffer
== NULL
) {
2970 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2971 "can't allocate oneshot buffer: %s",
2972 pcap_strerror(errno
));
2976 if (handle
->opt
.buffer_size
== 0) {
2977 /* by default request 2M for the ring buffer */
2978 handle
->opt
.buffer_size
= 2*1024*1024;
2980 ret
= prepare_tpacket_socket(handle
);
2982 free(handle
->md
.oneshot_buffer
);
2985 ret
= create_ring(handle
);
2987 free(handle
->md
.oneshot_buffer
);
2991 /* override some defaults and inherit the other fields from
2993 * handle->offset is used to get the current position into the rx ring
2994 * handle->cc is used to store the ring size */
2995 handle
->read_op
= pcap_read_linux_mmap
;
2996 handle
->cleanup_op
= pcap_cleanup_linux_mmap
;
2997 handle
->setfilter_op
= pcap_setfilter_linux_mmap
;
2998 handle
->setnonblock_op
= pcap_setnonblock_mmap
;
2999 handle
->getnonblock_op
= pcap_getnonblock_mmap
;
3000 handle
->oneshot_callback
= pcap_oneshot_mmap
;
3001 handle
->selectable_fd
= handle
->fd
;
3003 #else /* HAVE_PACKET_RING */
3005 #endif /* HAVE_PACKET_RING */
3008 #ifdef HAVE_PACKET_RING
3010 prepare_tpacket_socket(pcap_t
*handle
)
3012 #ifdef HAVE_TPACKET2
3017 handle
->md
.tp_version
= TPACKET_V1
;
3018 handle
->md
.tp_hdrlen
= sizeof(struct tpacket_hdr
);
3020 #ifdef HAVE_TPACKET2
3021 /* Probe whether kernel supports TPACKET_V2 */
3024 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_HDRLEN
, &val
, &len
) < 0) {
3025 if (errno
== ENOPROTOOPT
)
3026 return 1; /* no - just drive on */
3028 /* Yes - treat as a failure. */
3029 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3030 "can't get TPACKET_V2 header len on packet socket: %s",
3031 pcap_strerror(errno
));
3034 handle
->md
.tp_hdrlen
= val
;
3037 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_VERSION
, &val
,
3039 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3040 "can't activate TPACKET_V2 on packet socket: %s",
3041 pcap_strerror(errno
));
3044 handle
->md
.tp_version
= TPACKET_V2
;
3046 /* Reserve space for VLAN tag reconstruction */
3048 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
, &val
,
3050 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3051 "can't set up reserve on packet socket: %s",
3052 pcap_strerror(errno
));
3056 #endif /* HAVE_TPACKET2 */
3061 create_ring(pcap_t
*handle
)
3063 unsigned i
, j
, frames_per_block
;
3064 struct tpacket_req req
;
3066 /* Note that with large snapshot (say 64K) only a few frames
3067 * will be available in the ring even with pretty large ring size
3068 * (and a lot of memory will be unused).
3069 * The snap len should be carefully chosen to achive best
3071 req
.tp_frame_size
= TPACKET_ALIGN(handle
->snapshot
+
3072 TPACKET_ALIGN(handle
->md
.tp_hdrlen
) +
3073 sizeof(struct sockaddr_ll
));
3074 req
.tp_frame_nr
= handle
->opt
.buffer_size
/req
.tp_frame_size
;
3076 /* compute the minumum block size that will handle this frame.
3077 * The block has to be page size aligned.
3078 * The max block size allowed by the kernel is arch-dependent and
3079 * it's not explicitly checked here. */
3080 req
.tp_block_size
= getpagesize();
3081 while (req
.tp_block_size
< req
.tp_frame_size
)
3082 req
.tp_block_size
<<= 1;
3084 frames_per_block
= req
.tp_block_size
/req
.tp_frame_size
;
3086 /* ask the kernel to create the ring */
3088 req
.tp_block_nr
= req
.tp_frame_nr
/ frames_per_block
;
3090 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
3091 req
.tp_frame_nr
= req
.tp_block_nr
* frames_per_block
;
3093 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
3094 (void *) &req
, sizeof(req
))) {
3095 if ((errno
== ENOMEM
) && (req
.tp_block_nr
> 1)) {
3097 * Memory failure; try to reduce the requested ring
3100 * We used to reduce this by half -- do 5% instead.
3101 * That may result in more iterations and a longer
3102 * startup, but the user will be much happier with
3103 * the resulting buffer size.
3105 if (req
.tp_frame_nr
< 20)
3106 req
.tp_frame_nr
-= 1;
3108 req
.tp_frame_nr
-= req
.tp_frame_nr
/20;
3111 if (errno
== ENOPROTOOPT
) {
3113 * We don't have ring buffer support in this kernel.
3117 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3118 "can't create rx ring on packet socket: %s",
3119 pcap_strerror(errno
));
3123 /* memory map the rx ring */
3124 handle
->md
.mmapbuflen
= req
.tp_block_nr
* req
.tp_block_size
;
3125 handle
->md
.mmapbuf
= mmap(0, handle
->md
.mmapbuflen
,
3126 PROT_READ
|PROT_WRITE
, MAP_SHARED
, handle
->fd
, 0);
3127 if (handle
->md
.mmapbuf
== MAP_FAILED
) {
3128 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3129 "can't mmap rx ring: %s", pcap_strerror(errno
));
3131 /* clear the allocated ring on error*/
3132 destroy_ring(handle
);
3136 /* allocate a ring for each frame header pointer*/
3137 handle
->cc
= req
.tp_frame_nr
;
3138 handle
->buffer
= malloc(handle
->cc
* sizeof(union thdr
*));
3139 if (!handle
->buffer
) {
3140 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3141 "can't allocate ring of frame headers: %s",
3142 pcap_strerror(errno
));
3144 destroy_ring(handle
);
3148 /* fill the header ring with proper frame ptr*/
3150 for (i
=0; i
<req
.tp_block_nr
; ++i
) {
3151 void *base
= &handle
->md
.mmapbuf
[i
*req
.tp_block_size
];
3152 for (j
=0; j
<frames_per_block
; ++j
, ++handle
->offset
) {
3153 RING_GET_FRAME(handle
) = base
;
3154 base
+= req
.tp_frame_size
;
3158 handle
->bufsize
= req
.tp_frame_size
;
3163 /* free all ring related resources*/
3165 destroy_ring(pcap_t
*handle
)
3167 /* tell the kernel to destroy the ring*/
3168 struct tpacket_req req
;
3169 memset(&req
, 0, sizeof(req
));
3170 setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
3171 (void *) &req
, sizeof(req
));
3173 /* if ring is mapped, unmap it*/
3174 if (handle
->md
.mmapbuf
) {
3175 /* do not test for mmap failure, as we can't recover from any error */
3176 munmap(handle
->md
.mmapbuf
, handle
->md
.mmapbuflen
);
3177 handle
->md
.mmapbuf
= NULL
;
3182 * Special one-shot callback, used for pcap_next() and pcap_next_ex(),
3183 * for Linux mmapped capture.
3185 * The problem is that pcap_next() and pcap_next_ex() expect the packet
3186 * data handed to the callback to be valid after the callback returns,
3187 * but pcap_read_linux_mmap() has to release that packet as soon as
3188 * the callback returns (otherwise, the kernel thinks there's still
3189 * at least one unprocessed packet available in the ring, so a select()
3190 * will immediately return indicating that there's data to process), so,
3191 * in the callback, we have to make a copy of the packet.
3193 * Yes, this means that, if the capture is using the ring buffer, using
3194 * pcap_next() or pcap_next_ex() requires more copies than using
3195 * pcap_loop() or pcap_dispatch(). If that bothers you, don't use
3196 * pcap_next() or pcap_next_ex().
3199 pcap_oneshot_mmap(u_char
*user
, const struct pcap_pkthdr
*h
,
3200 const u_char
*bytes
)
3202 struct oneshot_userdata
*sp
= (struct oneshot_userdata
*)user
;
3205 memcpy(sp
->pd
->md
.oneshot_buffer
, bytes
, h
->caplen
);
3206 *sp
->pkt
= sp
->pd
->md
.oneshot_buffer
;
3210 pcap_cleanup_linux_mmap( pcap_t
*handle
)
3212 destroy_ring(handle
);
3213 if (handle
->md
.oneshot_buffer
!= NULL
) {
3214 free(handle
->md
.oneshot_buffer
);
3215 handle
->md
.oneshot_buffer
= NULL
;
3217 pcap_cleanup_linux(handle
);
3222 pcap_getnonblock_mmap(pcap_t
*p
, char *errbuf
)
3224 /* use negative value of timeout to indicate non blocking ops */
3225 return (p
->md
.timeout
<0);
3229 pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
, char *errbuf
)
3231 /* map each value to the corresponding 2's complement, to
3232 * preserve the timeout value provided with pcap_set_timeout */
3234 if (p
->md
.timeout
>= 0) {
3236 * Timeout is non-negative, so we're not already
3237 * in non-blocking mode; set it to the 2's
3238 * complement, to make it negative, as an
3239 * indication that we're in non-blocking mode.
3241 p
->md
.timeout
= p
->md
.timeout
*-1 - 1;
3244 if (p
->md
.timeout
< 0) {
3246 * Timeout is negative, so we're not already
3247 * in blocking mode; reverse the previous
3248 * operation, to make the timeout non-negative
3251 p
->md
.timeout
= (p
->md
.timeout
+1)*-1;
3257 static inline union thdr
*
3258 pcap_get_ring_frame(pcap_t
*handle
, int status
)
3262 h
.raw
= RING_GET_FRAME(handle
);
3263 switch (handle
->md
.tp_version
) {
3265 if (status
!= (h
.h1
->tp_status
? TP_STATUS_USER
:
3269 #ifdef HAVE_TPACKET2
3271 if (status
!= (h
.h2
->tp_status
? TP_STATUS_USER
:
3285 pcap_read_linux_mmap(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
3292 /* wait for frames availability.*/
3293 if (!pcap_get_ring_frame(handle
, TP_STATUS_USER
)) {
3294 struct pollfd pollinfo
;
3297 pollinfo
.fd
= handle
->fd
;
3298 pollinfo
.events
= POLLIN
;
3300 if (handle
->md
.timeout
== 0)
3301 timeout
= -1; /* block forever */
3302 else if (handle
->md
.timeout
> 0)
3303 timeout
= handle
->md
.timeout
; /* block for that amount of time */
3305 timeout
= 0; /* non-blocking mode - poll to pick up errors */
3307 ret
= poll(&pollinfo
, 1, timeout
);
3308 if (ret
< 0 && errno
!= EINTR
) {
3309 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3310 "can't poll on packet socket: %s",
3311 pcap_strerror(errno
));
3313 } else if (ret
> 0 &&
3314 (pollinfo
.revents
& (POLLHUP
|POLLRDHUP
|POLLERR
|POLLNVAL
))) {
3316 * There's some indication other than
3317 * "you can read on this descriptor" on
3320 if (pollinfo
.revents
& (POLLHUP
| POLLRDHUP
)) {
3321 snprintf(handle
->errbuf
,
3323 "Hangup on packet socket");
3326 if (pollinfo
.revents
& POLLERR
) {
3328 * A recv() will give us the
3329 * actual error code.
3331 * XXX - make the socket non-blocking?
3333 if (recv(handle
->fd
, &c
, sizeof c
,
3335 continue; /* what, no error? */
3336 if (errno
== ENETDOWN
) {
3338 * The device on which we're
3339 * capturing went away.
3341 * XXX - we should really return
3342 * PCAP_ERROR_IFACE_NOT_UP,
3343 * but pcap_dispatch() etc.
3344 * aren't defined to return
3347 snprintf(handle
->errbuf
,
3349 "The interface went down");
3351 snprintf(handle
->errbuf
,
3353 "Error condition on packet socket: %s",
3358 if (pollinfo
.revents
& POLLNVAL
) {
3359 snprintf(handle
->errbuf
,
3361 "Invalid polling request on packet socket");
3365 /* check for break loop condition on interrupted syscall*/
3366 if (handle
->break_loop
) {
3367 handle
->break_loop
= 0;
3368 return PCAP_ERROR_BREAK
;
3373 /* non-positive values of max_packets are used to require all
3374 * packets currently available in the ring */
3375 while ((pkts
< max_packets
) || (max_packets
<= 0)) {
3377 struct sockaddr_ll
*sll
;
3378 struct pcap_pkthdr pcaphdr
;
3381 unsigned int tp_len
;
3382 unsigned int tp_mac
;
3383 unsigned int tp_snaplen
;
3384 unsigned int tp_sec
;
3385 unsigned int tp_usec
;
3387 h
.raw
= pcap_get_ring_frame(handle
, TP_STATUS_USER
);
3391 switch (handle
->md
.tp_version
) {
3393 tp_len
= h
.h1
->tp_len
;
3394 tp_mac
= h
.h1
->tp_mac
;
3395 tp_snaplen
= h
.h1
->tp_snaplen
;
3396 tp_sec
= h
.h1
->tp_sec
;
3397 tp_usec
= h
.h1
->tp_usec
;
3399 #ifdef HAVE_TPACKET2
3401 tp_len
= h
.h2
->tp_len
;
3402 tp_mac
= h
.h2
->tp_mac
;
3403 tp_snaplen
= h
.h2
->tp_snaplen
;
3404 tp_sec
= h
.h2
->tp_sec
;
3405 tp_usec
= h
.h2
->tp_nsec
/ 1000;
3409 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3410 "unsupported tpacket version %d",
3411 handle
->md
.tp_version
);
3414 /* perform sanity check on internal offset. */
3415 if (tp_mac
+ tp_snaplen
> handle
->bufsize
) {
3416 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3417 "corrupted frame on kernel ring mac "
3418 "offset %d + caplen %d > frame len %d",
3419 tp_mac
, tp_snaplen
, handle
->bufsize
);
3423 /* run filter on received packet
3424 * If the kernel filtering is enabled we need to run the
3425 * filter until all the frames present into the ring
3426 * at filter creation time are processed.
3427 * In such case md.use_bpf is used as a counter for the
3428 * packet we need to filter.
3429 * Note: alternatively it could be possible to stop applying
3430 * the filter when the ring became empty, but it can possibly
3431 * happen a lot later... */
3432 bp
= (unsigned char*)h
.raw
+ tp_mac
;
3433 run_bpf
= (!handle
->md
.use_bpf
) ||
3434 ((handle
->md
.use_bpf
>1) && handle
->md
.use_bpf
--);
3435 if (run_bpf
&& handle
->fcode
.bf_insns
&&
3436 (bpf_filter(handle
->fcode
.bf_insns
, bp
,
3437 tp_len
, tp_snaplen
) == 0))
3441 * Do checks based on packet direction.
3443 sll
= (void *)h
.raw
+ TPACKET_ALIGN(handle
->md
.tp_hdrlen
);
3444 if (sll
->sll_pkttype
== PACKET_OUTGOING
) {
3447 * If this is from the loopback device, reject it;
3448 * we'll see the packet as an incoming packet as well,
3449 * and we don't want to see it twice.
3451 if (sll
->sll_ifindex
== handle
->md
.lo_ifindex
)
3455 * If the user only wants incoming packets, reject it.
3457 if (handle
->direction
== PCAP_D_IN
)
3462 * If the user only wants outgoing packets, reject it.
3464 if (handle
->direction
== PCAP_D_OUT
)
3468 /* get required packet info from ring header */
3469 pcaphdr
.ts
.tv_sec
= tp_sec
;
3470 pcaphdr
.ts
.tv_usec
= tp_usec
;
3471 pcaphdr
.caplen
= tp_snaplen
;
3472 pcaphdr
.len
= tp_len
;
3474 /* if required build in place the sll header*/
3475 if (handle
->md
.cooked
) {
3476 struct sll_header
*hdrp
;
3479 * The kernel should have left us with enough
3480 * space for an sll header; back up the packet
3481 * data pointer into that space, as that'll be
3482 * the beginning of the packet we pass to the
3488 * Let's make sure that's past the end of
3489 * the tpacket header, i.e. >=
3490 * ((u_char *)thdr + TPACKET_HDRLEN), so we
3491 * don't step on the header when we construct
3494 if (bp
< (u_char
*)h
.raw
+
3495 TPACKET_ALIGN(handle
->md
.tp_hdrlen
) +
3496 sizeof(struct sockaddr_ll
)) {
3497 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3498 "cooked-mode frame doesn't have room for sll header");
3503 * OK, that worked; construct the sll header.
3505 hdrp
= (struct sll_header
*)bp
;
3506 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(
3508 hdrp
->sll_hatype
= htons(sll
->sll_hatype
);
3509 hdrp
->sll_halen
= htons(sll
->sll_halen
);
3510 memcpy(hdrp
->sll_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
3511 hdrp
->sll_protocol
= sll
->sll_protocol
;
3513 /* update packet len */
3514 pcaphdr
.caplen
+= SLL_HDR_LEN
;
3515 pcaphdr
.len
+= SLL_HDR_LEN
;
3518 #ifdef HAVE_TPACKET2
3519 if (handle
->md
.tp_version
== TPACKET_V2
&& h
.h2
->tp_vlan_tci
&&
3520 tp_snaplen
>= 2 * ETH_ALEN
) {
3521 struct vlan_tag
*tag
;
3524 memmove(bp
, bp
+ VLAN_TAG_LEN
, 2 * ETH_ALEN
);
3526 tag
= (struct vlan_tag
*)(bp
+ 2 * ETH_ALEN
);
3527 tag
->vlan_tpid
= htons(ETH_P_8021Q
);
3528 tag
->vlan_tci
= htons(h
.h2
->tp_vlan_tci
);
3530 pcaphdr
.caplen
+= VLAN_TAG_LEN
;
3531 pcaphdr
.len
+= VLAN_TAG_LEN
;
3536 * The only way to tell the kernel to cut off the
3537 * packet at a snapshot length is with a filter program;
3538 * if there's no filter program, the kernel won't cut
3541 * Trim the snapshot length to be no longer than the
3542 * specified snapshot length.
3544 if (pcaphdr
.caplen
> handle
->snapshot
)
3545 pcaphdr
.caplen
= handle
->snapshot
;
3547 /* pass the packet to the user */
3549 callback(user
, &pcaphdr
, bp
);
3550 handle
->md
.packets_read
++;
3554 switch (handle
->md
.tp_version
) {
3556 h
.h1
->tp_status
= TP_STATUS_KERNEL
;
3558 #ifdef HAVE_TPACKET2
3560 h
.h2
->tp_status
= TP_STATUS_KERNEL
;
3564 if (++handle
->offset
>= handle
->cc
)
3567 /* check for break loop condition*/
3568 if (handle
->break_loop
) {
3569 handle
->break_loop
= 0;
3570 return PCAP_ERROR_BREAK
;
3577 pcap_setfilter_linux_mmap(pcap_t
*handle
, struct bpf_program
*filter
)
3583 * Don't rewrite "ret" instructions; we don't need to, as
3584 * we're not reading packets with recvmsg(), and we don't
3585 * want to, as, by not rewriting them, the kernel can avoid
3586 * copying extra data.
3588 ret
= pcap_setfilter_linux_common(handle
, filter
, 1);
3592 /* if the kernel filter is enabled, we need to apply the filter on
3593 * all packets present into the ring. Get an upper bound of their number
3595 if (!handle
->md
.use_bpf
)
3598 /* walk the ring backward and count the free slot */
3599 offset
= handle
->offset
;
3600 if (--handle
->offset
< 0)
3601 handle
->offset
= handle
->cc
- 1;
3602 for (n
=0; n
< handle
->cc
; ++n
) {
3603 if (--handle
->offset
< 0)
3604 handle
->offset
= handle
->cc
- 1;
3605 if (!pcap_get_ring_frame(handle
, TP_STATUS_KERNEL
))
3609 /* be careful to not change current ring position */
3610 handle
->offset
= offset
;
3612 /* store the number of packets currently present in the ring */
3613 handle
->md
.use_bpf
= 1 + (handle
->cc
- n
);
3617 #endif /* HAVE_PACKET_RING */
3620 #ifdef HAVE_PF_PACKET_SOCKETS
3622 * Return the index of the given device name. Fill ebuf and return
3626 iface_get_id(int fd
, const char *device
, char *ebuf
)
3630 memset(&ifr
, 0, sizeof(ifr
));
3631 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
3633 if (ioctl(fd
, SIOCGIFINDEX
, &ifr
) == -1) {
3634 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3635 "SIOCGIFINDEX: %s", pcap_strerror(errno
));
3639 return ifr
.ifr_ifindex
;
3643 * Bind the socket associated with FD to the given device.
3644 * Return 1 on success, 0 if we should try a SOCK_PACKET socket,
3645 * or a PCAP_ERROR_ value on a hard error.
3648 iface_bind(int fd
, int ifindex
, char *ebuf
)
3650 struct sockaddr_ll sll
;
3652 socklen_t errlen
= sizeof(err
);
3654 memset(&sll
, 0, sizeof(sll
));
3655 sll
.sll_family
= AF_PACKET
;
3656 sll
.sll_ifindex
= ifindex
;
3657 sll
.sll_protocol
= htons(ETH_P_ALL
);
3659 if (bind(fd
, (struct sockaddr
*) &sll
, sizeof(sll
)) == -1) {
3660 if (errno
== ENETDOWN
) {
3662 * Return a "network down" indication, so that
3663 * the application can report that rather than
3664 * saying we had a mysterious failure and
3665 * suggest that they report a problem to the
3666 * libpcap developers.
3668 return PCAP_ERROR_IFACE_NOT_UP
;
3670 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3671 "bind: %s", pcap_strerror(errno
));
3676 /* Any pending errors, e.g., network is down? */
3678 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
3679 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3680 "getsockopt: %s", pcap_strerror(errno
));
3684 if (err
== ENETDOWN
) {
3686 * Return a "network down" indication, so that
3687 * the application can report that rather than
3688 * saying we had a mysterious failure and
3689 * suggest that they report a problem to the
3690 * libpcap developers.
3692 return PCAP_ERROR_IFACE_NOT_UP
;
3693 } else if (err
> 0) {
3694 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3695 "bind: %s", pcap_strerror(err
));
3702 #ifdef IW_MODE_MONITOR
3704 * Check whether the device supports the Wireless Extensions.
3705 * Returns 1 if it does, 0 if it doesn't, PCAP_ERROR_NO_SUCH_DEVICE
3706 * if the device doesn't even exist.
3709 has_wext(int sock_fd
, const char *device
, char *ebuf
)
3713 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3714 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3715 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3716 if (ioctl(sock_fd
, SIOCGIWNAME
, &ireq
) >= 0)
3718 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3719 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
3720 if (errno
== ENODEV
)
3721 return PCAP_ERROR_NO_SUCH_DEVICE
;
3726 * Per me si va ne la citta dolente,
3727 * Per me si va ne l'etterno dolore,
3729 * Lasciate ogne speranza, voi ch'intrate.
3731 * XXX - airmon-ng does special stuff with the Orinoco driver and the
3747 * Use the Wireless Extensions, if we have them, to try to turn monitor mode
3748 * on if it's not already on.
3750 * Returns 1 on success, 0 if we don't support the Wireless Extensions
3751 * on this device, or a PCAP_ERROR_ value if we do support them but
3752 * we weren't able to turn monitor mode on.
3755 enter_rfmon_mode_wext(pcap_t
*handle
, int sock_fd
, const char *device
)
3758 * XXX - at least some adapters require non-Wireless Extensions
3759 * mechanisms to turn monitor mode on.
3761 * Atheros cards might require that a separate "monitor virtual access
3762 * point" be created, with later versions of the madwifi driver.
3763 * airmon-ng does "wlanconfig ath create wlandev {if} wlanmode
3764 * monitor -bssid", which apparently spits out a line "athN"
3765 * where "athN" is the monitor mode device. To leave monitor
3766 * mode, it destroys the monitor mode device.
3768 * Some Intel Centrino adapters might require private ioctls to get
3769 * radio headers; the ipw2200 and ipw3945 drivers allow you to
3770 * configure a separate "rtapN" interface to capture in monitor
3771 * mode without preventing the adapter from operating normally.
3772 * (airmon-ng doesn't appear to use that, though.)
3774 * It would be Truly Wonderful if mac80211 and nl80211 cleaned this
3775 * up, and if all drivers were converted to mac80211 drivers.
3777 * If interface {if} is a mac80211 driver, the file
3778 * /sys/class/net/{if}/phy80211 is a symlink to
3779 * /sys/class/ieee80211/{phydev}, for some {phydev}.
3781 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
3782 * least, has a "wmaster0" device and a "wlan0" device; the
3783 * latter is the one with the IP address. Both show up in
3784 * "tcpdump -D" output. Capturing on the wmaster0 device
3785 * captures with 802.11 headers.
3787 * airmon-ng searches through /sys/class/net for devices named
3788 * monN, starting with mon0; as soon as one *doesn't* exist,
3789 * it chooses that as the monitor device name. If the "iw"
3790 * command exists, it does "iw dev {if} interface add {monif}
3791 * type monitor", where {monif} is the monitor device. It
3792 * then (sigh) sleeps .1 second, and then configures the
3793 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
3794 * is a file, it writes {mondev}, without a newline, to that file,
3795 * and again (sigh) sleeps .1 second, and then iwconfig's that
3796 * device into monitor mode and configures it up. Otherwise,
3797 * you can't do monitor mode.
3799 * All these devices are "glued" together by having the
3800 * /sys/class/net/{device}/phy80211 links pointing to the same
3801 * place, so, given a wmaster, wlan, or mon device, you can
3802 * find the other devices by looking for devices with
3803 * the same phy80211 link.
3805 * To turn monitor mode off, delete the monitor interface,
3806 * either with "iw dev {monif} interface del" or by sending
3807 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
3809 * Note: if you try to create a monitor device named "monN", and
3810 * there's already a "monN" device, it fails, as least with
3811 * the netlink interface (which is what iw uses), with a return
3812 * value of -ENFILE. (Return values are negative errnos.) We
3813 * could probably use that to find an unused device.
3817 struct iw_priv_args
*priv
;
3818 monitor_type montype
;
3825 * Does this device *support* the Wireless Extensions?
3827 err
= has_wext(sock_fd
, device
, handle
->errbuf
);
3829 return err
; /* either it doesn't or the device doesn't even exist */
3831 * Try to get all the Wireless Extensions private ioctls
3832 * supported by this device.
3834 * First, get the size of the buffer we need, by supplying no
3835 * buffer and a length of 0. If the device supports private
3836 * ioctls, it should return E2BIG, with ireq.u.data.length set
3837 * to the length we need. If it doesn't support them, it should
3838 * return EOPNOTSUPP.
3840 memset(&ireq
, 0, sizeof ireq
);
3841 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3842 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3843 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3844 ireq
.u
.data
.pointer
= (void *)args
;
3845 ireq
.u
.data
.length
= 0;
3846 ireq
.u
.data
.flags
= 0;
3847 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) != -1) {
3848 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3849 "%s: SIOCGIWPRIV with a zero-length buffer didn't fail!",
3853 if (errno
== EOPNOTSUPP
) {
3855 * No private ioctls, so we assume that there's only one
3856 * DLT_ for monitor mode.
3860 if (errno
!= E2BIG
) {
3864 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3865 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
3868 priv
= malloc(ireq
.u
.data
.length
* sizeof (struct iw_priv_args
));
3870 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3871 "malloc: %s", pcap_strerror(errno
));
3874 ireq
.u
.data
.pointer
= (void *)priv
;
3875 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) == -1) {
3876 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3877 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
3883 * Look for private ioctls to turn monitor mode on or, if
3884 * monitor mode is on, to set the header type.
3886 montype
= MONITOR_WEXT
;
3888 for (i
= 0; i
< ireq
.u
.data
.length
; i
++) {
3889 if (strcmp(priv
[i
].name
, "monitor_type") == 0) {
3891 * Hostap driver, use this one.
3892 * Set monitor mode first.
3893 * You can set it to 0 to get DLT_IEEE80211,
3894 * 1 to get DLT_PRISM, 2 to get
3895 * DLT_IEEE80211_RADIO_AVS, and, with more
3896 * recent versions of the driver, 3 to get
3897 * DLT_IEEE80211_RADIO.
3899 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
3901 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
3903 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
3905 montype
= MONITOR_HOSTAP
;
3909 if (strcmp(priv
[i
].name
, "set_prismhdr") == 0) {
3911 * Prism54 driver, use this one.
3912 * Set monitor mode first.
3913 * You can set it to 2 to get DLT_IEEE80211
3914 * or 3 or get DLT_PRISM.
3916 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
3918 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
3920 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
3922 montype
= MONITOR_PRISM54
;
3926 if (strcmp(priv
[i
].name
, "forceprismheader") == 0) {
3928 * RT2570 driver, use this one.
3929 * Do this after turning monitor mode on.
3930 * You can set it to 1 to get DLT_PRISM or 2
3931 * to get DLT_IEEE80211.
3933 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
3935 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
3937 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
3939 montype
= MONITOR_RT2570
;
3943 if (strcmp(priv
[i
].name
, "forceprism") == 0) {
3945 * RT73 driver, use this one.
3946 * Do this after turning monitor mode on.
3947 * Its argument is a *string*; you can
3948 * set it to "1" to get DLT_PRISM or "2"
3949 * to get DLT_IEEE80211.
3951 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_CHAR
)
3953 if (priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
)
3955 montype
= MONITOR_RT73
;
3959 if (strcmp(priv
[i
].name
, "prismhdr") == 0) {
3961 * One of the RTL8xxx drivers, use this one.
3962 * It can only be done after monitor mode
3963 * has been turned on. You can set it to 1
3964 * to get DLT_PRISM or 0 to get DLT_IEEE80211.
3966 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
3968 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
3970 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
3972 montype
= MONITOR_RTL8XXX
;
3976 if (strcmp(priv
[i
].name
, "rfmontx") == 0) {
3978 * RT2500 or RT61 driver, use this one.
3979 * It has one one-byte parameter; set
3980 * u.data.length to 1 and u.data.pointer to
3981 * point to the parameter.
3982 * It doesn't itself turn monitor mode on.
3983 * You can set it to 1 to allow transmitting
3984 * in monitor mode(?) and get DLT_IEEE80211,
3985 * or set it to 0 to disallow transmitting in
3986 * monitor mode(?) and get DLT_PRISM.
3988 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
3990 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 2)
3992 montype
= MONITOR_RT2500
;
3996 if (strcmp(priv
[i
].name
, "monitor") == 0) {
3998 * Either ACX100 or hostap, use this one.
3999 * It turns monitor mode on.
4000 * If it takes two arguments, it's ACX100;
4001 * the first argument is 1 for DLT_PRISM
4002 * or 2 for DLT_IEEE80211, and the second
4003 * argument is the channel on which to
4004 * run. If it takes one argument, it's
4005 * HostAP, and the argument is 2 for
4006 * DLT_IEEE80211 and 3 for DLT_PRISM.
4008 * If we see this, we don't quit, as this
4009 * might be a version of the hostap driver
4010 * that also supports "monitor_type".
4012 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4014 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4016 switch (priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) {
4019 montype
= MONITOR_PRISM
;
4024 montype
= MONITOR_ACX100
;
4036 * XXX - ipw3945? islism?
4042 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4043 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4044 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4045 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) == -1) {
4047 * We probably won't be able to set the mode, either.
4049 return PCAP_ERROR_RFMON_NOTSUP
;
4053 * Is it currently in monitor mode?
4055 if (ireq
.u
.mode
== IW_MODE_MONITOR
) {
4057 * Yes. Just leave things as they are.
4058 * We don't offer multiple link-layer types, as
4059 * changing the link-layer type out from under
4060 * somebody else capturing in monitor mode would
4061 * be considered rude.
4066 * No. We have to put the adapter into rfmon mode.
4070 * If we haven't already done so, arrange to have
4071 * "pcap_close_all()" called when we exit.
4073 if (!pcap_do_addexit(handle
)) {
4075 * "atexit()" failed; don't put the interface
4076 * in rfmon mode, just give up.
4078 return PCAP_ERROR_RFMON_NOTSUP
;
4082 * Save the old mode.
4084 handle
->md
.oldmode
= ireq
.u
.mode
;
4087 * Put the adapter in rfmon mode. How we do this depends
4088 * on whether we have a special private ioctl or not.
4090 if (montype
== MONITOR_PRISM
) {
4092 * We have the "monitor" private ioctl, but none of
4093 * the other private ioctls. Use this, and select
4096 * If it fails, just fall back on SIOCSIWMODE.
4098 memset(&ireq
, 0, sizeof ireq
);
4099 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4100 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4101 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4102 ireq
.u
.data
.length
= 1; /* 1 argument */
4103 args
[0] = 3; /* request Prism header */
4104 memcpy(ireq
.u
.name
, args
, IFNAMSIZ
);
4105 if (ioctl(sock_fd
, cmd
, &ireq
) != -1) {
4108 * Note that we have to put the old mode back
4109 * when we close the device.
4111 handle
->md
.must_do_on_close
|= MUST_CLEAR_RFMON
;
4114 * Add this to the list of pcaps to close
4117 pcap_add_to_pcaps_to_close(handle
);
4123 * Failure. Fall back on SIOCSIWMODE.
4128 * First, turn monitor mode on.
4130 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4131 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4132 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4133 ireq
.u
.mode
= IW_MODE_MONITOR
;
4134 if (ioctl(sock_fd
, SIOCSIWMODE
, &ireq
) == -1) {
4136 * Scientist, you've failed.
4138 return PCAP_ERROR_RFMON_NOTSUP
;
4142 * XXX - airmon-ng does "iwconfig {if} key off" after setting
4143 * monitor mode and setting the channel, and then does
4148 * Now select the appropriate radio header.
4154 * We don't have any private ioctl to set the header.
4158 case MONITOR_HOSTAP
:
4160 * Try to select the radiotap header.
4162 memset(&ireq
, 0, sizeof ireq
);
4163 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4164 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4165 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4166 args
[0] = 3; /* request radiotap header */
4167 memcpy(ireq
.u
.name
, args
, sizeof (int));
4168 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
4169 break; /* success */
4172 * That failed. Try to select the AVS header.
4174 memset(&ireq
, 0, sizeof ireq
);
4175 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4176 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4177 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4178 args
[0] = 2; /* request AVS header */
4179 memcpy(ireq
.u
.name
, args
, sizeof (int));
4180 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
4181 break; /* success */
4184 * That failed. Try to select the Prism header.
4186 memset(&ireq
, 0, sizeof ireq
);
4187 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4188 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4189 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4190 args
[0] = 1; /* request Prism header */
4191 memcpy(ireq
.u
.name
, args
, sizeof (int));
4192 ioctl(sock_fd
, cmd
, &ireq
);
4197 * The private ioctl failed.
4201 case MONITOR_PRISM54
:
4203 * Select the Prism header.
4205 memset(&ireq
, 0, sizeof ireq
);
4206 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4207 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4208 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4209 args
[0] = 3; /* request Prism header */
4210 memcpy(ireq
.u
.name
, args
, sizeof (int));
4211 ioctl(sock_fd
, cmd
, &ireq
);
4214 case MONITOR_ACX100
:
4216 * Get the current channel.
4218 memset(&ireq
, 0, sizeof ireq
);
4219 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4220 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4221 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4222 if (ioctl(sock_fd
, SIOCGIWFREQ
, &ireq
) == -1) {
4223 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4224 "%s: SIOCGIWFREQ: %s", device
,
4225 pcap_strerror(errno
));
4228 channel
= ireq
.u
.freq
.m
;
4231 * Select the Prism header, and set the channel to the
4234 memset(&ireq
, 0, sizeof ireq
);
4235 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4236 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4237 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4238 args
[0] = 1; /* request Prism header */
4239 args
[1] = channel
; /* set channel */
4240 memcpy(ireq
.u
.name
, args
, 2*sizeof (int));
4241 ioctl(sock_fd
, cmd
, &ireq
);
4244 case MONITOR_RT2500
:
4246 * Disallow transmission - that turns on the
4249 memset(&ireq
, 0, sizeof ireq
);
4250 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4251 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4252 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4253 args
[0] = 0; /* disallow transmitting */
4254 memcpy(ireq
.u
.name
, args
, sizeof (int));
4255 ioctl(sock_fd
, cmd
, &ireq
);
4258 case MONITOR_RT2570
:
4260 * Force the Prism header.
4262 memset(&ireq
, 0, sizeof ireq
);
4263 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4264 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4265 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4266 args
[0] = 1; /* request Prism header */
4267 memcpy(ireq
.u
.name
, args
, sizeof (int));
4268 ioctl(sock_fd
, cmd
, &ireq
);
4273 * Force the Prism header.
4275 memset(&ireq
, 0, sizeof ireq
);
4276 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4277 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4278 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4279 ireq
.u
.data
.length
= 1; /* 1 argument */
4280 ireq
.u
.data
.pointer
= "1";
4281 ireq
.u
.data
.flags
= 0;
4282 ioctl(sock_fd
, cmd
, &ireq
);
4285 case MONITOR_RTL8XXX
:
4287 * Force the Prism header.
4289 memset(&ireq
, 0, sizeof ireq
);
4290 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4291 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4292 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4293 args
[0] = 1; /* request Prism header */
4294 memcpy(ireq
.u
.name
, args
, sizeof (int));
4295 ioctl(sock_fd
, cmd
, &ireq
);
4300 * Note that we have to put the old mode back when we
4303 handle
->md
.must_do_on_close
|= MUST_CLEAR_RFMON
;
4306 * Add this to the list of pcaps to close when we exit.
4308 pcap_add_to_pcaps_to_close(handle
);
4312 #endif /* IW_MODE_MONITOR */
4315 * Try various mechanisms to enter monitor mode.
4318 enter_rfmon_mode(pcap_t
*handle
, int sock_fd
, const char *device
)
4320 #if defined(HAVE_LIBNL) || defined(IW_MODE_MONITOR)
4325 ret
= enter_rfmon_mode_mac80211(handle
, sock_fd
, device
);
4327 return ret
; /* error attempting to do so */
4329 return 1; /* success */
4330 #endif /* HAVE_LIBNL */
4332 #ifdef IW_MODE_MONITOR
4333 ret
= enter_rfmon_mode_wext(handle
, sock_fd
, device
);
4335 return ret
; /* error attempting to do so */
4337 return 1; /* success */
4338 #endif /* IW_MODE_MONITOR */
4341 * Either none of the mechanisms we know about work or none
4342 * of those mechanisms are available, so we can't do monitor
4348 #endif /* HAVE_PF_PACKET_SOCKETS */
4350 /* ===== Functions to interface to the older kernels ================== */
4353 * Try to open a packet socket using the old kernel interface.
4354 * Returns 1 on success and a PCAP_ERROR_ value on an error.
4357 activate_old(pcap_t
*handle
)
4361 const char *device
= handle
->opt
.source
;
4362 struct utsname utsname
;
4365 /* Open the socket */
4367 handle
->fd
= socket(PF_INET
, SOCK_PACKET
, htons(ETH_P_ALL
));
4368 if (handle
->fd
== -1) {
4369 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4370 "socket: %s", pcap_strerror(errno
));
4371 return PCAP_ERROR_PERM_DENIED
;
4374 /* It worked - we are using the old interface */
4375 handle
->md
.sock_packet
= 1;
4377 /* ...which means we get the link-layer header. */
4378 handle
->md
.cooked
= 0;
4380 /* Bind to the given device */
4382 if (strcmp(device
, "any") == 0) {
4383 strncpy(handle
->errbuf
, "pcap_activate: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
4387 if (iface_bind_old(handle
->fd
, device
, handle
->errbuf
) == -1)
4391 * Try to get the link-layer type.
4393 arptype
= iface_get_arptype(handle
->fd
, device
, handle
->errbuf
);
4398 * Try to find the DLT_ type corresponding to that
4401 map_arphrd_to_dlt(handle
, arptype
, 0);
4402 if (handle
->linktype
== -1) {
4403 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4404 "unknown arptype %d", arptype
);
4408 /* Go to promisc mode if requested */
4410 if (handle
->opt
.promisc
) {
4411 memset(&ifr
, 0, sizeof(ifr
));
4412 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4413 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
4414 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4415 "SIOCGIFFLAGS: %s", pcap_strerror(errno
));
4418 if ((ifr
.ifr_flags
& IFF_PROMISC
) == 0) {
4420 * Promiscuous mode isn't currently on,
4421 * so turn it on, and remember that
4422 * we should turn it off when the
4427 * If we haven't already done so, arrange
4428 * to have "pcap_close_all()" called when
4431 if (!pcap_do_addexit(handle
)) {
4433 * "atexit()" failed; don't put
4434 * the interface in promiscuous
4435 * mode, just give up.
4440 ifr
.ifr_flags
|= IFF_PROMISC
;
4441 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
4442 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4444 pcap_strerror(errno
));
4447 handle
->md
.must_do_on_close
|= MUST_CLEAR_PROMISC
;
4450 * Add this to the list of pcaps
4451 * to close when we exit.
4453 pcap_add_to_pcaps_to_close(handle
);
4458 * Compute the buffer size.
4460 * We're using SOCK_PACKET, so this might be a 2.0[.x]
4461 * kernel, and might require special handling - check.
4463 if (uname(&utsname
) < 0 ||
4464 strncmp(utsname
.release
, "2.0", 3) == 0) {
4466 * Either we couldn't find out what kernel release
4467 * this is, or it's a 2.0[.x] kernel.
4469 * In the 2.0[.x] kernel, a "recvfrom()" on
4470 * a SOCK_PACKET socket, with MSG_TRUNC set, will
4471 * return the number of bytes read, so if we pass
4472 * a length based on the snapshot length, it'll
4473 * return the number of bytes from the packet
4474 * copied to userland, not the actual length
4477 * This means that, for example, the IP dissector
4478 * in tcpdump will get handed a packet length less
4479 * than the length in the IP header, and will
4480 * complain about "truncated-ip".
4482 * So we don't bother trying to copy from the
4483 * kernel only the bytes in which we're interested,
4484 * but instead copy them all, just as the older
4485 * versions of libpcap for Linux did.
4487 * The buffer therefore needs to be big enough to
4488 * hold the largest packet we can get from this
4489 * device. Unfortunately, we can't get the MRU
4490 * of the network; we can only get the MTU. The
4491 * MTU may be too small, in which case a packet larger
4492 * than the buffer size will be truncated *and* we
4493 * won't get the actual packet size.
4495 * However, if the snapshot length is larger than
4496 * the buffer size based on the MTU, we use the
4497 * snapshot length as the buffer size, instead;
4498 * this means that with a sufficiently large snapshot
4499 * length we won't artificially truncate packets
4500 * to the MTU-based size.
4502 * This mess just one of many problems with packet
4503 * capture on 2.0[.x] kernels; you really want a
4504 * 2.2[.x] or later kernel if you want packet capture
4507 mtu
= iface_get_mtu(handle
->fd
, device
, handle
->errbuf
);
4510 handle
->bufsize
= MAX_LINKHEADER_SIZE
+ mtu
;
4511 if (handle
->bufsize
< handle
->snapshot
)
4512 handle
->bufsize
= handle
->snapshot
;
4515 * This is a 2.2[.x] or later kernel.
4517 * We can safely pass "recvfrom()" a byte count
4518 * based on the snapshot length.
4520 handle
->bufsize
= handle
->snapshot
;
4524 * Default value for offset to align link-layer payload
4525 * on a 4-byte boundary.
4533 * Bind the socket associated with FD to the given device using the
4534 * interface of the old kernels.
4537 iface_bind_old(int fd
, const char *device
, char *ebuf
)
4539 struct sockaddr saddr
;
4541 socklen_t errlen
= sizeof(err
);
4543 memset(&saddr
, 0, sizeof(saddr
));
4544 strncpy(saddr
.sa_data
, device
, sizeof(saddr
.sa_data
));
4545 if (bind(fd
, &saddr
, sizeof(saddr
)) == -1) {
4546 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4547 "bind: %s", pcap_strerror(errno
));
4551 /* Any pending errors, e.g., network is down? */
4553 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
4554 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4555 "getsockopt: %s", pcap_strerror(errno
));
4560 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4561 "bind: %s", pcap_strerror(err
));
4569 /* ===== System calls available on all supported kernels ============== */
4572 * Query the kernel for the MTU of the given interface.
4575 iface_get_mtu(int fd
, const char *device
, char *ebuf
)
4580 return BIGGER_THAN_ALL_MTUS
;
4582 memset(&ifr
, 0, sizeof(ifr
));
4583 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4585 if (ioctl(fd
, SIOCGIFMTU
, &ifr
) == -1) {
4586 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4587 "SIOCGIFMTU: %s", pcap_strerror(errno
));
4595 * Get the hardware type of the given interface as ARPHRD_xxx constant.
4598 iface_get_arptype(int fd
, const char *device
, char *ebuf
)
4602 memset(&ifr
, 0, sizeof(ifr
));
4603 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4605 if (ioctl(fd
, SIOCGIFHWADDR
, &ifr
) == -1) {
4606 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4607 "SIOCGIFHWADDR: %s", pcap_strerror(errno
));
4608 if (errno
== ENODEV
) {
4612 return PCAP_ERROR_NO_SUCH_DEVICE
;
4617 return ifr
.ifr_hwaddr
.sa_family
;
4620 #ifdef SO_ATTACH_FILTER
4622 fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
, int is_mmapped
)
4626 register struct bpf_insn
*p
;
4631 * Make a copy of the filter, and modify that copy if
4634 prog_size
= sizeof(*handle
->fcode
.bf_insns
) * handle
->fcode
.bf_len
;
4635 len
= handle
->fcode
.bf_len
;
4636 f
= (struct bpf_insn
*)malloc(prog_size
);
4638 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4639 "malloc: %s", pcap_strerror(errno
));
4642 memcpy(f
, handle
->fcode
.bf_insns
, prog_size
);
4644 fcode
->filter
= (struct sock_filter
*) f
;
4646 for (i
= 0; i
< len
; ++i
) {
4649 * What type of instruction is this?
4651 switch (BPF_CLASS(p
->code
)) {
4655 * It's a return instruction; are we capturing
4656 * in memory-mapped mode?
4660 * No; is the snapshot length a constant,
4661 * rather than the contents of the
4664 if (BPF_MODE(p
->code
) == BPF_K
) {
4666 * Yes - if the value to be returned,
4667 * i.e. the snapshot length, is
4668 * anything other than 0, make it
4669 * 65535, so that the packet is
4670 * truncated by "recvfrom()",
4671 * not by the filter.
4673 * XXX - there's nothing we can
4674 * easily do if it's getting the
4675 * value from the accumulator; we'd
4676 * have to insert code to force
4677 * non-zero values to be 65535.
4688 * It's a load instruction; is it loading
4691 switch (BPF_MODE(p
->code
)) {
4697 * Yes; are we in cooked mode?
4699 if (handle
->md
.cooked
) {
4701 * Yes, so we need to fix this
4704 if (fix_offset(p
) < 0) {
4706 * We failed to do so.
4707 * Return 0, so our caller
4708 * knows to punt to userland.
4718 return 1; /* we succeeded */
4722 fix_offset(struct bpf_insn
*p
)
4725 * What's the offset?
4727 if (p
->k
>= SLL_HDR_LEN
) {
4729 * It's within the link-layer payload; that starts at an
4730 * offset of 0, as far as the kernel packet filter is
4731 * concerned, so subtract the length of the link-layer
4734 p
->k
-= SLL_HDR_LEN
;
4735 } else if (p
->k
== 14) {
4737 * It's the protocol field; map it to the special magic
4738 * kernel offset for that field.
4740 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
4743 * It's within the header, but it's not one of those
4744 * fields; we can't do that in the kernel, so punt
4753 set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
)
4755 int total_filter_on
= 0;
4761 * The socket filter code doesn't discard all packets queued
4762 * up on the socket when the filter is changed; this means
4763 * that packets that don't match the new filter may show up
4764 * after the new filter is put onto the socket, if those
4765 * packets haven't yet been read.
4767 * This means, for example, that if you do a tcpdump capture
4768 * with a filter, the first few packets in the capture might
4769 * be packets that wouldn't have passed the filter.
4771 * We therefore discard all packets queued up on the socket
4772 * when setting a kernel filter. (This isn't an issue for
4773 * userland filters, as the userland filtering is done after
4774 * packets are queued up.)
4776 * To flush those packets, we put the socket in read-only mode,
4777 * and read packets from the socket until there are no more to
4780 * In order to keep that from being an infinite loop - i.e.,
4781 * to keep more packets from arriving while we're draining
4782 * the queue - we put the "total filter", which is a filter
4783 * that rejects all packets, onto the socket before draining
4786 * This code deliberately ignores any errors, so that you may
4787 * get bogus packets if an error occurs, rather than having
4788 * the filtering done in userland even if it could have been
4789 * done in the kernel.
4791 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
4792 &total_fcode
, sizeof(total_fcode
)) == 0) {
4796 * Note that we've put the total filter onto the socket.
4798 total_filter_on
= 1;
4801 * Save the socket's current mode, and put it in
4802 * non-blocking mode; we drain it by reading packets
4803 * until we get an error (which is normally a
4804 * "nothing more to be read" error).
4806 save_mode
= fcntl(handle
->fd
, F_GETFL
, 0);
4807 if (save_mode
!= -1 &&
4808 fcntl(handle
->fd
, F_SETFL
, save_mode
| O_NONBLOCK
) >= 0) {
4809 while (recv(handle
->fd
, &drain
, sizeof drain
,
4813 fcntl(handle
->fd
, F_SETFL
, save_mode
);
4814 if (save_errno
!= EAGAIN
) {
4816 reset_kernel_filter(handle
);
4817 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4818 "recv: %s", pcap_strerror(save_errno
));
4825 * Now attach the new filter.
4827 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
4828 fcode
, sizeof(*fcode
));
4829 if (ret
== -1 && total_filter_on
) {
4831 * Well, we couldn't set that filter on the socket,
4832 * but we could set the total filter on the socket.
4834 * This could, for example, mean that the filter was
4835 * too big to put into the kernel, so we'll have to
4836 * filter in userland; in any case, we'll be doing
4837 * filtering in userland, so we need to remove the
4838 * total filter so we see packets.
4843 * XXX - if this fails, we're really screwed;
4844 * we have the total filter on the socket,
4845 * and it won't come off. What do we do then?
4847 reset_kernel_filter(handle
);
4855 reset_kernel_filter(pcap_t
*handle
)
4858 * setsockopt() barfs unless it get a dummy parameter.
4859 * valgrind whines unless the value is initialized,
4860 * as it has no idea that setsockopt() ignores its
4865 return setsockopt(handle
->fd
, SOL_SOCKET
, SO_DETACH_FILTER
,
4866 &dummy
, sizeof(dummy
));