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
;
420 * If interface {if} is a mac80211 driver, the file
421 * /sys/class/net/{if}/phy80211 is a symlink to
422 * /sys/class/ieee80211/{phydev}, for some {phydev}.
424 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
425 * least, has a "wmaster0" device and a "wlan0" device; the
426 * latter is the one with the IP address. Both show up in
427 * "tcpdump -D" output. Capturing on the wmaster0 device
428 * captures with 802.11 headers.
430 * airmon-ng searches through /sys/class/net for devices named
431 * monN, starting with mon0; as soon as one *doesn't* exist,
432 * it chooses that as the monitor device name. If the "iw"
433 * command exists, it does "iw dev {if} interface add {monif}
434 * type monitor", where {monif} is the monitor device. It
435 * then (sigh) sleeps .1 second, and then configures the
436 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
437 * is a file, it writes {mondev}, without a newline, to that file,
438 * and again (sigh) sleeps .1 second, and then iwconfig's that
439 * device into monitor mode and configures it up. Otherwise,
440 * you can't do monitor mode.
442 * All these devices are "glued" together by having the
443 * /sys/class/net/{device}/phy80211 links pointing to the same
444 * place, so, given a wmaster, wlan, or mon device, you can
445 * find the other devices by looking for devices with
446 * the same phy80211 link.
448 * To turn monitor mode off, delete the monitor interface,
449 * either with "iw dev {monif} interface del" or by sending
450 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
452 * Note: if you try to create a monitor device named "monN", and
453 * there's already a "monN" device, it fails, as least with
454 * the netlink interface (which is what iw uses), with a return
455 * value of -ENFILE. (Return values are negative errnos.) We
456 * could probably use that to find an unused device.
458 * Yes, you can have multiple monitor devices for a given
463 * Is this a mac80211 device? If so, fill in the physical device path and
464 * return 1; if not, return 0. On an error, fill in handle->errbuf and
468 get_mac80211_phydev(pcap_t
*handle
, const char *device
, char *phydev_path
,
469 size_t phydev_max_pathlen
)
475 * Generate the path string for the symlink to the physical device.
477 if (asprintf(&pathstr
, "/sys/class/net/%s/phy80211", device
) == -1) {
478 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
479 "%s: Can't generate path name string for /sys/class/net device",
483 bytes_read
= readlink(pathstr
, phydev_path
, phydev_max_pathlen
);
484 if (bytes_read
== -1) {
485 if (errno
== ENOENT
|| errno
== EINVAL
) {
487 * Doesn't exist, or not a symlink; assume that
488 * means it's not a mac80211 device.
493 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
494 "%s: Can't readlink %s: %s", device
, pathstr
,
500 phydev_path
[bytes_read
] = '\0';
504 struct nl80211_state
{
505 struct nl_handle
*nl_handle
;
506 struct nl_cache
*nl_cache
;
507 struct genl_family
*nl80211
;
511 nl80211_init(pcap_t
*handle
, struct nl80211_state
*state
, const char *device
)
513 state
->nl_handle
= nl_handle_alloc();
514 if (!state
->nl_handle
) {
515 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
516 "%s: failed to allocate netlink handle", device
);
520 if (genl_connect(state
->nl_handle
)) {
521 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
522 "%s: failed to connect to generic netlink", device
);
523 goto out_handle_destroy
;
526 state
->nl_cache
= genl_ctrl_alloc_cache(state
->nl_handle
);
527 if (!state
->nl_cache
) {
528 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
529 "%s: failed to allocate generic netlink cache", device
);
530 goto out_handle_destroy
;
533 state
->nl80211
= genl_ctrl_search_by_name(state
->nl_cache
, "nl80211");
534 if (!state
->nl80211
) {
535 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
536 "%s: nl80211 not found", device
);
543 nl_cache_free(state
->nl_cache
);
545 nl_handle_destroy(state
->nl_handle
);
550 nl80211_cleanup(struct nl80211_state
*state
)
552 genl_family_put(state
->nl80211
);
553 nl_cache_free(state
->nl_cache
);
554 nl_handle_destroy(state
->nl_handle
);
558 add_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
559 const char *device
, const char *mondevice
)
565 ifindex
= iface_get_id(sock_fd
, device
, handle
->errbuf
);
571 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
572 "%s: failed to allocate netlink msg", device
);
576 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
577 0, NL80211_CMD_NEW_INTERFACE
, 0);
578 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
579 NLA_PUT_STRING(msg
, NL80211_ATTR_IFNAME
, mondevice
);
580 NLA_PUT_U32(msg
, NL80211_ATTR_IFTYPE
, NL80211_IFTYPE_MONITOR
);
582 err
= nl_send_auto_complete(state
->nl_handle
, msg
);
584 if (err
== -ENFILE
) {
586 * Device not available; our caller should just
593 * Real failure, not just "that device is not
596 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
597 "%s: nl_send_auto_complete failed adding %s interface: %s",
598 device
, mondevice
, strerror(-err
));
603 err
= nl_wait_for_ack(state
->nl_handle
);
605 if (err
== -ENFILE
) {
607 * Device not available; our caller should just
614 * Real failure, not just "that device is not
617 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
618 "%s: nl_wait_for_ack failed adding %s interface: %s",
619 device
, mondevice
, strerror(-err
));
632 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
633 "%s: nl_put failed adding %s interface",
640 del_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
641 const char *device
, const char *mondevice
)
647 ifindex
= iface_get_id(sock_fd
, mondevice
, handle
->errbuf
);
653 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
654 "%s: failed to allocate netlink msg", device
);
658 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
659 0, NL80211_CMD_DEL_INTERFACE
, 0);
660 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
662 err
= nl_send_auto_complete(state
->nl_handle
, msg
);
664 if (err
== -ENFILE
) {
666 * Device not available; our caller should just
673 * Real failure, not just "that device is not
676 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
677 "%s: nl_send_auto_complete failed deleting %s interface: %s",
678 device
, mondevice
, strerror(-err
));
683 err
= nl_wait_for_ack(state
->nl_handle
);
685 if (err
== -ENFILE
) {
687 * Device not available; our caller should just
694 * Real failure, not just "that device is not
697 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
698 "%s: nl_wait_for_ack failed adding %s interface: %s",
699 device
, mondevice
, strerror(-err
));
712 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
713 "%s: nl_put failed deleting %s interface",
720 enter_rfmon_mode_mac80211(pcap_t
*handle
, int sock_fd
, const char *device
)
723 char phydev_path
[PATH_MAX
+1];
724 struct nl80211_state nlstate
;
729 * Is this a mac80211 device?
731 ret
= get_mac80211_phydev(handle
, device
, phydev_path
, PATH_MAX
);
733 return ret
; /* error */
735 return 0; /* no error, but not mac80211 device */
738 * XXX - is this already a monN device?
740 * Is that determined by old Wireless Extensions ioctls?
744 * OK, it's apparently a mac80211 device.
745 * Try to find an unused monN device for it.
747 ret
= nl80211_init(handle
, &nlstate
, device
);
750 for (n
= 0; n
< UINT_MAX
; n
++) {
754 char mondevice
[3+10+1]; /* mon{UINT_MAX}\0 */
756 snprintf(mondevice
, sizeof mondevice
, "mon%u", n
);
757 ret
= add_mon_if(handle
, sock_fd
, &nlstate
, device
, mondevice
);
759 handle
->md
.mondevice
= strdup(mondevice
);
764 * Hard failure. Just return ret; handle->errbuf
765 * has already been set.
767 nl80211_cleanup(&nlstate
);
772 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
773 "%s: No free monN interfaces", device
);
774 nl80211_cleanup(&nlstate
);
781 * Sleep for .1 seconds.
784 delay
.tv_nsec
= 500000000;
785 nanosleep(&delay
, NULL
);
789 * Now configure the monitor interface up.
791 memset(&ifr
, 0, sizeof(ifr
));
792 strncpy(ifr
.ifr_name
, handle
->md
.mondevice
, sizeof(ifr
.ifr_name
));
793 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
794 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
795 "%s: Can't get flags for %s: %s", device
,
796 handle
->md
.mondevice
, strerror(errno
));
797 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
798 handle
->md
.mondevice
);
799 nl80211_cleanup(&nlstate
);
802 ifr
.ifr_flags
|= IFF_UP
|IFF_RUNNING
;
803 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
804 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
805 "%s: Can't set flags for %s: %s", device
,
806 handle
->md
.mondevice
, strerror(errno
));
807 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
808 handle
->md
.mondevice
);
809 nl80211_cleanup(&nlstate
);
814 * Success. Clean up the libnl state.
816 nl80211_cleanup(&nlstate
);
819 * Note that we have to delete the monitor device when we close
822 handle
->md
.must_do_on_close
|= MUST_DELETE_MONIF
;
825 * Add this to the list of pcaps to close when we exit.
827 pcap_add_to_pcaps_to_close(handle
);
831 #endif /* HAVE_LIBNL */
834 pcap_can_set_rfmon_linux(pcap_t
*handle
)
837 char phydev_path
[PATH_MAX
+1];
840 #ifdef IW_MODE_MONITOR
845 if (strcmp(handle
->opt
.source
, "any") == 0) {
847 * Monitor mode makes no sense on the "any" device.
854 * Bleah. There doesn't seem to be a way to ask a mac80211
855 * device, through libnl, whether it supports monitor mode;
856 * we'll just check whether the device appears to be a
857 * mac80211 device and, if so, assume the device supports
860 * wmaster devices don't appear to support the Wireless
861 * Extensions, but we can create a mon device for a
862 * wmaster device, so we don't bother checking whether
863 * a mac80211 device supports the Wireless Extensions.
865 ret
= get_mac80211_phydev(handle
, handle
->opt
.source
, phydev_path
,
868 return ret
; /* error */
870 return 1; /* mac80211 device */
873 #ifdef IW_MODE_MONITOR
875 * Bleah. There doesn't appear to be an ioctl to use to ask
876 * whether a device supports monitor mode; we'll just do
877 * SIOCGIWMODE and, if it succeeds, assume the device supports
880 * Open a socket on which to attempt to get the mode.
881 * (We assume that if we have Wireless Extensions support
882 * we also have PF_PACKET support.)
884 sock_fd
= socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
));
886 (void)snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
887 "socket: %s", pcap_strerror(errno
));
892 * Attempt to get the current mode.
894 strncpy(ireq
.ifr_ifrn
.ifrn_name
, handle
->opt
.source
,
895 sizeof ireq
.ifr_ifrn
.ifrn_name
);
896 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
897 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) != -1) {
899 * Well, we got the mode; assume we can set it.
904 if (errno
== ENODEV
) {
905 /* The device doesn't even exist. */
906 (void)snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
907 "SIOCGIWMODE failed: %s", pcap_strerror(errno
));
909 return PCAP_ERROR_NO_SUCH_DEVICE
;
917 * Grabs the number of dropped packets by the interface from /proc/net/dev.
919 * XXX - what about /sys/class/net/{interface name}/rx_*? There are
920 * individual devices giving, in ASCII, various rx_ and tx_ statistics.
922 * Or can we get them in binary form from netlink?
925 linux_if_drops(const char * if_name
)
930 int field_to_convert
= 3, if_name_sz
= strlen(if_name
);
931 long int dropped_pkts
= 0;
933 file
= fopen("/proc/net/dev", "r");
937 while (!dropped_pkts
&& fgets( buffer
, sizeof(buffer
), file
))
939 /* search for 'bytes' -- if its in there, then
940 that means we need to grab the fourth field. otherwise
941 grab the third field. */
942 if (field_to_convert
!= 4 && strstr(buffer
, "bytes"))
944 field_to_convert
= 4;
948 /* find iface and make sure it actually matches -- space before the name and : after it */
949 if ((bufptr
= strstr(buffer
, if_name
)) &&
950 (bufptr
== buffer
|| *(bufptr
-1) == ' ') &&
951 *(bufptr
+ if_name_sz
) == ':')
953 bufptr
= bufptr
+ if_name_sz
+ 1;
955 /* grab the nth field from it */
956 while( --field_to_convert
&& *bufptr
!= '\0')
958 while (*bufptr
!= '\0' && *(bufptr
++) == ' ');
959 while (*bufptr
!= '\0' && *(bufptr
++) != ' ');
962 /* get rid of any final spaces */
963 while (*bufptr
!= '\0' && *bufptr
== ' ') bufptr
++;
966 dropped_pkts
= strtol(bufptr
, NULL
, 10);
978 * With older kernels promiscuous mode is kind of interesting because we
979 * have to reset the interface before exiting. The problem can't really
980 * be solved without some daemon taking care of managing usage counts.
981 * If we put the interface into promiscuous mode, we set a flag indicating
982 * that we must take it out of that mode when the interface is closed,
983 * and, when closing the interface, if that flag is set we take it out
984 * of promiscuous mode.
986 * Even with newer kernels, we have the same issue with rfmon mode.
989 static void pcap_cleanup_linux( pcap_t
*handle
)
993 struct nl80211_state nlstate
;
995 #endif /* HAVE_LIBNL */
996 #ifdef IW_MODE_MONITOR
998 #endif /* IW_MODE_MONITOR */
1000 if (handle
->md
.must_do_on_close
!= 0) {
1002 * There's something we have to do when closing this
1005 if (handle
->md
.must_do_on_close
& MUST_CLEAR_PROMISC
) {
1007 * We put the interface into promiscuous mode;
1008 * take it out of promiscuous mode.
1010 * XXX - if somebody else wants it in promiscuous
1011 * mode, this code cannot know that, so it'll take
1012 * it out of promiscuous mode. That's not fixable
1013 * in 2.0[.x] kernels.
1015 memset(&ifr
, 0, sizeof(ifr
));
1016 strncpy(ifr
.ifr_name
, handle
->md
.device
,
1017 sizeof(ifr
.ifr_name
));
1018 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
1020 "Can't restore interface flags (SIOCGIFFLAGS failed: %s).\n"
1021 "Please adjust manually.\n"
1022 "Hint: This can't happen with Linux >= 2.2.0.\n",
1025 if (ifr
.ifr_flags
& IFF_PROMISC
) {
1027 * Promiscuous mode is currently on;
1030 ifr
.ifr_flags
&= ~IFF_PROMISC
;
1031 if (ioctl(handle
->fd
, SIOCSIFFLAGS
,
1034 "Can't restore interface flags (SIOCSIFFLAGS failed: %s).\n"
1035 "Please adjust manually.\n"
1036 "Hint: This can't happen with Linux >= 2.2.0.\n",
1044 if (handle
->md
.must_do_on_close
& MUST_DELETE_MONIF
) {
1045 ret
= nl80211_init(handle
, &nlstate
, handle
->md
.device
);
1047 ret
= del_mon_if(handle
, handle
->fd
, &nlstate
,
1048 handle
->md
.device
, handle
->md
.mondevice
);
1049 nl80211_cleanup(&nlstate
);
1053 "Can't delete monitor interface %s (%s).\n"
1054 "Please delete manually.\n",
1055 handle
->md
.mondevice
, handle
->errbuf
);
1058 #endif /* HAVE_LIBNL */
1060 #ifdef IW_MODE_MONITOR
1061 if (handle
->md
.must_do_on_close
& MUST_CLEAR_RFMON
) {
1063 * We put the interface into rfmon mode;
1064 * take it out of rfmon mode.
1066 * XXX - if somebody else wants it in rfmon
1067 * mode, this code cannot know that, so it'll take
1068 * it out of rfmon mode.
1070 strncpy(ireq
.ifr_ifrn
.ifrn_name
, handle
->md
.device
,
1071 sizeof ireq
.ifr_ifrn
.ifrn_name
);
1072 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1]
1074 ireq
.u
.mode
= handle
->md
.oldmode
;
1075 if (ioctl(handle
->fd
, SIOCSIWMODE
, &ireq
) == -1) {
1077 * Scientist, you've failed.
1080 "Can't restore interface wireless mode (SIOCSIWMODE failed: %s).\n"
1081 "Please adjust manually.\n",
1085 #endif /* IW_MODE_MONITOR */
1088 * Take this pcap out of the list of pcaps for which we
1089 * have to take the interface out of some mode.
1091 pcap_remove_from_pcaps_to_close(handle
);
1094 if (handle
->md
.mondevice
!= NULL
) {
1095 free(handle
->md
.mondevice
);
1096 handle
->md
.mondevice
= NULL
;
1098 if (handle
->md
.device
!= NULL
) {
1099 free(handle
->md
.device
);
1100 handle
->md
.device
= NULL
;
1102 pcap_cleanup_live_common(handle
);
1106 * Get a handle for a live capture from the given device. You can
1107 * pass NULL as device to get all packages (without link level
1108 * information of course). If you pass 1 as promisc the interface
1109 * will be set to promiscous mode (XXX: I think this usage should
1110 * be deprecated and functions be added to select that later allow
1111 * modification of that values -- Torsten).
1114 pcap_activate_linux(pcap_t
*handle
)
1119 device
= handle
->opt
.source
;
1121 handle
->inject_op
= pcap_inject_linux
;
1122 handle
->setfilter_op
= pcap_setfilter_linux
;
1123 handle
->setdirection_op
= pcap_setdirection_linux
;
1124 handle
->set_datalink_op
= NULL
; /* can't change data link type */
1125 handle
->getnonblock_op
= pcap_getnonblock_fd
;
1126 handle
->setnonblock_op
= pcap_setnonblock_fd
;
1127 handle
->cleanup_op
= pcap_cleanup_linux
;
1128 handle
->read_op
= pcap_read_linux
;
1129 handle
->stats_op
= pcap_stats_linux
;
1132 * The "any" device is a special device which causes us not
1133 * to bind to a particular device and thus to look at all
1136 if (strcmp(device
, "any") == 0) {
1137 if (handle
->opt
.promisc
) {
1138 handle
->opt
.promisc
= 0;
1139 /* Just a warning. */
1140 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1141 "Promiscuous mode not supported on the \"any\" device");
1142 status
= PCAP_WARNING_PROMISC_NOTSUP
;
1146 handle
->md
.device
= strdup(device
);
1147 if (handle
->md
.device
== NULL
) {
1148 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "strdup: %s",
1149 pcap_strerror(errno
) );
1154 * If we're in promiscuous mode, then we probably want
1155 * to see when the interface drops packets too, so get an
1156 * initial count from /proc/net/dev
1158 if (handle
->opt
.promisc
)
1159 handle
->md
.proc_dropped
= linux_if_drops(handle
->md
.device
);
1162 * Current Linux kernels use the protocol family PF_PACKET to
1163 * allow direct access to all packets on the network while
1164 * older kernels had a special socket type SOCK_PACKET to
1165 * implement this feature.
1166 * While this old implementation is kind of obsolete we need
1167 * to be compatible with older kernels for a while so we are
1168 * trying both methods with the newer method preferred.
1171 if ((status
= activate_new(handle
)) == 1) {
1174 * Try to use memory-mapped access.
1176 switch (activate_mmap(handle
)) {
1179 /* we succeeded; nothing more to do */
1184 * Kernel doesn't support it - just continue
1185 * with non-memory-mapped access.
1192 * We failed to set up to use it, or kernel
1193 * supports it, but we failed to enable it;
1194 * return an error. handle->errbuf contains
1197 status
= PCAP_ERROR
;
1201 else if (status
== 0) {
1202 /* Non-fatal error; try old way */
1203 if ((status
= activate_old(handle
)) != 1) {
1205 * Both methods to open the packet socket failed.
1206 * Tidy up and report our failure (handle->errbuf
1207 * is expected to be set by the functions above).
1213 * Fatal error with the new way; just fail.
1214 * status has the error return; if it's PCAP_ERROR,
1215 * handle->errbuf has been set appropriately.
1221 * We set up the socket, but not with memory-mapped access.
1223 if (handle
->opt
.buffer_size
!= 0) {
1225 * Set the socket buffer size to the specified value.
1227 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_RCVBUF
,
1228 &handle
->opt
.buffer_size
,
1229 sizeof(handle
->opt
.buffer_size
)) == -1) {
1230 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1231 "SO_RCVBUF: %s", pcap_strerror(errno
));
1232 status
= PCAP_ERROR
;
1237 /* Allocate the buffer */
1239 handle
->buffer
= malloc(handle
->bufsize
+ handle
->offset
);
1240 if (!handle
->buffer
) {
1241 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1242 "malloc: %s", pcap_strerror(errno
));
1243 status
= PCAP_ERROR
;
1248 * "handle->fd" is a socket, so "select()" and "poll()"
1249 * should work on it.
1251 handle
->selectable_fd
= handle
->fd
;
1256 pcap_cleanup_linux(handle
);
1261 * Read at most max_packets from the capture stream and call the callback
1262 * for each of them. Returns the number of packets handled or -1 if an
1266 pcap_read_linux(pcap_t
*handle
, int max_packets
, pcap_handler callback
, u_char
*user
)
1269 * Currently, on Linux only one packet is delivered per read,
1272 return pcap_read_packet(handle
, callback
, user
);
1276 * Read a packet from the socket calling the handler provided by
1277 * the user. Returns the number of packets received or -1 if an
1281 pcap_read_packet(pcap_t
*handle
, pcap_handler callback
, u_char
*userdata
)
1285 #ifdef HAVE_PF_PACKET_SOCKETS
1286 struct sockaddr_ll from
;
1287 struct sll_header
*hdrp
;
1289 struct sockaddr from
;
1291 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1294 struct cmsghdr
*cmsg
;
1296 struct cmsghdr cmsg
;
1297 char buf
[CMSG_SPACE(sizeof(struct tpacket_auxdata
))];
1299 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1301 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1302 int packet_len
, caplen
;
1303 struct pcap_pkthdr pcap_header
;
1305 #ifdef HAVE_PF_PACKET_SOCKETS
1307 * If this is a cooked device, leave extra room for a
1308 * fake packet header.
1310 if (handle
->md
.cooked
)
1311 offset
= SLL_HDR_LEN
;
1316 * This system doesn't have PF_PACKET sockets, so it doesn't
1317 * support cooked devices.
1323 * Receive a single packet from the kernel.
1324 * We ignore EINTR, as that might just be due to a signal
1325 * being delivered - if the signal should interrupt the
1326 * loop, the signal handler should call pcap_breakloop()
1327 * to set handle->break_loop (we ignore it on other
1328 * platforms as well).
1329 * We also ignore ENETDOWN, so that we can continue to
1330 * capture traffic if the interface goes down and comes
1331 * back up again; comments in the kernel indicate that
1332 * we'll just block waiting for packets if we try to
1333 * receive from a socket that delivered ENETDOWN, and,
1334 * if we're using a memory-mapped buffer, we won't even
1335 * get notified of "network down" events.
1337 bp
= handle
->buffer
+ handle
->offset
;
1339 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1340 msg
.msg_name
= &from
;
1341 msg
.msg_namelen
= sizeof(from
);
1344 msg
.msg_control
= &cmsg_buf
;
1345 msg
.msg_controllen
= sizeof(cmsg_buf
);
1348 iov
.iov_len
= handle
->bufsize
- offset
;
1349 iov
.iov_base
= bp
+ offset
;
1350 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1354 * Has "pcap_breakloop()" been called?
1356 if (handle
->break_loop
) {
1358 * Yes - clear the flag that indicates that it has,
1359 * and return PCAP_ERROR_BREAK as an indication that
1360 * we were told to break out of the loop.
1362 handle
->break_loop
= 0;
1363 return PCAP_ERROR_BREAK
;
1366 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1367 packet_len
= recvmsg(handle
->fd
, &msg
, MSG_TRUNC
);
1368 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1369 fromlen
= sizeof(from
);
1370 packet_len
= recvfrom(
1371 handle
->fd
, bp
+ offset
,
1372 handle
->bufsize
- offset
, MSG_TRUNC
,
1373 (struct sockaddr
*) &from
, &fromlen
);
1374 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1375 } while (packet_len
== -1 && errno
== EINTR
);
1377 /* Check if an error occured */
1379 if (packet_len
== -1) {
1383 return 0; /* no packet there */
1387 * The device on which we're capturing went away.
1389 * XXX - we should really return
1390 * PCAP_ERROR_IFACE_NOT_UP, but pcap_dispatch()
1391 * etc. aren't defined to return that.
1393 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1394 "The interface went down");
1398 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1399 "recvfrom: %s", pcap_strerror(errno
));
1404 #ifdef HAVE_PF_PACKET_SOCKETS
1405 if (!handle
->md
.sock_packet
) {
1407 * Unfortunately, there is a window between socket() and
1408 * bind() where the kernel may queue packets from any
1409 * interface. If we're bound to a particular interface,
1410 * discard packets not from that interface.
1412 * (If socket filters are supported, we could do the
1413 * same thing we do when changing the filter; however,
1414 * that won't handle packet sockets without socket
1415 * filter support, and it's a bit more complicated.
1416 * It would save some instructions per packet, however.)
1418 if (handle
->md
.ifindex
!= -1 &&
1419 from
.sll_ifindex
!= handle
->md
.ifindex
)
1423 * Do checks based on packet direction.
1424 * We can only do this if we're using PF_PACKET; the
1425 * address returned for SOCK_PACKET is a "sockaddr_pkt"
1426 * which lacks the relevant packet type information.
1428 if (from
.sll_pkttype
== PACKET_OUTGOING
) {
1431 * If this is from the loopback device, reject it;
1432 * we'll see the packet as an incoming packet as well,
1433 * and we don't want to see it twice.
1435 if (from
.sll_ifindex
== handle
->md
.lo_ifindex
)
1439 * If the user only wants incoming packets, reject it.
1441 if (handle
->direction
== PCAP_D_IN
)
1446 * If the user only wants outgoing packets, reject it.
1448 if (handle
->direction
== PCAP_D_OUT
)
1454 #ifdef HAVE_PF_PACKET_SOCKETS
1456 * If this is a cooked device, fill in the fake packet header.
1458 if (handle
->md
.cooked
) {
1460 * Add the length of the fake header to the length
1461 * of packet data we read.
1463 packet_len
+= SLL_HDR_LEN
;
1465 hdrp
= (struct sll_header
*)bp
;
1466 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(from
.sll_pkttype
);
1467 hdrp
->sll_hatype
= htons(from
.sll_hatype
);
1468 hdrp
->sll_halen
= htons(from
.sll_halen
);
1469 memcpy(hdrp
->sll_addr
, from
.sll_addr
,
1470 (from
.sll_halen
> SLL_ADDRLEN
) ?
1473 hdrp
->sll_protocol
= from
.sll_protocol
;
1476 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1477 for (cmsg
= CMSG_FIRSTHDR(&msg
); cmsg
; cmsg
= CMSG_NXTHDR(&msg
, cmsg
)) {
1478 struct tpacket_auxdata
*aux
;
1480 struct vlan_tag
*tag
;
1482 if (cmsg
->cmsg_len
< CMSG_LEN(sizeof(struct tpacket_auxdata
)) ||
1483 cmsg
->cmsg_level
!= SOL_PACKET
||
1484 cmsg
->cmsg_type
!= PACKET_AUXDATA
)
1487 aux
= (struct tpacket_auxdata
*)CMSG_DATA(cmsg
);
1488 if (aux
->tp_vlan_tci
== 0)
1491 len
= packet_len
> iov
.iov_len
? iov
.iov_len
: packet_len
;
1492 if (len
< 2 * ETH_ALEN
)
1496 memmove(bp
, bp
+ VLAN_TAG_LEN
, 2 * ETH_ALEN
);
1498 tag
= (struct vlan_tag
*)(bp
+ 2 * ETH_ALEN
);
1499 tag
->vlan_tpid
= htons(ETH_P_8021Q
);
1500 tag
->vlan_tci
= htons(aux
->tp_vlan_tci
);
1502 packet_len
+= VLAN_TAG_LEN
;
1504 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1505 #endif /* HAVE_PF_PACKET_SOCKETS */
1508 * XXX: According to the kernel source we should get the real
1509 * packet len if calling recvfrom with MSG_TRUNC set. It does
1510 * not seem to work here :(, but it is supported by this code
1512 * To be honest the code RELIES on that feature so this is really
1513 * broken with 2.2.x kernels.
1514 * I spend a day to figure out what's going on and I found out
1515 * that the following is happening:
1517 * The packet comes from a random interface and the packet_rcv
1518 * hook is called with a clone of the packet. That code inserts
1519 * the packet into the receive queue of the packet socket.
1520 * If a filter is attached to that socket that filter is run
1521 * first - and there lies the problem. The default filter always
1522 * cuts the packet at the snaplen:
1527 * So the packet filter cuts down the packet. The recvfrom call
1528 * says "hey, it's only 68 bytes, it fits into the buffer" with
1529 * the result that we don't get the real packet length. This
1530 * is valid at least until kernel 2.2.17pre6.
1532 * We currently handle this by making a copy of the filter
1533 * program, fixing all "ret" instructions with non-zero
1534 * operands to have an operand of 65535 so that the filter
1535 * doesn't truncate the packet, and supplying that modified
1536 * filter to the kernel.
1539 caplen
= packet_len
;
1540 if (caplen
> handle
->snapshot
)
1541 caplen
= handle
->snapshot
;
1543 /* Run the packet filter if not using kernel filter */
1544 if (!handle
->md
.use_bpf
&& handle
->fcode
.bf_insns
) {
1545 if (bpf_filter(handle
->fcode
.bf_insns
, bp
,
1546 packet_len
, caplen
) == 0)
1548 /* rejected by filter */
1553 /* Fill in our own header data */
1555 if (ioctl(handle
->fd
, SIOCGSTAMP
, &pcap_header
.ts
) == -1) {
1556 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1557 "SIOCGSTAMP: %s", pcap_strerror(errno
));
1560 pcap_header
.caplen
= caplen
;
1561 pcap_header
.len
= packet_len
;
1566 * Arguably, we should count them before we check the filter,
1567 * as on many other platforms "ps_recv" counts packets
1568 * handed to the filter rather than packets that passed
1569 * the filter, but if filtering is done in the kernel, we
1570 * can't get a count of packets that passed the filter,
1571 * and that would mean the meaning of "ps_recv" wouldn't
1572 * be the same on all Linux systems.
1574 * XXX - it's not the same on all systems in any case;
1575 * ideally, we should have a "get the statistics" call
1576 * that supplies more counts and indicates which of them
1577 * it supplies, so that we supply a count of packets
1578 * handed to the filter only on platforms where that
1579 * information is available.
1581 * We count them here even if we can get the packet count
1582 * from the kernel, as we can only determine at run time
1583 * whether we'll be able to get it from the kernel (if
1584 * HAVE_TPACKET_STATS isn't defined, we can't get it from
1585 * the kernel, but if it is defined, the library might
1586 * have been built with a 2.4 or later kernel, but we
1587 * might be running on a 2.2[.x] kernel without Alexey
1588 * Kuznetzov's turbopacket patches, and thus the kernel
1589 * might not be able to supply those statistics). We
1590 * could, I guess, try, when opening the socket, to get
1591 * the statistics, and if we can not increment the count
1592 * here, but it's not clear that always incrementing
1593 * the count is more expensive than always testing a flag
1596 * We keep the count in "md.packets_read", and use that for
1597 * "ps_recv" if we can't get the statistics from the kernel.
1598 * We do that because, if we *can* get the statistics from
1599 * the kernel, we use "md.stat.ps_recv" and "md.stat.ps_drop"
1600 * as running counts, as reading the statistics from the
1601 * kernel resets the kernel statistics, and if we directly
1602 * increment "md.stat.ps_recv" here, that means it will
1603 * count packets *twice* on systems where we can get kernel
1604 * statistics - once here, and once in pcap_stats_linux().
1606 handle
->md
.packets_read
++;
1608 /* Call the user supplied callback function */
1609 callback(userdata
, &pcap_header
, bp
);
1615 pcap_inject_linux(pcap_t
*handle
, const void *buf
, size_t size
)
1619 #ifdef HAVE_PF_PACKET_SOCKETS
1620 if (!handle
->md
.sock_packet
) {
1621 /* PF_PACKET socket */
1622 if (handle
->md
.ifindex
== -1) {
1624 * We don't support sending on the "any" device.
1626 strlcpy(handle
->errbuf
,
1627 "Sending packets isn't supported on the \"any\" device",
1632 if (handle
->md
.cooked
) {
1634 * We don't support sending on the "any" device.
1636 * XXX - how do you send on a bound cooked-mode
1638 * Is a "sendto()" required there?
1640 strlcpy(handle
->errbuf
,
1641 "Sending packets isn't supported in cooked mode",
1648 ret
= send(handle
->fd
, buf
, size
, 0);
1650 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "send: %s",
1651 pcap_strerror(errno
));
1658 * Get the statistics for the given packet capture handle.
1659 * Reports the number of dropped packets iff the kernel supports
1660 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
1661 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
1662 * patches); otherwise, that information isn't available, and we lie
1663 * and report 0 as the count of dropped packets.
1666 pcap_stats_linux(pcap_t
*handle
, struct pcap_stat
*stats
)
1668 #ifdef HAVE_TPACKET_STATS
1669 struct tpacket_stats kstats
;
1670 socklen_t len
= sizeof (struct tpacket_stats
);
1673 long if_dropped
= 0;
1676 * To fill in ps_ifdrop, we parse /proc/net/dev for the number
1678 if (handle
->opt
.promisc
)
1680 if_dropped
= handle
->md
.proc_dropped
;
1681 handle
->md
.proc_dropped
= linux_if_drops(handle
->md
.device
);
1682 handle
->md
.stat
.ps_ifdrop
+= (handle
->md
.proc_dropped
- if_dropped
);
1685 #ifdef HAVE_TPACKET_STATS
1687 * Try to get the packet counts from the kernel.
1689 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_STATISTICS
,
1690 &kstats
, &len
) > -1) {
1692 * On systems where the PACKET_STATISTICS "getsockopt()"
1693 * argument is supported on PF_PACKET sockets:
1695 * "ps_recv" counts only packets that *passed* the
1696 * filter, not packets that didn't pass the filter.
1697 * This includes packets later dropped because we
1698 * ran out of buffer space.
1700 * "ps_drop" counts packets dropped because we ran
1701 * out of buffer space. It doesn't count packets
1702 * dropped by the interface driver. It counts only
1703 * packets that passed the filter.
1705 * See above for ps_ifdrop.
1707 * Both statistics include packets not yet read from
1708 * the kernel by libpcap, and thus not yet seen by
1711 * In "linux/net/packet/af_packet.c", at least in the
1712 * 2.4.9 kernel, "tp_packets" is incremented for every
1713 * packet that passes the packet filter *and* is
1714 * successfully queued on the socket; "tp_drops" is
1715 * incremented for every packet dropped because there's
1716 * not enough free space in the socket buffer.
1718 * When the statistics are returned for a PACKET_STATISTICS
1719 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
1720 * so that "tp_packets" counts all packets handed to
1721 * the PF_PACKET socket, including packets dropped because
1722 * there wasn't room on the socket buffer - but not
1723 * including packets that didn't pass the filter.
1725 * In the BSD BPF, the count of received packets is
1726 * incremented for every packet handed to BPF, regardless
1727 * of whether it passed the filter.
1729 * We can't make "pcap_stats()" work the same on both
1730 * platforms, but the best approximation is to return
1731 * "tp_packets" as the count of packets and "tp_drops"
1732 * as the count of drops.
1734 * Keep a running total because each call to
1735 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
1736 * resets the counters to zero.
1738 handle
->md
.stat
.ps_recv
+= kstats
.tp_packets
;
1739 handle
->md
.stat
.ps_drop
+= kstats
.tp_drops
;
1740 *stats
= handle
->md
.stat
;
1746 * If the error was EOPNOTSUPP, fall through, so that
1747 * if you build the library on a system with
1748 * "struct tpacket_stats" and run it on a system
1749 * that doesn't, it works as it does if the library
1750 * is built on a system without "struct tpacket_stats".
1752 if (errno
!= EOPNOTSUPP
) {
1753 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1754 "pcap_stats: %s", pcap_strerror(errno
));
1760 * On systems where the PACKET_STATISTICS "getsockopt()" argument
1761 * is not supported on PF_PACKET sockets:
1763 * "ps_recv" counts only packets that *passed* the filter,
1764 * not packets that didn't pass the filter. It does not
1765 * count packets dropped because we ran out of buffer
1768 * "ps_drop" is not supported.
1770 * "ps_ifdrop" is supported. It will return the number
1771 * of drops the interface reports in /proc/net/dev,
1772 * if that is available.
1774 * "ps_recv" doesn't include packets not yet read from
1775 * the kernel by libpcap.
1777 * We maintain the count of packets processed by libpcap in
1778 * "md.packets_read", for reasons described in the comment
1779 * at the end of pcap_read_packet(). We have no idea how many
1780 * packets were dropped by the kernel buffers -- but we know
1781 * how many the interface dropped, so we can return that.
1784 stats
->ps_recv
= handle
->md
.packets_read
;
1786 stats
->ps_ifdrop
= handle
->md
.stat
.ps_ifdrop
;
1791 * Get from "/sys/class/net" all interfaces listed there; if they're
1792 * already in the list of interfaces we have, that won't add another
1793 * instance, but if they're not, that'll add them.
1795 * We don't bother getting any addresses for them; it appears you can't
1796 * use SIOCGIFADDR on Linux to get IPv6 addresses for interfaces, and,
1797 * although some other types of addresses can be fetched with SIOCGIFADDR,
1798 * we don't bother with them for now.
1800 * We also don't fail if we couldn't open "/sys/class/net"; we just leave
1801 * the list of interfaces as is, and return 0, so that we can try
1802 * scanning /proc/net/dev.
1805 scan_sys_class_net(pcap_if_t
**devlistp
, char *errbuf
)
1807 DIR *sys_class_net_d
;
1811 char name
[512]; /* XXX - pick a size */
1813 struct ifreq ifrflags
;
1816 sys_class_net_d
= opendir("/sys/class/net");
1817 if (sys_class_net_d
== NULL
&& errno
== ENOENT
)
1821 * Create a socket from which to fetch interface information.
1823 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
1825 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1826 "socket: %s", pcap_strerror(errno
));
1832 ent
= readdir(sys_class_net_d
);
1835 * Error or EOF; if errno != 0, it's an error.
1841 * Ignore directories (".", "..", and any subdirectories).
1843 if (ent
->d_type
== DT_DIR
)
1847 * Get the interface name.
1849 p
= &ent
->d_name
[0];
1851 while (*p
!= '\0' && isascii(*p
) && !isspace(*p
)) {
1854 * This could be the separator between a
1855 * name and an alias number, or it could be
1856 * the separator between a name with no
1857 * alias number and the next field.
1859 * If there's a colon after digits, it
1860 * separates the name and the alias number,
1861 * otherwise it separates the name and the
1865 while (isascii(*p
) && isdigit(*p
))
1869 * That was the next field,
1870 * not the alias number.
1881 * Get the flags for this interface, and skip it if
1884 strncpy(ifrflags
.ifr_name
, name
, sizeof(ifrflags
.ifr_name
));
1885 if (ioctl(fd
, SIOCGIFFLAGS
, (char *)&ifrflags
) < 0) {
1888 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1889 "SIOCGIFFLAGS: %.*s: %s",
1890 (int)sizeof(ifrflags
.ifr_name
),
1892 pcap_strerror(errno
));
1896 if (!(ifrflags
.ifr_flags
& IFF_UP
))
1900 * Add an entry for this interface, with no addresses.
1902 if (pcap_add_if(devlistp
, name
, ifrflags
.ifr_flags
, NULL
,
1913 * Well, we didn't fail for any other reason; did we
1914 * fail due to an error reading the directory?
1917 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1918 "Error reading /sys/class/net: %s",
1919 pcap_strerror(errno
));
1925 (void)closedir(sys_class_net_d
);
1930 * Get from "/proc/net/dev" all interfaces listed there; if they're
1931 * already in the list of interfaces we have, that won't add another
1932 * instance, but if they're not, that'll add them.
1934 * See comments from scan_sys_class_net().
1937 scan_proc_net_dev(pcap_if_t
**devlistp
, char *errbuf
)
1944 char name
[512]; /* XXX - pick a size */
1946 struct ifreq ifrflags
;
1949 proc_net_f
= fopen("/proc/net/dev", "r");
1950 if (proc_net_f
== NULL
&& errno
== ENOENT
)
1954 * Create a socket from which to fetch interface information.
1956 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
1958 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1959 "socket: %s", pcap_strerror(errno
));
1964 fgets(linebuf
, sizeof linebuf
, proc_net_f
) != NULL
; linenum
++) {
1966 * Skip the first two lines - they're headers.
1974 * Skip leading white space.
1976 while (*p
!= '\0' && isascii(*p
) && isspace(*p
))
1978 if (*p
== '\0' || *p
== '\n')
1979 continue; /* blank line */
1982 * Get the interface name.
1985 while (*p
!= '\0' && isascii(*p
) && !isspace(*p
)) {
1988 * This could be the separator between a
1989 * name and an alias number, or it could be
1990 * the separator between a name with no
1991 * alias number and the next field.
1993 * If there's a colon after digits, it
1994 * separates the name and the alias number,
1995 * otherwise it separates the name and the
1999 while (isascii(*p
) && isdigit(*p
))
2003 * That was the next field,
2004 * not the alias number.
2015 * Get the flags for this interface, and skip it if
2018 strncpy(ifrflags
.ifr_name
, name
, sizeof(ifrflags
.ifr_name
));
2019 if (ioctl(fd
, SIOCGIFFLAGS
, (char *)&ifrflags
) < 0) {
2022 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2023 "SIOCGIFFLAGS: %.*s: %s",
2024 (int)sizeof(ifrflags
.ifr_name
),
2026 pcap_strerror(errno
));
2030 if (!(ifrflags
.ifr_flags
& IFF_UP
))
2034 * Add an entry for this interface, with no addresses.
2036 if (pcap_add_if(devlistp
, name
, ifrflags
.ifr_flags
, NULL
,
2047 * Well, we didn't fail for any other reason; did we
2048 * fail due to an error reading the file?
2050 if (ferror(proc_net_f
)) {
2051 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2052 "Error reading /proc/net/dev: %s",
2053 pcap_strerror(errno
));
2059 (void)fclose(proc_net_f
);
2064 * Description string for the "any" device.
2066 static const char any_descr
[] = "Pseudo-device that captures on all interfaces";
2069 pcap_platform_finddevs(pcap_if_t
**alldevsp
, char *errbuf
)
2074 * Read "/sys/class/net", and add to the list of interfaces all
2075 * interfaces listed there that we don't already have, because,
2076 * on Linux, SIOCGIFCONF reports only interfaces with IPv4 addresses,
2077 * and even getifaddrs() won't return information about
2078 * interfaces with no addresses, so you need to read "/sys/class/net"
2079 * to get the names of the rest of the interfaces.
2081 ret
= scan_sys_class_net(alldevsp
, errbuf
);
2083 return (-1); /* failed */
2086 * No /sys/class/net; try reading /proc/net/dev instead.
2088 if (scan_proc_net_dev(alldevsp
, errbuf
) == -1)
2093 * Add the "any" device.
2095 if (pcap_add_if(alldevsp
, "any", 0, any_descr
, errbuf
) < 0)
2102 if (dag_platform_finddevs(alldevsp
, errbuf
) < 0)
2104 #endif /* HAVE_DAG_API */
2106 #ifdef HAVE_SEPTEL_API
2108 * Add Septel devices.
2110 if (septel_platform_finddevs(alldevsp
, errbuf
) < 0)
2112 #endif /* HAVE_SEPTEL_API */
2115 if (snf_platform_finddevs(alldevsp
, errbuf
) < 0)
2117 #endif /* HAVE_SNF_API */
2119 #ifdef PCAP_SUPPORT_BT
2121 * Add Bluetooth devices.
2123 if (bt_platform_finddevs(alldevsp
, errbuf
) < 0)
2127 #ifdef PCAP_SUPPORT_USB
2131 if (usb_platform_finddevs(alldevsp
, errbuf
) < 0)
2139 * Attach the given BPF code to the packet capture device.
2142 pcap_setfilter_linux_common(pcap_t
*handle
, struct bpf_program
*filter
,
2145 #ifdef SO_ATTACH_FILTER
2146 struct sock_fprog fcode
;
2147 int can_filter_in_kernel
;
2154 strncpy(handle
->errbuf
, "setfilter: No filter specified",
2159 /* Make our private copy of the filter */
2161 if (install_bpf_program(handle
, filter
) < 0)
2162 /* install_bpf_program() filled in errbuf */
2166 * Run user level packet filter by default. Will be overriden if
2167 * installing a kernel filter succeeds.
2169 handle
->md
.use_bpf
= 0;
2171 /* Install kernel level filter if possible */
2173 #ifdef SO_ATTACH_FILTER
2175 if (handle
->fcode
.bf_len
> USHRT_MAX
) {
2177 * fcode.len is an unsigned short for current kernel.
2178 * I have yet to see BPF-Code with that much
2179 * instructions but still it is possible. So for the
2180 * sake of correctness I added this check.
2182 fprintf(stderr
, "Warning: Filter too complex for kernel\n");
2184 fcode
.filter
= NULL
;
2185 can_filter_in_kernel
= 0;
2187 #endif /* USHRT_MAX */
2190 * Oh joy, the Linux kernel uses struct sock_fprog instead
2191 * of struct bpf_program and of course the length field is
2192 * of different size. Pointed out by Sebastian
2194 * Oh, and we also need to fix it up so that all "ret"
2195 * instructions with non-zero operands have 65535 as the
2196 * operand if we're not capturing in memory-mapped modee,
2197 * and so that, if we're in cooked mode, all memory-reference
2198 * instructions use special magic offsets in references to
2199 * the link-layer header and assume that the link-layer
2200 * payload begins at 0; "fix_program()" will do that.
2202 switch (fix_program(handle
, &fcode
, is_mmapped
)) {
2207 * Fatal error; just quit.
2208 * (The "default" case shouldn't happen; we
2209 * return -1 for that reason.)
2215 * The program performed checks that we can't make
2216 * work in the kernel.
2218 can_filter_in_kernel
= 0;
2223 * We have a filter that'll work in the kernel.
2225 can_filter_in_kernel
= 1;
2230 if (can_filter_in_kernel
) {
2231 if ((err
= set_kernel_filter(handle
, &fcode
)) == 0)
2233 /* Installation succeded - using kernel filter. */
2234 handle
->md
.use_bpf
= 1;
2236 else if (err
== -1) /* Non-fatal error */
2239 * Print a warning if we weren't able to install
2240 * the filter for a reason other than "this kernel
2241 * isn't configured to support socket filters.
2243 if (errno
!= ENOPROTOOPT
&& errno
!= EOPNOTSUPP
) {
2245 "Warning: Kernel filter failed: %s\n",
2246 pcap_strerror(errno
));
2252 * If we're not using the kernel filter, get rid of any kernel
2253 * filter that might've been there before, e.g. because the
2254 * previous filter could work in the kernel, or because some other
2255 * code attached a filter to the socket by some means other than
2256 * calling "pcap_setfilter()". Otherwise, the kernel filter may
2257 * filter out packets that would pass the new userland filter.
2259 if (!handle
->md
.use_bpf
)
2260 reset_kernel_filter(handle
);
2263 * Free up the copy of the filter that was made by "fix_program()".
2265 if (fcode
.filter
!= NULL
)
2271 #endif /* SO_ATTACH_FILTER */
2277 pcap_setfilter_linux(pcap_t
*handle
, struct bpf_program
*filter
)
2279 return pcap_setfilter_linux_common(handle
, filter
, 0);
2284 * Set direction flag: Which packets do we accept on a forwarding
2285 * single device? IN, OUT or both?
2288 pcap_setdirection_linux(pcap_t
*handle
, pcap_direction_t d
)
2290 #ifdef HAVE_PF_PACKET_SOCKETS
2291 if (!handle
->md
.sock_packet
) {
2292 handle
->direction
= d
;
2297 * We're not using PF_PACKET sockets, so we can't determine
2298 * the direction of the packet.
2300 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2301 "Setting direction is not supported on SOCK_PACKET sockets");
2306 #ifdef HAVE_PF_PACKET_SOCKETS
2308 * Map the PACKET_ value to a LINUX_SLL_ value; we
2309 * want the same numerical value to be used in
2310 * the link-layer header even if the numerical values
2311 * for the PACKET_ #defines change, so that programs
2312 * that look at the packet type field will always be
2313 * able to handle DLT_LINUX_SLL captures.
2316 map_packet_type_to_sll_type(short int sll_pkttype
)
2318 switch (sll_pkttype
) {
2321 return htons(LINUX_SLL_HOST
);
2323 case PACKET_BROADCAST
:
2324 return htons(LINUX_SLL_BROADCAST
);
2326 case PACKET_MULTICAST
:
2327 return htons(LINUX_SLL_MULTICAST
);
2329 case PACKET_OTHERHOST
:
2330 return htons(LINUX_SLL_OTHERHOST
);
2332 case PACKET_OUTGOING
:
2333 return htons(LINUX_SLL_OUTGOING
);
2342 * Linux uses the ARP hardware type to identify the type of an
2343 * interface. pcap uses the DLT_xxx constants for this. This
2344 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
2345 * constant, as arguments, and sets "handle->linktype" to the
2346 * appropriate DLT_XXX constant and sets "handle->offset" to
2347 * the appropriate value (to make "handle->offset" plus link-layer
2348 * header length be a multiple of 4, so that the link-layer payload
2349 * will be aligned on a 4-byte boundary when capturing packets).
2350 * (If the offset isn't set here, it'll be 0; add code as appropriate
2351 * for cases where it shouldn't be 0.)
2353 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
2354 * in cooked mode; otherwise, we can't use cooked mode, so we have
2355 * to pick some type that works in raw mode, or fail.
2357 * Sets the link type to -1 if unable to map the type.
2359 static void map_arphrd_to_dlt(pcap_t
*handle
, int arptype
, int cooked_ok
)
2365 * This is (presumably) a real Ethernet capture; give it a
2366 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
2367 * that an application can let you choose it, in case you're
2368 * capturing DOCSIS traffic that a Cisco Cable Modem
2369 * Termination System is putting out onto an Ethernet (it
2370 * doesn't put an Ethernet header onto the wire, it puts raw
2371 * DOCSIS frames out on the wire inside the low-level
2372 * Ethernet framing).
2374 * XXX - are there any sorts of "fake Ethernet" that have
2375 * ARPHRD_ETHER but that *shouldn't offer DLT_DOCSIS as
2376 * a Cisco CMTS won't put traffic onto it or get traffic
2377 * bridged onto it? ISDN is handled in "activate_new()",
2378 * as we fall back on cooked mode there; are there any
2381 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
2383 * If that fails, just leave the list empty.
2385 if (handle
->dlt_list
!= NULL
) {
2386 handle
->dlt_list
[0] = DLT_EN10MB
;
2387 handle
->dlt_list
[1] = DLT_DOCSIS
;
2388 handle
->dlt_count
= 2;
2392 case ARPHRD_METRICOM
:
2393 case ARPHRD_LOOPBACK
:
2394 handle
->linktype
= DLT_EN10MB
;
2399 handle
->linktype
= DLT_EN3MB
;
2403 handle
->linktype
= DLT_AX25_KISS
;
2407 handle
->linktype
= DLT_PRONET
;
2411 handle
->linktype
= DLT_CHAOS
;
2414 #define ARPHRD_CAN 280
2417 handle
->linktype
= DLT_CAN_SOCKETCAN
;
2420 #ifndef ARPHRD_IEEE802_TR
2421 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
2423 case ARPHRD_IEEE802_TR
:
2424 case ARPHRD_IEEE802
:
2425 handle
->linktype
= DLT_IEEE802
;
2430 handle
->linktype
= DLT_ARCNET_LINUX
;
2433 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
2434 #define ARPHRD_FDDI 774
2437 handle
->linktype
= DLT_FDDI
;
2441 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
2442 #define ARPHRD_ATM 19
2446 * The Classical IP implementation in ATM for Linux
2447 * supports both what RFC 1483 calls "LLC Encapsulation",
2448 * in which each packet has an LLC header, possibly
2449 * with a SNAP header as well, prepended to it, and
2450 * what RFC 1483 calls "VC Based Multiplexing", in which
2451 * different virtual circuits carry different network
2452 * layer protocols, and no header is prepended to packets.
2454 * They both have an ARPHRD_ type of ARPHRD_ATM, so
2455 * you can't use the ARPHRD_ type to find out whether
2456 * captured packets will have an LLC header, and,
2457 * while there's a socket ioctl to *set* the encapsulation
2458 * type, there's no ioctl to *get* the encapsulation type.
2462 * programs that dissect Linux Classical IP frames
2463 * would have to check for an LLC header and,
2464 * depending on whether they see one or not, dissect
2465 * the frame as LLC-encapsulated or as raw IP (I
2466 * don't know whether there's any traffic other than
2467 * IP that would show up on the socket, or whether
2468 * there's any support for IPv6 in the Linux
2469 * Classical IP code);
2471 * filter expressions would have to compile into
2472 * code that checks for an LLC header and does
2475 * Both of those are a nuisance - and, at least on systems
2476 * that support PF_PACKET sockets, we don't have to put
2477 * up with those nuisances; instead, we can just capture
2478 * in cooked mode. That's what we'll do, if we can.
2479 * Otherwise, we'll just fail.
2482 handle
->linktype
= DLT_LINUX_SLL
;
2484 handle
->linktype
= -1;
2487 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
2488 #define ARPHRD_IEEE80211 801
2490 case ARPHRD_IEEE80211
:
2491 handle
->linktype
= DLT_IEEE802_11
;
2494 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
2495 #define ARPHRD_IEEE80211_PRISM 802
2497 case ARPHRD_IEEE80211_PRISM
:
2498 handle
->linktype
= DLT_PRISM_HEADER
;
2501 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
2502 #define ARPHRD_IEEE80211_RADIOTAP 803
2504 case ARPHRD_IEEE80211_RADIOTAP
:
2505 handle
->linktype
= DLT_IEEE802_11_RADIO
;
2510 * Some PPP code in the kernel supplies no link-layer
2511 * header whatsoever to PF_PACKET sockets; other PPP
2512 * code supplies PPP link-layer headers ("syncppp.c");
2513 * some PPP code might supply random link-layer
2514 * headers (PPP over ISDN - there's code in Ethereal,
2515 * for example, to cope with PPP-over-ISDN captures
2516 * with which the Ethereal developers have had to cope,
2517 * heuristically trying to determine which of the
2518 * oddball link-layer headers particular packets have).
2520 * As such, we just punt, and run all PPP interfaces
2521 * in cooked mode, if we can; otherwise, we just treat
2522 * it as DLT_RAW, for now - if somebody needs to capture,
2523 * on a 2.0[.x] kernel, on PPP devices that supply a
2524 * link-layer header, they'll have to add code here to
2525 * map to the appropriate DLT_ type (possibly adding a
2526 * new DLT_ type, if necessary).
2529 handle
->linktype
= DLT_LINUX_SLL
;
2532 * XXX - handle ISDN types here? We can't fall
2533 * back on cooked sockets, so we'd have to
2534 * figure out from the device name what type of
2535 * link-layer encapsulation it's using, and map
2536 * that to an appropriate DLT_ value, meaning
2537 * we'd map "isdnN" devices to DLT_RAW (they
2538 * supply raw IP packets with no link-layer
2539 * header) and "isdY" devices to a new DLT_I4L_IP
2540 * type that has only an Ethernet packet type as
2541 * a link-layer header.
2543 * But sometimes we seem to get random crap
2544 * in the link-layer header when capturing on
2547 handle
->linktype
= DLT_RAW
;
2551 #ifndef ARPHRD_CISCO
2552 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
2555 handle
->linktype
= DLT_C_HDLC
;
2558 /* Not sure if this is correct for all tunnels, but it
2562 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
2570 #ifndef ARPHRD_RAWHDLC
2571 #define ARPHRD_RAWHDLC 518
2573 case ARPHRD_RAWHDLC
:
2575 #define ARPHRD_DLCI 15
2579 * XXX - should some of those be mapped to DLT_LINUX_SLL
2580 * instead? Should we just map all of them to DLT_LINUX_SLL?
2582 handle
->linktype
= DLT_RAW
;
2586 #define ARPHRD_FRAD 770
2589 handle
->linktype
= DLT_FRELAY
;
2592 case ARPHRD_LOCALTLK
:
2593 handle
->linktype
= DLT_LTALK
;
2597 #define ARPHRD_FCPP 784
2601 #define ARPHRD_FCAL 785
2605 #define ARPHRD_FCPL 786
2608 #ifndef ARPHRD_FCFABRIC
2609 #define ARPHRD_FCFABRIC 787
2611 case ARPHRD_FCFABRIC
:
2613 * We assume that those all mean RFC 2625 IP-over-
2614 * Fibre Channel, with the RFC 2625 header at
2615 * the beginning of the packet.
2617 handle
->linktype
= DLT_IP_OVER_FC
;
2621 #define ARPHRD_IRDA 783
2624 /* Don't expect IP packet out of this interfaces... */
2625 handle
->linktype
= DLT_LINUX_IRDA
;
2626 /* We need to save packet direction for IrDA decoding,
2627 * so let's use "Linux-cooked" mode. Jean II */
2628 //handle->md.cooked = 1;
2631 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
2632 * is needed, please report it to <daniele@orlandi.com> */
2634 #define ARPHRD_LAPD 8445
2637 /* Don't expect IP packet out of this interfaces... */
2638 handle
->linktype
= DLT_LINUX_LAPD
;
2642 #define ARPHRD_NONE 0xFFFE
2646 * No link-layer header; packets are just IP
2647 * packets, so use DLT_RAW.
2649 handle
->linktype
= DLT_RAW
;
2653 handle
->linktype
= -1;
2658 /* ===== Functions to interface to the newer kernels ================== */
2661 * Try to open a packet socket using the new kernel PF_PACKET interface.
2662 * Returns 1 on success, 0 on an error that means the new interface isn't
2663 * present (so the old SOCK_PACKET interface should be tried), and a
2664 * PCAP_ERROR_ value on an error that means that the old mechanism won't
2665 * work either (so it shouldn't be tried).
2668 activate_new(pcap_t
*handle
)
2670 #ifdef HAVE_PF_PACKET_SOCKETS
2671 const char *device
= handle
->opt
.source
;
2672 int is_any_device
= (strcmp(device
, "any") == 0);
2673 int sock_fd
= -1, arptype
;
2674 #ifdef HAVE_PACKET_AUXDATA
2678 struct packet_mreq mr
;
2681 * Open a socket with protocol family packet. If the
2682 * "any" device was specified, we open a SOCK_DGRAM
2683 * socket for the cooked interface, otherwise we first
2684 * try a SOCK_RAW socket for the raw interface.
2686 sock_fd
= is_any_device
?
2687 socket(PF_PACKET
, SOCK_DGRAM
, htons(ETH_P_ALL
)) :
2688 socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
));
2690 if (sock_fd
== -1) {
2691 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "socket: %s",
2692 pcap_strerror(errno
) );
2693 return 0; /* try old mechanism */
2696 /* It seems the kernel supports the new interface. */
2697 handle
->md
.sock_packet
= 0;
2700 * Get the interface index of the loopback device.
2701 * If the attempt fails, don't fail, just set the
2702 * "md.lo_ifindex" to -1.
2704 * XXX - can there be more than one device that loops
2705 * packets back, i.e. devices other than "lo"? If so,
2706 * we'd need to find them all, and have an array of
2707 * indices for them, and check all of them in
2708 * "pcap_read_packet()".
2710 handle
->md
.lo_ifindex
= iface_get_id(sock_fd
, "lo", handle
->errbuf
);
2713 * Default value for offset to align link-layer payload
2714 * on a 4-byte boundary.
2719 * What kind of frames do we have to deal with? Fall back
2720 * to cooked mode if we have an unknown interface type
2721 * or a type we know doesn't work well in raw mode.
2723 if (!is_any_device
) {
2724 /* Assume for now we don't need cooked mode. */
2725 handle
->md
.cooked
= 0;
2727 if (handle
->opt
.rfmon
) {
2729 * We were asked to turn on monitor mode.
2730 * Do so before we get the link-layer type,
2731 * because entering monitor mode could change
2732 * the link-layer type.
2734 err
= enter_rfmon_mode(handle
, sock_fd
, device
);
2742 * Nothing worked for turning monitor mode
2746 return PCAP_ERROR_RFMON_NOTSUP
;
2750 * Either monitor mode has been turned on for
2751 * the device, or we've been given a different
2752 * device to open for monitor mode. If we've
2753 * been given a different device, use it.
2755 if (handle
->md
.mondevice
!= NULL
)
2756 device
= handle
->md
.mondevice
;
2758 arptype
= iface_get_arptype(sock_fd
, device
, handle
->errbuf
);
2763 map_arphrd_to_dlt(handle
, arptype
, 1);
2764 if (handle
->linktype
== -1 ||
2765 handle
->linktype
== DLT_LINUX_SLL
||
2766 handle
->linktype
== DLT_LINUX_IRDA
||
2767 handle
->linktype
== DLT_LINUX_LAPD
||
2768 (handle
->linktype
== DLT_EN10MB
&&
2769 (strncmp("isdn", device
, 4) == 0 ||
2770 strncmp("isdY", device
, 4) == 0))) {
2772 * Unknown interface type (-1), or a
2773 * device we explicitly chose to run
2774 * in cooked mode (e.g., PPP devices),
2775 * or an ISDN device (whose link-layer
2776 * type we can only determine by using
2777 * APIs that may be different on different
2778 * kernels) - reopen in cooked mode.
2780 if (close(sock_fd
) == -1) {
2781 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2782 "close: %s", pcap_strerror(errno
));
2785 sock_fd
= socket(PF_PACKET
, SOCK_DGRAM
,
2787 if (sock_fd
== -1) {
2788 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2789 "socket: %s", pcap_strerror(errno
));
2792 handle
->md
.cooked
= 1;
2795 * Get rid of any link-layer type list
2796 * we allocated - this only supports cooked
2799 if (handle
->dlt_list
!= NULL
) {
2800 free(handle
->dlt_list
);
2801 handle
->dlt_list
= NULL
;
2802 handle
->dlt_count
= 0;
2805 if (handle
->linktype
== -1) {
2807 * Warn that we're falling back on
2808 * cooked mode; we may want to
2809 * update "map_arphrd_to_dlt()"
2810 * to handle the new type.
2812 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2814 "supported by libpcap - "
2815 "falling back to cooked "
2821 * IrDA capture is not a real "cooked" capture,
2822 * it's IrLAP frames, not IP packets. The
2823 * same applies to LAPD capture.
2825 if (handle
->linktype
!= DLT_LINUX_IRDA
&&
2826 handle
->linktype
!= DLT_LINUX_LAPD
)
2827 handle
->linktype
= DLT_LINUX_SLL
;
2830 handle
->md
.ifindex
= iface_get_id(sock_fd
, device
,
2832 if (handle
->md
.ifindex
== -1) {
2837 if ((err
= iface_bind(sock_fd
, handle
->md
.ifindex
,
2838 handle
->errbuf
)) != 1) {
2843 return 0; /* try old mechanism */
2849 if (handle
->opt
.rfmon
) {
2851 * It doesn't support monitor mode.
2853 return PCAP_ERROR_RFMON_NOTSUP
;
2857 * It uses cooked mode.
2859 handle
->md
.cooked
= 1;
2860 handle
->linktype
= DLT_LINUX_SLL
;
2863 * We're not bound to a device.
2864 * For now, we're using this as an indication
2865 * that we can't transmit; stop doing that only
2866 * if we figure out how to transmit in cooked
2869 handle
->md
.ifindex
= -1;
2873 * Select promiscuous mode on if "promisc" is set.
2875 * Do not turn allmulti mode on if we don't select
2876 * promiscuous mode - on some devices (e.g., Orinoco
2877 * wireless interfaces), allmulti mode isn't supported
2878 * and the driver implements it by turning promiscuous
2879 * mode on, and that screws up the operation of the
2880 * card as a normal networking interface, and on no
2881 * other platform I know of does starting a non-
2882 * promiscuous capture affect which multicast packets
2883 * are received by the interface.
2887 * Hmm, how can we set promiscuous mode on all interfaces?
2888 * I am not sure if that is possible at all. For now, we
2889 * silently ignore attempts to turn promiscuous mode on
2890 * for the "any" device (so you don't have to explicitly
2891 * disable it in programs such as tcpdump).
2894 if (!is_any_device
&& handle
->opt
.promisc
) {
2895 memset(&mr
, 0, sizeof(mr
));
2896 mr
.mr_ifindex
= handle
->md
.ifindex
;
2897 mr
.mr_type
= PACKET_MR_PROMISC
;
2898 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_ADD_MEMBERSHIP
,
2899 &mr
, sizeof(mr
)) == -1) {
2900 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2901 "setsockopt: %s", pcap_strerror(errno
));
2907 /* Enable auxillary data if supported and reserve room for
2908 * reconstructing VLAN headers. */
2909 #ifdef HAVE_PACKET_AUXDATA
2911 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_AUXDATA
, &val
,
2912 sizeof(val
)) == -1 && errno
!= ENOPROTOOPT
) {
2913 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2914 "setsockopt: %s", pcap_strerror(errno
));
2918 handle
->offset
+= VLAN_TAG_LEN
;
2919 #endif /* HAVE_PACKET_AUXDATA */
2922 * This is a 2.2[.x] or later kernel (we know that
2923 * because we're not using a SOCK_PACKET socket -
2924 * PF_PACKET is supported only in 2.2 and later
2927 * We can safely pass "recvfrom()" a byte count
2928 * based on the snapshot length.
2930 * If we're in cooked mode, make the snapshot length
2931 * large enough to hold a "cooked mode" header plus
2932 * 1 byte of packet data (so we don't pass a byte
2933 * count of 0 to "recvfrom()").
2935 if (handle
->md
.cooked
) {
2936 if (handle
->snapshot
< SLL_HDR_LEN
+ 1)
2937 handle
->snapshot
= SLL_HDR_LEN
+ 1;
2939 handle
->bufsize
= handle
->snapshot
;
2941 /* Save the socket FD in the pcap structure */
2942 handle
->fd
= sock_fd
;
2947 "New packet capturing interface not supported by build "
2948 "environment", PCAP_ERRBUF_SIZE
);
2954 activate_mmap(pcap_t
*handle
)
2956 #ifdef HAVE_PACKET_RING
2960 * Attempt to allocate a buffer to hold the contents of one
2961 * packet, for use by the oneshot callback.
2963 handle
->md
.oneshot_buffer
= malloc(handle
->snapshot
);
2964 if (handle
->md
.oneshot_buffer
== NULL
) {
2965 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2966 "can't allocate oneshot buffer: %s",
2967 pcap_strerror(errno
));
2971 if (handle
->opt
.buffer_size
== 0) {
2972 /* by default request 2M for the ring buffer */
2973 handle
->opt
.buffer_size
= 2*1024*1024;
2975 ret
= prepare_tpacket_socket(handle
);
2977 free(handle
->md
.oneshot_buffer
);
2980 ret
= create_ring(handle
);
2982 free(handle
->md
.oneshot_buffer
);
2986 /* override some defaults and inherit the other fields from
2988 * handle->offset is used to get the current position into the rx ring
2989 * handle->cc is used to store the ring size */
2990 handle
->read_op
= pcap_read_linux_mmap
;
2991 handle
->cleanup_op
= pcap_cleanup_linux_mmap
;
2992 handle
->setfilter_op
= pcap_setfilter_linux_mmap
;
2993 handle
->setnonblock_op
= pcap_setnonblock_mmap
;
2994 handle
->getnonblock_op
= pcap_getnonblock_mmap
;
2995 handle
->oneshot_callback
= pcap_oneshot_mmap
;
2996 handle
->selectable_fd
= handle
->fd
;
2998 #else /* HAVE_PACKET_RING */
3000 #endif /* HAVE_PACKET_RING */
3003 #ifdef HAVE_PACKET_RING
3005 prepare_tpacket_socket(pcap_t
*handle
)
3007 #ifdef HAVE_TPACKET2
3012 handle
->md
.tp_version
= TPACKET_V1
;
3013 handle
->md
.tp_hdrlen
= sizeof(struct tpacket_hdr
);
3015 #ifdef HAVE_TPACKET2
3016 /* Probe whether kernel supports TPACKET_V2 */
3019 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_HDRLEN
, &val
, &len
) < 0) {
3020 if (errno
== ENOPROTOOPT
)
3021 return 1; /* no - just drive on */
3023 /* Yes - treat as a failure. */
3024 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3025 "can't get TPACKET_V2 header len on packet socket: %s",
3026 pcap_strerror(errno
));
3029 handle
->md
.tp_hdrlen
= val
;
3032 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_VERSION
, &val
,
3034 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3035 "can't activate TPACKET_V2 on packet socket: %s",
3036 pcap_strerror(errno
));
3039 handle
->md
.tp_version
= TPACKET_V2
;
3041 /* Reserve space for VLAN tag reconstruction */
3043 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
, &val
,
3045 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3046 "can't set up reserve on packet socket: %s",
3047 pcap_strerror(errno
));
3051 #endif /* HAVE_TPACKET2 */
3056 create_ring(pcap_t
*handle
)
3058 unsigned i
, j
, frames_per_block
;
3059 struct tpacket_req req
;
3061 /* Note that with large snapshot (say 64K) only a few frames
3062 * will be available in the ring even with pretty large ring size
3063 * (and a lot of memory will be unused).
3064 * The snap len should be carefully chosen to achive best
3066 req
.tp_frame_size
= TPACKET_ALIGN(handle
->snapshot
+
3067 TPACKET_ALIGN(handle
->md
.tp_hdrlen
) +
3068 sizeof(struct sockaddr_ll
));
3069 req
.tp_frame_nr
= handle
->opt
.buffer_size
/req
.tp_frame_size
;
3071 /* compute the minumum block size that will handle this frame.
3072 * The block has to be page size aligned.
3073 * The max block size allowed by the kernel is arch-dependent and
3074 * it's not explicitly checked here. */
3075 req
.tp_block_size
= getpagesize();
3076 while (req
.tp_block_size
< req
.tp_frame_size
)
3077 req
.tp_block_size
<<= 1;
3079 frames_per_block
= req
.tp_block_size
/req
.tp_frame_size
;
3081 /* ask the kernel to create the ring */
3083 req
.tp_block_nr
= req
.tp_frame_nr
/ frames_per_block
;
3085 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
3086 req
.tp_frame_nr
= req
.tp_block_nr
* frames_per_block
;
3088 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
3089 (void *) &req
, sizeof(req
))) {
3090 if ((errno
== ENOMEM
) && (req
.tp_block_nr
> 1)) {
3092 * Memory failure; try to reduce the requested ring
3095 * We used to reduce this by half -- do 5% instead.
3096 * That may result in more iterations and a longer
3097 * startup, but the user will be much happier with
3098 * the resulting buffer size.
3100 if (req
.tp_frame_nr
< 20)
3101 req
.tp_frame_nr
-= 1;
3103 req
.tp_frame_nr
-= req
.tp_frame_nr
/20;
3106 if (errno
== ENOPROTOOPT
) {
3108 * We don't have ring buffer support in this kernel.
3112 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3113 "can't create rx ring on packet socket: %s",
3114 pcap_strerror(errno
));
3118 /* memory map the rx ring */
3119 handle
->md
.mmapbuflen
= req
.tp_block_nr
* req
.tp_block_size
;
3120 handle
->md
.mmapbuf
= mmap(0, handle
->md
.mmapbuflen
,
3121 PROT_READ
|PROT_WRITE
, MAP_SHARED
, handle
->fd
, 0);
3122 if (handle
->md
.mmapbuf
== MAP_FAILED
) {
3123 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3124 "can't mmap rx ring: %s", pcap_strerror(errno
));
3126 /* clear the allocated ring on error*/
3127 destroy_ring(handle
);
3131 /* allocate a ring for each frame header pointer*/
3132 handle
->cc
= req
.tp_frame_nr
;
3133 handle
->buffer
= malloc(handle
->cc
* sizeof(union thdr
*));
3134 if (!handle
->buffer
) {
3135 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3136 "can't allocate ring of frame headers: %s",
3137 pcap_strerror(errno
));
3139 destroy_ring(handle
);
3143 /* fill the header ring with proper frame ptr*/
3145 for (i
=0; i
<req
.tp_block_nr
; ++i
) {
3146 void *base
= &handle
->md
.mmapbuf
[i
*req
.tp_block_size
];
3147 for (j
=0; j
<frames_per_block
; ++j
, ++handle
->offset
) {
3148 RING_GET_FRAME(handle
) = base
;
3149 base
+= req
.tp_frame_size
;
3153 handle
->bufsize
= req
.tp_frame_size
;
3158 /* free all ring related resources*/
3160 destroy_ring(pcap_t
*handle
)
3162 /* tell the kernel to destroy the ring*/
3163 struct tpacket_req req
;
3164 memset(&req
, 0, sizeof(req
));
3165 setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
3166 (void *) &req
, sizeof(req
));
3168 /* if ring is mapped, unmap it*/
3169 if (handle
->md
.mmapbuf
) {
3170 /* do not test for mmap failure, as we can't recover from any error */
3171 munmap(handle
->md
.mmapbuf
, handle
->md
.mmapbuflen
);
3172 handle
->md
.mmapbuf
= NULL
;
3177 * Special one-shot callback, used for pcap_next() and pcap_next_ex(),
3178 * for Linux mmapped capture.
3180 * The problem is that pcap_next() and pcap_next_ex() expect the packet
3181 * data handed to the callback to be valid after the callback returns,
3182 * but pcap_read_linux_mmap() has to release that packet as soon as
3183 * the callback returns (otherwise, the kernel thinks there's still
3184 * at least one unprocessed packet available in the ring, so a select()
3185 * will immediately return indicating that there's data to process), so,
3186 * in the callback, we have to make a copy of the packet.
3188 * Yes, this means that, if the capture is using the ring buffer, using
3189 * pcap_next() or pcap_next_ex() requires more copies than using
3190 * pcap_loop() or pcap_dispatch(). If that bothers you, don't use
3191 * pcap_next() or pcap_next_ex().
3194 pcap_oneshot_mmap(u_char
*user
, const struct pcap_pkthdr
*h
,
3195 const u_char
*bytes
)
3197 struct oneshot_userdata
*sp
= (struct oneshot_userdata
*)user
;
3200 memcpy(sp
->pd
->md
.oneshot_buffer
, bytes
, h
->caplen
);
3201 *sp
->pkt
= sp
->pd
->md
.oneshot_buffer
;
3205 pcap_cleanup_linux_mmap( pcap_t
*handle
)
3207 destroy_ring(handle
);
3208 if (handle
->md
.oneshot_buffer
!= NULL
) {
3209 free(handle
->md
.oneshot_buffer
);
3210 handle
->md
.oneshot_buffer
= NULL
;
3212 pcap_cleanup_linux(handle
);
3217 pcap_getnonblock_mmap(pcap_t
*p
, char *errbuf
)
3219 /* use negative value of timeout to indicate non blocking ops */
3220 return (p
->md
.timeout
<0);
3224 pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
, char *errbuf
)
3226 /* map each value to the corresponding 2's complement, to
3227 * preserve the timeout value provided with pcap_set_timeout */
3229 if (p
->md
.timeout
>= 0) {
3231 * Timeout is non-negative, so we're not already
3232 * in non-blocking mode; set it to the 2's
3233 * complement, to make it negative, as an
3234 * indication that we're in non-blocking mode.
3236 p
->md
.timeout
= p
->md
.timeout
*-1 - 1;
3239 if (p
->md
.timeout
< 0) {
3241 * Timeout is negative, so we're not already
3242 * in blocking mode; reverse the previous
3243 * operation, to make the timeout non-negative
3246 p
->md
.timeout
= (p
->md
.timeout
+1)*-1;
3252 static inline union thdr
*
3253 pcap_get_ring_frame(pcap_t
*handle
, int status
)
3257 h
.raw
= RING_GET_FRAME(handle
);
3258 switch (handle
->md
.tp_version
) {
3260 if (status
!= (h
.h1
->tp_status
? TP_STATUS_USER
:
3264 #ifdef HAVE_TPACKET2
3266 if (status
!= (h
.h2
->tp_status
? TP_STATUS_USER
:
3280 pcap_read_linux_mmap(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
3287 /* wait for frames availability.*/
3288 if (!pcap_get_ring_frame(handle
, TP_STATUS_USER
)) {
3289 struct pollfd pollinfo
;
3292 pollinfo
.fd
= handle
->fd
;
3293 pollinfo
.events
= POLLIN
;
3295 if (handle
->md
.timeout
== 0)
3296 timeout
= -1; /* block forever */
3297 else if (handle
->md
.timeout
> 0)
3298 timeout
= handle
->md
.timeout
; /* block for that amount of time */
3300 timeout
= 0; /* non-blocking mode - poll to pick up errors */
3302 ret
= poll(&pollinfo
, 1, timeout
);
3303 if (ret
< 0 && errno
!= EINTR
) {
3304 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3305 "can't poll on packet socket: %s",
3306 pcap_strerror(errno
));
3308 } else if (ret
> 0 &&
3309 (pollinfo
.revents
& (POLLHUP
|POLLRDHUP
|POLLERR
|POLLNVAL
))) {
3311 * There's some indication other than
3312 * "you can read on this descriptor" on
3315 if (pollinfo
.revents
& (POLLHUP
| POLLRDHUP
)) {
3316 snprintf(handle
->errbuf
,
3318 "Hangup on packet socket");
3321 if (pollinfo
.revents
& POLLERR
) {
3323 * A recv() will give us the
3324 * actual error code.
3326 * XXX - make the socket non-blocking?
3328 if (recv(handle
->fd
, &c
, sizeof c
,
3330 continue; /* what, no error? */
3331 if (errno
== ENETDOWN
) {
3333 * The device on which we're
3334 * capturing went away.
3336 * XXX - we should really return
3337 * PCAP_ERROR_IFACE_NOT_UP,
3338 * but pcap_dispatch() etc.
3339 * aren't defined to return
3342 snprintf(handle
->errbuf
,
3344 "The interface went down");
3346 snprintf(handle
->errbuf
,
3348 "Error condition on packet socket: %s",
3353 if (pollinfo
.revents
& POLLNVAL
) {
3354 snprintf(handle
->errbuf
,
3356 "Invalid polling request on packet socket");
3360 /* check for break loop condition on interrupted syscall*/
3361 if (handle
->break_loop
) {
3362 handle
->break_loop
= 0;
3363 return PCAP_ERROR_BREAK
;
3368 /* non-positive values of max_packets are used to require all
3369 * packets currently available in the ring */
3370 while ((pkts
< max_packets
) || (max_packets
<= 0)) {
3372 struct sockaddr_ll
*sll
;
3373 struct pcap_pkthdr pcaphdr
;
3376 unsigned int tp_len
;
3377 unsigned int tp_mac
;
3378 unsigned int tp_snaplen
;
3379 unsigned int tp_sec
;
3380 unsigned int tp_usec
;
3382 h
.raw
= pcap_get_ring_frame(handle
, TP_STATUS_USER
);
3386 switch (handle
->md
.tp_version
) {
3388 tp_len
= h
.h1
->tp_len
;
3389 tp_mac
= h
.h1
->tp_mac
;
3390 tp_snaplen
= h
.h1
->tp_snaplen
;
3391 tp_sec
= h
.h1
->tp_sec
;
3392 tp_usec
= h
.h1
->tp_usec
;
3394 #ifdef HAVE_TPACKET2
3396 tp_len
= h
.h2
->tp_len
;
3397 tp_mac
= h
.h2
->tp_mac
;
3398 tp_snaplen
= h
.h2
->tp_snaplen
;
3399 tp_sec
= h
.h2
->tp_sec
;
3400 tp_usec
= h
.h2
->tp_nsec
/ 1000;
3404 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3405 "unsupported tpacket version %d",
3406 handle
->md
.tp_version
);
3409 /* perform sanity check on internal offset. */
3410 if (tp_mac
+ tp_snaplen
> handle
->bufsize
) {
3411 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3412 "corrupted frame on kernel ring mac "
3413 "offset %d + caplen %d > frame len %d",
3414 tp_mac
, tp_snaplen
, handle
->bufsize
);
3418 /* run filter on received packet
3419 * If the kernel filtering is enabled we need to run the
3420 * filter until all the frames present into the ring
3421 * at filter creation time are processed.
3422 * In such case md.use_bpf is used as a counter for the
3423 * packet we need to filter.
3424 * Note: alternatively it could be possible to stop applying
3425 * the filter when the ring became empty, but it can possibly
3426 * happen a lot later... */
3427 bp
= (unsigned char*)h
.raw
+ tp_mac
;
3428 run_bpf
= (!handle
->md
.use_bpf
) ||
3429 ((handle
->md
.use_bpf
>1) && handle
->md
.use_bpf
--);
3430 if (run_bpf
&& handle
->fcode
.bf_insns
&&
3431 (bpf_filter(handle
->fcode
.bf_insns
, bp
,
3432 tp_len
, tp_snaplen
) == 0))
3436 * Do checks based on packet direction.
3438 sll
= (void *)h
.raw
+ TPACKET_ALIGN(handle
->md
.tp_hdrlen
);
3439 if (sll
->sll_pkttype
== PACKET_OUTGOING
) {
3442 * If this is from the loopback device, reject it;
3443 * we'll see the packet as an incoming packet as well,
3444 * and we don't want to see it twice.
3446 if (sll
->sll_ifindex
== handle
->md
.lo_ifindex
)
3450 * If the user only wants incoming packets, reject it.
3452 if (handle
->direction
== PCAP_D_IN
)
3457 * If the user only wants outgoing packets, reject it.
3459 if (handle
->direction
== PCAP_D_OUT
)
3463 /* get required packet info from ring header */
3464 pcaphdr
.ts
.tv_sec
= tp_sec
;
3465 pcaphdr
.ts
.tv_usec
= tp_usec
;
3466 pcaphdr
.caplen
= tp_snaplen
;
3467 pcaphdr
.len
= tp_len
;
3469 /* if required build in place the sll header*/
3470 if (handle
->md
.cooked
) {
3471 struct sll_header
*hdrp
;
3474 * The kernel should have left us with enough
3475 * space for an sll header; back up the packet
3476 * data pointer into that space, as that'll be
3477 * the beginning of the packet we pass to the
3483 * Let's make sure that's past the end of
3484 * the tpacket header, i.e. >=
3485 * ((u_char *)thdr + TPACKET_HDRLEN), so we
3486 * don't step on the header when we construct
3489 if (bp
< (u_char
*)h
.raw
+
3490 TPACKET_ALIGN(handle
->md
.tp_hdrlen
) +
3491 sizeof(struct sockaddr_ll
)) {
3492 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3493 "cooked-mode frame doesn't have room for sll header");
3498 * OK, that worked; construct the sll header.
3500 hdrp
= (struct sll_header
*)bp
;
3501 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(
3503 hdrp
->sll_hatype
= htons(sll
->sll_hatype
);
3504 hdrp
->sll_halen
= htons(sll
->sll_halen
);
3505 memcpy(hdrp
->sll_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
3506 hdrp
->sll_protocol
= sll
->sll_protocol
;
3508 /* update packet len */
3509 pcaphdr
.caplen
+= SLL_HDR_LEN
;
3510 pcaphdr
.len
+= SLL_HDR_LEN
;
3513 #ifdef HAVE_TPACKET2
3514 if (handle
->md
.tp_version
== TPACKET_V2
&& h
.h2
->tp_vlan_tci
&&
3515 tp_snaplen
>= 2 * ETH_ALEN
) {
3516 struct vlan_tag
*tag
;
3519 memmove(bp
, bp
+ VLAN_TAG_LEN
, 2 * ETH_ALEN
);
3521 tag
= (struct vlan_tag
*)(bp
+ 2 * ETH_ALEN
);
3522 tag
->vlan_tpid
= htons(ETH_P_8021Q
);
3523 tag
->vlan_tci
= htons(h
.h2
->tp_vlan_tci
);
3525 pcaphdr
.caplen
+= VLAN_TAG_LEN
;
3526 pcaphdr
.len
+= VLAN_TAG_LEN
;
3531 * The only way to tell the kernel to cut off the
3532 * packet at a snapshot length is with a filter program;
3533 * if there's no filter program, the kernel won't cut
3536 * Trim the snapshot length to be no longer than the
3537 * specified snapshot length.
3539 if (pcaphdr
.caplen
> handle
->snapshot
)
3540 pcaphdr
.caplen
= handle
->snapshot
;
3542 /* pass the packet to the user */
3544 callback(user
, &pcaphdr
, bp
);
3545 handle
->md
.packets_read
++;
3549 switch (handle
->md
.tp_version
) {
3551 h
.h1
->tp_status
= TP_STATUS_KERNEL
;
3553 #ifdef HAVE_TPACKET2
3555 h
.h2
->tp_status
= TP_STATUS_KERNEL
;
3559 if (++handle
->offset
>= handle
->cc
)
3562 /* check for break loop condition*/
3563 if (handle
->break_loop
) {
3564 handle
->break_loop
= 0;
3565 return PCAP_ERROR_BREAK
;
3572 pcap_setfilter_linux_mmap(pcap_t
*handle
, struct bpf_program
*filter
)
3578 * Don't rewrite "ret" instructions; we don't need to, as
3579 * we're not reading packets with recvmsg(), and we don't
3580 * want to, as, by not rewriting them, the kernel can avoid
3581 * copying extra data.
3583 ret
= pcap_setfilter_linux_common(handle
, filter
, 1);
3587 /* if the kernel filter is enabled, we need to apply the filter on
3588 * all packets present into the ring. Get an upper bound of their number
3590 if (!handle
->md
.use_bpf
)
3593 /* walk the ring backward and count the free slot */
3594 offset
= handle
->offset
;
3595 if (--handle
->offset
< 0)
3596 handle
->offset
= handle
->cc
- 1;
3597 for (n
=0; n
< handle
->cc
; ++n
) {
3598 if (--handle
->offset
< 0)
3599 handle
->offset
= handle
->cc
- 1;
3600 if (!pcap_get_ring_frame(handle
, TP_STATUS_KERNEL
))
3604 /* be careful to not change current ring position */
3605 handle
->offset
= offset
;
3607 /* store the number of packets currently present in the ring */
3608 handle
->md
.use_bpf
= 1 + (handle
->cc
- n
);
3612 #endif /* HAVE_PACKET_RING */
3615 #ifdef HAVE_PF_PACKET_SOCKETS
3617 * Return the index of the given device name. Fill ebuf and return
3621 iface_get_id(int fd
, const char *device
, char *ebuf
)
3625 memset(&ifr
, 0, sizeof(ifr
));
3626 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
3628 if (ioctl(fd
, SIOCGIFINDEX
, &ifr
) == -1) {
3629 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3630 "SIOCGIFINDEX: %s", pcap_strerror(errno
));
3634 return ifr
.ifr_ifindex
;
3638 * Bind the socket associated with FD to the given device.
3639 * Return 1 on success, 0 if we should try a SOCK_PACKET socket,
3640 * or a PCAP_ERROR_ value on a hard error.
3643 iface_bind(int fd
, int ifindex
, char *ebuf
)
3645 struct sockaddr_ll sll
;
3647 socklen_t errlen
= sizeof(err
);
3649 memset(&sll
, 0, sizeof(sll
));
3650 sll
.sll_family
= AF_PACKET
;
3651 sll
.sll_ifindex
= ifindex
;
3652 sll
.sll_protocol
= htons(ETH_P_ALL
);
3654 if (bind(fd
, (struct sockaddr
*) &sll
, sizeof(sll
)) == -1) {
3655 if (errno
== ENETDOWN
) {
3657 * Return a "network down" indication, so that
3658 * the application can report that rather than
3659 * saying we had a mysterious failure and
3660 * suggest that they report a problem to the
3661 * libpcap developers.
3663 return PCAP_ERROR_IFACE_NOT_UP
;
3665 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3666 "bind: %s", pcap_strerror(errno
));
3671 /* Any pending errors, e.g., network is down? */
3673 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
3674 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3675 "getsockopt: %s", pcap_strerror(errno
));
3679 if (err
== ENETDOWN
) {
3681 * Return a "network down" indication, so that
3682 * the application can report that rather than
3683 * saying we had a mysterious failure and
3684 * suggest that they report a problem to the
3685 * libpcap developers.
3687 return PCAP_ERROR_IFACE_NOT_UP
;
3688 } else if (err
> 0) {
3689 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3690 "bind: %s", pcap_strerror(err
));
3697 #ifdef IW_MODE_MONITOR
3699 * Check whether the device supports the Wireless Extensions.
3700 * Returns 1 if it does, 0 if it doesn't, PCAP_ERROR_NO_SUCH_DEVICE
3701 * if the device doesn't even exist.
3704 has_wext(int sock_fd
, const char *device
, char *ebuf
)
3708 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3709 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3710 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3711 if (ioctl(sock_fd
, SIOCGIWNAME
, &ireq
) >= 0)
3713 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3714 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
3715 if (errno
== ENODEV
)
3716 return PCAP_ERROR_NO_SUCH_DEVICE
;
3721 * Per me si va ne la citta dolente,
3722 * Per me si va ne l'etterno dolore,
3724 * Lasciate ogne speranza, voi ch'intrate.
3726 * XXX - airmon-ng does special stuff with the Orinoco driver and the
3742 * Use the Wireless Extensions, if we have them, to try to turn monitor mode
3743 * on if it's not already on.
3745 * Returns 1 on success, 0 if we don't support the Wireless Extensions
3746 * on this device, or a PCAP_ERROR_ value if we do support them but
3747 * we weren't able to turn monitor mode on.
3750 enter_rfmon_mode_wext(pcap_t
*handle
, int sock_fd
, const char *device
)
3753 * XXX - at least some adapters require non-Wireless Extensions
3754 * mechanisms to turn monitor mode on.
3756 * Atheros cards might require that a separate "monitor virtual access
3757 * point" be created, with later versions of the madwifi driver.
3758 * airmon-ng does "wlanconfig ath create wlandev {if} wlanmode
3759 * monitor -bssid", which apparently spits out a line "athN"
3760 * where "athN" is the monitor mode device. To leave monitor
3761 * mode, it destroys the monitor mode device.
3763 * Some Intel Centrino adapters might require private ioctls to get
3764 * radio headers; the ipw2200 and ipw3945 drivers allow you to
3765 * configure a separate "rtapN" interface to capture in monitor
3766 * mode without preventing the adapter from operating normally.
3767 * (airmon-ng doesn't appear to use that, though.)
3769 * It would be Truly Wonderful if mac80211 and nl80211 cleaned this
3770 * up, and if all drivers were converted to mac80211 drivers.
3772 * If interface {if} is a mac80211 driver, the file
3773 * /sys/class/net/{if}/phy80211 is a symlink to
3774 * /sys/class/ieee80211/{phydev}, for some {phydev}.
3776 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
3777 * least, has a "wmaster0" device and a "wlan0" device; the
3778 * latter is the one with the IP address. Both show up in
3779 * "tcpdump -D" output. Capturing on the wmaster0 device
3780 * captures with 802.11 headers.
3782 * airmon-ng searches through /sys/class/net for devices named
3783 * monN, starting with mon0; as soon as one *doesn't* exist,
3784 * it chooses that as the monitor device name. If the "iw"
3785 * command exists, it does "iw dev {if} interface add {monif}
3786 * type monitor", where {monif} is the monitor device. It
3787 * then (sigh) sleeps .1 second, and then configures the
3788 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
3789 * is a file, it writes {mondev}, without a newline, to that file,
3790 * and again (sigh) sleeps .1 second, and then iwconfig's that
3791 * device into monitor mode and configures it up. Otherwise,
3792 * you can't do monitor mode.
3794 * All these devices are "glued" together by having the
3795 * /sys/class/net/{device}/phy80211 links pointing to the same
3796 * place, so, given a wmaster, wlan, or mon device, you can
3797 * find the other devices by looking for devices with
3798 * the same phy80211 link.
3800 * To turn monitor mode off, delete the monitor interface,
3801 * either with "iw dev {monif} interface del" or by sending
3802 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
3804 * Note: if you try to create a monitor device named "monN", and
3805 * there's already a "monN" device, it fails, as least with
3806 * the netlink interface (which is what iw uses), with a return
3807 * value of -ENFILE. (Return values are negative errnos.) We
3808 * could probably use that to find an unused device.
3812 struct iw_priv_args
*priv
;
3813 monitor_type montype
;
3820 * Does this device *support* the Wireless Extensions?
3822 err
= has_wext(sock_fd
, device
, handle
->errbuf
);
3824 return err
; /* either it doesn't or the device doesn't even exist */
3826 * Try to get all the Wireless Extensions private ioctls
3827 * supported by this device.
3829 * First, get the size of the buffer we need, by supplying no
3830 * buffer and a length of 0. If the device supports private
3831 * ioctls, it should return E2BIG, with ireq.u.data.length set
3832 * to the length we need. If it doesn't support them, it should
3833 * return EOPNOTSUPP.
3835 memset(&ireq
, 0, sizeof ireq
);
3836 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3837 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3838 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3839 ireq
.u
.data
.pointer
= (void *)args
;
3840 ireq
.u
.data
.length
= 0;
3841 ireq
.u
.data
.flags
= 0;
3842 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) != -1) {
3843 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3844 "%s: SIOCGIWPRIV with a zero-length buffer didn't fail!",
3848 if (errno
== EOPNOTSUPP
) {
3850 * No private ioctls, so we assume that there's only one
3851 * DLT_ for monitor mode.
3855 if (errno
!= E2BIG
) {
3859 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3860 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
3863 priv
= malloc(ireq
.u
.data
.length
* sizeof (struct iw_priv_args
));
3865 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3866 "malloc: %s", pcap_strerror(errno
));
3869 ireq
.u
.data
.pointer
= (void *)priv
;
3870 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) == -1) {
3871 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3872 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
3878 * Look for private ioctls to turn monitor mode on or, if
3879 * monitor mode is on, to set the header type.
3881 montype
= MONITOR_WEXT
;
3883 for (i
= 0; i
< ireq
.u
.data
.length
; i
++) {
3884 if (strcmp(priv
[i
].name
, "monitor_type") == 0) {
3886 * Hostap driver, use this one.
3887 * Set monitor mode first.
3888 * You can set it to 0 to get DLT_IEEE80211,
3889 * 1 to get DLT_PRISM, 2 to get
3890 * DLT_IEEE80211_RADIO_AVS, and, with more
3891 * recent versions of the driver, 3 to get
3892 * DLT_IEEE80211_RADIO.
3894 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
3896 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
3898 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
3900 montype
= MONITOR_HOSTAP
;
3904 if (strcmp(priv
[i
].name
, "set_prismhdr") == 0) {
3906 * Prism54 driver, use this one.
3907 * Set monitor mode first.
3908 * You can set it to 2 to get DLT_IEEE80211
3909 * or 3 or get DLT_PRISM.
3911 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
3913 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
3915 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
3917 montype
= MONITOR_PRISM54
;
3921 if (strcmp(priv
[i
].name
, "forceprismheader") == 0) {
3923 * RT2570 driver, use this one.
3924 * Do this after turning monitor mode on.
3925 * You can set it to 1 to get DLT_PRISM or 2
3926 * to get DLT_IEEE80211.
3928 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
3930 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
3932 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
3934 montype
= MONITOR_RT2570
;
3938 if (strcmp(priv
[i
].name
, "forceprism") == 0) {
3940 * RT73 driver, use this one.
3941 * Do this after turning monitor mode on.
3942 * Its argument is a *string*; you can
3943 * set it to "1" to get DLT_PRISM or "2"
3944 * to get DLT_IEEE80211.
3946 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_CHAR
)
3948 if (priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
)
3950 montype
= MONITOR_RT73
;
3954 if (strcmp(priv
[i
].name
, "prismhdr") == 0) {
3956 * One of the RTL8xxx drivers, use this one.
3957 * It can only be done after monitor mode
3958 * has been turned on. You can set it to 1
3959 * to get DLT_PRISM or 0 to get DLT_IEEE80211.
3961 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
3963 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
3965 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
3967 montype
= MONITOR_RTL8XXX
;
3971 if (strcmp(priv
[i
].name
, "rfmontx") == 0) {
3973 * RT2500 or RT61 driver, use this one.
3974 * It has one one-byte parameter; set
3975 * u.data.length to 1 and u.data.pointer to
3976 * point to the parameter.
3977 * It doesn't itself turn monitor mode on.
3978 * You can set it to 1 to allow transmitting
3979 * in monitor mode(?) and get DLT_IEEE80211,
3980 * or set it to 0 to disallow transmitting in
3981 * monitor mode(?) and get DLT_PRISM.
3983 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
3985 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 2)
3987 montype
= MONITOR_RT2500
;
3991 if (strcmp(priv
[i
].name
, "monitor") == 0) {
3993 * Either ACX100 or hostap, use this one.
3994 * It turns monitor mode on.
3995 * If it takes two arguments, it's ACX100;
3996 * the first argument is 1 for DLT_PRISM
3997 * or 2 for DLT_IEEE80211, and the second
3998 * argument is the channel on which to
3999 * run. If it takes one argument, it's
4000 * HostAP, and the argument is 2 for
4001 * DLT_IEEE80211 and 3 for DLT_PRISM.
4003 * If we see this, we don't quit, as this
4004 * might be a version of the hostap driver
4005 * that also supports "monitor_type".
4007 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4009 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4011 switch (priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) {
4014 montype
= MONITOR_PRISM
;
4019 montype
= MONITOR_ACX100
;
4031 * XXX - ipw3945? islism?
4037 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4038 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4039 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4040 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) == -1) {
4042 * We probably won't be able to set the mode, either.
4044 return PCAP_ERROR_RFMON_NOTSUP
;
4048 * Is it currently in monitor mode?
4050 if (ireq
.u
.mode
== IW_MODE_MONITOR
) {
4052 * Yes. Just leave things as they are.
4053 * We don't offer multiple link-layer types, as
4054 * changing the link-layer type out from under
4055 * somebody else capturing in monitor mode would
4056 * be considered rude.
4061 * No. We have to put the adapter into rfmon mode.
4065 * If we haven't already done so, arrange to have
4066 * "pcap_close_all()" called when we exit.
4068 if (!pcap_do_addexit(handle
)) {
4070 * "atexit()" failed; don't put the interface
4071 * in rfmon mode, just give up.
4073 return PCAP_ERROR_RFMON_NOTSUP
;
4077 * Save the old mode.
4079 handle
->md
.oldmode
= ireq
.u
.mode
;
4082 * Put the adapter in rfmon mode. How we do this depends
4083 * on whether we have a special private ioctl or not.
4085 if (montype
== MONITOR_PRISM
) {
4087 * We have the "monitor" private ioctl, but none of
4088 * the other private ioctls. Use this, and select
4091 * If it fails, just fall back on SIOCSIWMODE.
4093 memset(&ireq
, 0, sizeof ireq
);
4094 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4095 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4096 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4097 ireq
.u
.data
.length
= 1; /* 1 argument */
4098 args
[0] = 3; /* request Prism header */
4099 memcpy(ireq
.u
.name
, args
, IFNAMSIZ
);
4100 if (ioctl(sock_fd
, cmd
, &ireq
) != -1) {
4103 * Note that we have to put the old mode back
4104 * when we close the device.
4106 handle
->md
.must_do_on_close
|= MUST_CLEAR_RFMON
;
4109 * Add this to the list of pcaps to close
4112 pcap_add_to_pcaps_to_close(handle
);
4118 * Failure. Fall back on SIOCSIWMODE.
4123 * First, turn monitor mode on.
4125 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4126 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4127 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4128 ireq
.u
.mode
= IW_MODE_MONITOR
;
4129 if (ioctl(sock_fd
, SIOCSIWMODE
, &ireq
) == -1) {
4131 * Scientist, you've failed.
4133 return PCAP_ERROR_RFMON_NOTSUP
;
4137 * XXX - airmon-ng does "iwconfig {if} key off" after setting
4138 * monitor mode and setting the channel, and then does
4143 * Now select the appropriate radio header.
4149 * We don't have any private ioctl to set the header.
4153 case MONITOR_HOSTAP
:
4155 * Try to select the radiotap header.
4157 memset(&ireq
, 0, sizeof ireq
);
4158 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4159 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4160 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4161 args
[0] = 3; /* request radiotap header */
4162 memcpy(ireq
.u
.name
, args
, sizeof (int));
4163 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
4164 break; /* success */
4167 * That failed. Try to select the AVS header.
4169 memset(&ireq
, 0, sizeof ireq
);
4170 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4171 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4172 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4173 args
[0] = 2; /* request AVS header */
4174 memcpy(ireq
.u
.name
, args
, sizeof (int));
4175 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
4176 break; /* success */
4179 * That failed. Try to select the Prism header.
4181 memset(&ireq
, 0, sizeof ireq
);
4182 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4183 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4184 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4185 args
[0] = 1; /* request Prism header */
4186 memcpy(ireq
.u
.name
, args
, sizeof (int));
4187 ioctl(sock_fd
, cmd
, &ireq
);
4192 * The private ioctl failed.
4196 case MONITOR_PRISM54
:
4198 * Select the Prism header.
4200 memset(&ireq
, 0, sizeof ireq
);
4201 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4202 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4203 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4204 args
[0] = 3; /* request Prism header */
4205 memcpy(ireq
.u
.name
, args
, sizeof (int));
4206 ioctl(sock_fd
, cmd
, &ireq
);
4209 case MONITOR_ACX100
:
4211 * Get the current channel.
4213 memset(&ireq
, 0, sizeof ireq
);
4214 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4215 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4216 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4217 if (ioctl(sock_fd
, SIOCGIWFREQ
, &ireq
) == -1) {
4218 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4219 "%s: SIOCGIWFREQ: %s", device
,
4220 pcap_strerror(errno
));
4223 channel
= ireq
.u
.freq
.m
;
4226 * Select the Prism header, and set the channel to the
4229 memset(&ireq
, 0, sizeof ireq
);
4230 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4231 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4232 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4233 args
[0] = 1; /* request Prism header */
4234 args
[1] = channel
; /* set channel */
4235 memcpy(ireq
.u
.name
, args
, 2*sizeof (int));
4236 ioctl(sock_fd
, cmd
, &ireq
);
4239 case MONITOR_RT2500
:
4241 * Disallow transmission - that turns on the
4244 memset(&ireq
, 0, sizeof ireq
);
4245 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4246 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4247 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4248 args
[0] = 0; /* disallow transmitting */
4249 memcpy(ireq
.u
.name
, args
, sizeof (int));
4250 ioctl(sock_fd
, cmd
, &ireq
);
4253 case MONITOR_RT2570
:
4255 * Force the Prism header.
4257 memset(&ireq
, 0, sizeof ireq
);
4258 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4259 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4260 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4261 args
[0] = 1; /* request Prism header */
4262 memcpy(ireq
.u
.name
, args
, sizeof (int));
4263 ioctl(sock_fd
, cmd
, &ireq
);
4268 * Force the Prism header.
4270 memset(&ireq
, 0, sizeof ireq
);
4271 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4272 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4273 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4274 ireq
.u
.data
.length
= 1; /* 1 argument */
4275 ireq
.u
.data
.pointer
= "1";
4276 ireq
.u
.data
.flags
= 0;
4277 ioctl(sock_fd
, cmd
, &ireq
);
4280 case MONITOR_RTL8XXX
:
4282 * Force the Prism header.
4284 memset(&ireq
, 0, sizeof ireq
);
4285 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4286 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4287 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4288 args
[0] = 1; /* request Prism header */
4289 memcpy(ireq
.u
.name
, args
, sizeof (int));
4290 ioctl(sock_fd
, cmd
, &ireq
);
4295 * Note that we have to put the old mode back when we
4298 handle
->md
.must_do_on_close
|= MUST_CLEAR_RFMON
;
4301 * Add this to the list of pcaps to close when we exit.
4303 pcap_add_to_pcaps_to_close(handle
);
4307 #endif /* IW_MODE_MONITOR */
4310 * Try various mechanisms to enter monitor mode.
4313 enter_rfmon_mode(pcap_t
*handle
, int sock_fd
, const char *device
)
4315 #if defined(HAVE_LIBNL) || defined(IW_MODE_MONITOR)
4320 ret
= enter_rfmon_mode_mac80211(handle
, sock_fd
, device
);
4322 return ret
; /* error attempting to do so */
4324 return 1; /* success */
4325 #endif /* HAVE_LIBNL */
4327 #ifdef IW_MODE_MONITOR
4328 ret
= enter_rfmon_mode_wext(handle
, sock_fd
, device
);
4330 return ret
; /* error attempting to do so */
4332 return 1; /* success */
4333 #endif /* IW_MODE_MONITOR */
4336 * Either none of the mechanisms we know about work or none
4337 * of those mechanisms are available, so we can't do monitor
4343 #endif /* HAVE_PF_PACKET_SOCKETS */
4345 /* ===== Functions to interface to the older kernels ================== */
4348 * Try to open a packet socket using the old kernel interface.
4349 * Returns 1 on success and a PCAP_ERROR_ value on an error.
4352 activate_old(pcap_t
*handle
)
4356 const char *device
= handle
->opt
.source
;
4357 struct utsname utsname
;
4360 /* Open the socket */
4362 handle
->fd
= socket(PF_INET
, SOCK_PACKET
, htons(ETH_P_ALL
));
4363 if (handle
->fd
== -1) {
4364 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4365 "socket: %s", pcap_strerror(errno
));
4366 return PCAP_ERROR_PERM_DENIED
;
4369 /* It worked - we are using the old interface */
4370 handle
->md
.sock_packet
= 1;
4372 /* ...which means we get the link-layer header. */
4373 handle
->md
.cooked
= 0;
4375 /* Bind to the given device */
4377 if (strcmp(device
, "any") == 0) {
4378 strncpy(handle
->errbuf
, "pcap_activate: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
4382 if (iface_bind_old(handle
->fd
, device
, handle
->errbuf
) == -1)
4386 * Try to get the link-layer type.
4388 arptype
= iface_get_arptype(handle
->fd
, device
, handle
->errbuf
);
4393 * Try to find the DLT_ type corresponding to that
4396 map_arphrd_to_dlt(handle
, arptype
, 0);
4397 if (handle
->linktype
== -1) {
4398 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4399 "unknown arptype %d", arptype
);
4403 /* Go to promisc mode if requested */
4405 if (handle
->opt
.promisc
) {
4406 memset(&ifr
, 0, sizeof(ifr
));
4407 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4408 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
4409 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4410 "SIOCGIFFLAGS: %s", pcap_strerror(errno
));
4413 if ((ifr
.ifr_flags
& IFF_PROMISC
) == 0) {
4415 * Promiscuous mode isn't currently on,
4416 * so turn it on, and remember that
4417 * we should turn it off when the
4422 * If we haven't already done so, arrange
4423 * to have "pcap_close_all()" called when
4426 if (!pcap_do_addexit(handle
)) {
4428 * "atexit()" failed; don't put
4429 * the interface in promiscuous
4430 * mode, just give up.
4435 ifr
.ifr_flags
|= IFF_PROMISC
;
4436 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
4437 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4439 pcap_strerror(errno
));
4442 handle
->md
.must_do_on_close
|= MUST_CLEAR_PROMISC
;
4445 * Add this to the list of pcaps
4446 * to close when we exit.
4448 pcap_add_to_pcaps_to_close(handle
);
4453 * Compute the buffer size.
4455 * We're using SOCK_PACKET, so this might be a 2.0[.x]
4456 * kernel, and might require special handling - check.
4458 if (uname(&utsname
) < 0 ||
4459 strncmp(utsname
.release
, "2.0", 3) == 0) {
4461 * Either we couldn't find out what kernel release
4462 * this is, or it's a 2.0[.x] kernel.
4464 * In the 2.0[.x] kernel, a "recvfrom()" on
4465 * a SOCK_PACKET socket, with MSG_TRUNC set, will
4466 * return the number of bytes read, so if we pass
4467 * a length based on the snapshot length, it'll
4468 * return the number of bytes from the packet
4469 * copied to userland, not the actual length
4472 * This means that, for example, the IP dissector
4473 * in tcpdump will get handed a packet length less
4474 * than the length in the IP header, and will
4475 * complain about "truncated-ip".
4477 * So we don't bother trying to copy from the
4478 * kernel only the bytes in which we're interested,
4479 * but instead copy them all, just as the older
4480 * versions of libpcap for Linux did.
4482 * The buffer therefore needs to be big enough to
4483 * hold the largest packet we can get from this
4484 * device. Unfortunately, we can't get the MRU
4485 * of the network; we can only get the MTU. The
4486 * MTU may be too small, in which case a packet larger
4487 * than the buffer size will be truncated *and* we
4488 * won't get the actual packet size.
4490 * However, if the snapshot length is larger than
4491 * the buffer size based on the MTU, we use the
4492 * snapshot length as the buffer size, instead;
4493 * this means that with a sufficiently large snapshot
4494 * length we won't artificially truncate packets
4495 * to the MTU-based size.
4497 * This mess just one of many problems with packet
4498 * capture on 2.0[.x] kernels; you really want a
4499 * 2.2[.x] or later kernel if you want packet capture
4502 mtu
= iface_get_mtu(handle
->fd
, device
, handle
->errbuf
);
4505 handle
->bufsize
= MAX_LINKHEADER_SIZE
+ mtu
;
4506 if (handle
->bufsize
< handle
->snapshot
)
4507 handle
->bufsize
= handle
->snapshot
;
4510 * This is a 2.2[.x] or later kernel.
4512 * We can safely pass "recvfrom()" a byte count
4513 * based on the snapshot length.
4515 handle
->bufsize
= handle
->snapshot
;
4519 * Default value for offset to align link-layer payload
4520 * on a 4-byte boundary.
4528 * Bind the socket associated with FD to the given device using the
4529 * interface of the old kernels.
4532 iface_bind_old(int fd
, const char *device
, char *ebuf
)
4534 struct sockaddr saddr
;
4536 socklen_t errlen
= sizeof(err
);
4538 memset(&saddr
, 0, sizeof(saddr
));
4539 strncpy(saddr
.sa_data
, device
, sizeof(saddr
.sa_data
));
4540 if (bind(fd
, &saddr
, sizeof(saddr
)) == -1) {
4541 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4542 "bind: %s", pcap_strerror(errno
));
4546 /* Any pending errors, e.g., network is down? */
4548 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
4549 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4550 "getsockopt: %s", pcap_strerror(errno
));
4555 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4556 "bind: %s", pcap_strerror(err
));
4564 /* ===== System calls available on all supported kernels ============== */
4567 * Query the kernel for the MTU of the given interface.
4570 iface_get_mtu(int fd
, const char *device
, char *ebuf
)
4575 return BIGGER_THAN_ALL_MTUS
;
4577 memset(&ifr
, 0, sizeof(ifr
));
4578 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4580 if (ioctl(fd
, SIOCGIFMTU
, &ifr
) == -1) {
4581 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4582 "SIOCGIFMTU: %s", pcap_strerror(errno
));
4590 * Get the hardware type of the given interface as ARPHRD_xxx constant.
4593 iface_get_arptype(int fd
, const char *device
, char *ebuf
)
4597 memset(&ifr
, 0, sizeof(ifr
));
4598 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4600 if (ioctl(fd
, SIOCGIFHWADDR
, &ifr
) == -1) {
4601 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4602 "SIOCGIFHWADDR: %s", pcap_strerror(errno
));
4603 if (errno
== ENODEV
) {
4607 return PCAP_ERROR_NO_SUCH_DEVICE
;
4612 return ifr
.ifr_hwaddr
.sa_family
;
4615 #ifdef SO_ATTACH_FILTER
4617 fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
, int is_mmapped
)
4621 register struct bpf_insn
*p
;
4626 * Make a copy of the filter, and modify that copy if
4629 prog_size
= sizeof(*handle
->fcode
.bf_insns
) * handle
->fcode
.bf_len
;
4630 len
= handle
->fcode
.bf_len
;
4631 f
= (struct bpf_insn
*)malloc(prog_size
);
4633 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4634 "malloc: %s", pcap_strerror(errno
));
4637 memcpy(f
, handle
->fcode
.bf_insns
, prog_size
);
4639 fcode
->filter
= (struct sock_filter
*) f
;
4641 for (i
= 0; i
< len
; ++i
) {
4644 * What type of instruction is this?
4646 switch (BPF_CLASS(p
->code
)) {
4650 * It's a return instruction; are we capturing
4651 * in memory-mapped mode?
4655 * No; is the snapshot length a constant,
4656 * rather than the contents of the
4659 if (BPF_MODE(p
->code
) == BPF_K
) {
4661 * Yes - if the value to be returned,
4662 * i.e. the snapshot length, is
4663 * anything other than 0, make it
4664 * 65535, so that the packet is
4665 * truncated by "recvfrom()",
4666 * not by the filter.
4668 * XXX - there's nothing we can
4669 * easily do if it's getting the
4670 * value from the accumulator; we'd
4671 * have to insert code to force
4672 * non-zero values to be 65535.
4683 * It's a load instruction; is it loading
4686 switch (BPF_MODE(p
->code
)) {
4692 * Yes; are we in cooked mode?
4694 if (handle
->md
.cooked
) {
4696 * Yes, so we need to fix this
4699 if (fix_offset(p
) < 0) {
4701 * We failed to do so.
4702 * Return 0, so our caller
4703 * knows to punt to userland.
4713 return 1; /* we succeeded */
4717 fix_offset(struct bpf_insn
*p
)
4720 * What's the offset?
4722 if (p
->k
>= SLL_HDR_LEN
) {
4724 * It's within the link-layer payload; that starts at an
4725 * offset of 0, as far as the kernel packet filter is
4726 * concerned, so subtract the length of the link-layer
4729 p
->k
-= SLL_HDR_LEN
;
4730 } else if (p
->k
== 14) {
4732 * It's the protocol field; map it to the special magic
4733 * kernel offset for that field.
4735 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
4738 * It's within the header, but it's not one of those
4739 * fields; we can't do that in the kernel, so punt
4748 set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
)
4750 int total_filter_on
= 0;
4756 * The socket filter code doesn't discard all packets queued
4757 * up on the socket when the filter is changed; this means
4758 * that packets that don't match the new filter may show up
4759 * after the new filter is put onto the socket, if those
4760 * packets haven't yet been read.
4762 * This means, for example, that if you do a tcpdump capture
4763 * with a filter, the first few packets in the capture might
4764 * be packets that wouldn't have passed the filter.
4766 * We therefore discard all packets queued up on the socket
4767 * when setting a kernel filter. (This isn't an issue for
4768 * userland filters, as the userland filtering is done after
4769 * packets are queued up.)
4771 * To flush those packets, we put the socket in read-only mode,
4772 * and read packets from the socket until there are no more to
4775 * In order to keep that from being an infinite loop - i.e.,
4776 * to keep more packets from arriving while we're draining
4777 * the queue - we put the "total filter", which is a filter
4778 * that rejects all packets, onto the socket before draining
4781 * This code deliberately ignores any errors, so that you may
4782 * get bogus packets if an error occurs, rather than having
4783 * the filtering done in userland even if it could have been
4784 * done in the kernel.
4786 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
4787 &total_fcode
, sizeof(total_fcode
)) == 0) {
4791 * Note that we've put the total filter onto the socket.
4793 total_filter_on
= 1;
4796 * Save the socket's current mode, and put it in
4797 * non-blocking mode; we drain it by reading packets
4798 * until we get an error (which is normally a
4799 * "nothing more to be read" error).
4801 save_mode
= fcntl(handle
->fd
, F_GETFL
, 0);
4802 if (save_mode
!= -1 &&
4803 fcntl(handle
->fd
, F_SETFL
, save_mode
| O_NONBLOCK
) >= 0) {
4804 while (recv(handle
->fd
, &drain
, sizeof drain
,
4808 fcntl(handle
->fd
, F_SETFL
, save_mode
);
4809 if (save_errno
!= EAGAIN
) {
4811 reset_kernel_filter(handle
);
4812 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4813 "recv: %s", pcap_strerror(save_errno
));
4820 * Now attach the new filter.
4822 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
4823 fcode
, sizeof(*fcode
));
4824 if (ret
== -1 && total_filter_on
) {
4826 * Well, we couldn't set that filter on the socket,
4827 * but we could set the total filter on the socket.
4829 * This could, for example, mean that the filter was
4830 * too big to put into the kernel, so we'll have to
4831 * filter in userland; in any case, we'll be doing
4832 * filtering in userland, so we need to remove the
4833 * total filter so we see packets.
4838 * XXX - if this fails, we're really screwed;
4839 * we have the total filter on the socket,
4840 * and it won't come off. What do we do then?
4842 reset_kernel_filter(handle
);
4850 reset_kernel_filter(pcap_t
*handle
)
4853 * setsockopt() barfs unless it get a dummy parameter.
4854 * valgrind whines unless the value is initialized,
4855 * as it has no idea that setsockopt() ignores its
4860 return setsockopt(handle
->fd
, SOL_SOCKET
, SO_DETACH_FILTER
,
4861 &dummy
, sizeof(dummy
));