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 */
173 #ifdef PCAP_SUPPORT_USB
174 #include "pcap-usb-linux.h"
177 #ifdef PCAP_SUPPORT_BT
178 #include "pcap-bt-linux.h"
181 #ifdef PCAP_SUPPORT_CAN
182 #include "pcap-can-linux.h"
186 * If PF_PACKET is defined, we can use {SOCK_RAW,SOCK_DGRAM}/PF_PACKET
187 * sockets rather than SOCK_PACKET sockets.
189 * To use them, we include <linux/if_packet.h> rather than
190 * <netpacket/packet.h>; we do so because
192 * some Linux distributions (e.g., Slackware 4.0) have 2.2 or
193 * later kernels and libc5, and don't provide a <netpacket/packet.h>
196 * not all versions of glibc2 have a <netpacket/packet.h> file
197 * that defines stuff needed for some of the 2.4-or-later-kernel
198 * features, so if the system has a 2.4 or later kernel, we
199 * still can't use those features.
201 * We're already including a number of other <linux/XXX.h> headers, and
202 * this code is Linux-specific (no other OS has PF_PACKET sockets as
203 * a raw packet capture mechanism), so it's not as if you gain any
204 * useful portability by using <netpacket/packet.h>
206 * XXX - should we just include <linux/if_packet.h> even if PF_PACKET
207 * isn't defined? It only defines one data structure in 2.0.x, so
208 * it shouldn't cause any problems.
211 # include <linux/if_packet.h>
214 * On at least some Linux distributions (for example, Red Hat 5.2),
215 * there's no <netpacket/packet.h> file, but PF_PACKET is defined if
216 * you include <sys/socket.h>, but <linux/if_packet.h> doesn't define
217 * any of the PF_PACKET stuff such as "struct sockaddr_ll" or any of
218 * the PACKET_xxx stuff.
220 * So we check whether PACKET_HOST is defined, and assume that we have
221 * PF_PACKET sockets only if it is defined.
224 # define HAVE_PF_PACKET_SOCKETS
225 # ifdef PACKET_AUXDATA
226 # define HAVE_PACKET_AUXDATA
227 # endif /* PACKET_AUXDATA */
228 # endif /* PACKET_HOST */
231 /* check for memory mapped access avaibility. We assume every needed
232 * struct is defined if the macro TPACKET_HDRLEN is defined, because it
233 * uses many ring related structs and macros */
234 # ifdef TPACKET_HDRLEN
235 # define HAVE_PACKET_RING
236 # ifdef TPACKET2_HDRLEN
237 # define HAVE_TPACKET2
239 # define TPACKET_V1 0
240 # endif /* TPACKET2_HDRLEN */
241 # endif /* TPACKET_HDRLEN */
242 #endif /* PF_PACKET */
244 #ifdef SO_ATTACH_FILTER
245 #include <linux/types.h>
246 #include <linux/filter.h>
249 #ifndef HAVE_SOCKLEN_T
250 typedef int socklen_t
;
255 * This is being compiled on a system that lacks MSG_TRUNC; define it
256 * with the value it has in the 2.2 and later kernels, so that, on
257 * those kernels, when we pass it in the flags argument to "recvfrom()"
258 * we're passing the right value and thus get the MSG_TRUNC behavior
259 * we want. (We don't get that behavior on 2.0[.x] kernels, because
260 * they didn't support MSG_TRUNC.)
262 #define MSG_TRUNC 0x20
267 * This is being compiled on a system that lacks SOL_PACKET; define it
268 * with the value it has in the 2.2 and later kernels, so that we can
269 * set promiscuous mode in the good modern way rather than the old
270 * 2.0-kernel crappy way.
272 #define SOL_PACKET 263
275 #define MAX_LINKHEADER_SIZE 256
278 * When capturing on all interfaces we use this as the buffer size.
279 * Should be bigger then all MTUs that occur in real life.
280 * 64kB should be enough for now.
282 #define BIGGER_THAN_ALL_MTUS (64*1024)
285 * Prototypes for internal functions and methods.
287 static void map_arphrd_to_dlt(pcap_t
*, int, int);
288 #ifdef HAVE_PF_PACKET_SOCKETS
289 static short int map_packet_type_to_sll_type(short int);
291 static int pcap_activate_linux(pcap_t
*);
292 static int activate_old(pcap_t
*);
293 static int activate_new(pcap_t
*);
294 static int activate_mmap(pcap_t
*);
295 static int pcap_can_set_rfmon_linux(pcap_t
*);
296 static int pcap_read_linux(pcap_t
*, int, pcap_handler
, u_char
*);
297 static int pcap_read_packet(pcap_t
*, pcap_handler
, u_char
*);
298 static int pcap_inject_linux(pcap_t
*, const void *, size_t);
299 static int pcap_stats_linux(pcap_t
*, struct pcap_stat
*);
300 static int pcap_setfilter_linux(pcap_t
*, struct bpf_program
*);
301 static int pcap_setdirection_linux(pcap_t
*, pcap_direction_t
);
302 static void pcap_cleanup_linux(pcap_t
*);
305 struct tpacket_hdr
*h1
;
306 struct tpacket2_hdr
*h2
;
310 #ifdef HAVE_PACKET_RING
311 #define RING_GET_FRAME(h) (((union thdr **)h->buffer)[h->offset])
313 static void destroy_ring(pcap_t
*handle
);
314 static int create_ring(pcap_t
*handle
);
315 static int prepare_tpacket_socket(pcap_t
*handle
);
316 static void pcap_cleanup_linux_mmap(pcap_t
*);
317 static int pcap_read_linux_mmap(pcap_t
*, int, pcap_handler
, u_char
*);
318 static int pcap_setfilter_linux_mmap(pcap_t
*, struct bpf_program
*);
319 static int pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
, char *errbuf
);
320 static int pcap_getnonblock_mmap(pcap_t
*p
, char *errbuf
);
321 static void pcap_oneshot_mmap(u_char
*user
, const struct pcap_pkthdr
*h
,
322 const u_char
*bytes
);
326 * Wrap some ioctl calls
328 #ifdef HAVE_PF_PACKET_SOCKETS
329 static int iface_get_id(int fd
, const char *device
, char *ebuf
);
331 static int iface_get_mtu(int fd
, const char *device
, char *ebuf
);
332 static int iface_get_arptype(int fd
, const char *device
, char *ebuf
);
333 #ifdef HAVE_PF_PACKET_SOCKETS
334 static int iface_bind(int fd
, int ifindex
, char *ebuf
);
335 #ifdef IW_MODE_MONITOR
336 static int has_wext(int sock_fd
, const char *device
, char *ebuf
);
337 #endif /* IW_MODE_MONITOR */
338 static int enter_rfmon_mode(pcap_t
*handle
, int sock_fd
,
340 #endif /* HAVE_PF_PACKET_SOCKETS */
341 static int iface_bind_old(int fd
, const char *device
, char *ebuf
);
343 #ifdef SO_ATTACH_FILTER
344 static int fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
,
346 static int fix_offset(struct bpf_insn
*p
);
347 static int set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
);
348 static int reset_kernel_filter(pcap_t
*handle
);
350 static struct sock_filter total_insn
351 = BPF_STMT(BPF_RET
| BPF_K
, 0);
352 static struct sock_fprog total_fcode
353 = { 1, &total_insn
};
357 pcap_create(const char *device
, char *ebuf
)
362 * A null device name is equivalent to the "any" device.
368 if (strstr(device
, "dag")) {
369 return dag_create(device
, ebuf
);
371 #endif /* HAVE_DAG_API */
373 #ifdef HAVE_SEPTEL_API
374 if (strstr(device
, "septel")) {
375 return septel_create(device
, ebuf
);
377 #endif /* HAVE_SEPTEL_API */
379 #ifdef PCAP_SUPPORT_BT
380 if (strstr(device
, "bluetooth")) {
381 return bt_create(device
, ebuf
);
385 #ifdef PCAP_SUPPORT_CAN
386 if (strstr(device
, "can") || strstr(device
, "vcan")) {
387 return can_create(device
, ebuf
);
391 #ifdef PCAP_SUPPORT_USB
392 if (strstr(device
, "usbmon")) {
393 return usb_create(device
, ebuf
);
397 handle
= pcap_create_common(device
, ebuf
);
401 handle
->activate_op
= pcap_activate_linux
;
402 handle
->can_set_rfmon_op
= pcap_can_set_rfmon_linux
;
409 * If interface {if} is a mac80211 driver, the file
410 * /sys/class/net/{if}/phy80211 is a symlink to
411 * /sys/class/ieee80211/{phydev}, for some {phydev}.
413 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
414 * least, has a "wmaster0" device and a "wlan0" device; the
415 * latter is the one with the IP address. Both show up in
416 * "tcpdump -D" output. Capturing on the wmaster0 device
417 * captures with 802.11 headers.
419 * airmon-ng searches through /sys/class/net for devices named
420 * monN, starting with mon0; as soon as one *doesn't* exist,
421 * it chooses that as the monitor device name. If the "iw"
422 * command exists, it does "iw dev {if} interface add {monif}
423 * type monitor", where {monif} is the monitor device. It
424 * then (sigh) sleeps .1 second, and then configures the
425 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
426 * is a file, it writes {mondev}, without a newline, to that file,
427 * and again (sigh) sleeps .1 second, and then iwconfig's that
428 * device into monitor mode and configures it up. Otherwise,
429 * you can't do monitor mode.
431 * All these devices are "glued" together by having the
432 * /sys/class/net/{device}/phy80211 links pointing to the same
433 * place, so, given a wmaster, wlan, or mon device, you can
434 * find the other devices by looking for devices with
435 * the same phy80211 link.
437 * To turn monitor mode off, delete the monitor interface,
438 * either with "iw dev {monif} interface del" or by sending
439 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
441 * Note: if you try to create a monitor device named "monN", and
442 * there's already a "monN" device, it fails, as least with
443 * the netlink interface (which is what iw uses), with a return
444 * value of -ENFILE. (Return values are negative errnos.) We
445 * could probably use that to find an unused device.
447 * Yes, you can have multiple monitor devices for a given
452 * Is this a mac80211 device? If so, fill in the physical device path and
453 * return 1; if not, return 0. On an error, fill in handle->errbuf and
457 get_mac80211_phydev(pcap_t
*handle
, const char *device
, char *phydev_path
,
458 size_t phydev_max_pathlen
)
464 * Generate the path string for the symlink to the physical device.
466 if (asprintf(&pathstr
, "/sys/class/net/%s/phy80211", device
) == -1) {
467 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
468 "%s: Can't generate path name string for /sys/class/net device",
472 bytes_read
= readlink(pathstr
, phydev_path
, phydev_max_pathlen
);
473 if (bytes_read
== -1) {
474 if (errno
== ENOENT
|| errno
== EINVAL
) {
476 * Doesn't exist, or not a symlink; assume that
477 * means it's not a mac80211 device.
482 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
483 "%s: Can't readlink %s: %s", device
, pathstr
,
489 phydev_path
[bytes_read
] = '\0';
493 struct nl80211_state
{
494 struct nl_handle
*nl_handle
;
495 struct nl_cache
*nl_cache
;
496 struct genl_family
*nl80211
;
500 nl80211_init(pcap_t
*handle
, struct nl80211_state
*state
, const char *device
)
502 state
->nl_handle
= nl_handle_alloc();
503 if (!state
->nl_handle
) {
504 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
505 "%s: failed to allocate netlink handle", device
);
509 if (genl_connect(state
->nl_handle
)) {
510 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
511 "%s: failed to connect to generic netlink", device
);
512 goto out_handle_destroy
;
515 state
->nl_cache
= genl_ctrl_alloc_cache(state
->nl_handle
);
516 if (!state
->nl_cache
) {
517 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
518 "%s: failed to allocate generic netlink cache", device
);
519 goto out_handle_destroy
;
522 state
->nl80211
= genl_ctrl_search_by_name(state
->nl_cache
, "nl80211");
523 if (!state
->nl80211
) {
524 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
525 "%s: nl80211 not found", device
);
532 nl_cache_free(state
->nl_cache
);
534 nl_handle_destroy(state
->nl_handle
);
539 nl80211_cleanup(struct nl80211_state
*state
)
541 genl_family_put(state
->nl80211
);
542 nl_cache_free(state
->nl_cache
);
543 nl_handle_destroy(state
->nl_handle
);
547 add_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
548 const char *device
, const char *mondevice
)
554 ifindex
= iface_get_id(sock_fd
, device
, handle
->errbuf
);
560 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
561 "%s: failed to allocate netlink msg", device
);
565 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
566 0, NL80211_CMD_NEW_INTERFACE
, 0);
567 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
568 NLA_PUT_STRING(msg
, NL80211_ATTR_IFNAME
, mondevice
);
569 NLA_PUT_U32(msg
, NL80211_ATTR_IFTYPE
, NL80211_IFTYPE_MONITOR
);
571 err
= nl_send_auto_complete(state
->nl_handle
, msg
);
573 if (err
== -ENFILE
) {
575 * Device not available; our caller should just
582 * Real failure, not just "that device is not
585 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
586 "%s: nl_send_auto_complete failed adding %s interface: %s",
587 device
, mondevice
, strerror(-err
));
592 err
= nl_wait_for_ack(state
->nl_handle
);
594 if (err
== -ENFILE
) {
596 * Device not available; our caller should just
603 * Real failure, not just "that device is not
606 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
607 "%s: nl_wait_for_ack failed adding %s interface: %s",
608 device
, mondevice
, strerror(-err
));
621 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
622 "%s: nl_put failed adding %s interface",
629 del_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
630 const char *device
, const char *mondevice
)
636 ifindex
= iface_get_id(sock_fd
, mondevice
, handle
->errbuf
);
642 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
643 "%s: failed to allocate netlink msg", device
);
647 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
648 0, NL80211_CMD_DEL_INTERFACE
, 0);
649 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
651 err
= nl_send_auto_complete(state
->nl_handle
, msg
);
653 if (err
== -ENFILE
) {
655 * Device not available; our caller should just
662 * Real failure, not just "that device is not
665 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
666 "%s: nl_send_auto_complete failed deleting %s interface: %s",
667 device
, mondevice
, strerror(-err
));
672 err
= nl_wait_for_ack(state
->nl_handle
);
674 if (err
== -ENFILE
) {
676 * Device not available; our caller should just
683 * Real failure, not just "that device is not
686 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
687 "%s: nl_wait_for_ack failed adding %s interface: %s",
688 device
, mondevice
, strerror(-err
));
701 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
702 "%s: nl_put failed deleting %s interface",
709 enter_rfmon_mode_mac80211(pcap_t
*handle
, int sock_fd
, const char *device
)
712 char phydev_path
[PATH_MAX
+1];
713 struct nl80211_state nlstate
;
718 * Is this a mac80211 device?
720 ret
= get_mac80211_phydev(handle
, device
, phydev_path
, PATH_MAX
);
722 return ret
; /* error */
724 return 0; /* no error, but not mac80211 device */
727 * XXX - is this already a monN device?
729 * Is that determined by old Wireless Extensions ioctls?
733 * OK, it's apparently a mac80211 device.
734 * Try to find an unused monN device for it.
736 ret
= nl80211_init(handle
, &nlstate
, device
);
739 for (n
= 0; n
< UINT_MAX
; n
++) {
743 char mondevice
[3+10+1]; /* mon{UINT_MAX}\0 */
745 snprintf(mondevice
, sizeof mondevice
, "mon%u", n
);
746 ret
= add_mon_if(handle
, sock_fd
, &nlstate
, device
, mondevice
);
748 handle
->md
.mondevice
= strdup(mondevice
);
753 * Hard failure. Just return ret; handle->errbuf
754 * has already been set.
756 nl80211_cleanup(&nlstate
);
761 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
762 "%s: No free monN interfaces", device
);
763 nl80211_cleanup(&nlstate
);
770 * Sleep for .1 seconds.
773 delay
.tv_nsec
= 500000000;
774 nanosleep(&delay
, NULL
);
778 * Now configure the monitor interface up.
780 memset(&ifr
, 0, sizeof(ifr
));
781 strncpy(ifr
.ifr_name
, handle
->md
.mondevice
, sizeof(ifr
.ifr_name
));
782 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
783 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
784 "%s: Can't get flags for %s: %s", device
,
785 handle
->md
.mondevice
, strerror(errno
));
786 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
787 handle
->md
.mondevice
);
788 nl80211_cleanup(&nlstate
);
791 ifr
.ifr_flags
|= IFF_UP
|IFF_RUNNING
;
792 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
793 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
794 "%s: Can't set flags for %s: %s", device
,
795 handle
->md
.mondevice
, strerror(errno
));
796 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
797 handle
->md
.mondevice
);
798 nl80211_cleanup(&nlstate
);
803 * Success. Clean up the libnl state.
805 nl80211_cleanup(&nlstate
);
808 * Note that we have to delete the monitor device when we close
811 handle
->md
.must_do_on_close
|= MUST_DELETE_MONIF
;
814 * Add this to the list of pcaps to close when we exit.
816 pcap_add_to_pcaps_to_close(handle
);
820 #endif /* HAVE_LIBNL */
823 pcap_can_set_rfmon_linux(pcap_t
*handle
)
826 char phydev_path
[PATH_MAX
+1];
829 #ifdef IW_MODE_MONITOR
834 if (strcmp(handle
->opt
.source
, "any") == 0) {
836 * Monitor mode makes no sense on the "any" device.
843 * Bleah. There doesn't seem to be a way to ask a mac80211
844 * device, through libnl, whether it supports monitor mode;
845 * we'll just check whether the device appears to be a
846 * mac80211 device and, if so, assume the device supports
849 * wmaster devices don't appear to support the Wireless
850 * Extensions, but we can create a mon device for a
851 * wmaster device, so we don't bother checking whether
852 * a mac80211 device supports the Wireless Extensions.
854 ret
= get_mac80211_phydev(handle
, handle
->opt
.source
, phydev_path
,
857 return ret
; /* error */
859 return 1; /* mac80211 device */
862 #ifdef IW_MODE_MONITOR
864 * Bleah. There doesn't appear to be an ioctl to use to ask
865 * whether a device supports monitor mode; we'll just do
866 * SIOCGIWMODE and, if it succeeds, assume the device supports
869 * Open a socket on which to attempt to get the mode.
870 * (We assume that if we have Wireless Extensions support
871 * we also have PF_PACKET support.)
873 sock_fd
= socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
));
875 (void)snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
876 "socket: %s", pcap_strerror(errno
));
881 * Attempt to get the current mode.
883 strncpy(ireq
.ifr_ifrn
.ifrn_name
, handle
->opt
.source
,
884 sizeof ireq
.ifr_ifrn
.ifrn_name
);
885 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
886 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) != -1) {
888 * Well, we got the mode; assume we can set it.
893 if (errno
== ENODEV
) {
894 /* The device doesn't even exist. */
895 (void)snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
896 "SIOCGIWMODE failed: %s", pcap_strerror(errno
));
898 return PCAP_ERROR_NO_SUCH_DEVICE
;
906 * Grabs the number of dropped packets by the interface from /proc/net/dev.
908 * XXX - what about /sys/class/net/{interface name}/rx_*? There are
909 * individual devices giving, in ASCII, various rx_ and tx_ statistics.
911 * Or can we get them in binary form from netlink?
914 linux_if_drops(const char * if_name
)
919 int field_to_convert
= 3, if_name_sz
= strlen(if_name
);
920 long int dropped_pkts
= 0;
922 file
= fopen("/proc/net/dev", "r");
926 while (!dropped_pkts
&& fgets( buffer
, sizeof(buffer
), file
))
928 /* search for 'bytes' -- if its in there, then
929 that means we need to grab the fourth field. otherwise
930 grab the third field. */
931 if (field_to_convert
!= 4 && strstr(buffer
, "bytes"))
933 field_to_convert
= 4;
937 /* find iface and make sure it actually matches -- space before the name and : after it */
938 if ((bufptr
= strstr(buffer
, if_name
)) &&
939 (bufptr
== buffer
|| *(bufptr
-1) == ' ') &&
940 *(bufptr
+ if_name_sz
) == ':')
942 bufptr
= bufptr
+ if_name_sz
+ 1;
944 /* grab the nth field from it */
945 while( --field_to_convert
&& *bufptr
!= '\0')
947 while (*bufptr
!= '\0' && *(bufptr
++) == ' ');
948 while (*bufptr
!= '\0' && *(bufptr
++) != ' ');
951 /* get rid of any final spaces */
952 while (*bufptr
!= '\0' && *bufptr
== ' ') bufptr
++;
955 dropped_pkts
= strtol(bufptr
, NULL
, 10);
967 * With older kernels promiscuous mode is kind of interesting because we
968 * have to reset the interface before exiting. The problem can't really
969 * be solved without some daemon taking care of managing usage counts.
970 * If we put the interface into promiscuous mode, we set a flag indicating
971 * that we must take it out of that mode when the interface is closed,
972 * and, when closing the interface, if that flag is set we take it out
973 * of promiscuous mode.
975 * Even with newer kernels, we have the same issue with rfmon mode.
978 static void pcap_cleanup_linux( pcap_t
*handle
)
982 struct nl80211_state nlstate
;
984 #endif /* HAVE_LIBNL */
985 #ifdef IW_MODE_MONITOR
987 #endif /* IW_MODE_MONITOR */
989 if (handle
->md
.must_do_on_close
!= 0) {
991 * There's something we have to do when closing this
994 if (handle
->md
.must_do_on_close
& MUST_CLEAR_PROMISC
) {
996 * We put the interface into promiscuous mode;
997 * take it out of promiscuous mode.
999 * XXX - if somebody else wants it in promiscuous
1000 * mode, this code cannot know that, so it'll take
1001 * it out of promiscuous mode. That's not fixable
1002 * in 2.0[.x] kernels.
1004 memset(&ifr
, 0, sizeof(ifr
));
1005 strncpy(ifr
.ifr_name
, handle
->md
.device
,
1006 sizeof(ifr
.ifr_name
));
1007 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
1009 "Can't restore interface flags (SIOCGIFFLAGS failed: %s).\n"
1010 "Please adjust manually.\n"
1011 "Hint: This can't happen with Linux >= 2.2.0.\n",
1014 if (ifr
.ifr_flags
& IFF_PROMISC
) {
1016 * Promiscuous mode is currently on;
1019 ifr
.ifr_flags
&= ~IFF_PROMISC
;
1020 if (ioctl(handle
->fd
, SIOCSIFFLAGS
,
1023 "Can't restore interface flags (SIOCSIFFLAGS failed: %s).\n"
1024 "Please adjust manually.\n"
1025 "Hint: This can't happen with Linux >= 2.2.0.\n",
1033 if (handle
->md
.must_do_on_close
& MUST_DELETE_MONIF
) {
1034 ret
= nl80211_init(handle
, &nlstate
, handle
->md
.device
);
1036 ret
= del_mon_if(handle
, handle
->fd
, &nlstate
,
1037 handle
->md
.device
, handle
->md
.mondevice
);
1038 nl80211_cleanup(&nlstate
);
1042 "Can't delete monitor interface %s (%s).\n"
1043 "Please delete manually.\n",
1044 handle
->md
.mondevice
, handle
->errbuf
);
1047 #endif /* HAVE_LIBNL */
1049 #ifdef IW_MODE_MONITOR
1050 if (handle
->md
.must_do_on_close
& MUST_CLEAR_RFMON
) {
1052 * We put the interface into rfmon mode;
1053 * take it out of rfmon mode.
1055 * XXX - if somebody else wants it in rfmon
1056 * mode, this code cannot know that, so it'll take
1057 * it out of rfmon mode.
1059 strncpy(ireq
.ifr_ifrn
.ifrn_name
, handle
->md
.device
,
1060 sizeof ireq
.ifr_ifrn
.ifrn_name
);
1061 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1]
1063 ireq
.u
.mode
= handle
->md
.oldmode
;
1064 if (ioctl(handle
->fd
, SIOCSIWMODE
, &ireq
) == -1) {
1066 * Scientist, you've failed.
1069 "Can't restore interface wireless mode (SIOCSIWMODE failed: %s).\n"
1070 "Please adjust manually.\n",
1074 #endif /* IW_MODE_MONITOR */
1077 * Take this pcap out of the list of pcaps for which we
1078 * have to take the interface out of some mode.
1080 pcap_remove_from_pcaps_to_close(handle
);
1083 if (handle
->md
.mondevice
!= NULL
) {
1084 free(handle
->md
.mondevice
);
1085 handle
->md
.mondevice
= NULL
;
1087 if (handle
->md
.device
!= NULL
) {
1088 free(handle
->md
.device
);
1089 handle
->md
.device
= NULL
;
1091 pcap_cleanup_live_common(handle
);
1095 * Get a handle for a live capture from the given device. You can
1096 * pass NULL as device to get all packages (without link level
1097 * information of course). If you pass 1 as promisc the interface
1098 * will be set to promiscous mode (XXX: I think this usage should
1099 * be deprecated and functions be added to select that later allow
1100 * modification of that values -- Torsten).
1103 pcap_activate_linux(pcap_t
*handle
)
1108 device
= handle
->opt
.source
;
1110 handle
->inject_op
= pcap_inject_linux
;
1111 handle
->setfilter_op
= pcap_setfilter_linux
;
1112 handle
->setdirection_op
= pcap_setdirection_linux
;
1113 handle
->set_datalink_op
= NULL
; /* can't change data link type */
1114 handle
->getnonblock_op
= pcap_getnonblock_fd
;
1115 handle
->setnonblock_op
= pcap_setnonblock_fd
;
1116 handle
->cleanup_op
= pcap_cleanup_linux
;
1117 handle
->read_op
= pcap_read_linux
;
1118 handle
->stats_op
= pcap_stats_linux
;
1121 * The "any" device is a special device which causes us not
1122 * to bind to a particular device and thus to look at all
1125 if (strcmp(device
, "any") == 0) {
1126 if (handle
->opt
.promisc
) {
1127 handle
->opt
.promisc
= 0;
1128 /* Just a warning. */
1129 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1130 "Promiscuous mode not supported on the \"any\" device");
1131 status
= PCAP_WARNING_PROMISC_NOTSUP
;
1135 handle
->md
.device
= strdup(device
);
1136 if (handle
->md
.device
== NULL
) {
1137 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "strdup: %s",
1138 pcap_strerror(errno
) );
1143 * If we're in promiscuous mode, then we probably want
1144 * to see when the interface drops packets too, so get an
1145 * initial count from /proc/net/dev
1147 if (handle
->opt
.promisc
)
1148 handle
->md
.proc_dropped
= linux_if_drops(handle
->md
.device
);
1151 * Current Linux kernels use the protocol family PF_PACKET to
1152 * allow direct access to all packets on the network while
1153 * older kernels had a special socket type SOCK_PACKET to
1154 * implement this feature.
1155 * While this old implementation is kind of obsolete we need
1156 * to be compatible with older kernels for a while so we are
1157 * trying both methods with the newer method preferred.
1160 if ((status
= activate_new(handle
)) == 1) {
1163 * Try to use memory-mapped access.
1165 switch (activate_mmap(handle
)) {
1168 /* we succeeded; nothing more to do */
1173 * Kernel doesn't support it - just continue
1174 * with non-memory-mapped access.
1181 * We failed to set up to use it, or kernel
1182 * supports it, but we failed to enable it;
1183 * return an error. handle->errbuf contains
1186 status
= PCAP_ERROR
;
1190 else if (status
== 0) {
1191 /* Non-fatal error; try old way */
1192 if ((status
= activate_old(handle
)) != 1) {
1194 * Both methods to open the packet socket failed.
1195 * Tidy up and report our failure (handle->errbuf
1196 * is expected to be set by the functions above).
1202 * Fatal error with the new way; just fail.
1203 * status has the error return; if it's PCAP_ERROR,
1204 * handle->errbuf has been set appropriately.
1210 * We set up the socket, but not with memory-mapped access.
1212 if (handle
->opt
.buffer_size
!= 0) {
1214 * Set the socket buffer size to the specified value.
1216 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_RCVBUF
,
1217 &handle
->opt
.buffer_size
,
1218 sizeof(handle
->opt
.buffer_size
)) == -1) {
1219 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1220 "SO_RCVBUF: %s", pcap_strerror(errno
));
1221 status
= PCAP_ERROR
;
1226 /* Allocate the buffer */
1228 handle
->buffer
= malloc(handle
->bufsize
+ handle
->offset
);
1229 if (!handle
->buffer
) {
1230 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1231 "malloc: %s", pcap_strerror(errno
));
1232 status
= PCAP_ERROR
;
1237 * "handle->fd" is a socket, so "select()" and "poll()"
1238 * should work on it.
1240 handle
->selectable_fd
= handle
->fd
;
1245 pcap_cleanup_linux(handle
);
1250 * Read at most max_packets from the capture stream and call the callback
1251 * for each of them. Returns the number of packets handled or -1 if an
1255 pcap_read_linux(pcap_t
*handle
, int max_packets
, pcap_handler callback
, u_char
*user
)
1258 * Currently, on Linux only one packet is delivered per read,
1261 return pcap_read_packet(handle
, callback
, user
);
1265 * Read a packet from the socket calling the handler provided by
1266 * the user. Returns the number of packets received or -1 if an
1270 pcap_read_packet(pcap_t
*handle
, pcap_handler callback
, u_char
*userdata
)
1274 #ifdef HAVE_PF_PACKET_SOCKETS
1275 struct sockaddr_ll from
;
1276 struct sll_header
*hdrp
;
1278 struct sockaddr from
;
1280 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1283 struct cmsghdr
*cmsg
;
1285 struct cmsghdr cmsg
;
1286 char buf
[CMSG_SPACE(sizeof(struct tpacket_auxdata
))];
1288 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1290 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1291 int packet_len
, caplen
;
1292 struct pcap_pkthdr pcap_header
;
1294 #ifdef HAVE_PF_PACKET_SOCKETS
1296 * If this is a cooked device, leave extra room for a
1297 * fake packet header.
1299 if (handle
->md
.cooked
)
1300 offset
= SLL_HDR_LEN
;
1305 * This system doesn't have PF_PACKET sockets, so it doesn't
1306 * support cooked devices.
1312 * Receive a single packet from the kernel.
1313 * We ignore EINTR, as that might just be due to a signal
1314 * being delivered - if the signal should interrupt the
1315 * loop, the signal handler should call pcap_breakloop()
1316 * to set handle->break_loop (we ignore it on other
1317 * platforms as well).
1318 * We also ignore ENETDOWN, so that we can continue to
1319 * capture traffic if the interface goes down and comes
1320 * back up again; comments in the kernel indicate that
1321 * we'll just block waiting for packets if we try to
1322 * receive from a socket that delivered ENETDOWN, and,
1323 * if we're using a memory-mapped buffer, we won't even
1324 * get notified of "network down" events.
1326 bp
= handle
->buffer
+ handle
->offset
;
1328 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1329 msg
.msg_name
= &from
;
1330 msg
.msg_namelen
= sizeof(from
);
1333 msg
.msg_control
= &cmsg_buf
;
1334 msg
.msg_controllen
= sizeof(cmsg_buf
);
1337 iov
.iov_len
= handle
->bufsize
- offset
;
1338 iov
.iov_base
= bp
+ offset
;
1339 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1343 * Has "pcap_breakloop()" been called?
1345 if (handle
->break_loop
) {
1347 * Yes - clear the flag that indicates that it has,
1348 * and return PCAP_ERROR_BREAK as an indication that
1349 * we were told to break out of the loop.
1351 handle
->break_loop
= 0;
1352 return PCAP_ERROR_BREAK
;
1355 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1356 packet_len
= recvmsg(handle
->fd
, &msg
, MSG_TRUNC
);
1357 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1358 fromlen
= sizeof(from
);
1359 packet_len
= recvfrom(
1360 handle
->fd
, bp
+ offset
,
1361 handle
->bufsize
- offset
, MSG_TRUNC
,
1362 (struct sockaddr
*) &from
, &fromlen
);
1363 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1364 } while (packet_len
== -1 && errno
== EINTR
);
1366 /* Check if an error occured */
1368 if (packet_len
== -1) {
1372 return 0; /* no packet there */
1376 * The device on which we're capturing went away.
1378 * XXX - we should really return
1379 * PCAP_ERROR_IFACE_NOT_UP, but pcap_dispatch()
1380 * etc. aren't defined to return that.
1382 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1383 "The interface went down");
1387 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1388 "recvfrom: %s", pcap_strerror(errno
));
1393 #ifdef HAVE_PF_PACKET_SOCKETS
1394 if (!handle
->md
.sock_packet
) {
1396 * Unfortunately, there is a window between socket() and
1397 * bind() where the kernel may queue packets from any
1398 * interface. If we're bound to a particular interface,
1399 * discard packets not from that interface.
1401 * (If socket filters are supported, we could do the
1402 * same thing we do when changing the filter; however,
1403 * that won't handle packet sockets without socket
1404 * filter support, and it's a bit more complicated.
1405 * It would save some instructions per packet, however.)
1407 if (handle
->md
.ifindex
!= -1 &&
1408 from
.sll_ifindex
!= handle
->md
.ifindex
)
1412 * Do checks based on packet direction.
1413 * We can only do this if we're using PF_PACKET; the
1414 * address returned for SOCK_PACKET is a "sockaddr_pkt"
1415 * which lacks the relevant packet type information.
1417 if (from
.sll_pkttype
== PACKET_OUTGOING
) {
1420 * If this is from the loopback device, reject it;
1421 * we'll see the packet as an incoming packet as well,
1422 * and we don't want to see it twice.
1424 if (from
.sll_ifindex
== handle
->md
.lo_ifindex
)
1428 * If the user only wants incoming packets, reject it.
1430 if (handle
->direction
== PCAP_D_IN
)
1435 * If the user only wants outgoing packets, reject it.
1437 if (handle
->direction
== PCAP_D_OUT
)
1443 #ifdef HAVE_PF_PACKET_SOCKETS
1445 * If this is a cooked device, fill in the fake packet header.
1447 if (handle
->md
.cooked
) {
1449 * Add the length of the fake header to the length
1450 * of packet data we read.
1452 packet_len
+= SLL_HDR_LEN
;
1454 hdrp
= (struct sll_header
*)bp
;
1455 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(from
.sll_pkttype
);
1456 hdrp
->sll_hatype
= htons(from
.sll_hatype
);
1457 hdrp
->sll_halen
= htons(from
.sll_halen
);
1458 memcpy(hdrp
->sll_addr
, from
.sll_addr
,
1459 (from
.sll_halen
> SLL_ADDRLEN
) ?
1462 hdrp
->sll_protocol
= from
.sll_protocol
;
1465 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1466 for (cmsg
= CMSG_FIRSTHDR(&msg
); cmsg
; cmsg
= CMSG_NXTHDR(&msg
, cmsg
)) {
1467 struct tpacket_auxdata
*aux
;
1469 struct vlan_tag
*tag
;
1471 if (cmsg
->cmsg_len
< CMSG_LEN(sizeof(struct tpacket_auxdata
)) ||
1472 cmsg
->cmsg_level
!= SOL_PACKET
||
1473 cmsg
->cmsg_type
!= PACKET_AUXDATA
)
1476 aux
= (struct tpacket_auxdata
*)CMSG_DATA(cmsg
);
1477 if (aux
->tp_vlan_tci
== 0)
1480 len
= packet_len
> iov
.iov_len
? iov
.iov_len
: packet_len
;
1481 if (len
< 2 * ETH_ALEN
)
1485 memmove(bp
, bp
+ VLAN_TAG_LEN
, 2 * ETH_ALEN
);
1487 tag
= (struct vlan_tag
*)(bp
+ 2 * ETH_ALEN
);
1488 tag
->vlan_tpid
= htons(ETH_P_8021Q
);
1489 tag
->vlan_tci
= htons(aux
->tp_vlan_tci
);
1491 packet_len
+= VLAN_TAG_LEN
;
1493 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1494 #endif /* HAVE_PF_PACKET_SOCKETS */
1497 * XXX: According to the kernel source we should get the real
1498 * packet len if calling recvfrom with MSG_TRUNC set. It does
1499 * not seem to work here :(, but it is supported by this code
1501 * To be honest the code RELIES on that feature so this is really
1502 * broken with 2.2.x kernels.
1503 * I spend a day to figure out what's going on and I found out
1504 * that the following is happening:
1506 * The packet comes from a random interface and the packet_rcv
1507 * hook is called with a clone of the packet. That code inserts
1508 * the packet into the receive queue of the packet socket.
1509 * If a filter is attached to that socket that filter is run
1510 * first - and there lies the problem. The default filter always
1511 * cuts the packet at the snaplen:
1516 * So the packet filter cuts down the packet. The recvfrom call
1517 * says "hey, it's only 68 bytes, it fits into the buffer" with
1518 * the result that we don't get the real packet length. This
1519 * is valid at least until kernel 2.2.17pre6.
1521 * We currently handle this by making a copy of the filter
1522 * program, fixing all "ret" instructions with non-zero
1523 * operands to have an operand of 65535 so that the filter
1524 * doesn't truncate the packet, and supplying that modified
1525 * filter to the kernel.
1528 caplen
= packet_len
;
1529 if (caplen
> handle
->snapshot
)
1530 caplen
= handle
->snapshot
;
1532 /* Run the packet filter if not using kernel filter */
1533 if (!handle
->md
.use_bpf
&& handle
->fcode
.bf_insns
) {
1534 if (bpf_filter(handle
->fcode
.bf_insns
, bp
,
1535 packet_len
, caplen
) == 0)
1537 /* rejected by filter */
1542 /* Fill in our own header data */
1544 if (ioctl(handle
->fd
, SIOCGSTAMP
, &pcap_header
.ts
) == -1) {
1545 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1546 "SIOCGSTAMP: %s", pcap_strerror(errno
));
1549 pcap_header
.caplen
= caplen
;
1550 pcap_header
.len
= packet_len
;
1555 * Arguably, we should count them before we check the filter,
1556 * as on many other platforms "ps_recv" counts packets
1557 * handed to the filter rather than packets that passed
1558 * the filter, but if filtering is done in the kernel, we
1559 * can't get a count of packets that passed the filter,
1560 * and that would mean the meaning of "ps_recv" wouldn't
1561 * be the same on all Linux systems.
1563 * XXX - it's not the same on all systems in any case;
1564 * ideally, we should have a "get the statistics" call
1565 * that supplies more counts and indicates which of them
1566 * it supplies, so that we supply a count of packets
1567 * handed to the filter only on platforms where that
1568 * information is available.
1570 * We count them here even if we can get the packet count
1571 * from the kernel, as we can only determine at run time
1572 * whether we'll be able to get it from the kernel (if
1573 * HAVE_TPACKET_STATS isn't defined, we can't get it from
1574 * the kernel, but if it is defined, the library might
1575 * have been built with a 2.4 or later kernel, but we
1576 * might be running on a 2.2[.x] kernel without Alexey
1577 * Kuznetzov's turbopacket patches, and thus the kernel
1578 * might not be able to supply those statistics). We
1579 * could, I guess, try, when opening the socket, to get
1580 * the statistics, and if we can not increment the count
1581 * here, but it's not clear that always incrementing
1582 * the count is more expensive than always testing a flag
1585 * We keep the count in "md.packets_read", and use that for
1586 * "ps_recv" if we can't get the statistics from the kernel.
1587 * We do that because, if we *can* get the statistics from
1588 * the kernel, we use "md.stat.ps_recv" and "md.stat.ps_drop"
1589 * as running counts, as reading the statistics from the
1590 * kernel resets the kernel statistics, and if we directly
1591 * increment "md.stat.ps_recv" here, that means it will
1592 * count packets *twice* on systems where we can get kernel
1593 * statistics - once here, and once in pcap_stats_linux().
1595 handle
->md
.packets_read
++;
1597 /* Call the user supplied callback function */
1598 callback(userdata
, &pcap_header
, bp
);
1604 pcap_inject_linux(pcap_t
*handle
, const void *buf
, size_t size
)
1608 #ifdef HAVE_PF_PACKET_SOCKETS
1609 if (!handle
->md
.sock_packet
) {
1610 /* PF_PACKET socket */
1611 if (handle
->md
.ifindex
== -1) {
1613 * We don't support sending on the "any" device.
1615 strlcpy(handle
->errbuf
,
1616 "Sending packets isn't supported on the \"any\" device",
1621 if (handle
->md
.cooked
) {
1623 * We don't support sending on the "any" device.
1625 * XXX - how do you send on a bound cooked-mode
1627 * Is a "sendto()" required there?
1629 strlcpy(handle
->errbuf
,
1630 "Sending packets isn't supported in cooked mode",
1637 ret
= send(handle
->fd
, buf
, size
, 0);
1639 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "send: %s",
1640 pcap_strerror(errno
));
1647 * Get the statistics for the given packet capture handle.
1648 * Reports the number of dropped packets iff the kernel supports
1649 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
1650 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
1651 * patches); otherwise, that information isn't available, and we lie
1652 * and report 0 as the count of dropped packets.
1655 pcap_stats_linux(pcap_t
*handle
, struct pcap_stat
*stats
)
1657 #ifdef HAVE_TPACKET_STATS
1658 struct tpacket_stats kstats
;
1659 socklen_t len
= sizeof (struct tpacket_stats
);
1662 long if_dropped
= 0;
1665 * To fill in ps_ifdrop, we parse /proc/net/dev for the number
1667 if (handle
->opt
.promisc
)
1669 if_dropped
= handle
->md
.proc_dropped
;
1670 handle
->md
.proc_dropped
= linux_if_drops(handle
->md
.device
);
1671 handle
->md
.stat
.ps_ifdrop
+= (handle
->md
.proc_dropped
- if_dropped
);
1674 #ifdef HAVE_TPACKET_STATS
1676 * Try to get the packet counts from the kernel.
1678 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_STATISTICS
,
1679 &kstats
, &len
) > -1) {
1681 * On systems where the PACKET_STATISTICS "getsockopt()"
1682 * argument is supported on PF_PACKET sockets:
1684 * "ps_recv" counts only packets that *passed* the
1685 * filter, not packets that didn't pass the filter.
1686 * This includes packets later dropped because we
1687 * ran out of buffer space.
1689 * "ps_drop" counts packets dropped because we ran
1690 * out of buffer space. It doesn't count packets
1691 * dropped by the interface driver. It counts only
1692 * packets that passed the filter.
1694 * See above for ps_ifdrop.
1696 * Both statistics include packets not yet read from
1697 * the kernel by libpcap, and thus not yet seen by
1700 * In "linux/net/packet/af_packet.c", at least in the
1701 * 2.4.9 kernel, "tp_packets" is incremented for every
1702 * packet that passes the packet filter *and* is
1703 * successfully queued on the socket; "tp_drops" is
1704 * incremented for every packet dropped because there's
1705 * not enough free space in the socket buffer.
1707 * When the statistics are returned for a PACKET_STATISTICS
1708 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
1709 * so that "tp_packets" counts all packets handed to
1710 * the PF_PACKET socket, including packets dropped because
1711 * there wasn't room on the socket buffer - but not
1712 * including packets that didn't pass the filter.
1714 * In the BSD BPF, the count of received packets is
1715 * incremented for every packet handed to BPF, regardless
1716 * of whether it passed the filter.
1718 * We can't make "pcap_stats()" work the same on both
1719 * platforms, but the best approximation is to return
1720 * "tp_packets" as the count of packets and "tp_drops"
1721 * as the count of drops.
1723 * Keep a running total because each call to
1724 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
1725 * resets the counters to zero.
1727 handle
->md
.stat
.ps_recv
+= kstats
.tp_packets
;
1728 handle
->md
.stat
.ps_drop
+= kstats
.tp_drops
;
1729 *stats
= handle
->md
.stat
;
1735 * If the error was EOPNOTSUPP, fall through, so that
1736 * if you build the library on a system with
1737 * "struct tpacket_stats" and run it on a system
1738 * that doesn't, it works as it does if the library
1739 * is built on a system without "struct tpacket_stats".
1741 if (errno
!= EOPNOTSUPP
) {
1742 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1743 "pcap_stats: %s", pcap_strerror(errno
));
1749 * On systems where the PACKET_STATISTICS "getsockopt()" argument
1750 * is not supported on PF_PACKET sockets:
1752 * "ps_recv" counts only packets that *passed* the filter,
1753 * not packets that didn't pass the filter. It does not
1754 * count packets dropped because we ran out of buffer
1757 * "ps_drop" is not supported.
1759 * "ps_ifdrop" is supported. It will return the number
1760 * of drops the interface reports in /proc/net/dev,
1761 * if that is available.
1763 * "ps_recv" doesn't include packets not yet read from
1764 * the kernel by libpcap.
1766 * We maintain the count of packets processed by libpcap in
1767 * "md.packets_read", for reasons described in the comment
1768 * at the end of pcap_read_packet(). We have no idea how many
1769 * packets were dropped by the kernel buffers -- but we know
1770 * how many the interface dropped, so we can return that.
1773 stats
->ps_recv
= handle
->md
.packets_read
;
1775 stats
->ps_ifdrop
= handle
->md
.stat
.ps_ifdrop
;
1780 * Get from "/sys/class/net" all interfaces listed there; if they're
1781 * already in the list of interfaces we have, that won't add another
1782 * instance, but if they're not, that'll add them.
1784 * We don't bother getting any addresses for them; it appears you can't
1785 * use SIOCGIFADDR on Linux to get IPv6 addresses for interfaces, and,
1786 * although some other types of addresses can be fetched with SIOCGIFADDR,
1787 * we don't bother with them for now.
1789 * We also don't fail if we couldn't open "/sys/class/net"; we just leave
1790 * the list of interfaces as is, and return 0, so that we can try
1791 * scanning /proc/net/dev.
1794 scan_sys_class_net(pcap_if_t
**devlistp
, char *errbuf
)
1796 DIR *sys_class_net_d
;
1800 char name
[512]; /* XXX - pick a size */
1802 struct ifreq ifrflags
;
1805 sys_class_net_d
= opendir("/sys/class/net");
1806 if (sys_class_net_d
== NULL
&& errno
== ENOENT
)
1810 * Create a socket from which to fetch interface information.
1812 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
1814 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1815 "socket: %s", pcap_strerror(errno
));
1821 ent
= readdir(sys_class_net_d
);
1824 * Error or EOF; if errno != 0, it's an error.
1830 * Ignore directories (".", "..", and any subdirectories).
1832 if (ent
->d_type
== DT_DIR
)
1836 * Get the interface name.
1838 p
= &ent
->d_name
[0];
1840 while (*p
!= '\0' && isascii(*p
) && !isspace(*p
)) {
1843 * This could be the separator between a
1844 * name and an alias number, or it could be
1845 * the separator between a name with no
1846 * alias number and the next field.
1848 * If there's a colon after digits, it
1849 * separates the name and the alias number,
1850 * otherwise it separates the name and the
1854 while (isascii(*p
) && isdigit(*p
))
1858 * That was the next field,
1859 * not the alias number.
1870 * Get the flags for this interface, and skip it if
1873 strncpy(ifrflags
.ifr_name
, name
, sizeof(ifrflags
.ifr_name
));
1874 if (ioctl(fd
, SIOCGIFFLAGS
, (char *)&ifrflags
) < 0) {
1877 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1878 "SIOCGIFFLAGS: %.*s: %s",
1879 (int)sizeof(ifrflags
.ifr_name
),
1881 pcap_strerror(errno
));
1885 if (!(ifrflags
.ifr_flags
& IFF_UP
))
1889 * Add an entry for this interface, with no addresses.
1891 if (pcap_add_if(devlistp
, name
, ifrflags
.ifr_flags
, NULL
,
1902 * Well, we didn't fail for any other reason; did we
1903 * fail due to an error reading the directory?
1906 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1907 "Error reading /sys/class/net: %s",
1908 pcap_strerror(errno
));
1914 (void)closedir(sys_class_net_d
);
1919 * Get from "/proc/net/dev" all interfaces listed there; if they're
1920 * already in the list of interfaces we have, that won't add another
1921 * instance, but if they're not, that'll add them.
1923 * See comments from scan_sys_class_net().
1926 scan_proc_net_dev(pcap_if_t
**devlistp
, char *errbuf
)
1933 char name
[512]; /* XXX - pick a size */
1935 struct ifreq ifrflags
;
1938 proc_net_f
= fopen("/proc/net/dev", "r");
1939 if (proc_net_f
== NULL
&& errno
== ENOENT
)
1943 * Create a socket from which to fetch interface information.
1945 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
1947 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1948 "socket: %s", pcap_strerror(errno
));
1953 fgets(linebuf
, sizeof linebuf
, proc_net_f
) != NULL
; linenum
++) {
1955 * Skip the first two lines - they're headers.
1963 * Skip leading white space.
1965 while (*p
!= '\0' && isascii(*p
) && isspace(*p
))
1967 if (*p
== '\0' || *p
== '\n')
1968 continue; /* blank line */
1971 * Get the interface name.
1974 while (*p
!= '\0' && isascii(*p
) && !isspace(*p
)) {
1977 * This could be the separator between a
1978 * name and an alias number, or it could be
1979 * the separator between a name with no
1980 * alias number and the next field.
1982 * If there's a colon after digits, it
1983 * separates the name and the alias number,
1984 * otherwise it separates the name and the
1988 while (isascii(*p
) && isdigit(*p
))
1992 * That was the next field,
1993 * not the alias number.
2004 * Get the flags for this interface, and skip it if
2007 strncpy(ifrflags
.ifr_name
, name
, sizeof(ifrflags
.ifr_name
));
2008 if (ioctl(fd
, SIOCGIFFLAGS
, (char *)&ifrflags
) < 0) {
2011 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2012 "SIOCGIFFLAGS: %.*s: %s",
2013 (int)sizeof(ifrflags
.ifr_name
),
2015 pcap_strerror(errno
));
2019 if (!(ifrflags
.ifr_flags
& IFF_UP
))
2023 * Add an entry for this interface, with no addresses.
2025 if (pcap_add_if(devlistp
, name
, ifrflags
.ifr_flags
, NULL
,
2036 * Well, we didn't fail for any other reason; did we
2037 * fail due to an error reading the file?
2039 if (ferror(proc_net_f
)) {
2040 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2041 "Error reading /proc/net/dev: %s",
2042 pcap_strerror(errno
));
2048 (void)fclose(proc_net_f
);
2053 * Description string for the "any" device.
2055 static const char any_descr
[] = "Pseudo-device that captures on all interfaces";
2058 pcap_platform_finddevs(pcap_if_t
**alldevsp
, char *errbuf
)
2063 * Read "/sys/class/net", and add to the list of interfaces all
2064 * interfaces listed there that we don't already have, because,
2065 * on Linux, SIOCGIFCONF reports only interfaces with IPv4 addresses,
2066 * and even getifaddrs() won't return information about
2067 * interfaces with no addresses, so you need to read "/sys/class/net"
2068 * to get the names of the rest of the interfaces.
2070 ret
= scan_sys_class_net(alldevsp
, errbuf
);
2072 return (-1); /* failed */
2075 * No /sys/class/net; try reading /proc/net/dev instead.
2077 if (scan_proc_net_dev(alldevsp
, errbuf
) == -1)
2082 * Add the "any" device.
2084 if (pcap_add_if(alldevsp
, "any", 0, any_descr
, errbuf
) < 0)
2091 if (dag_platform_finddevs(alldevsp
, errbuf
) < 0)
2093 #endif /* HAVE_DAG_API */
2095 #ifdef HAVE_SEPTEL_API
2097 * Add Septel devices.
2099 if (septel_platform_finddevs(alldevsp
, errbuf
) < 0)
2101 #endif /* HAVE_SEPTEL_API */
2103 #ifdef PCAP_SUPPORT_BT
2105 * Add Bluetooth devices.
2107 if (bt_platform_finddevs(alldevsp
, errbuf
) < 0)
2111 #ifdef PCAP_SUPPORT_USB
2115 if (usb_platform_finddevs(alldevsp
, errbuf
) < 0)
2123 * Attach the given BPF code to the packet capture device.
2126 pcap_setfilter_linux_common(pcap_t
*handle
, struct bpf_program
*filter
,
2129 #ifdef SO_ATTACH_FILTER
2130 struct sock_fprog fcode
;
2131 int can_filter_in_kernel
;
2138 strncpy(handle
->errbuf
, "setfilter: No filter specified",
2143 /* Make our private copy of the filter */
2145 if (install_bpf_program(handle
, filter
) < 0)
2146 /* install_bpf_program() filled in errbuf */
2150 * Run user level packet filter by default. Will be overriden if
2151 * installing a kernel filter succeeds.
2153 handle
->md
.use_bpf
= 0;
2155 /* Install kernel level filter if possible */
2157 #ifdef SO_ATTACH_FILTER
2159 if (handle
->fcode
.bf_len
> USHRT_MAX
) {
2161 * fcode.len is an unsigned short for current kernel.
2162 * I have yet to see BPF-Code with that much
2163 * instructions but still it is possible. So for the
2164 * sake of correctness I added this check.
2166 fprintf(stderr
, "Warning: Filter too complex for kernel\n");
2168 fcode
.filter
= NULL
;
2169 can_filter_in_kernel
= 0;
2171 #endif /* USHRT_MAX */
2174 * Oh joy, the Linux kernel uses struct sock_fprog instead
2175 * of struct bpf_program and of course the length field is
2176 * of different size. Pointed out by Sebastian
2178 * Oh, and we also need to fix it up so that all "ret"
2179 * instructions with non-zero operands have 65535 as the
2180 * operand if we're not capturing in memory-mapped modee,
2181 * and so that, if we're in cooked mode, all memory-reference
2182 * instructions use special magic offsets in references to
2183 * the link-layer header and assume that the link-layer
2184 * payload begins at 0; "fix_program()" will do that.
2186 switch (fix_program(handle
, &fcode
, is_mmapped
)) {
2191 * Fatal error; just quit.
2192 * (The "default" case shouldn't happen; we
2193 * return -1 for that reason.)
2199 * The program performed checks that we can't make
2200 * work in the kernel.
2202 can_filter_in_kernel
= 0;
2207 * We have a filter that'll work in the kernel.
2209 can_filter_in_kernel
= 1;
2214 if (can_filter_in_kernel
) {
2215 if ((err
= set_kernel_filter(handle
, &fcode
)) == 0)
2217 /* Installation succeded - using kernel filter. */
2218 handle
->md
.use_bpf
= 1;
2220 else if (err
== -1) /* Non-fatal error */
2223 * Print a warning if we weren't able to install
2224 * the filter for a reason other than "this kernel
2225 * isn't configured to support socket filters.
2227 if (errno
!= ENOPROTOOPT
&& errno
!= EOPNOTSUPP
) {
2229 "Warning: Kernel filter failed: %s\n",
2230 pcap_strerror(errno
));
2236 * If we're not using the kernel filter, get rid of any kernel
2237 * filter that might've been there before, e.g. because the
2238 * previous filter could work in the kernel, or because some other
2239 * code attached a filter to the socket by some means other than
2240 * calling "pcap_setfilter()". Otherwise, the kernel filter may
2241 * filter out packets that would pass the new userland filter.
2243 if (!handle
->md
.use_bpf
)
2244 reset_kernel_filter(handle
);
2247 * Free up the copy of the filter that was made by "fix_program()".
2249 if (fcode
.filter
!= NULL
)
2255 #endif /* SO_ATTACH_FILTER */
2261 pcap_setfilter_linux(pcap_t
*handle
, struct bpf_program
*filter
)
2263 return pcap_setfilter_linux_common(handle
, filter
, 0);
2268 * Set direction flag: Which packets do we accept on a forwarding
2269 * single device? IN, OUT or both?
2272 pcap_setdirection_linux(pcap_t
*handle
, pcap_direction_t d
)
2274 #ifdef HAVE_PF_PACKET_SOCKETS
2275 if (!handle
->md
.sock_packet
) {
2276 handle
->direction
= d
;
2281 * We're not using PF_PACKET sockets, so we can't determine
2282 * the direction of the packet.
2284 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2285 "Setting direction is not supported on SOCK_PACKET sockets");
2290 #ifdef HAVE_PF_PACKET_SOCKETS
2292 * Map the PACKET_ value to a LINUX_SLL_ value; we
2293 * want the same numerical value to be used in
2294 * the link-layer header even if the numerical values
2295 * for the PACKET_ #defines change, so that programs
2296 * that look at the packet type field will always be
2297 * able to handle DLT_LINUX_SLL captures.
2300 map_packet_type_to_sll_type(short int sll_pkttype
)
2302 switch (sll_pkttype
) {
2305 return htons(LINUX_SLL_HOST
);
2307 case PACKET_BROADCAST
:
2308 return htons(LINUX_SLL_BROADCAST
);
2310 case PACKET_MULTICAST
:
2311 return htons(LINUX_SLL_MULTICAST
);
2313 case PACKET_OTHERHOST
:
2314 return htons(LINUX_SLL_OTHERHOST
);
2316 case PACKET_OUTGOING
:
2317 return htons(LINUX_SLL_OUTGOING
);
2326 * Linux uses the ARP hardware type to identify the type of an
2327 * interface. pcap uses the DLT_xxx constants for this. This
2328 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
2329 * constant, as arguments, and sets "handle->linktype" to the
2330 * appropriate DLT_XXX constant and sets "handle->offset" to
2331 * the appropriate value (to make "handle->offset" plus link-layer
2332 * header length be a multiple of 4, so that the link-layer payload
2333 * will be aligned on a 4-byte boundary when capturing packets).
2334 * (If the offset isn't set here, it'll be 0; add code as appropriate
2335 * for cases where it shouldn't be 0.)
2337 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
2338 * in cooked mode; otherwise, we can't use cooked mode, so we have
2339 * to pick some type that works in raw mode, or fail.
2341 * Sets the link type to -1 if unable to map the type.
2343 static void map_arphrd_to_dlt(pcap_t
*handle
, int arptype
, int cooked_ok
)
2349 * This is (presumably) a real Ethernet capture; give it a
2350 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
2351 * that an application can let you choose it, in case you're
2352 * capturing DOCSIS traffic that a Cisco Cable Modem
2353 * Termination System is putting out onto an Ethernet (it
2354 * doesn't put an Ethernet header onto the wire, it puts raw
2355 * DOCSIS frames out on the wire inside the low-level
2356 * Ethernet framing).
2358 * XXX - are there any sorts of "fake Ethernet" that have
2359 * ARPHRD_ETHER but that *shouldn't offer DLT_DOCSIS as
2360 * a Cisco CMTS won't put traffic onto it or get traffic
2361 * bridged onto it? ISDN is handled in "activate_new()",
2362 * as we fall back on cooked mode there; are there any
2365 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
2367 * If that fails, just leave the list empty.
2369 if (handle
->dlt_list
!= NULL
) {
2370 handle
->dlt_list
[0] = DLT_EN10MB
;
2371 handle
->dlt_list
[1] = DLT_DOCSIS
;
2372 handle
->dlt_count
= 2;
2376 case ARPHRD_METRICOM
:
2377 case ARPHRD_LOOPBACK
:
2378 handle
->linktype
= DLT_EN10MB
;
2383 handle
->linktype
= DLT_EN3MB
;
2387 handle
->linktype
= DLT_AX25_KISS
;
2391 handle
->linktype
= DLT_PRONET
;
2395 handle
->linktype
= DLT_CHAOS
;
2398 #define ARPHRD_CAN 280
2401 handle
->linktype
= DLT_CAN_SOCKETCAN
;
2404 #ifndef ARPHRD_IEEE802_TR
2405 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
2407 case ARPHRD_IEEE802_TR
:
2408 case ARPHRD_IEEE802
:
2409 handle
->linktype
= DLT_IEEE802
;
2414 handle
->linktype
= DLT_ARCNET_LINUX
;
2417 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
2418 #define ARPHRD_FDDI 774
2421 handle
->linktype
= DLT_FDDI
;
2425 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
2426 #define ARPHRD_ATM 19
2430 * The Classical IP implementation in ATM for Linux
2431 * supports both what RFC 1483 calls "LLC Encapsulation",
2432 * in which each packet has an LLC header, possibly
2433 * with a SNAP header as well, prepended to it, and
2434 * what RFC 1483 calls "VC Based Multiplexing", in which
2435 * different virtual circuits carry different network
2436 * layer protocols, and no header is prepended to packets.
2438 * They both have an ARPHRD_ type of ARPHRD_ATM, so
2439 * you can't use the ARPHRD_ type to find out whether
2440 * captured packets will have an LLC header, and,
2441 * while there's a socket ioctl to *set* the encapsulation
2442 * type, there's no ioctl to *get* the encapsulation type.
2446 * programs that dissect Linux Classical IP frames
2447 * would have to check for an LLC header and,
2448 * depending on whether they see one or not, dissect
2449 * the frame as LLC-encapsulated or as raw IP (I
2450 * don't know whether there's any traffic other than
2451 * IP that would show up on the socket, or whether
2452 * there's any support for IPv6 in the Linux
2453 * Classical IP code);
2455 * filter expressions would have to compile into
2456 * code that checks for an LLC header and does
2459 * Both of those are a nuisance - and, at least on systems
2460 * that support PF_PACKET sockets, we don't have to put
2461 * up with those nuisances; instead, we can just capture
2462 * in cooked mode. That's what we'll do, if we can.
2463 * Otherwise, we'll just fail.
2466 handle
->linktype
= DLT_LINUX_SLL
;
2468 handle
->linktype
= -1;
2471 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
2472 #define ARPHRD_IEEE80211 801
2474 case ARPHRD_IEEE80211
:
2475 handle
->linktype
= DLT_IEEE802_11
;
2478 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
2479 #define ARPHRD_IEEE80211_PRISM 802
2481 case ARPHRD_IEEE80211_PRISM
:
2482 handle
->linktype
= DLT_PRISM_HEADER
;
2485 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
2486 #define ARPHRD_IEEE80211_RADIOTAP 803
2488 case ARPHRD_IEEE80211_RADIOTAP
:
2489 handle
->linktype
= DLT_IEEE802_11_RADIO
;
2494 * Some PPP code in the kernel supplies no link-layer
2495 * header whatsoever to PF_PACKET sockets; other PPP
2496 * code supplies PPP link-layer headers ("syncppp.c");
2497 * some PPP code might supply random link-layer
2498 * headers (PPP over ISDN - there's code in Ethereal,
2499 * for example, to cope with PPP-over-ISDN captures
2500 * with which the Ethereal developers have had to cope,
2501 * heuristically trying to determine which of the
2502 * oddball link-layer headers particular packets have).
2504 * As such, we just punt, and run all PPP interfaces
2505 * in cooked mode, if we can; otherwise, we just treat
2506 * it as DLT_RAW, for now - if somebody needs to capture,
2507 * on a 2.0[.x] kernel, on PPP devices that supply a
2508 * link-layer header, they'll have to add code here to
2509 * map to the appropriate DLT_ type (possibly adding a
2510 * new DLT_ type, if necessary).
2513 handle
->linktype
= DLT_LINUX_SLL
;
2516 * XXX - handle ISDN types here? We can't fall
2517 * back on cooked sockets, so we'd have to
2518 * figure out from the device name what type of
2519 * link-layer encapsulation it's using, and map
2520 * that to an appropriate DLT_ value, meaning
2521 * we'd map "isdnN" devices to DLT_RAW (they
2522 * supply raw IP packets with no link-layer
2523 * header) and "isdY" devices to a new DLT_I4L_IP
2524 * type that has only an Ethernet packet type as
2525 * a link-layer header.
2527 * But sometimes we seem to get random crap
2528 * in the link-layer header when capturing on
2531 handle
->linktype
= DLT_RAW
;
2535 #ifndef ARPHRD_CISCO
2536 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
2539 handle
->linktype
= DLT_C_HDLC
;
2542 /* Not sure if this is correct for all tunnels, but it
2546 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
2554 #ifndef ARPHRD_RAWHDLC
2555 #define ARPHRD_RAWHDLC 518
2557 case ARPHRD_RAWHDLC
:
2559 #define ARPHRD_DLCI 15
2563 * XXX - should some of those be mapped to DLT_LINUX_SLL
2564 * instead? Should we just map all of them to DLT_LINUX_SLL?
2566 handle
->linktype
= DLT_RAW
;
2570 #define ARPHRD_FRAD 770
2573 handle
->linktype
= DLT_FRELAY
;
2576 case ARPHRD_LOCALTLK
:
2577 handle
->linktype
= DLT_LTALK
;
2581 #define ARPHRD_FCPP 784
2585 #define ARPHRD_FCAL 785
2589 #define ARPHRD_FCPL 786
2592 #ifndef ARPHRD_FCFABRIC
2593 #define ARPHRD_FCFABRIC 787
2595 case ARPHRD_FCFABRIC
:
2597 * We assume that those all mean RFC 2625 IP-over-
2598 * Fibre Channel, with the RFC 2625 header at
2599 * the beginning of the packet.
2601 handle
->linktype
= DLT_IP_OVER_FC
;
2605 #define ARPHRD_IRDA 783
2608 /* Don't expect IP packet out of this interfaces... */
2609 handle
->linktype
= DLT_LINUX_IRDA
;
2610 /* We need to save packet direction for IrDA decoding,
2611 * so let's use "Linux-cooked" mode. Jean II */
2612 //handle->md.cooked = 1;
2615 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
2616 * is needed, please report it to <daniele@orlandi.com> */
2618 #define ARPHRD_LAPD 8445
2621 /* Don't expect IP packet out of this interfaces... */
2622 handle
->linktype
= DLT_LINUX_LAPD
;
2626 #define ARPHRD_NONE 0xFFFE
2630 * No link-layer header; packets are just IP
2631 * packets, so use DLT_RAW.
2633 handle
->linktype
= DLT_RAW
;
2637 handle
->linktype
= -1;
2642 /* ===== Functions to interface to the newer kernels ================== */
2645 * Try to open a packet socket using the new kernel PF_PACKET interface.
2646 * Returns 1 on success, 0 on an error that means the new interface isn't
2647 * present (so the old SOCK_PACKET interface should be tried), and a
2648 * PCAP_ERROR_ value on an error that means that the old mechanism won't
2649 * work either (so it shouldn't be tried).
2652 activate_new(pcap_t
*handle
)
2654 #ifdef HAVE_PF_PACKET_SOCKETS
2655 const char *device
= handle
->opt
.source
;
2656 int is_any_device
= (strcmp(device
, "any") == 0);
2657 int sock_fd
= -1, arptype
;
2658 #ifdef HAVE_PACKET_AUXDATA
2662 struct packet_mreq mr
;
2665 * Open a socket with protocol family packet. If the
2666 * "any" device was specified, we open a SOCK_DGRAM
2667 * socket for the cooked interface, otherwise we first
2668 * try a SOCK_RAW socket for the raw interface.
2670 sock_fd
= is_any_device
?
2671 socket(PF_PACKET
, SOCK_DGRAM
, htons(ETH_P_ALL
)) :
2672 socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
));
2674 if (sock_fd
== -1) {
2675 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "socket: %s",
2676 pcap_strerror(errno
) );
2677 return 0; /* try old mechanism */
2680 /* It seems the kernel supports the new interface. */
2681 handle
->md
.sock_packet
= 0;
2684 * Get the interface index of the loopback device.
2685 * If the attempt fails, don't fail, just set the
2686 * "md.lo_ifindex" to -1.
2688 * XXX - can there be more than one device that loops
2689 * packets back, i.e. devices other than "lo"? If so,
2690 * we'd need to find them all, and have an array of
2691 * indices for them, and check all of them in
2692 * "pcap_read_packet()".
2694 handle
->md
.lo_ifindex
= iface_get_id(sock_fd
, "lo", handle
->errbuf
);
2697 * Default value for offset to align link-layer payload
2698 * on a 4-byte boundary.
2703 * What kind of frames do we have to deal with? Fall back
2704 * to cooked mode if we have an unknown interface type
2705 * or a type we know doesn't work well in raw mode.
2707 if (!is_any_device
) {
2708 /* Assume for now we don't need cooked mode. */
2709 handle
->md
.cooked
= 0;
2711 if (handle
->opt
.rfmon
) {
2713 * We were asked to turn on monitor mode.
2714 * Do so before we get the link-layer type,
2715 * because entering monitor mode could change
2716 * the link-layer type.
2718 err
= enter_rfmon_mode(handle
, sock_fd
, device
);
2726 * Nothing worked for turning monitor mode
2730 return PCAP_ERROR_RFMON_NOTSUP
;
2734 * Either monitor mode has been turned on for
2735 * the device, or we've been given a different
2736 * device to open for monitor mode. If we've
2737 * been given a different device, use it.
2739 if (handle
->md
.mondevice
!= NULL
)
2740 device
= handle
->md
.mondevice
;
2742 arptype
= iface_get_arptype(sock_fd
, device
, handle
->errbuf
);
2747 map_arphrd_to_dlt(handle
, arptype
, 1);
2748 if (handle
->linktype
== -1 ||
2749 handle
->linktype
== DLT_LINUX_SLL
||
2750 handle
->linktype
== DLT_LINUX_IRDA
||
2751 handle
->linktype
== DLT_LINUX_LAPD
||
2752 (handle
->linktype
== DLT_EN10MB
&&
2753 (strncmp("isdn", device
, 4) == 0 ||
2754 strncmp("isdY", device
, 4) == 0))) {
2756 * Unknown interface type (-1), or a
2757 * device we explicitly chose to run
2758 * in cooked mode (e.g., PPP devices),
2759 * or an ISDN device (whose link-layer
2760 * type we can only determine by using
2761 * APIs that may be different on different
2762 * kernels) - reopen in cooked mode.
2764 if (close(sock_fd
) == -1) {
2765 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2766 "close: %s", pcap_strerror(errno
));
2769 sock_fd
= socket(PF_PACKET
, SOCK_DGRAM
,
2771 if (sock_fd
== -1) {
2772 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2773 "socket: %s", pcap_strerror(errno
));
2776 handle
->md
.cooked
= 1;
2779 * Get rid of any link-layer type list
2780 * we allocated - this only supports cooked
2783 if (handle
->dlt_list
!= NULL
) {
2784 free(handle
->dlt_list
);
2785 handle
->dlt_list
= NULL
;
2786 handle
->dlt_count
= 0;
2789 if (handle
->linktype
== -1) {
2791 * Warn that we're falling back on
2792 * cooked mode; we may want to
2793 * update "map_arphrd_to_dlt()"
2794 * to handle the new type.
2796 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2798 "supported by libpcap - "
2799 "falling back to cooked "
2805 * IrDA capture is not a real "cooked" capture,
2806 * it's IrLAP frames, not IP packets. The
2807 * same applies to LAPD capture.
2809 if (handle
->linktype
!= DLT_LINUX_IRDA
&&
2810 handle
->linktype
!= DLT_LINUX_LAPD
)
2811 handle
->linktype
= DLT_LINUX_SLL
;
2814 handle
->md
.ifindex
= iface_get_id(sock_fd
, device
,
2816 if (handle
->md
.ifindex
== -1) {
2821 if ((err
= iface_bind(sock_fd
, handle
->md
.ifindex
,
2822 handle
->errbuf
)) != 1) {
2827 return 0; /* try old mechanism */
2833 if (handle
->opt
.rfmon
) {
2835 * It doesn't support monitor mode.
2837 return PCAP_ERROR_RFMON_NOTSUP
;
2841 * It uses cooked mode.
2843 handle
->md
.cooked
= 1;
2844 handle
->linktype
= DLT_LINUX_SLL
;
2847 * We're not bound to a device.
2848 * For now, we're using this as an indication
2849 * that we can't transmit; stop doing that only
2850 * if we figure out how to transmit in cooked
2853 handle
->md
.ifindex
= -1;
2857 * Select promiscuous mode on if "promisc" is set.
2859 * Do not turn allmulti mode on if we don't select
2860 * promiscuous mode - on some devices (e.g., Orinoco
2861 * wireless interfaces), allmulti mode isn't supported
2862 * and the driver implements it by turning promiscuous
2863 * mode on, and that screws up the operation of the
2864 * card as a normal networking interface, and on no
2865 * other platform I know of does starting a non-
2866 * promiscuous capture affect which multicast packets
2867 * are received by the interface.
2871 * Hmm, how can we set promiscuous mode on all interfaces?
2872 * I am not sure if that is possible at all. For now, we
2873 * silently ignore attempts to turn promiscuous mode on
2874 * for the "any" device (so you don't have to explicitly
2875 * disable it in programs such as tcpdump).
2878 if (!is_any_device
&& handle
->opt
.promisc
) {
2879 memset(&mr
, 0, sizeof(mr
));
2880 mr
.mr_ifindex
= handle
->md
.ifindex
;
2881 mr
.mr_type
= PACKET_MR_PROMISC
;
2882 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_ADD_MEMBERSHIP
,
2883 &mr
, sizeof(mr
)) == -1) {
2884 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2885 "setsockopt: %s", pcap_strerror(errno
));
2891 /* Enable auxillary data if supported and reserve room for
2892 * reconstructing VLAN headers. */
2893 #ifdef HAVE_PACKET_AUXDATA
2895 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_AUXDATA
, &val
,
2896 sizeof(val
)) == -1 && errno
!= ENOPROTOOPT
) {
2897 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2898 "setsockopt: %s", pcap_strerror(errno
));
2902 handle
->offset
+= VLAN_TAG_LEN
;
2903 #endif /* HAVE_PACKET_AUXDATA */
2906 * This is a 2.2[.x] or later kernel (we know that
2907 * because we're not using a SOCK_PACKET socket -
2908 * PF_PACKET is supported only in 2.2 and later
2911 * We can safely pass "recvfrom()" a byte count
2912 * based on the snapshot length.
2914 * If we're in cooked mode, make the snapshot length
2915 * large enough to hold a "cooked mode" header plus
2916 * 1 byte of packet data (so we don't pass a byte
2917 * count of 0 to "recvfrom()").
2919 if (handle
->md
.cooked
) {
2920 if (handle
->snapshot
< SLL_HDR_LEN
+ 1)
2921 handle
->snapshot
= SLL_HDR_LEN
+ 1;
2923 handle
->bufsize
= handle
->snapshot
;
2925 /* Save the socket FD in the pcap structure */
2926 handle
->fd
= sock_fd
;
2931 "New packet capturing interface not supported by build "
2932 "environment", PCAP_ERRBUF_SIZE
);
2938 activate_mmap(pcap_t
*handle
)
2940 #ifdef HAVE_PACKET_RING
2944 * Attempt to allocate a buffer to hold the contents of one
2945 * packet, for use by the oneshot callback.
2947 handle
->md
.oneshot_buffer
= malloc(handle
->snapshot
);
2948 if (handle
->md
.oneshot_buffer
== NULL
) {
2949 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2950 "can't allocate oneshot buffer: %s",
2951 pcap_strerror(errno
));
2955 if (handle
->opt
.buffer_size
== 0) {
2956 /* by default request 2M for the ring buffer */
2957 handle
->opt
.buffer_size
= 2*1024*1024;
2959 ret
= prepare_tpacket_socket(handle
);
2961 free(handle
->md
.oneshot_buffer
);
2964 ret
= create_ring(handle
);
2966 free(handle
->md
.oneshot_buffer
);
2970 /* override some defaults and inherit the other fields from
2972 * handle->offset is used to get the current position into the rx ring
2973 * handle->cc is used to store the ring size */
2974 handle
->read_op
= pcap_read_linux_mmap
;
2975 handle
->cleanup_op
= pcap_cleanup_linux_mmap
;
2976 handle
->setfilter_op
= pcap_setfilter_linux_mmap
;
2977 handle
->setnonblock_op
= pcap_setnonblock_mmap
;
2978 handle
->getnonblock_op
= pcap_getnonblock_mmap
;
2979 handle
->oneshot_callback
= pcap_oneshot_mmap
;
2980 handle
->selectable_fd
= handle
->fd
;
2982 #else /* HAVE_PACKET_RING */
2984 #endif /* HAVE_PACKET_RING */
2987 #ifdef HAVE_PACKET_RING
2989 prepare_tpacket_socket(pcap_t
*handle
)
2991 #ifdef HAVE_TPACKET2
2996 handle
->md
.tp_version
= TPACKET_V1
;
2997 handle
->md
.tp_hdrlen
= sizeof(struct tpacket_hdr
);
2999 #ifdef HAVE_TPACKET2
3000 /* Probe whether kernel supports TPACKET_V2 */
3003 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_HDRLEN
, &val
, &len
) < 0) {
3004 if (errno
== ENOPROTOOPT
)
3005 return 1; /* no - just drive on */
3007 /* Yes - treat as a failure. */
3008 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3009 "can't get TPACKET_V2 header len on packet socket: %s",
3010 pcap_strerror(errno
));
3013 handle
->md
.tp_hdrlen
= val
;
3016 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_VERSION
, &val
,
3018 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3019 "can't activate TPACKET_V2 on packet socket: %s",
3020 pcap_strerror(errno
));
3023 handle
->md
.tp_version
= TPACKET_V2
;
3025 /* Reserve space for VLAN tag reconstruction */
3027 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
, &val
,
3029 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3030 "can't set up reserve on packet socket: %s",
3031 pcap_strerror(errno
));
3035 #endif /* HAVE_TPACKET2 */
3040 create_ring(pcap_t
*handle
)
3042 unsigned i
, j
, frames_per_block
;
3043 struct tpacket_req req
;
3045 /* Note that with large snapshot (say 64K) only a few frames
3046 * will be available in the ring even with pretty large ring size
3047 * (and a lot of memory will be unused).
3048 * The snap len should be carefully chosen to achive best
3050 req
.tp_frame_size
= TPACKET_ALIGN(handle
->snapshot
+
3051 TPACKET_ALIGN(handle
->md
.tp_hdrlen
) +
3052 sizeof(struct sockaddr_ll
));
3053 req
.tp_frame_nr
= handle
->opt
.buffer_size
/req
.tp_frame_size
;
3055 /* compute the minumum block size that will handle this frame.
3056 * The block has to be page size aligned.
3057 * The max block size allowed by the kernel is arch-dependent and
3058 * it's not explicitly checked here. */
3059 req
.tp_block_size
= getpagesize();
3060 while (req
.tp_block_size
< req
.tp_frame_size
)
3061 req
.tp_block_size
<<= 1;
3063 frames_per_block
= req
.tp_block_size
/req
.tp_frame_size
;
3065 /* ask the kernel to create the ring */
3067 req
.tp_block_nr
= req
.tp_frame_nr
/ frames_per_block
;
3069 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
3070 req
.tp_frame_nr
= req
.tp_block_nr
* frames_per_block
;
3072 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
3073 (void *) &req
, sizeof(req
))) {
3074 if ((errno
== ENOMEM
) && (req
.tp_block_nr
> 1)) {
3076 * Memory failure; try to reduce the requested ring
3079 * We used to reduce this by half -- do 5% instead.
3080 * That may result in more iterations and a longer
3081 * startup, but the user will be much happier with
3082 * the resulting buffer size.
3084 if (req
.tp_frame_nr
< 20)
3085 req
.tp_frame_nr
-= 1;
3087 req
.tp_frame_nr
-= req
.tp_frame_nr
/20;
3090 if (errno
== ENOPROTOOPT
) {
3092 * We don't have ring buffer support in this kernel.
3096 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3097 "can't create rx ring on packet socket: %s",
3098 pcap_strerror(errno
));
3102 /* memory map the rx ring */
3103 handle
->md
.mmapbuflen
= req
.tp_block_nr
* req
.tp_block_size
;
3104 handle
->md
.mmapbuf
= mmap(0, handle
->md
.mmapbuflen
,
3105 PROT_READ
|PROT_WRITE
, MAP_SHARED
, handle
->fd
, 0);
3106 if (handle
->md
.mmapbuf
== MAP_FAILED
) {
3107 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3108 "can't mmap rx ring: %s", pcap_strerror(errno
));
3110 /* clear the allocated ring on error*/
3111 destroy_ring(handle
);
3115 /* allocate a ring for each frame header pointer*/
3116 handle
->cc
= req
.tp_frame_nr
;
3117 handle
->buffer
= malloc(handle
->cc
* sizeof(union thdr
*));
3118 if (!handle
->buffer
) {
3119 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3120 "can't allocate ring of frame headers: %s",
3121 pcap_strerror(errno
));
3123 destroy_ring(handle
);
3127 /* fill the header ring with proper frame ptr*/
3129 for (i
=0; i
<req
.tp_block_nr
; ++i
) {
3130 void *base
= &handle
->md
.mmapbuf
[i
*req
.tp_block_size
];
3131 for (j
=0; j
<frames_per_block
; ++j
, ++handle
->offset
) {
3132 RING_GET_FRAME(handle
) = base
;
3133 base
+= req
.tp_frame_size
;
3137 handle
->bufsize
= req
.tp_frame_size
;
3142 /* free all ring related resources*/
3144 destroy_ring(pcap_t
*handle
)
3146 /* tell the kernel to destroy the ring*/
3147 struct tpacket_req req
;
3148 memset(&req
, 0, sizeof(req
));
3149 setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
3150 (void *) &req
, sizeof(req
));
3152 /* if ring is mapped, unmap it*/
3153 if (handle
->md
.mmapbuf
) {
3154 /* do not test for mmap failure, as we can't recover from any error */
3155 munmap(handle
->md
.mmapbuf
, handle
->md
.mmapbuflen
);
3156 handle
->md
.mmapbuf
= NULL
;
3161 * Special one-shot callback, used for pcap_next() and pcap_next_ex(),
3162 * for Linux mmapped capture.
3164 * The problem is that pcap_next() and pcap_next_ex() expect the packet
3165 * data handed to the callback to be valid after the callback returns,
3166 * but pcap_read_linux_mmap() has to release that packet as soon as
3167 * the callback returns (otherwise, the kernel thinks there's still
3168 * at least one unprocessed packet available in the ring, so a select()
3169 * will immediately return indicating that there's data to process), so,
3170 * in the callback, we have to make a copy of the packet.
3172 * Yes, this means that, if the capture is using the ring buffer, using
3173 * pcap_next() or pcap_next_ex() requires more copies than using
3174 * pcap_loop() or pcap_dispatch(). If that bothers you, don't use
3175 * pcap_next() or pcap_next_ex().
3178 pcap_oneshot_mmap(u_char
*user
, const struct pcap_pkthdr
*h
,
3179 const u_char
*bytes
)
3181 struct oneshot_userdata
*sp
= (struct oneshot_userdata
*)user
;
3184 memcpy(sp
->pd
->md
.oneshot_buffer
, bytes
, h
->caplen
);
3185 *sp
->pkt
= sp
->pd
->md
.oneshot_buffer
;
3189 pcap_cleanup_linux_mmap( pcap_t
*handle
)
3191 destroy_ring(handle
);
3192 if (handle
->md
.oneshot_buffer
!= NULL
) {
3193 free(handle
->md
.oneshot_buffer
);
3194 handle
->md
.oneshot_buffer
= NULL
;
3196 pcap_cleanup_linux(handle
);
3201 pcap_getnonblock_mmap(pcap_t
*p
, char *errbuf
)
3203 /* use negative value of timeout to indicate non blocking ops */
3204 return (p
->md
.timeout
<0);
3208 pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
, char *errbuf
)
3210 /* map each value to the corresponding 2's complement, to
3211 * preserve the timeout value provided with pcap_set_timeout */
3213 if (p
->md
.timeout
>= 0) {
3215 * Timeout is non-negative, so we're not already
3216 * in non-blocking mode; set it to the 2's
3217 * complement, to make it negative, as an
3218 * indication that we're in non-blocking mode.
3220 p
->md
.timeout
= p
->md
.timeout
*-1 - 1;
3223 if (p
->md
.timeout
< 0) {
3225 * Timeout is negative, so we're not already
3226 * in blocking mode; reverse the previous
3227 * operation, to make the timeout non-negative
3230 p
->md
.timeout
= (p
->md
.timeout
+1)*-1;
3236 static inline union thdr
*
3237 pcap_get_ring_frame(pcap_t
*handle
, int status
)
3241 h
.raw
= RING_GET_FRAME(handle
);
3242 switch (handle
->md
.tp_version
) {
3244 if (status
!= (h
.h1
->tp_status
? TP_STATUS_USER
:
3248 #ifdef HAVE_TPACKET2
3250 if (status
!= (h
.h2
->tp_status
? TP_STATUS_USER
:
3264 pcap_read_linux_mmap(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
3271 /* wait for frames availability.*/
3272 if (!pcap_get_ring_frame(handle
, TP_STATUS_USER
)) {
3273 struct pollfd pollinfo
;
3276 pollinfo
.fd
= handle
->fd
;
3277 pollinfo
.events
= POLLIN
;
3279 if (handle
->md
.timeout
== 0)
3280 timeout
= -1; /* block forever */
3281 else if (handle
->md
.timeout
> 0)
3282 timeout
= handle
->md
.timeout
; /* block for that amount of time */
3284 timeout
= 0; /* non-blocking mode - poll to pick up errors */
3286 ret
= poll(&pollinfo
, 1, timeout
);
3287 if (ret
< 0 && errno
!= EINTR
) {
3288 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3289 "can't poll on packet socket: %s",
3290 pcap_strerror(errno
));
3292 } else if (ret
> 0 &&
3293 (pollinfo
.revents
& (POLLHUP
|POLLRDHUP
|POLLERR
|POLLNVAL
))) {
3295 * There's some indication other than
3296 * "you can read on this descriptor" on
3299 if (pollinfo
.revents
& (POLLHUP
| POLLRDHUP
)) {
3300 snprintf(handle
->errbuf
,
3302 "Hangup on packet socket");
3305 if (pollinfo
.revents
& POLLERR
) {
3307 * A recv() will give us the
3308 * actual error code.
3310 * XXX - make the socket non-blocking?
3312 if (recv(handle
->fd
, &c
, sizeof c
,
3314 continue; /* what, no error? */
3315 if (errno
== ENETDOWN
) {
3317 * The device on which we're
3318 * capturing went away.
3320 * XXX - we should really return
3321 * PCAP_ERROR_IFACE_NOT_UP,
3322 * but pcap_dispatch() etc.
3323 * aren't defined to return
3326 snprintf(handle
->errbuf
,
3328 "The interface went down");
3330 snprintf(handle
->errbuf
,
3332 "Error condition on packet socket: %s",
3337 if (pollinfo
.revents
& POLLNVAL
) {
3338 snprintf(handle
->errbuf
,
3340 "Invalid polling request on packet socket");
3344 /* check for break loop condition on interrupted syscall*/
3345 if (handle
->break_loop
) {
3346 handle
->break_loop
= 0;
3347 return PCAP_ERROR_BREAK
;
3352 /* non-positive values of max_packets are used to require all
3353 * packets currently available in the ring */
3354 while ((pkts
< max_packets
) || (max_packets
<= 0)) {
3356 struct sockaddr_ll
*sll
;
3357 struct pcap_pkthdr pcaphdr
;
3360 unsigned int tp_len
;
3361 unsigned int tp_mac
;
3362 unsigned int tp_snaplen
;
3363 unsigned int tp_sec
;
3364 unsigned int tp_usec
;
3366 h
.raw
= pcap_get_ring_frame(handle
, TP_STATUS_USER
);
3370 switch (handle
->md
.tp_version
) {
3372 tp_len
= h
.h1
->tp_len
;
3373 tp_mac
= h
.h1
->tp_mac
;
3374 tp_snaplen
= h
.h1
->tp_snaplen
;
3375 tp_sec
= h
.h1
->tp_sec
;
3376 tp_usec
= h
.h1
->tp_usec
;
3378 #ifdef HAVE_TPACKET2
3380 tp_len
= h
.h2
->tp_len
;
3381 tp_mac
= h
.h2
->tp_mac
;
3382 tp_snaplen
= h
.h2
->tp_snaplen
;
3383 tp_sec
= h
.h2
->tp_sec
;
3384 tp_usec
= h
.h2
->tp_nsec
/ 1000;
3388 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3389 "unsupported tpacket version %d",
3390 handle
->md
.tp_version
);
3393 /* perform sanity check on internal offset. */
3394 if (tp_mac
+ tp_snaplen
> handle
->bufsize
) {
3395 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3396 "corrupted frame on kernel ring mac "
3397 "offset %d + caplen %d > frame len %d",
3398 tp_mac
, tp_snaplen
, handle
->bufsize
);
3402 /* run filter on received packet
3403 * If the kernel filtering is enabled we need to run the
3404 * filter until all the frames present into the ring
3405 * at filter creation time are processed.
3406 * In such case md.use_bpf is used as a counter for the
3407 * packet we need to filter.
3408 * Note: alternatively it could be possible to stop applying
3409 * the filter when the ring became empty, but it can possibly
3410 * happen a lot later... */
3411 bp
= (unsigned char*)h
.raw
+ tp_mac
;
3412 run_bpf
= (!handle
->md
.use_bpf
) ||
3413 ((handle
->md
.use_bpf
>1) && handle
->md
.use_bpf
--);
3414 if (run_bpf
&& handle
->fcode
.bf_insns
&&
3415 (bpf_filter(handle
->fcode
.bf_insns
, bp
,
3416 tp_len
, tp_snaplen
) == 0))
3420 * Do checks based on packet direction.
3422 sll
= (void *)h
.raw
+ TPACKET_ALIGN(handle
->md
.tp_hdrlen
);
3423 if (sll
->sll_pkttype
== PACKET_OUTGOING
) {
3426 * If this is from the loopback device, reject it;
3427 * we'll see the packet as an incoming packet as well,
3428 * and we don't want to see it twice.
3430 if (sll
->sll_ifindex
== handle
->md
.lo_ifindex
)
3434 * If the user only wants incoming packets, reject it.
3436 if (handle
->direction
== PCAP_D_IN
)
3441 * If the user only wants outgoing packets, reject it.
3443 if (handle
->direction
== PCAP_D_OUT
)
3447 /* get required packet info from ring header */
3448 pcaphdr
.ts
.tv_sec
= tp_sec
;
3449 pcaphdr
.ts
.tv_usec
= tp_usec
;
3450 pcaphdr
.caplen
= tp_snaplen
;
3451 pcaphdr
.len
= tp_len
;
3453 /* if required build in place the sll header*/
3454 if (handle
->md
.cooked
) {
3455 struct sll_header
*hdrp
;
3458 * The kernel should have left us with enough
3459 * space for an sll header; back up the packet
3460 * data pointer into that space, as that'll be
3461 * the beginning of the packet we pass to the
3467 * Let's make sure that's past the end of
3468 * the tpacket header, i.e. >=
3469 * ((u_char *)thdr + TPACKET_HDRLEN), so we
3470 * don't step on the header when we construct
3473 if (bp
< (u_char
*)h
.raw
+
3474 TPACKET_ALIGN(handle
->md
.tp_hdrlen
) +
3475 sizeof(struct sockaddr_ll
)) {
3476 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3477 "cooked-mode frame doesn't have room for sll header");
3482 * OK, that worked; construct the sll header.
3484 hdrp
= (struct sll_header
*)bp
;
3485 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(
3487 hdrp
->sll_hatype
= htons(sll
->sll_hatype
);
3488 hdrp
->sll_halen
= htons(sll
->sll_halen
);
3489 memcpy(hdrp
->sll_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
3490 hdrp
->sll_protocol
= sll
->sll_protocol
;
3492 /* update packet len */
3493 pcaphdr
.caplen
+= SLL_HDR_LEN
;
3494 pcaphdr
.len
+= SLL_HDR_LEN
;
3497 #ifdef HAVE_TPACKET2
3498 if (handle
->md
.tp_version
== TPACKET_V2
&& h
.h2
->tp_vlan_tci
&&
3499 tp_snaplen
>= 2 * ETH_ALEN
) {
3500 struct vlan_tag
*tag
;
3503 memmove(bp
, bp
+ VLAN_TAG_LEN
, 2 * ETH_ALEN
);
3505 tag
= (struct vlan_tag
*)(bp
+ 2 * ETH_ALEN
);
3506 tag
->vlan_tpid
= htons(ETH_P_8021Q
);
3507 tag
->vlan_tci
= htons(h
.h2
->tp_vlan_tci
);
3509 pcaphdr
.caplen
+= VLAN_TAG_LEN
;
3510 pcaphdr
.len
+= VLAN_TAG_LEN
;
3515 * The only way to tell the kernel to cut off the
3516 * packet at a snapshot length is with a filter program;
3517 * if there's no filter program, the kernel won't cut
3520 * Trim the snapshot length to be no longer than the
3521 * specified snapshot length.
3523 if (pcaphdr
.caplen
> handle
->snapshot
)
3524 pcaphdr
.caplen
= handle
->snapshot
;
3526 /* pass the packet to the user */
3528 callback(user
, &pcaphdr
, bp
);
3529 handle
->md
.packets_read
++;
3533 switch (handle
->md
.tp_version
) {
3535 h
.h1
->tp_status
= TP_STATUS_KERNEL
;
3537 #ifdef HAVE_TPACKET2
3539 h
.h2
->tp_status
= TP_STATUS_KERNEL
;
3543 if (++handle
->offset
>= handle
->cc
)
3546 /* check for break loop condition*/
3547 if (handle
->break_loop
) {
3548 handle
->break_loop
= 0;
3549 return PCAP_ERROR_BREAK
;
3556 pcap_setfilter_linux_mmap(pcap_t
*handle
, struct bpf_program
*filter
)
3562 * Don't rewrite "ret" instructions; we don't need to, as
3563 * we're not reading packets with recvmsg(), and we don't
3564 * want to, as, by not rewriting them, the kernel can avoid
3565 * copying extra data.
3567 ret
= pcap_setfilter_linux_common(handle
, filter
, 1);
3571 /* if the kernel filter is enabled, we need to apply the filter on
3572 * all packets present into the ring. Get an upper bound of their number
3574 if (!handle
->md
.use_bpf
)
3577 /* walk the ring backward and count the free slot */
3578 offset
= handle
->offset
;
3579 if (--handle
->offset
< 0)
3580 handle
->offset
= handle
->cc
- 1;
3581 for (n
=0; n
< handle
->cc
; ++n
) {
3582 if (--handle
->offset
< 0)
3583 handle
->offset
= handle
->cc
- 1;
3584 if (!pcap_get_ring_frame(handle
, TP_STATUS_KERNEL
))
3588 /* be careful to not change current ring position */
3589 handle
->offset
= offset
;
3591 /* store the number of packets currently present in the ring */
3592 handle
->md
.use_bpf
= 1 + (handle
->cc
- n
);
3596 #endif /* HAVE_PACKET_RING */
3599 #ifdef HAVE_PF_PACKET_SOCKETS
3601 * Return the index of the given device name. Fill ebuf and return
3605 iface_get_id(int fd
, const char *device
, char *ebuf
)
3609 memset(&ifr
, 0, sizeof(ifr
));
3610 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
3612 if (ioctl(fd
, SIOCGIFINDEX
, &ifr
) == -1) {
3613 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3614 "SIOCGIFINDEX: %s", pcap_strerror(errno
));
3618 return ifr
.ifr_ifindex
;
3622 * Bind the socket associated with FD to the given device.
3623 * Return 1 on success, 0 if we should try a SOCK_PACKET socket,
3624 * or a PCAP_ERROR_ value on a hard error.
3627 iface_bind(int fd
, int ifindex
, char *ebuf
)
3629 struct sockaddr_ll sll
;
3631 socklen_t errlen
= sizeof(err
);
3633 memset(&sll
, 0, sizeof(sll
));
3634 sll
.sll_family
= AF_PACKET
;
3635 sll
.sll_ifindex
= ifindex
;
3636 sll
.sll_protocol
= htons(ETH_P_ALL
);
3638 if (bind(fd
, (struct sockaddr
*) &sll
, sizeof(sll
)) == -1) {
3639 if (errno
== ENETDOWN
) {
3641 * Return a "network down" indication, so that
3642 * the application can report that rather than
3643 * saying we had a mysterious failure and
3644 * suggest that they report a problem to the
3645 * libpcap developers.
3647 return PCAP_ERROR_IFACE_NOT_UP
;
3649 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3650 "bind: %s", pcap_strerror(errno
));
3655 /* Any pending errors, e.g., network is down? */
3657 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
3658 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3659 "getsockopt: %s", pcap_strerror(errno
));
3663 if (err
== ENETDOWN
) {
3665 * Return a "network down" indication, so that
3666 * the application can report that rather than
3667 * saying we had a mysterious failure and
3668 * suggest that they report a problem to the
3669 * libpcap developers.
3671 return PCAP_ERROR_IFACE_NOT_UP
;
3672 } else if (err
> 0) {
3673 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3674 "bind: %s", pcap_strerror(err
));
3681 #ifdef IW_MODE_MONITOR
3683 * Check whether the device supports the Wireless Extensions.
3684 * Returns 1 if it does, 0 if it doesn't, PCAP_ERROR_NO_SUCH_DEVICE
3685 * if the device doesn't even exist.
3688 has_wext(int sock_fd
, const char *device
, char *ebuf
)
3692 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3693 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3694 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3695 if (ioctl(sock_fd
, SIOCGIWNAME
, &ireq
) >= 0)
3697 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3698 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
3699 if (errno
== ENODEV
)
3700 return PCAP_ERROR_NO_SUCH_DEVICE
;
3705 * Per me si va ne la citta dolente,
3706 * Per me si va ne l'etterno dolore,
3708 * Lasciate ogne speranza, voi ch'intrate.
3710 * XXX - airmon-ng does special stuff with the Orinoco driver and the
3726 * Use the Wireless Extensions, if we have them, to try to turn monitor mode
3727 * on if it's not already on.
3729 * Returns 1 on success, 0 if we don't support the Wireless Extensions
3730 * on this device, or a PCAP_ERROR_ value if we do support them but
3731 * we weren't able to turn monitor mode on.
3734 enter_rfmon_mode_wext(pcap_t
*handle
, int sock_fd
, const char *device
)
3737 * XXX - at least some adapters require non-Wireless Extensions
3738 * mechanisms to turn monitor mode on.
3740 * Atheros cards might require that a separate "monitor virtual access
3741 * point" be created, with later versions of the madwifi driver.
3742 * airmon-ng does "wlanconfig ath create wlandev {if} wlanmode
3743 * monitor -bssid", which apparently spits out a line "athN"
3744 * where "athN" is the monitor mode device. To leave monitor
3745 * mode, it destroys the monitor mode device.
3747 * Some Intel Centrino adapters might require private ioctls to get
3748 * radio headers; the ipw2200 and ipw3945 drivers allow you to
3749 * configure a separate "rtapN" interface to capture in monitor
3750 * mode without preventing the adapter from operating normally.
3751 * (airmon-ng doesn't appear to use that, though.)
3753 * It would be Truly Wonderful if mac80211 and nl80211 cleaned this
3754 * up, and if all drivers were converted to mac80211 drivers.
3756 * If interface {if} is a mac80211 driver, the file
3757 * /sys/class/net/{if}/phy80211 is a symlink to
3758 * /sys/class/ieee80211/{phydev}, for some {phydev}.
3760 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
3761 * least, has a "wmaster0" device and a "wlan0" device; the
3762 * latter is the one with the IP address. Both show up in
3763 * "tcpdump -D" output. Capturing on the wmaster0 device
3764 * captures with 802.11 headers.
3766 * airmon-ng searches through /sys/class/net for devices named
3767 * monN, starting with mon0; as soon as one *doesn't* exist,
3768 * it chooses that as the monitor device name. If the "iw"
3769 * command exists, it does "iw dev {if} interface add {monif}
3770 * type monitor", where {monif} is the monitor device. It
3771 * then (sigh) sleeps .1 second, and then configures the
3772 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
3773 * is a file, it writes {mondev}, without a newline, to that file,
3774 * and again (sigh) sleeps .1 second, and then iwconfig's that
3775 * device into monitor mode and configures it up. Otherwise,
3776 * you can't do monitor mode.
3778 * All these devices are "glued" together by having the
3779 * /sys/class/net/{device}/phy80211 links pointing to the same
3780 * place, so, given a wmaster, wlan, or mon device, you can
3781 * find the other devices by looking for devices with
3782 * the same phy80211 link.
3784 * To turn monitor mode off, delete the monitor interface,
3785 * either with "iw dev {monif} interface del" or by sending
3786 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
3788 * Note: if you try to create a monitor device named "monN", and
3789 * there's already a "monN" device, it fails, as least with
3790 * the netlink interface (which is what iw uses), with a return
3791 * value of -ENFILE. (Return values are negative errnos.) We
3792 * could probably use that to find an unused device.
3796 struct iw_priv_args
*priv
;
3797 monitor_type montype
;
3804 * Does this device *support* the Wireless Extensions?
3806 err
= has_wext(sock_fd
, device
, handle
->errbuf
);
3808 return err
; /* either it doesn't or the device doesn't even exist */
3810 * Try to get all the Wireless Extensions private ioctls
3811 * supported by this device.
3813 * First, get the size of the buffer we need, by supplying no
3814 * buffer and a length of 0. If the device supports private
3815 * ioctls, it should return E2BIG, with ireq.u.data.length set
3816 * to the length we need. If it doesn't support them, it should
3817 * return EOPNOTSUPP.
3819 memset(&ireq
, 0, sizeof ireq
);
3820 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3821 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3822 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3823 ireq
.u
.data
.pointer
= (void *)args
;
3824 ireq
.u
.data
.length
= 0;
3825 ireq
.u
.data
.flags
= 0;
3826 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) != -1) {
3827 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3828 "%s: SIOCGIWPRIV with a zero-length buffer didn't fail!",
3832 if (errno
== EOPNOTSUPP
) {
3834 * No private ioctls, so we assume that there's only one
3835 * DLT_ for monitor mode.
3839 if (errno
!= E2BIG
) {
3843 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3844 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
3847 priv
= malloc(ireq
.u
.data
.length
* sizeof (struct iw_priv_args
));
3849 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3850 "malloc: %s", pcap_strerror(errno
));
3853 ireq
.u
.data
.pointer
= (void *)priv
;
3854 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) == -1) {
3855 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3856 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
3862 * Look for private ioctls to turn monitor mode on or, if
3863 * monitor mode is on, to set the header type.
3865 montype
= MONITOR_WEXT
;
3867 for (i
= 0; i
< ireq
.u
.data
.length
; i
++) {
3868 if (strcmp(priv
[i
].name
, "monitor_type") == 0) {
3870 * Hostap driver, use this one.
3871 * Set monitor mode first.
3872 * You can set it to 0 to get DLT_IEEE80211,
3873 * 1 to get DLT_PRISM, 2 to get
3874 * DLT_IEEE80211_RADIO_AVS, and, with more
3875 * recent versions of the driver, 3 to get
3876 * DLT_IEEE80211_RADIO.
3878 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
3880 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
3882 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
3884 montype
= MONITOR_HOSTAP
;
3888 if (strcmp(priv
[i
].name
, "set_prismhdr") == 0) {
3890 * Prism54 driver, use this one.
3891 * Set monitor mode first.
3892 * You can set it to 2 to get DLT_IEEE80211
3893 * or 3 or get DLT_PRISM.
3895 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
3897 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
3899 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
3901 montype
= MONITOR_PRISM54
;
3905 if (strcmp(priv
[i
].name
, "forceprismheader") == 0) {
3907 * RT2570 driver, use this one.
3908 * Do this after turning monitor mode on.
3909 * You can set it to 1 to get DLT_PRISM or 2
3910 * to get DLT_IEEE80211.
3912 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
3914 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
3916 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
3918 montype
= MONITOR_RT2570
;
3922 if (strcmp(priv
[i
].name
, "forceprism") == 0) {
3924 * RT73 driver, use this one.
3925 * Do this after turning monitor mode on.
3926 * Its argument is a *string*; you can
3927 * set it to "1" to get DLT_PRISM or "2"
3928 * to get DLT_IEEE80211.
3930 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_CHAR
)
3932 if (priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
)
3934 montype
= MONITOR_RT73
;
3938 if (strcmp(priv
[i
].name
, "prismhdr") == 0) {
3940 * One of the RTL8xxx drivers, use this one.
3941 * It can only be done after monitor mode
3942 * has been turned on. You can set it to 1
3943 * to get DLT_PRISM or 0 to get DLT_IEEE80211.
3945 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
3947 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
3949 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
3951 montype
= MONITOR_RTL8XXX
;
3955 if (strcmp(priv
[i
].name
, "rfmontx") == 0) {
3957 * RT2500 or RT61 driver, use this one.
3958 * It has one one-byte parameter; set
3959 * u.data.length to 1 and u.data.pointer to
3960 * point to the parameter.
3961 * It doesn't itself turn monitor mode on.
3962 * You can set it to 1 to allow transmitting
3963 * in monitor mode(?) and get DLT_IEEE80211,
3964 * or set it to 0 to disallow transmitting in
3965 * monitor mode(?) and get DLT_PRISM.
3967 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
3969 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 2)
3971 montype
= MONITOR_RT2500
;
3975 if (strcmp(priv
[i
].name
, "monitor") == 0) {
3977 * Either ACX100 or hostap, use this one.
3978 * It turns monitor mode on.
3979 * If it takes two arguments, it's ACX100;
3980 * the first argument is 1 for DLT_PRISM
3981 * or 2 for DLT_IEEE80211, and the second
3982 * argument is the channel on which to
3983 * run. If it takes one argument, it's
3984 * HostAP, and the argument is 2 for
3985 * DLT_IEEE80211 and 3 for DLT_PRISM.
3987 * If we see this, we don't quit, as this
3988 * might be a version of the hostap driver
3989 * that also supports "monitor_type".
3991 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
3993 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
3995 switch (priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) {
3998 montype
= MONITOR_PRISM
;
4003 montype
= MONITOR_ACX100
;
4015 * XXX - ipw3945? islism?
4021 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4022 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4023 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4024 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) == -1) {
4026 * We probably won't be able to set the mode, either.
4028 return PCAP_ERROR_RFMON_NOTSUP
;
4032 * Is it currently in monitor mode?
4034 if (ireq
.u
.mode
== IW_MODE_MONITOR
) {
4036 * Yes. Just leave things as they are.
4037 * We don't offer multiple link-layer types, as
4038 * changing the link-layer type out from under
4039 * somebody else capturing in monitor mode would
4040 * be considered rude.
4045 * No. We have to put the adapter into rfmon mode.
4049 * If we haven't already done so, arrange to have
4050 * "pcap_close_all()" called when we exit.
4052 if (!pcap_do_addexit(handle
)) {
4054 * "atexit()" failed; don't put the interface
4055 * in rfmon mode, just give up.
4057 return PCAP_ERROR_RFMON_NOTSUP
;
4061 * Save the old mode.
4063 handle
->md
.oldmode
= ireq
.u
.mode
;
4066 * Put the adapter in rfmon mode. How we do this depends
4067 * on whether we have a special private ioctl or not.
4069 if (montype
== MONITOR_PRISM
) {
4071 * We have the "monitor" private ioctl, but none of
4072 * the other private ioctls. Use this, and select
4075 * If it fails, just fall back on SIOCSIWMODE.
4077 memset(&ireq
, 0, sizeof ireq
);
4078 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4079 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4080 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4081 ireq
.u
.data
.length
= 1; /* 1 argument */
4082 args
[0] = 3; /* request Prism header */
4083 memcpy(ireq
.u
.name
, args
, IFNAMSIZ
);
4084 if (ioctl(sock_fd
, cmd
, &ireq
) != -1) {
4087 * Note that we have to put the old mode back
4088 * when we close the device.
4090 handle
->md
.must_do_on_close
|= MUST_CLEAR_RFMON
;
4093 * Add this to the list of pcaps to close
4096 pcap_add_to_pcaps_to_close(handle
);
4102 * Failure. Fall back on SIOCSIWMODE.
4107 * First, turn monitor mode on.
4109 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4110 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4111 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4112 ireq
.u
.mode
= IW_MODE_MONITOR
;
4113 if (ioctl(sock_fd
, SIOCSIWMODE
, &ireq
) == -1) {
4115 * Scientist, you've failed.
4117 return PCAP_ERROR_RFMON_NOTSUP
;
4121 * XXX - airmon-ng does "iwconfig {if} key off" after setting
4122 * monitor mode and setting the channel, and then does
4127 * Now select the appropriate radio header.
4133 * We don't have any private ioctl to set the header.
4137 case MONITOR_HOSTAP
:
4139 * Try to select the radiotap header.
4141 memset(&ireq
, 0, sizeof ireq
);
4142 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4143 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4144 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4145 args
[0] = 3; /* request radiotap header */
4146 memcpy(ireq
.u
.name
, args
, sizeof (int));
4147 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
4148 break; /* success */
4151 * That failed. Try to select the AVS header.
4153 memset(&ireq
, 0, sizeof ireq
);
4154 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4155 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4156 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4157 args
[0] = 2; /* request AVS header */
4158 memcpy(ireq
.u
.name
, args
, sizeof (int));
4159 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
4160 break; /* success */
4163 * That failed. Try to select the Prism header.
4165 memset(&ireq
, 0, sizeof ireq
);
4166 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4167 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4168 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4169 args
[0] = 1; /* request Prism header */
4170 memcpy(ireq
.u
.name
, args
, sizeof (int));
4171 ioctl(sock_fd
, cmd
, &ireq
);
4176 * The private ioctl failed.
4180 case MONITOR_PRISM54
:
4182 * Select the Prism header.
4184 memset(&ireq
, 0, sizeof ireq
);
4185 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4186 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4187 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4188 args
[0] = 3; /* request Prism header */
4189 memcpy(ireq
.u
.name
, args
, sizeof (int));
4190 ioctl(sock_fd
, cmd
, &ireq
);
4193 case MONITOR_ACX100
:
4195 * Get the current channel.
4197 memset(&ireq
, 0, sizeof ireq
);
4198 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4199 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4200 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4201 if (ioctl(sock_fd
, SIOCGIWFREQ
, &ireq
) == -1) {
4202 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4203 "%s: SIOCGIWFREQ: %s", device
,
4204 pcap_strerror(errno
));
4207 channel
= ireq
.u
.freq
.m
;
4210 * Select the Prism header, and set the channel to the
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 args
[0] = 1; /* request Prism header */
4218 args
[1] = channel
; /* set channel */
4219 memcpy(ireq
.u
.name
, args
, 2*sizeof (int));
4220 ioctl(sock_fd
, cmd
, &ireq
);
4223 case MONITOR_RT2500
:
4225 * Disallow transmission - that turns on the
4228 memset(&ireq
, 0, sizeof ireq
);
4229 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4230 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4231 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4232 args
[0] = 0; /* disallow transmitting */
4233 memcpy(ireq
.u
.name
, args
, sizeof (int));
4234 ioctl(sock_fd
, cmd
, &ireq
);
4237 case MONITOR_RT2570
:
4239 * Force the Prism header.
4241 memset(&ireq
, 0, sizeof ireq
);
4242 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4243 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4244 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4245 args
[0] = 1; /* request Prism header */
4246 memcpy(ireq
.u
.name
, args
, sizeof (int));
4247 ioctl(sock_fd
, cmd
, &ireq
);
4252 * Force the Prism header.
4254 memset(&ireq
, 0, sizeof ireq
);
4255 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4256 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4257 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4258 ireq
.u
.data
.length
= 1; /* 1 argument */
4259 ireq
.u
.data
.pointer
= "1";
4260 ireq
.u
.data
.flags
= 0;
4261 ioctl(sock_fd
, cmd
, &ireq
);
4264 case MONITOR_RTL8XXX
:
4266 * Force the Prism header.
4268 memset(&ireq
, 0, sizeof ireq
);
4269 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4270 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4271 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4272 args
[0] = 1; /* request Prism header */
4273 memcpy(ireq
.u
.name
, args
, sizeof (int));
4274 ioctl(sock_fd
, cmd
, &ireq
);
4279 * Note that we have to put the old mode back when we
4282 handle
->md
.must_do_on_close
|= MUST_CLEAR_RFMON
;
4285 * Add this to the list of pcaps to close when we exit.
4287 pcap_add_to_pcaps_to_close(handle
);
4291 #endif /* IW_MODE_MONITOR */
4294 * Try various mechanisms to enter monitor mode.
4297 enter_rfmon_mode(pcap_t
*handle
, int sock_fd
, const char *device
)
4299 #if defined(HAVE_LIBNL) || defined(IW_MODE_MONITOR)
4304 ret
= enter_rfmon_mode_mac80211(handle
, sock_fd
, device
);
4306 return ret
; /* error attempting to do so */
4308 return 1; /* success */
4309 #endif /* HAVE_LIBNL */
4311 #ifdef IW_MODE_MONITOR
4312 ret
= enter_rfmon_mode_wext(handle
, sock_fd
, device
);
4314 return ret
; /* error attempting to do so */
4316 return 1; /* success */
4317 #endif /* IW_MODE_MONITOR */
4320 * Either none of the mechanisms we know about work or none
4321 * of those mechanisms are available, so we can't do monitor
4327 #endif /* HAVE_PF_PACKET_SOCKETS */
4329 /* ===== Functions to interface to the older kernels ================== */
4332 * Try to open a packet socket using the old kernel interface.
4333 * Returns 1 on success and a PCAP_ERROR_ value on an error.
4336 activate_old(pcap_t
*handle
)
4340 const char *device
= handle
->opt
.source
;
4341 struct utsname utsname
;
4344 /* Open the socket */
4346 handle
->fd
= socket(PF_INET
, SOCK_PACKET
, htons(ETH_P_ALL
));
4347 if (handle
->fd
== -1) {
4348 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4349 "socket: %s", pcap_strerror(errno
));
4350 return PCAP_ERROR_PERM_DENIED
;
4353 /* It worked - we are using the old interface */
4354 handle
->md
.sock_packet
= 1;
4356 /* ...which means we get the link-layer header. */
4357 handle
->md
.cooked
= 0;
4359 /* Bind to the given device */
4361 if (strcmp(device
, "any") == 0) {
4362 strncpy(handle
->errbuf
, "pcap_activate: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
4366 if (iface_bind_old(handle
->fd
, device
, handle
->errbuf
) == -1)
4370 * Try to get the link-layer type.
4372 arptype
= iface_get_arptype(handle
->fd
, device
, handle
->errbuf
);
4377 * Try to find the DLT_ type corresponding to that
4380 map_arphrd_to_dlt(handle
, arptype
, 0);
4381 if (handle
->linktype
== -1) {
4382 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4383 "unknown arptype %d", arptype
);
4387 /* Go to promisc mode if requested */
4389 if (handle
->opt
.promisc
) {
4390 memset(&ifr
, 0, sizeof(ifr
));
4391 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4392 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
4393 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4394 "SIOCGIFFLAGS: %s", pcap_strerror(errno
));
4397 if ((ifr
.ifr_flags
& IFF_PROMISC
) == 0) {
4399 * Promiscuous mode isn't currently on,
4400 * so turn it on, and remember that
4401 * we should turn it off when the
4406 * If we haven't already done so, arrange
4407 * to have "pcap_close_all()" called when
4410 if (!pcap_do_addexit(handle
)) {
4412 * "atexit()" failed; don't put
4413 * the interface in promiscuous
4414 * mode, just give up.
4419 ifr
.ifr_flags
|= IFF_PROMISC
;
4420 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
4421 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4423 pcap_strerror(errno
));
4426 handle
->md
.must_do_on_close
|= MUST_CLEAR_PROMISC
;
4429 * Add this to the list of pcaps
4430 * to close when we exit.
4432 pcap_add_to_pcaps_to_close(handle
);
4437 * Compute the buffer size.
4439 * We're using SOCK_PACKET, so this might be a 2.0[.x]
4440 * kernel, and might require special handling - check.
4442 if (uname(&utsname
) < 0 ||
4443 strncmp(utsname
.release
, "2.0", 3) == 0) {
4445 * Either we couldn't find out what kernel release
4446 * this is, or it's a 2.0[.x] kernel.
4448 * In the 2.0[.x] kernel, a "recvfrom()" on
4449 * a SOCK_PACKET socket, with MSG_TRUNC set, will
4450 * return the number of bytes read, so if we pass
4451 * a length based on the snapshot length, it'll
4452 * return the number of bytes from the packet
4453 * copied to userland, not the actual length
4456 * This means that, for example, the IP dissector
4457 * in tcpdump will get handed a packet length less
4458 * than the length in the IP header, and will
4459 * complain about "truncated-ip".
4461 * So we don't bother trying to copy from the
4462 * kernel only the bytes in which we're interested,
4463 * but instead copy them all, just as the older
4464 * versions of libpcap for Linux did.
4466 * The buffer therefore needs to be big enough to
4467 * hold the largest packet we can get from this
4468 * device. Unfortunately, we can't get the MRU
4469 * of the network; we can only get the MTU. The
4470 * MTU may be too small, in which case a packet larger
4471 * than the buffer size will be truncated *and* we
4472 * won't get the actual packet size.
4474 * However, if the snapshot length is larger than
4475 * the buffer size based on the MTU, we use the
4476 * snapshot length as the buffer size, instead;
4477 * this means that with a sufficiently large snapshot
4478 * length we won't artificially truncate packets
4479 * to the MTU-based size.
4481 * This mess just one of many problems with packet
4482 * capture on 2.0[.x] kernels; you really want a
4483 * 2.2[.x] or later kernel if you want packet capture
4486 mtu
= iface_get_mtu(handle
->fd
, device
, handle
->errbuf
);
4489 handle
->bufsize
= MAX_LINKHEADER_SIZE
+ mtu
;
4490 if (handle
->bufsize
< handle
->snapshot
)
4491 handle
->bufsize
= handle
->snapshot
;
4494 * This is a 2.2[.x] or later kernel.
4496 * We can safely pass "recvfrom()" a byte count
4497 * based on the snapshot length.
4499 handle
->bufsize
= handle
->snapshot
;
4503 * Default value for offset to align link-layer payload
4504 * on a 4-byte boundary.
4512 * Bind the socket associated with FD to the given device using the
4513 * interface of the old kernels.
4516 iface_bind_old(int fd
, const char *device
, char *ebuf
)
4518 struct sockaddr saddr
;
4520 socklen_t errlen
= sizeof(err
);
4522 memset(&saddr
, 0, sizeof(saddr
));
4523 strncpy(saddr
.sa_data
, device
, sizeof(saddr
.sa_data
));
4524 if (bind(fd
, &saddr
, sizeof(saddr
)) == -1) {
4525 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4526 "bind: %s", pcap_strerror(errno
));
4530 /* Any pending errors, e.g., network is down? */
4532 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
4533 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4534 "getsockopt: %s", pcap_strerror(errno
));
4539 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4540 "bind: %s", pcap_strerror(err
));
4548 /* ===== System calls available on all supported kernels ============== */
4551 * Query the kernel for the MTU of the given interface.
4554 iface_get_mtu(int fd
, const char *device
, char *ebuf
)
4559 return BIGGER_THAN_ALL_MTUS
;
4561 memset(&ifr
, 0, sizeof(ifr
));
4562 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4564 if (ioctl(fd
, SIOCGIFMTU
, &ifr
) == -1) {
4565 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4566 "SIOCGIFMTU: %s", pcap_strerror(errno
));
4574 * Get the hardware type of the given interface as ARPHRD_xxx constant.
4577 iface_get_arptype(int fd
, const char *device
, char *ebuf
)
4581 memset(&ifr
, 0, sizeof(ifr
));
4582 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4584 if (ioctl(fd
, SIOCGIFHWADDR
, &ifr
) == -1) {
4585 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4586 "SIOCGIFHWADDR: %s", pcap_strerror(errno
));
4587 if (errno
== ENODEV
) {
4591 return PCAP_ERROR_NO_SUCH_DEVICE
;
4596 return ifr
.ifr_hwaddr
.sa_family
;
4599 #ifdef SO_ATTACH_FILTER
4601 fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
, int is_mmapped
)
4605 register struct bpf_insn
*p
;
4610 * Make a copy of the filter, and modify that copy if
4613 prog_size
= sizeof(*handle
->fcode
.bf_insns
) * handle
->fcode
.bf_len
;
4614 len
= handle
->fcode
.bf_len
;
4615 f
= (struct bpf_insn
*)malloc(prog_size
);
4617 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4618 "malloc: %s", pcap_strerror(errno
));
4621 memcpy(f
, handle
->fcode
.bf_insns
, prog_size
);
4623 fcode
->filter
= (struct sock_filter
*) f
;
4625 for (i
= 0; i
< len
; ++i
) {
4628 * What type of instruction is this?
4630 switch (BPF_CLASS(p
->code
)) {
4634 * It's a return instruction; are we capturing
4635 * in memory-mapped mode?
4639 * No; is the snapshot length a constant,
4640 * rather than the contents of the
4643 if (BPF_MODE(p
->code
) == BPF_K
) {
4645 * Yes - if the value to be returned,
4646 * i.e. the snapshot length, is
4647 * anything other than 0, make it
4648 * 65535, so that the packet is
4649 * truncated by "recvfrom()",
4650 * not by the filter.
4652 * XXX - there's nothing we can
4653 * easily do if it's getting the
4654 * value from the accumulator; we'd
4655 * have to insert code to force
4656 * non-zero values to be 65535.
4667 * It's a load instruction; is it loading
4670 switch (BPF_MODE(p
->code
)) {
4676 * Yes; are we in cooked mode?
4678 if (handle
->md
.cooked
) {
4680 * Yes, so we need to fix this
4683 if (fix_offset(p
) < 0) {
4685 * We failed to do so.
4686 * Return 0, so our caller
4687 * knows to punt to userland.
4697 return 1; /* we succeeded */
4701 fix_offset(struct bpf_insn
*p
)
4704 * What's the offset?
4706 if (p
->k
>= SLL_HDR_LEN
) {
4708 * It's within the link-layer payload; that starts at an
4709 * offset of 0, as far as the kernel packet filter is
4710 * concerned, so subtract the length of the link-layer
4713 p
->k
-= SLL_HDR_LEN
;
4714 } else if (p
->k
== 14) {
4716 * It's the protocol field; map it to the special magic
4717 * kernel offset for that field.
4719 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
4722 * It's within the header, but it's not one of those
4723 * fields; we can't do that in the kernel, so punt
4732 set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
)
4734 int total_filter_on
= 0;
4740 * The socket filter code doesn't discard all packets queued
4741 * up on the socket when the filter is changed; this means
4742 * that packets that don't match the new filter may show up
4743 * after the new filter is put onto the socket, if those
4744 * packets haven't yet been read.
4746 * This means, for example, that if you do a tcpdump capture
4747 * with a filter, the first few packets in the capture might
4748 * be packets that wouldn't have passed the filter.
4750 * We therefore discard all packets queued up on the socket
4751 * when setting a kernel filter. (This isn't an issue for
4752 * userland filters, as the userland filtering is done after
4753 * packets are queued up.)
4755 * To flush those packets, we put the socket in read-only mode,
4756 * and read packets from the socket until there are no more to
4759 * In order to keep that from being an infinite loop - i.e.,
4760 * to keep more packets from arriving while we're draining
4761 * the queue - we put the "total filter", which is a filter
4762 * that rejects all packets, onto the socket before draining
4765 * This code deliberately ignores any errors, so that you may
4766 * get bogus packets if an error occurs, rather than having
4767 * the filtering done in userland even if it could have been
4768 * done in the kernel.
4770 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
4771 &total_fcode
, sizeof(total_fcode
)) == 0) {
4775 * Note that we've put the total filter onto the socket.
4777 total_filter_on
= 1;
4780 * Save the socket's current mode, and put it in
4781 * non-blocking mode; we drain it by reading packets
4782 * until we get an error (which is normally a
4783 * "nothing more to be read" error).
4785 save_mode
= fcntl(handle
->fd
, F_GETFL
, 0);
4786 if (save_mode
!= -1 &&
4787 fcntl(handle
->fd
, F_SETFL
, save_mode
| O_NONBLOCK
) >= 0) {
4788 while (recv(handle
->fd
, &drain
, sizeof drain
,
4792 fcntl(handle
->fd
, F_SETFL
, save_mode
);
4793 if (save_errno
!= EAGAIN
) {
4795 reset_kernel_filter(handle
);
4796 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4797 "recv: %s", pcap_strerror(save_errno
));
4804 * Now attach the new filter.
4806 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
4807 fcode
, sizeof(*fcode
));
4808 if (ret
== -1 && total_filter_on
) {
4810 * Well, we couldn't set that filter on the socket,
4811 * but we could set the total filter on the socket.
4813 * This could, for example, mean that the filter was
4814 * too big to put into the kernel, so we'll have to
4815 * filter in userland; in any case, we'll be doing
4816 * filtering in userland, so we need to remove the
4817 * total filter so we see packets.
4822 * XXX - if this fails, we're really screwed;
4823 * we have the total filter on the socket,
4824 * and it won't come off. What do we do then?
4826 reset_kernel_filter(handle
);
4834 reset_kernel_filter(pcap_t
*handle
)
4837 * setsockopt() barfs unless it get a dummy parameter.
4838 * valgrind whines unless the value is initialized,
4839 * as it has no idea that setsockopt() ignores its
4844 return setsockopt(handle
->fd
, SOL_SOCKET
, SO_DETACH_FILTER
,
4845 &dummy
, sizeof(dummy
));