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>
141 #include "pcap-int.h"
142 #include "pcap/sll.h"
143 #include "pcap/vlan.h"
146 #include "pcap-dag.h"
147 #endif /* HAVE_DAG_API */
149 #ifdef HAVE_SEPTEL_API
150 #include "pcap-septel.h"
151 #endif /* HAVE_SEPTEL_API */
154 #include "pcap-snf.h"
155 #endif /* HAVE_SNF_API */
157 #ifdef PCAP_SUPPORT_USB
158 #include "pcap-usb-linux.h"
161 #ifdef PCAP_SUPPORT_BT
162 #include "pcap-bt-linux.h"
165 #ifdef PCAP_SUPPORT_CAN
166 #include "pcap-can-linux.h"
169 #if PCAP_SUPPORT_CANUSB
170 #include "pcap-canusb-linux.h"
173 #ifdef PCAP_SUPPORT_NETFILTER
174 #include "pcap-netfilter-linux.h"
178 #include <pcap-remote.h>
182 * If PF_PACKET is defined, we can use {SOCK_RAW,SOCK_DGRAM}/PF_PACKET
183 * sockets rather than SOCK_PACKET sockets.
185 * To use them, we include <linux/if_packet.h> rather than
186 * <netpacket/packet.h>; we do so because
188 * some Linux distributions (e.g., Slackware 4.0) have 2.2 or
189 * later kernels and libc5, and don't provide a <netpacket/packet.h>
192 * not all versions of glibc2 have a <netpacket/packet.h> file
193 * that defines stuff needed for some of the 2.4-or-later-kernel
194 * features, so if the system has a 2.4 or later kernel, we
195 * still can't use those features.
197 * We're already including a number of other <linux/XXX.h> headers, and
198 * this code is Linux-specific (no other OS has PF_PACKET sockets as
199 * a raw packet capture mechanism), so it's not as if you gain any
200 * useful portability by using <netpacket/packet.h>
202 * XXX - should we just include <linux/if_packet.h> even if PF_PACKET
203 * isn't defined? It only defines one data structure in 2.0.x, so
204 * it shouldn't cause any problems.
207 # include <linux/if_packet.h>
210 * On at least some Linux distributions (for example, Red Hat 5.2),
211 * there's no <netpacket/packet.h> file, but PF_PACKET is defined if
212 * you include <sys/socket.h>, but <linux/if_packet.h> doesn't define
213 * any of the PF_PACKET stuff such as "struct sockaddr_ll" or any of
214 * the PACKET_xxx stuff.
216 * So we check whether PACKET_HOST is defined, and assume that we have
217 * PF_PACKET sockets only if it is defined.
220 # define HAVE_PF_PACKET_SOCKETS
221 # ifdef PACKET_AUXDATA
222 # define HAVE_PACKET_AUXDATA
223 # endif /* PACKET_AUXDATA */
224 # endif /* PACKET_HOST */
227 /* check for memory mapped access avaibility. We assume every needed
228 * struct is defined if the macro TPACKET_HDRLEN is defined, because it
229 * uses many ring related structs and macros */
230 # ifdef TPACKET_HDRLEN
231 # define HAVE_PACKET_RING
232 # ifdef TPACKET2_HDRLEN
233 # define HAVE_TPACKET2
235 # define TPACKET_V1 0
236 # endif /* TPACKET2_HDRLEN */
237 # endif /* TPACKET_HDRLEN */
238 #endif /* PF_PACKET */
240 #ifdef SO_ATTACH_FILTER
241 #include <linux/types.h>
242 #include <linux/filter.h>
246 * We need linux/sockios.h if we have linux/net_tstamp.h (for time stamp
247 * specification) or linux/ethtool.h (for ethtool ioctls to get offloading
250 #if defined(HAVE_LINUX_NET_TSTAMP_H) || defined(HAVE_LINUX_ETHTOOL_H)
251 #include <linux/sockios.h>
254 #ifdef HAVE_LINUX_NET_TSTAMP_H
255 #include <linux/net_tstamp.h>
259 * Got Wireless Extensions?
261 #ifdef HAVE_LINUX_WIRELESS_H
262 #include <linux/wireless.h>
263 #endif /* HAVE_LINUX_WIRELESS_H */
269 #include <linux/nl80211.h>
271 #include <netlink/genl/genl.h>
272 #include <netlink/genl/family.h>
273 #include <netlink/genl/ctrl.h>
274 #include <netlink/msg.h>
275 #include <netlink/attr.h>
276 #endif /* HAVE_LIBNL */
279 * Got ethtool support?
281 #ifdef HAVE_LINUX_ETHTOOL_H
282 #include <linux/ethtool.h>
285 #ifndef HAVE_SOCKLEN_T
286 typedef int socklen_t
;
291 * This is being compiled on a system that lacks MSG_TRUNC; define it
292 * with the value it has in the 2.2 and later kernels, so that, on
293 * those kernels, when we pass it in the flags argument to "recvfrom()"
294 * we're passing the right value and thus get the MSG_TRUNC behavior
295 * we want. (We don't get that behavior on 2.0[.x] kernels, because
296 * they didn't support MSG_TRUNC.)
298 #define MSG_TRUNC 0x20
303 * This is being compiled on a system that lacks SOL_PACKET; define it
304 * with the value it has in the 2.2 and later kernels, so that we can
305 * set promiscuous mode in the good modern way rather than the old
306 * 2.0-kernel crappy way.
308 #define SOL_PACKET 263
311 #define MAX_LINKHEADER_SIZE 256
314 * When capturing on all interfaces we use this as the buffer size.
315 * Should be bigger then all MTUs that occur in real life.
316 * 64kB should be enough for now.
318 #define BIGGER_THAN_ALL_MTUS (64*1024)
321 * Prototypes for internal functions and methods.
323 static void map_arphrd_to_dlt(pcap_t
*, int, int);
324 #ifdef HAVE_PF_PACKET_SOCKETS
325 static short int map_packet_type_to_sll_type(short int);
327 static int pcap_activate_linux(pcap_t
*);
328 static int activate_old(pcap_t
*);
329 static int activate_new(pcap_t
*);
330 static int activate_mmap(pcap_t
*, int *);
331 static int pcap_can_set_rfmon_linux(pcap_t
*);
332 static int pcap_read_linux(pcap_t
*, int, pcap_handler
, u_char
*);
333 static int pcap_read_packet(pcap_t
*, pcap_handler
, u_char
*);
334 static int pcap_inject_linux(pcap_t
*, const void *, size_t);
335 static int pcap_stats_linux(pcap_t
*, struct pcap_stat
*);
336 static int pcap_setfilter_linux(pcap_t
*, struct bpf_program
*);
337 static int pcap_setdirection_linux(pcap_t
*, pcap_direction_t
);
338 static void pcap_cleanup_linux(pcap_t
*);
341 struct tpacket_hdr
*h1
;
342 struct tpacket2_hdr
*h2
;
346 #ifdef HAVE_PACKET_RING
347 #define RING_GET_FRAME(h) (((union thdr **)h->buffer)[h->offset])
349 static void destroy_ring(pcap_t
*handle
);
350 static int create_ring(pcap_t
*handle
, int *status
);
351 static int prepare_tpacket_socket(pcap_t
*handle
);
352 static void pcap_cleanup_linux_mmap(pcap_t
*);
353 static int pcap_read_linux_mmap(pcap_t
*, int, pcap_handler
, u_char
*);
354 static int pcap_setfilter_linux_mmap(pcap_t
*, struct bpf_program
*);
355 static int pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
, char *errbuf
);
356 static int pcap_getnonblock_mmap(pcap_t
*p
, char *errbuf
);
357 static void pcap_oneshot_mmap(u_char
*user
, const struct pcap_pkthdr
*h
,
358 const u_char
*bytes
);
362 * Wrap some ioctl calls
364 #ifdef HAVE_PF_PACKET_SOCKETS
365 static int iface_get_id(int fd
, const char *device
, char *ebuf
);
366 #endif /* HAVE_PF_PACKET_SOCKETS */
367 static int iface_get_mtu(int fd
, const char *device
, char *ebuf
);
368 static int iface_get_arptype(int fd
, const char *device
, char *ebuf
);
369 #ifdef HAVE_PF_PACKET_SOCKETS
370 static int iface_bind(int fd
, int ifindex
, char *ebuf
);
371 #ifdef IW_MODE_MONITOR
372 static int has_wext(int sock_fd
, const char *device
, char *ebuf
);
373 #endif /* IW_MODE_MONITOR */
374 static int enter_rfmon_mode(pcap_t
*handle
, int sock_fd
,
376 #endif /* HAVE_PF_PACKET_SOCKETS */
377 static int iface_get_offload(pcap_t
*handle
);
378 static int iface_bind_old(int fd
, const char *device
, char *ebuf
);
380 #ifdef SO_ATTACH_FILTER
381 static int fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
,
383 static int fix_offset(struct bpf_insn
*p
);
384 static int set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
);
385 static int reset_kernel_filter(pcap_t
*handle
);
387 static struct sock_filter total_insn
388 = BPF_STMT(BPF_RET
| BPF_K
, 0);
389 static struct sock_fprog total_fcode
390 = { 1, &total_insn
};
391 #endif /* SO_ATTACH_FILTER */
394 pcap_create(const char *device
, char *ebuf
)
399 * A null device name is equivalent to the "any" device.
405 if (strstr(device
, "dag")) {
406 return dag_create(device
, ebuf
);
408 #endif /* HAVE_DAG_API */
410 #ifdef HAVE_SEPTEL_API
411 if (strstr(device
, "septel")) {
412 return septel_create(device
, ebuf
);
414 #endif /* HAVE_SEPTEL_API */
417 handle
= snf_create(device
, ebuf
);
418 if (strstr(device
, "snf") || handle
!= NULL
)
421 #endif /* HAVE_SNF_API */
423 #ifdef PCAP_SUPPORT_BT
424 if (strstr(device
, "bluetooth")) {
425 return bt_create(device
, ebuf
);
429 #if PCAP_SUPPORT_CANUSB
430 if (strstr(device
, "canusb")) {
431 return canusb_create(device
, ebuf
);
435 #ifdef PCAP_SUPPORT_CAN
436 if ((strncmp(device
, "can", 3) == 0 && isdigit(device
[3])) ||
437 (strncmp(device
, "vcan", 4) == 0 && isdigit(device
[4]))) {
438 return can_create(device
, ebuf
);
442 #ifdef PCAP_SUPPORT_USB
443 if (strstr(device
, "usbmon")) {
444 return usb_create(device
, ebuf
);
448 #ifdef PCAP_SUPPORT_NETFILTER
449 if (strncmp(device
, "nflog", strlen("nflog")) == 0) {
450 return nflog_create(device
, ebuf
);
454 handle
= pcap_create_common(device
, ebuf
);
458 handle
->activate_op
= pcap_activate_linux
;
459 handle
->can_set_rfmon_op
= pcap_can_set_rfmon_linux
;
460 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
462 * We claim that we support:
464 * software time stamps, with no details about their precision;
465 * hardware time stamps, synced to the host time;
466 * hardware time stamps, not synced to the host time.
468 * XXX - we can't ask a device whether it supports
469 * hardware time stamps, so we just claim all devices do.
471 handle
->tstamp_type_count
= 3;
472 handle
->tstamp_type_list
= malloc(3 * sizeof(u_int
));
473 if (handle
->tstamp_type_list
== NULL
) {
477 handle
->tstamp_type_list
[0] = PCAP_TSTAMP_HOST
;
478 handle
->tstamp_type_list
[1] = PCAP_TSTAMP_ADAPTER
;
479 handle
->tstamp_type_list
[2] = PCAP_TSTAMP_ADAPTER_UNSYNCED
;
487 * If interface {if} is a mac80211 driver, the file
488 * /sys/class/net/{if}/phy80211 is a symlink to
489 * /sys/class/ieee80211/{phydev}, for some {phydev}.
491 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
492 * least, has a "wmaster0" device and a "wlan0" device; the
493 * latter is the one with the IP address. Both show up in
494 * "tcpdump -D" output. Capturing on the wmaster0 device
495 * captures with 802.11 headers.
497 * airmon-ng searches through /sys/class/net for devices named
498 * monN, starting with mon0; as soon as one *doesn't* exist,
499 * it chooses that as the monitor device name. If the "iw"
500 * command exists, it does "iw dev {if} interface add {monif}
501 * type monitor", where {monif} is the monitor device. It
502 * then (sigh) sleeps .1 second, and then configures the
503 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
504 * is a file, it writes {mondev}, without a newline, to that file,
505 * and again (sigh) sleeps .1 second, and then iwconfig's that
506 * device into monitor mode and configures it up. Otherwise,
507 * you can't do monitor mode.
509 * All these devices are "glued" together by having the
510 * /sys/class/net/{device}/phy80211 links pointing to the same
511 * place, so, given a wmaster, wlan, or mon device, you can
512 * find the other devices by looking for devices with
513 * the same phy80211 link.
515 * To turn monitor mode off, delete the monitor interface,
516 * either with "iw dev {monif} interface del" or by sending
517 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
519 * Note: if you try to create a monitor device named "monN", and
520 * there's already a "monN" device, it fails, as least with
521 * the netlink interface (which is what iw uses), with a return
522 * value of -ENFILE. (Return values are negative errnos.) We
523 * could probably use that to find an unused device.
525 * Yes, you can have multiple monitor devices for a given
530 * Is this a mac80211 device? If so, fill in the physical device path and
531 * return 1; if not, return 0. On an error, fill in handle->errbuf and
535 get_mac80211_phydev(pcap_t
*handle
, const char *device
, char *phydev_path
,
536 size_t phydev_max_pathlen
)
542 * Generate the path string for the symlink to the physical device.
544 if (asprintf(&pathstr
, "/sys/class/net/%s/phy80211", device
) == -1) {
545 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
546 "%s: Can't generate path name string for /sys/class/net device",
550 bytes_read
= readlink(pathstr
, phydev_path
, phydev_max_pathlen
);
551 if (bytes_read
== -1) {
552 if (errno
== ENOENT
|| errno
== EINVAL
) {
554 * Doesn't exist, or not a symlink; assume that
555 * means it's not a mac80211 device.
560 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
561 "%s: Can't readlink %s: %s", device
, pathstr
,
567 phydev_path
[bytes_read
] = '\0';
571 #ifdef HAVE_LIBNL_2_x
572 #define get_nl_errmsg nl_geterror
574 /* libnl 2.x compatibility code */
576 #define nl_sock nl_handle
578 static inline struct nl_handle
*
579 nl_socket_alloc(void)
581 return nl_handle_alloc();
585 nl_socket_free(struct nl_handle
*h
)
587 nl_handle_destroy(h
);
590 #define get_nl_errmsg strerror
593 __genl_ctrl_alloc_cache(struct nl_handle
*h
, struct nl_cache
**cache
)
595 struct nl_cache
*tmp
= genl_ctrl_alloc_cache(h
);
601 #define genl_ctrl_alloc_cache __genl_ctrl_alloc_cache
602 #endif /* !HAVE_LIBNL_2_x */
604 struct nl80211_state
{
605 struct nl_sock
*nl_sock
;
606 struct nl_cache
*nl_cache
;
607 struct genl_family
*nl80211
;
611 nl80211_init(pcap_t
*handle
, struct nl80211_state
*state
, const char *device
)
615 state
->nl_sock
= nl_socket_alloc();
616 if (!state
->nl_sock
) {
617 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
618 "%s: failed to allocate netlink handle", device
);
622 if (genl_connect(state
->nl_sock
)) {
623 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
624 "%s: failed to connect to generic netlink", device
);
625 goto out_handle_destroy
;
628 err
= genl_ctrl_alloc_cache(state
->nl_sock
, &state
->nl_cache
);
630 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
631 "%s: failed to allocate generic netlink cache: %s",
632 device
, get_nl_errmsg(-err
));
633 goto out_handle_destroy
;
636 state
->nl80211
= genl_ctrl_search_by_name(state
->nl_cache
, "nl80211");
637 if (!state
->nl80211
) {
638 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
639 "%s: nl80211 not found", device
);
646 nl_cache_free(state
->nl_cache
);
648 nl_socket_free(state
->nl_sock
);
653 nl80211_cleanup(struct nl80211_state
*state
)
655 genl_family_put(state
->nl80211
);
656 nl_cache_free(state
->nl_cache
);
657 nl_socket_free(state
->nl_sock
);
661 add_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
662 const char *device
, const char *mondevice
)
668 ifindex
= iface_get_id(sock_fd
, device
, handle
->errbuf
);
674 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
675 "%s: failed to allocate netlink msg", device
);
679 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
680 0, NL80211_CMD_NEW_INTERFACE
, 0);
681 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
682 NLA_PUT_STRING(msg
, NL80211_ATTR_IFNAME
, mondevice
);
683 NLA_PUT_U32(msg
, NL80211_ATTR_IFTYPE
, NL80211_IFTYPE_MONITOR
);
685 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
687 #ifdef HAVE_LIBNL_2_x
688 if (err
== -NLE_FAILURE
) {
690 if (err
== -ENFILE
) {
693 * Device not available; our caller should just
694 * keep trying. (libnl 2.x maps ENFILE to
695 * NLE_FAILURE; it can also map other errors
696 * to that, but there's not much we can do
703 * Real failure, not just "that device is not
706 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
707 "%s: nl_send_auto_complete failed adding %s interface: %s",
708 device
, mondevice
, get_nl_errmsg(-err
));
713 err
= nl_wait_for_ack(state
->nl_sock
);
715 #ifdef HAVE_LIBNL_2_x
716 if (err
== -NLE_FAILURE
) {
718 if (err
== -ENFILE
) {
721 * Device not available; our caller should just
722 * keep trying. (libnl 2.x maps ENFILE to
723 * NLE_FAILURE; it can also map other errors
724 * to that, but there's not much we can do
731 * Real failure, not just "that device is not
734 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
735 "%s: nl_wait_for_ack failed adding %s interface: %s",
736 device
, mondevice
, get_nl_errmsg(-err
));
749 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
750 "%s: nl_put failed adding %s interface",
757 del_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
758 const char *device
, const char *mondevice
)
764 ifindex
= iface_get_id(sock_fd
, mondevice
, handle
->errbuf
);
770 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
771 "%s: failed to allocate netlink msg", device
);
775 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
776 0, NL80211_CMD_DEL_INTERFACE
, 0);
777 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
779 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
781 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
782 "%s: nl_send_auto_complete failed deleting %s interface: %s",
783 device
, mondevice
, get_nl_errmsg(-err
));
787 err
= nl_wait_for_ack(state
->nl_sock
);
789 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
790 "%s: nl_wait_for_ack failed adding %s interface: %s",
791 device
, mondevice
, get_nl_errmsg(-err
));
803 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
804 "%s: nl_put failed deleting %s interface",
811 enter_rfmon_mode_mac80211(pcap_t
*handle
, int sock_fd
, const char *device
)
814 char phydev_path
[PATH_MAX
+1];
815 struct nl80211_state nlstate
;
820 * Is this a mac80211 device?
822 ret
= get_mac80211_phydev(handle
, device
, phydev_path
, PATH_MAX
);
824 return ret
; /* error */
826 return 0; /* no error, but not mac80211 device */
829 * XXX - is this already a monN device?
831 * Is that determined by old Wireless Extensions ioctls?
835 * OK, it's apparently a mac80211 device.
836 * Try to find an unused monN device for it.
838 ret
= nl80211_init(handle
, &nlstate
, device
);
841 for (n
= 0; n
< UINT_MAX
; n
++) {
845 char mondevice
[3+10+1]; /* mon{UINT_MAX}\0 */
847 snprintf(mondevice
, sizeof mondevice
, "mon%u", n
);
848 ret
= add_mon_if(handle
, sock_fd
, &nlstate
, device
, mondevice
);
850 handle
->md
.mondevice
= strdup(mondevice
);
855 * Hard failure. Just return ret; handle->errbuf
856 * has already been set.
858 nl80211_cleanup(&nlstate
);
863 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
864 "%s: No free monN interfaces", device
);
865 nl80211_cleanup(&nlstate
);
872 * Sleep for .1 seconds.
875 delay
.tv_nsec
= 500000000;
876 nanosleep(&delay
, NULL
);
880 * If we haven't already done so, arrange to have
881 * "pcap_close_all()" called when we exit.
883 if (!pcap_do_addexit(handle
)) {
885 * "atexit()" failed; don't put the interface
886 * in rfmon mode, just give up.
888 return PCAP_ERROR_RFMON_NOTSUP
;
892 * Now configure the monitor interface up.
894 memset(&ifr
, 0, sizeof(ifr
));
895 strncpy(ifr
.ifr_name
, handle
->md
.mondevice
, sizeof(ifr
.ifr_name
));
896 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
897 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
898 "%s: Can't get flags for %s: %s", device
,
899 handle
->md
.mondevice
, strerror(errno
));
900 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
901 handle
->md
.mondevice
);
902 nl80211_cleanup(&nlstate
);
905 ifr
.ifr_flags
|= IFF_UP
|IFF_RUNNING
;
906 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
907 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
908 "%s: Can't set flags for %s: %s", device
,
909 handle
->md
.mondevice
, strerror(errno
));
910 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
911 handle
->md
.mondevice
);
912 nl80211_cleanup(&nlstate
);
917 * Success. Clean up the libnl state.
919 nl80211_cleanup(&nlstate
);
922 * Note that we have to delete the monitor device when we close
925 handle
->md
.must_do_on_close
|= MUST_DELETE_MONIF
;
928 * Add this to the list of pcaps to close when we exit.
930 pcap_add_to_pcaps_to_close(handle
);
934 #endif /* HAVE_LIBNL */
937 pcap_can_set_rfmon_linux(pcap_t
*handle
)
940 char phydev_path
[PATH_MAX
+1];
943 #ifdef IW_MODE_MONITOR
944 int sock_fd
; struct iwreq ireq
;
947 if (strcmp(handle
->opt
.source
, "any") == 0) {
949 * Monitor mode makes no sense on the "any" device.
956 * Bleah. There doesn't seem to be a way to ask a mac80211
957 * device, through libnl, whether it supports monitor mode;
958 * we'll just check whether the device appears to be a
959 * mac80211 device and, if so, assume the device supports
962 * wmaster devices don't appear to support the Wireless
963 * Extensions, but we can create a mon device for a
964 * wmaster device, so we don't bother checking whether
965 * a mac80211 device supports the Wireless Extensions.
967 ret
= get_mac80211_phydev(handle
, handle
->opt
.source
, phydev_path
,
970 return ret
; /* error */
972 return 1; /* mac80211 device */
975 #ifdef IW_MODE_MONITOR
977 * Bleah. There doesn't appear to be an ioctl to use to ask
978 * whether a device supports monitor mode; we'll just do
979 * SIOCGIWMODE and, if it succeeds, assume the device supports
982 * Open a socket on which to attempt to get the mode.
983 * (We assume that if we have Wireless Extensions support
984 * we also have PF_PACKET support.)
986 sock_fd
= socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
));
988 (void)snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
989 "socket: %s", pcap_strerror(errno
));
994 * Attempt to get the current mode.
996 strncpy(ireq
.ifr_ifrn
.ifrn_name
, handle
->opt
.source
,
997 sizeof ireq
.ifr_ifrn
.ifrn_name
);
998 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
999 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) != -1) {
1001 * Well, we got the mode; assume we can set it.
1006 if (errno
== ENODEV
) {
1007 /* The device doesn't even exist. */
1008 (void)snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1009 "SIOCGIWMODE failed: %s", pcap_strerror(errno
));
1011 return PCAP_ERROR_NO_SUCH_DEVICE
;
1019 * Grabs the number of dropped packets by the interface from /proc/net/dev.
1021 * XXX - what about /sys/class/net/{interface name}/rx_*? There are
1022 * individual devices giving, in ASCII, various rx_ and tx_ statistics.
1024 * Or can we get them in binary form from netlink?
1027 linux_if_drops(const char * if_name
)
1032 int field_to_convert
= 3, if_name_sz
= strlen(if_name
);
1033 long int dropped_pkts
= 0;
1035 file
= fopen("/proc/net/dev", "r");
1039 while (!dropped_pkts
&& fgets( buffer
, sizeof(buffer
), file
))
1041 /* search for 'bytes' -- if its in there, then
1042 that means we need to grab the fourth field. otherwise
1043 grab the third field. */
1044 if (field_to_convert
!= 4 && strstr(buffer
, "bytes"))
1046 field_to_convert
= 4;
1050 /* find iface and make sure it actually matches -- space before the name and : after it */
1051 if ((bufptr
= strstr(buffer
, if_name
)) &&
1052 (bufptr
== buffer
|| *(bufptr
-1) == ' ') &&
1053 *(bufptr
+ if_name_sz
) == ':')
1055 bufptr
= bufptr
+ if_name_sz
+ 1;
1057 /* grab the nth field from it */
1058 while( --field_to_convert
&& *bufptr
!= '\0')
1060 while (*bufptr
!= '\0' && *(bufptr
++) == ' ');
1061 while (*bufptr
!= '\0' && *(bufptr
++) != ' ');
1064 /* get rid of any final spaces */
1065 while (*bufptr
!= '\0' && *bufptr
== ' ') bufptr
++;
1067 if (*bufptr
!= '\0')
1068 dropped_pkts
= strtol(bufptr
, NULL
, 10);
1075 return dropped_pkts
;
1080 * With older kernels promiscuous mode is kind of interesting because we
1081 * have to reset the interface before exiting. The problem can't really
1082 * be solved without some daemon taking care of managing usage counts.
1083 * If we put the interface into promiscuous mode, we set a flag indicating
1084 * that we must take it out of that mode when the interface is closed,
1085 * and, when closing the interface, if that flag is set we take it out
1086 * of promiscuous mode.
1088 * Even with newer kernels, we have the same issue with rfmon mode.
1091 static void pcap_cleanup_linux( pcap_t
*handle
)
1095 struct nl80211_state nlstate
;
1097 #endif /* HAVE_LIBNL */
1098 #ifdef IW_MODE_MONITOR
1101 #endif /* IW_MODE_MONITOR */
1103 if (handle
->md
.must_do_on_close
!= 0) {
1105 * There's something we have to do when closing this
1108 if (handle
->md
.must_do_on_close
& MUST_CLEAR_PROMISC
) {
1110 * We put the interface into promiscuous mode;
1111 * take it out of promiscuous mode.
1113 * XXX - if somebody else wants it in promiscuous
1114 * mode, this code cannot know that, so it'll take
1115 * it out of promiscuous mode. That's not fixable
1116 * in 2.0[.x] kernels.
1118 memset(&ifr
, 0, sizeof(ifr
));
1119 strncpy(ifr
.ifr_name
, handle
->md
.device
,
1120 sizeof(ifr
.ifr_name
));
1121 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
1123 "Can't restore interface %s flags (SIOCGIFFLAGS failed: %s).\n"
1124 "Please adjust manually.\n"
1125 "Hint: This can't happen with Linux >= 2.2.0.\n",
1126 handle
->md
.device
, strerror(errno
));
1128 if (ifr
.ifr_flags
& IFF_PROMISC
) {
1130 * Promiscuous mode is currently on;
1133 ifr
.ifr_flags
&= ~IFF_PROMISC
;
1134 if (ioctl(handle
->fd
, SIOCSIFFLAGS
,
1137 "Can't restore interface %s flags (SIOCSIFFLAGS failed: %s).\n"
1138 "Please adjust manually.\n"
1139 "Hint: This can't happen with Linux >= 2.2.0.\n",
1148 if (handle
->md
.must_do_on_close
& MUST_DELETE_MONIF
) {
1149 ret
= nl80211_init(handle
, &nlstate
, handle
->md
.device
);
1151 ret
= del_mon_if(handle
, handle
->fd
, &nlstate
,
1152 handle
->md
.device
, handle
->md
.mondevice
);
1153 nl80211_cleanup(&nlstate
);
1157 "Can't delete monitor interface %s (%s).\n"
1158 "Please delete manually.\n",
1159 handle
->md
.mondevice
, handle
->errbuf
);
1162 #endif /* HAVE_LIBNL */
1164 #ifdef IW_MODE_MONITOR
1165 if (handle
->md
.must_do_on_close
& MUST_CLEAR_RFMON
) {
1167 * We put the interface into rfmon mode;
1168 * take it out of rfmon mode.
1170 * XXX - if somebody else wants it in rfmon
1171 * mode, this code cannot know that, so it'll take
1172 * it out of rfmon mode.
1176 * First, take the interface down if it's up;
1177 * otherwise, we might get EBUSY.
1178 * If we get errors, just drive on and print
1179 * a warning if we can't restore the mode.
1182 memset(&ifr
, 0, sizeof(ifr
));
1183 strncpy(ifr
.ifr_name
, handle
->md
.device
,
1184 sizeof(ifr
.ifr_name
));
1185 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) != -1) {
1186 if (ifr
.ifr_flags
& IFF_UP
) {
1187 oldflags
= ifr
.ifr_flags
;
1188 ifr
.ifr_flags
&= ~IFF_UP
;
1189 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1)
1190 oldflags
= 0; /* didn't set, don't restore */
1195 * Now restore the mode.
1197 strncpy(ireq
.ifr_ifrn
.ifrn_name
, handle
->md
.device
,
1198 sizeof ireq
.ifr_ifrn
.ifrn_name
);
1199 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1]
1201 ireq
.u
.mode
= handle
->md
.oldmode
;
1202 if (ioctl(handle
->fd
, SIOCSIWMODE
, &ireq
) == -1) {
1204 * Scientist, you've failed.
1207 "Can't restore interface %s wireless mode (SIOCSIWMODE failed: %s).\n"
1208 "Please adjust manually.\n",
1209 handle
->md
.device
, strerror(errno
));
1213 * Now bring the interface back up if we brought
1216 if (oldflags
!= 0) {
1217 ifr
.ifr_flags
= oldflags
;
1218 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
1220 "Can't bring interface %s back up (SIOCSIFFLAGS failed: %s).\n"
1221 "Please adjust manually.\n",
1222 handle
->md
.device
, strerror(errno
));
1226 #endif /* IW_MODE_MONITOR */
1229 * Take this pcap out of the list of pcaps for which we
1230 * have to take the interface out of some mode.
1232 pcap_remove_from_pcaps_to_close(handle
);
1235 if (handle
->md
.mondevice
!= NULL
) {
1236 free(handle
->md
.mondevice
);
1237 handle
->md
.mondevice
= NULL
;
1239 if (handle
->md
.device
!= NULL
) {
1240 free(handle
->md
.device
);
1241 handle
->md
.device
= NULL
;
1243 pcap_cleanup_live_common(handle
);
1247 * Get a handle for a live capture from the given device. You can
1248 * pass NULL as device to get all packages (without link level
1249 * information of course). If you pass 1 as promisc the interface
1250 * will be set to promiscous mode (XXX: I think this usage should
1251 * be deprecated and functions be added to select that later allow
1252 * modification of that values -- Torsten).
1255 pcap_activate_linux(pcap_t
*handle
)
1262 char host
[PCAP_BUF_SIZE
+ 1];
1263 char port
[PCAP_BUF_SIZE
+ 1];
1264 char name
[PCAP_BUF_SIZE
+ 1];
1266 int opensource_remote_result
;
1269 Retrofit; we have to make older applications compatible with the remote capture
1270 So, we're calling the pcap_open_remote() from here, that is a very dirty thing.
1271 Obviously, we cannot exploit all the new features; for instance, we cannot
1272 send authentication, we cannot use a UDP data connection, and so on.
1274 if (pcap_parsesrcstr(handle
->opt
.source
, &srctype
, host
, port
, name
, handle
->errbuf
) )
1277 if (srctype
== PCAP_SRC_IFREMOTE
)
1279 opensource_remote_result
= pcap_opensource_remote(handle
, NULL
);
1281 if (opensource_remote_result
!= 0)
1282 return opensource_remote_result
;
1284 handle
->rmt_flags
= (handle
->opt
.promisc
) ? PCAP_OPENFLAG_PROMISCUOUS
: 0;
1289 if (srctype
== PCAP_SRC_IFLOCAL
)
1292 * If it starts with rpcap://, cut down the string
1294 if (strncmp(handle
->opt
.source
, PCAP_SRC_IF_STRING
, strlen(PCAP_SRC_IF_STRING
)) == 0)
1296 size_t len
= strlen(handle
->opt
.source
) - strlen(PCAP_SRC_IF_STRING
) + 1;
1299 allocate a new string and free the old one
1303 new_string
= (char*)malloc(len
);
1304 if (new_string
!= NULL
)
1307 strcpy(new_string
, handle
->opt
.source
+ strlen(PCAP_SRC_IF_STRING
));
1308 tmp
= handle
->opt
.source
;
1309 handle
->opt
.source
= new_string
;
1316 #endif /* HAVE_REMOTE */
1318 device
= handle
->opt
.source
;
1320 handle
->inject_op
= pcap_inject_linux
;
1321 handle
->setfilter_op
= pcap_setfilter_linux
;
1322 handle
->setdirection_op
= pcap_setdirection_linux
;
1323 handle
->set_datalink_op
= NULL
; /* can't change data link type */
1324 handle
->getnonblock_op
= pcap_getnonblock_fd
;
1325 handle
->setnonblock_op
= pcap_setnonblock_fd
;
1326 handle
->cleanup_op
= pcap_cleanup_linux
;
1327 handle
->read_op
= pcap_read_linux
;
1328 handle
->stats_op
= pcap_stats_linux
;
1331 * The "any" device is a special device which causes us not
1332 * to bind to a particular device and thus to look at all
1335 if (strcmp(device
, "any") == 0) {
1336 if (handle
->opt
.promisc
) {
1337 handle
->opt
.promisc
= 0;
1338 /* Just a warning. */
1339 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1340 "Promiscuous mode not supported on the \"any\" device");
1341 status
= PCAP_WARNING_PROMISC_NOTSUP
;
1345 handle
->md
.device
= strdup(device
);
1346 if (handle
->md
.device
== NULL
) {
1347 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "strdup: %s",
1348 pcap_strerror(errno
) );
1353 * If we're in promiscuous mode, then we probably want
1354 * to see when the interface drops packets too, so get an
1355 * initial count from /proc/net/dev
1357 if (handle
->opt
.promisc
)
1358 handle
->md
.proc_dropped
= linux_if_drops(handle
->md
.device
);
1361 * Current Linux kernels use the protocol family PF_PACKET to
1362 * allow direct access to all packets on the network while
1363 * older kernels had a special socket type SOCK_PACKET to
1364 * implement this feature.
1365 * While this old implementation is kind of obsolete we need
1366 * to be compatible with older kernels for a while so we are
1367 * trying both methods with the newer method preferred.
1369 status
= activate_new(handle
);
1372 * Fatal error with the new way; just fail.
1373 * status has the error return; if it's PCAP_ERROR,
1374 * handle->errbuf has been set appropriately.
1381 * Try to use memory-mapped access.
1383 switch (activate_mmap(handle
, &status
)) {
1387 * We succeeded. status has been
1388 * set to the status to return,
1389 * which might be 0, or might be
1390 * a PCAP_WARNING_ value.
1396 * Kernel doesn't support it - just continue
1397 * with non-memory-mapped access.
1403 * We failed to set up to use it, or the kernel
1404 * supports it, but we failed to enable it.
1405 * status has been set to the error status to
1406 * return and, if it's PCAP_ERROR, handle->errbuf
1407 * contains the error message.
1412 else if (status
== 0) {
1413 /* Non-fatal error; try old way */
1414 if ((status
= activate_old(handle
)) != 1) {
1416 * Both methods to open the packet socket failed.
1417 * Tidy up and report our failure (handle->errbuf
1418 * is expected to be set by the functions above).
1425 * We set up the socket, but not with memory-mapped access.
1428 if (handle
->opt
.buffer_size
!= 0) {
1430 * Set the socket buffer size to the specified value.
1432 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_RCVBUF
,
1433 &handle
->opt
.buffer_size
,
1434 sizeof(handle
->opt
.buffer_size
)) == -1) {
1435 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1436 "SO_RCVBUF: %s", pcap_strerror(errno
));
1437 status
= PCAP_ERROR
;
1442 /* Allocate the buffer */
1444 handle
->buffer
= malloc(handle
->bufsize
+ handle
->offset
);
1445 if (!handle
->buffer
) {
1446 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1447 "malloc: %s", pcap_strerror(errno
));
1448 status
= PCAP_ERROR
;
1453 * "handle->fd" is a socket, so "select()" and "poll()"
1454 * should work on it.
1456 handle
->selectable_fd
= handle
->fd
;
1461 pcap_cleanup_linux(handle
);
1466 * Read at most max_packets from the capture stream and call the callback
1467 * for each of them. Returns the number of packets handled or -1 if an
1471 pcap_read_linux(pcap_t
*handle
, int max_packets
, pcap_handler callback
, u_char
*user
)
1474 * Currently, on Linux only one packet is delivered per read,
1477 return pcap_read_packet(handle
, callback
, user
);
1481 * Read a packet from the socket calling the handler provided by
1482 * the user. Returns the number of packets received or -1 if an
1486 pcap_read_packet(pcap_t
*handle
, pcap_handler callback
, u_char
*userdata
)
1490 #ifdef HAVE_PF_PACKET_SOCKETS
1491 struct sockaddr_ll from
;
1492 struct sll_header
*hdrp
;
1494 struct sockaddr from
;
1496 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1499 struct cmsghdr
*cmsg
;
1501 struct cmsghdr cmsg
;
1502 char buf
[CMSG_SPACE(sizeof(struct tpacket_auxdata
))];
1504 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1506 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1507 int packet_len
, caplen
;
1508 struct pcap_pkthdr pcap_header
;
1510 #ifdef HAVE_PF_PACKET_SOCKETS
1512 * If this is a cooked device, leave extra room for a
1513 * fake packet header.
1515 if (handle
->md
.cooked
)
1516 offset
= SLL_HDR_LEN
;
1521 * This system doesn't have PF_PACKET sockets, so it doesn't
1522 * support cooked devices.
1528 * Receive a single packet from the kernel.
1529 * We ignore EINTR, as that might just be due to a signal
1530 * being delivered - if the signal should interrupt the
1531 * loop, the signal handler should call pcap_breakloop()
1532 * to set handle->break_loop (we ignore it on other
1533 * platforms as well).
1534 * We also ignore ENETDOWN, so that we can continue to
1535 * capture traffic if the interface goes down and comes
1536 * back up again; comments in the kernel indicate that
1537 * we'll just block waiting for packets if we try to
1538 * receive from a socket that delivered ENETDOWN, and,
1539 * if we're using a memory-mapped buffer, we won't even
1540 * get notified of "network down" events.
1542 bp
= handle
->buffer
+ handle
->offset
;
1544 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1545 msg
.msg_name
= &from
;
1546 msg
.msg_namelen
= sizeof(from
);
1549 msg
.msg_control
= &cmsg_buf
;
1550 msg
.msg_controllen
= sizeof(cmsg_buf
);
1553 iov
.iov_len
= handle
->bufsize
- offset
;
1554 iov
.iov_base
= bp
+ offset
;
1555 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1559 * Has "pcap_breakloop()" been called?
1561 if (handle
->break_loop
) {
1563 * Yes - clear the flag that indicates that it has,
1564 * and return PCAP_ERROR_BREAK as an indication that
1565 * we were told to break out of the loop.
1567 handle
->break_loop
= 0;
1568 return PCAP_ERROR_BREAK
;
1571 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1572 packet_len
= recvmsg(handle
->fd
, &msg
, MSG_TRUNC
);
1573 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1574 fromlen
= sizeof(from
);
1575 packet_len
= recvfrom(
1576 handle
->fd
, bp
+ offset
,
1577 handle
->bufsize
- offset
, MSG_TRUNC
,
1578 (struct sockaddr
*) &from
, &fromlen
);
1579 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1580 } while (packet_len
== -1 && errno
== EINTR
);
1582 /* Check if an error occured */
1584 if (packet_len
== -1) {
1588 return 0; /* no packet there */
1592 * The device on which we're capturing went away.
1594 * XXX - we should really return
1595 * PCAP_ERROR_IFACE_NOT_UP, but pcap_dispatch()
1596 * etc. aren't defined to return that.
1598 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1599 "The interface went down");
1603 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1604 "recvfrom: %s", pcap_strerror(errno
));
1609 #ifdef HAVE_PF_PACKET_SOCKETS
1610 if (!handle
->md
.sock_packet
) {
1612 * Unfortunately, there is a window between socket() and
1613 * bind() where the kernel may queue packets from any
1614 * interface. If we're bound to a particular interface,
1615 * discard packets not from that interface.
1617 * (If socket filters are supported, we could do the
1618 * same thing we do when changing the filter; however,
1619 * that won't handle packet sockets without socket
1620 * filter support, and it's a bit more complicated.
1621 * It would save some instructions per packet, however.)
1623 if (handle
->md
.ifindex
!= -1 &&
1624 from
.sll_ifindex
!= handle
->md
.ifindex
)
1628 * Do checks based on packet direction.
1629 * We can only do this if we're using PF_PACKET; the
1630 * address returned for SOCK_PACKET is a "sockaddr_pkt"
1631 * which lacks the relevant packet type information.
1633 if (from
.sll_pkttype
== PACKET_OUTGOING
) {
1636 * If this is from the loopback device, reject it;
1637 * we'll see the packet as an incoming packet as well,
1638 * and we don't want to see it twice.
1640 if (from
.sll_ifindex
== handle
->md
.lo_ifindex
)
1644 * If the user only wants incoming packets, reject it.
1646 if (handle
->direction
== PCAP_D_IN
)
1651 * If the user only wants outgoing packets, reject it.
1653 if (handle
->direction
== PCAP_D_OUT
)
1659 #ifdef HAVE_PF_PACKET_SOCKETS
1661 * If this is a cooked device, fill in the fake packet header.
1663 if (handle
->md
.cooked
) {
1665 * Add the length of the fake header to the length
1666 * of packet data we read.
1668 packet_len
+= SLL_HDR_LEN
;
1670 hdrp
= (struct sll_header
*)bp
;
1671 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(from
.sll_pkttype
);
1672 hdrp
->sll_hatype
= htons(from
.sll_hatype
);
1673 hdrp
->sll_halen
= htons(from
.sll_halen
);
1674 memcpy(hdrp
->sll_addr
, from
.sll_addr
,
1675 (from
.sll_halen
> SLL_ADDRLEN
) ?
1678 hdrp
->sll_protocol
= from
.sll_protocol
;
1681 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1682 for (cmsg
= CMSG_FIRSTHDR(&msg
); cmsg
; cmsg
= CMSG_NXTHDR(&msg
, cmsg
)) {
1683 struct tpacket_auxdata
*aux
;
1685 struct vlan_tag
*tag
;
1687 if (cmsg
->cmsg_len
< CMSG_LEN(sizeof(struct tpacket_auxdata
)) ||
1688 cmsg
->cmsg_level
!= SOL_PACKET
||
1689 cmsg
->cmsg_type
!= PACKET_AUXDATA
)
1692 aux
= (struct tpacket_auxdata
*)CMSG_DATA(cmsg
);
1693 if (aux
->tp_vlan_tci
== 0)
1696 len
= packet_len
> iov
.iov_len
? iov
.iov_len
: packet_len
;
1697 if (len
< 2 * ETH_ALEN
)
1701 memmove(bp
, bp
+ VLAN_TAG_LEN
, 2 * ETH_ALEN
);
1703 tag
= (struct vlan_tag
*)(bp
+ 2 * ETH_ALEN
);
1704 tag
->vlan_tpid
= htons(ETH_P_8021Q
);
1705 tag
->vlan_tci
= htons(aux
->tp_vlan_tci
);
1707 packet_len
+= VLAN_TAG_LEN
;
1709 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1710 #endif /* HAVE_PF_PACKET_SOCKETS */
1713 * XXX: According to the kernel source we should get the real
1714 * packet len if calling recvfrom with MSG_TRUNC set. It does
1715 * not seem to work here :(, but it is supported by this code
1717 * To be honest the code RELIES on that feature so this is really
1718 * broken with 2.2.x kernels.
1719 * I spend a day to figure out what's going on and I found out
1720 * that the following is happening:
1722 * The packet comes from a random interface and the packet_rcv
1723 * hook is called with a clone of the packet. That code inserts
1724 * the packet into the receive queue of the packet socket.
1725 * If a filter is attached to that socket that filter is run
1726 * first - and there lies the problem. The default filter always
1727 * cuts the packet at the snaplen:
1732 * So the packet filter cuts down the packet. The recvfrom call
1733 * says "hey, it's only 68 bytes, it fits into the buffer" with
1734 * the result that we don't get the real packet length. This
1735 * is valid at least until kernel 2.2.17pre6.
1737 * We currently handle this by making a copy of the filter
1738 * program, fixing all "ret" instructions with non-zero
1739 * operands to have an operand of 65535 so that the filter
1740 * doesn't truncate the packet, and supplying that modified
1741 * filter to the kernel.
1744 caplen
= packet_len
;
1745 if (caplen
> handle
->snapshot
)
1746 caplen
= handle
->snapshot
;
1748 /* Run the packet filter if not using kernel filter */
1749 if (!handle
->md
.use_bpf
&& handle
->fcode
.bf_insns
) {
1750 if (bpf_filter(handle
->fcode
.bf_insns
, bp
,
1751 packet_len
, caplen
) == 0)
1753 /* rejected by filter */
1758 /* Fill in our own header data */
1760 if (ioctl(handle
->fd
, SIOCGSTAMP
, &pcap_header
.ts
) == -1) {
1761 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1762 "SIOCGSTAMP: %s", pcap_strerror(errno
));
1765 pcap_header
.caplen
= caplen
;
1766 pcap_header
.len
= packet_len
;
1771 * Arguably, we should count them before we check the filter,
1772 * as on many other platforms "ps_recv" counts packets
1773 * handed to the filter rather than packets that passed
1774 * the filter, but if filtering is done in the kernel, we
1775 * can't get a count of packets that passed the filter,
1776 * and that would mean the meaning of "ps_recv" wouldn't
1777 * be the same on all Linux systems.
1779 * XXX - it's not the same on all systems in any case;
1780 * ideally, we should have a "get the statistics" call
1781 * that supplies more counts and indicates which of them
1782 * it supplies, so that we supply a count of packets
1783 * handed to the filter only on platforms where that
1784 * information is available.
1786 * We count them here even if we can get the packet count
1787 * from the kernel, as we can only determine at run time
1788 * whether we'll be able to get it from the kernel (if
1789 * HAVE_TPACKET_STATS isn't defined, we can't get it from
1790 * the kernel, but if it is defined, the library might
1791 * have been built with a 2.4 or later kernel, but we
1792 * might be running on a 2.2[.x] kernel without Alexey
1793 * Kuznetzov's turbopacket patches, and thus the kernel
1794 * might not be able to supply those statistics). We
1795 * could, I guess, try, when opening the socket, to get
1796 * the statistics, and if we can not increment the count
1797 * here, but it's not clear that always incrementing
1798 * the count is more expensive than always testing a flag
1801 * We keep the count in "md.packets_read", and use that for
1802 * "ps_recv" if we can't get the statistics from the kernel.
1803 * We do that because, if we *can* get the statistics from
1804 * the kernel, we use "md.stat.ps_recv" and "md.stat.ps_drop"
1805 * as running counts, as reading the statistics from the
1806 * kernel resets the kernel statistics, and if we directly
1807 * increment "md.stat.ps_recv" here, that means it will
1808 * count packets *twice* on systems where we can get kernel
1809 * statistics - once here, and once in pcap_stats_linux().
1811 handle
->md
.packets_read
++;
1813 /* Call the user supplied callback function */
1814 callback(userdata
, &pcap_header
, bp
);
1820 pcap_inject_linux(pcap_t
*handle
, const void *buf
, size_t size
)
1824 #ifdef HAVE_PF_PACKET_SOCKETS
1825 if (!handle
->md
.sock_packet
) {
1826 /* PF_PACKET socket */
1827 if (handle
->md
.ifindex
== -1) {
1829 * We don't support sending on the "any" device.
1831 strlcpy(handle
->errbuf
,
1832 "Sending packets isn't supported on the \"any\" device",
1837 if (handle
->md
.cooked
) {
1839 * We don't support sending on the "any" device.
1841 * XXX - how do you send on a bound cooked-mode
1843 * Is a "sendto()" required there?
1845 strlcpy(handle
->errbuf
,
1846 "Sending packets isn't supported in cooked mode",
1853 ret
= send(handle
->fd
, buf
, size
, 0);
1855 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "send: %s",
1856 pcap_strerror(errno
));
1863 * Get the statistics for the given packet capture handle.
1864 * Reports the number of dropped packets iff the kernel supports
1865 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
1866 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
1867 * patches); otherwise, that information isn't available, and we lie
1868 * and report 0 as the count of dropped packets.
1871 pcap_stats_linux(pcap_t
*handle
, struct pcap_stat
*stats
)
1873 #ifdef HAVE_TPACKET_STATS
1874 struct tpacket_stats kstats
;
1875 socklen_t len
= sizeof (struct tpacket_stats
);
1878 long if_dropped
= 0;
1881 * To fill in ps_ifdrop, we parse /proc/net/dev for the number
1883 if (handle
->opt
.promisc
)
1885 if_dropped
= handle
->md
.proc_dropped
;
1886 handle
->md
.proc_dropped
= linux_if_drops(handle
->md
.device
);
1887 handle
->md
.stat
.ps_ifdrop
+= (handle
->md
.proc_dropped
- if_dropped
);
1890 #ifdef HAVE_TPACKET_STATS
1892 * Try to get the packet counts from the kernel.
1894 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_STATISTICS
,
1895 &kstats
, &len
) > -1) {
1897 * On systems where the PACKET_STATISTICS "getsockopt()"
1898 * argument is supported on PF_PACKET sockets:
1900 * "ps_recv" counts only packets that *passed* the
1901 * filter, not packets that didn't pass the filter.
1902 * This includes packets later dropped because we
1903 * ran out of buffer space.
1905 * "ps_drop" counts packets dropped because we ran
1906 * out of buffer space. It doesn't count packets
1907 * dropped by the interface driver. It counts only
1908 * packets that passed the filter.
1910 * See above for ps_ifdrop.
1912 * Both statistics include packets not yet read from
1913 * the kernel by libpcap, and thus not yet seen by
1916 * In "linux/net/packet/af_packet.c", at least in the
1917 * 2.4.9 kernel, "tp_packets" is incremented for every
1918 * packet that passes the packet filter *and* is
1919 * successfully queued on the socket; "tp_drops" is
1920 * incremented for every packet dropped because there's
1921 * not enough free space in the socket buffer.
1923 * When the statistics are returned for a PACKET_STATISTICS
1924 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
1925 * so that "tp_packets" counts all packets handed to
1926 * the PF_PACKET socket, including packets dropped because
1927 * there wasn't room on the socket buffer - but not
1928 * including packets that didn't pass the filter.
1930 * In the BSD BPF, the count of received packets is
1931 * incremented for every packet handed to BPF, regardless
1932 * of whether it passed the filter.
1934 * We can't make "pcap_stats()" work the same on both
1935 * platforms, but the best approximation is to return
1936 * "tp_packets" as the count of packets and "tp_drops"
1937 * as the count of drops.
1939 * Keep a running total because each call to
1940 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
1941 * resets the counters to zero.
1943 handle
->md
.stat
.ps_recv
+= kstats
.tp_packets
;
1944 handle
->md
.stat
.ps_drop
+= kstats
.tp_drops
;
1945 *stats
= handle
->md
.stat
;
1951 * If the error was EOPNOTSUPP, fall through, so that
1952 * if you build the library on a system with
1953 * "struct tpacket_stats" and run it on a system
1954 * that doesn't, it works as it does if the library
1955 * is built on a system without "struct tpacket_stats".
1957 if (errno
!= EOPNOTSUPP
) {
1958 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1959 "pcap_stats: %s", pcap_strerror(errno
));
1965 * On systems where the PACKET_STATISTICS "getsockopt()" argument
1966 * is not supported on PF_PACKET sockets:
1968 * "ps_recv" counts only packets that *passed* the filter,
1969 * not packets that didn't pass the filter. It does not
1970 * count packets dropped because we ran out of buffer
1973 * "ps_drop" is not supported.
1975 * "ps_ifdrop" is supported. It will return the number
1976 * of drops the interface reports in /proc/net/dev,
1977 * if that is available.
1979 * "ps_recv" doesn't include packets not yet read from
1980 * the kernel by libpcap.
1982 * We maintain the count of packets processed by libpcap in
1983 * "md.packets_read", for reasons described in the comment
1984 * at the end of pcap_read_packet(). We have no idea how many
1985 * packets were dropped by the kernel buffers -- but we know
1986 * how many the interface dropped, so we can return that.
1989 stats
->ps_recv
= handle
->md
.packets_read
;
1991 stats
->ps_ifdrop
= handle
->md
.stat
.ps_ifdrop
;
1996 * Get from "/sys/class/net" all interfaces listed there; if they're
1997 * already in the list of interfaces we have, that won't add another
1998 * instance, but if they're not, that'll add them.
2000 * We don't bother getting any addresses for them; it appears you can't
2001 * use SIOCGIFADDR on Linux to get IPv6 addresses for interfaces, and,
2002 * although some other types of addresses can be fetched with SIOCGIFADDR,
2003 * we don't bother with them for now.
2005 * We also don't fail if we couldn't open "/sys/class/net"; we just leave
2006 * the list of interfaces as is, and return 0, so that we can try
2007 * scanning /proc/net/dev.
2010 scan_sys_class_net(pcap_if_t
**devlistp
, char *errbuf
)
2012 DIR *sys_class_net_d
;
2016 char name
[512]; /* XXX - pick a size */
2018 struct ifreq ifrflags
;
2021 sys_class_net_d
= opendir("/sys/class/net");
2022 if (sys_class_net_d
== NULL
) {
2024 * Don't fail if it doesn't exist at all.
2026 if (errno
== ENOENT
)
2030 * Fail if we got some other error.
2032 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2033 "Can't open /sys/class/net: %s", pcap_strerror(errno
));
2038 * Create a socket from which to fetch interface information.
2040 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
2042 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2043 "socket: %s", pcap_strerror(errno
));
2044 (void)closedir(sys_class_net_d
);
2050 ent
= readdir(sys_class_net_d
);
2053 * Error or EOF; if errno != 0, it's an error.
2059 * Ignore directories (".", "..", and any subdirectories).
2061 if (ent
->d_type
== DT_DIR
)
2065 * Get the interface name.
2067 p
= &ent
->d_name
[0];
2069 while (*p
!= '\0' && isascii(*p
) && !isspace(*p
)) {
2072 * This could be the separator between a
2073 * name and an alias number, or it could be
2074 * the separator between a name with no
2075 * alias number and the next field.
2077 * If there's a colon after digits, it
2078 * separates the name and the alias number,
2079 * otherwise it separates the name and the
2083 while (isascii(*p
) && isdigit(*p
))
2087 * That was the next field,
2088 * not the alias number.
2099 * Get the flags for this interface, and skip it if
2102 strncpy(ifrflags
.ifr_name
, name
, sizeof(ifrflags
.ifr_name
));
2103 if (ioctl(fd
, SIOCGIFFLAGS
, (char *)&ifrflags
) < 0) {
2104 if (errno
== ENXIO
|| errno
== ENODEV
)
2106 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2107 "SIOCGIFFLAGS: %.*s: %s",
2108 (int)sizeof(ifrflags
.ifr_name
),
2110 pcap_strerror(errno
));
2114 if (!(ifrflags
.ifr_flags
& IFF_UP
))
2118 * Add an entry for this interface, with no addresses.
2120 if (pcap_add_if(devlistp
, name
, ifrflags
.ifr_flags
, NULL
,
2131 * Well, we didn't fail for any other reason; did we
2132 * fail due to an error reading the directory?
2135 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2136 "Error reading /sys/class/net: %s",
2137 pcap_strerror(errno
));
2143 (void)closedir(sys_class_net_d
);
2148 * Get from "/proc/net/dev" all interfaces listed there; if they're
2149 * already in the list of interfaces we have, that won't add another
2150 * instance, but if they're not, that'll add them.
2152 * See comments from scan_sys_class_net().
2155 scan_proc_net_dev(pcap_if_t
**devlistp
, char *errbuf
)
2162 char name
[512]; /* XXX - pick a size */
2164 struct ifreq ifrflags
;
2167 proc_net_f
= fopen("/proc/net/dev", "r");
2168 if (proc_net_f
== NULL
) {
2170 * Don't fail if it doesn't exist at all.
2172 if (errno
== ENOENT
)
2176 * Fail if we got some other error.
2178 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2179 "Can't open /proc/net/dev: %s", pcap_strerror(errno
));
2184 * Create a socket from which to fetch interface information.
2186 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
2188 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2189 "socket: %s", pcap_strerror(errno
));
2190 (void)fclose(proc_net_f
);
2195 fgets(linebuf
, sizeof linebuf
, proc_net_f
) != NULL
; linenum
++) {
2197 * Skip the first two lines - they're headers.
2205 * Skip leading white space.
2207 while (*p
!= '\0' && isascii(*p
) && isspace(*p
))
2209 if (*p
== '\0' || *p
== '\n')
2210 continue; /* blank line */
2213 * Get the interface name.
2216 while (*p
!= '\0' && isascii(*p
) && !isspace(*p
)) {
2219 * This could be the separator between a
2220 * name and an alias number, or it could be
2221 * the separator between a name with no
2222 * alias number and the next field.
2224 * If there's a colon after digits, it
2225 * separates the name and the alias number,
2226 * otherwise it separates the name and the
2230 while (isascii(*p
) && isdigit(*p
))
2234 * That was the next field,
2235 * not the alias number.
2246 * Get the flags for this interface, and skip it if
2249 strncpy(ifrflags
.ifr_name
, name
, sizeof(ifrflags
.ifr_name
));
2250 if (ioctl(fd
, SIOCGIFFLAGS
, (char *)&ifrflags
) < 0) {
2253 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2254 "SIOCGIFFLAGS: %.*s: %s",
2255 (int)sizeof(ifrflags
.ifr_name
),
2257 pcap_strerror(errno
));
2261 if (!(ifrflags
.ifr_flags
& IFF_UP
))
2265 * Add an entry for this interface, with no addresses.
2267 if (pcap_add_if(devlistp
, name
, ifrflags
.ifr_flags
, NULL
,
2278 * Well, we didn't fail for any other reason; did we
2279 * fail due to an error reading the file?
2281 if (ferror(proc_net_f
)) {
2282 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2283 "Error reading /proc/net/dev: %s",
2284 pcap_strerror(errno
));
2290 (void)fclose(proc_net_f
);
2295 * Description string for the "any" device.
2297 static const char any_descr
[] = "Pseudo-device that captures on all interfaces";
2300 pcap_platform_finddevs(pcap_if_t
**alldevsp
, char *errbuf
)
2305 * Read "/sys/class/net", and add to the list of interfaces all
2306 * interfaces listed there that we don't already have, because,
2307 * on Linux, SIOCGIFCONF reports only interfaces with IPv4 addresses,
2308 * and even getifaddrs() won't return information about
2309 * interfaces with no addresses, so you need to read "/sys/class/net"
2310 * to get the names of the rest of the interfaces.
2312 ret
= scan_sys_class_net(alldevsp
, errbuf
);
2314 return (-1); /* failed */
2317 * No /sys/class/net; try reading /proc/net/dev instead.
2319 if (scan_proc_net_dev(alldevsp
, errbuf
) == -1)
2324 * Add the "any" device.
2326 if (pcap_add_if(alldevsp
, "any", 0, any_descr
, errbuf
) < 0)
2333 if (dag_platform_finddevs(alldevsp
, errbuf
) < 0)
2335 #endif /* HAVE_DAG_API */
2337 #ifdef HAVE_SEPTEL_API
2339 * Add Septel devices.
2341 if (septel_platform_finddevs(alldevsp
, errbuf
) < 0)
2343 #endif /* HAVE_SEPTEL_API */
2346 if (snf_platform_finddevs(alldevsp
, errbuf
) < 0)
2348 #endif /* HAVE_SNF_API */
2350 #ifdef PCAP_SUPPORT_BT
2352 * Add Bluetooth devices.
2354 if (bt_platform_finddevs(alldevsp
, errbuf
) < 0)
2358 #ifdef PCAP_SUPPORT_USB
2362 if (usb_platform_finddevs(alldevsp
, errbuf
) < 0)
2366 #ifdef PCAP_SUPPORT_NETFILTER
2368 * Add netfilter devices.
2370 if (netfilter_platform_finddevs(alldevsp
, errbuf
) < 0)
2374 #if PCAP_SUPPORT_CANUSB
2375 if (canusb_platform_finddevs(alldevsp
, errbuf
) < 0)
2383 * Attach the given BPF code to the packet capture device.
2386 pcap_setfilter_linux_common(pcap_t
*handle
, struct bpf_program
*filter
,
2389 #ifdef SO_ATTACH_FILTER
2390 struct sock_fprog fcode
;
2391 int can_filter_in_kernel
;
2398 strncpy(handle
->errbuf
, "setfilter: No filter specified",
2403 /* Make our private copy of the filter */
2405 if (install_bpf_program(handle
, filter
) < 0)
2406 /* install_bpf_program() filled in errbuf */
2410 * Run user level packet filter by default. Will be overriden if
2411 * installing a kernel filter succeeds.
2413 handle
->md
.use_bpf
= 0;
2415 /* Install kernel level filter if possible */
2417 #ifdef SO_ATTACH_FILTER
2419 if (handle
->fcode
.bf_len
> USHRT_MAX
) {
2421 * fcode.len is an unsigned short for current kernel.
2422 * I have yet to see BPF-Code with that much
2423 * instructions but still it is possible. So for the
2424 * sake of correctness I added this check.
2426 fprintf(stderr
, "Warning: Filter too complex for kernel\n");
2428 fcode
.filter
= NULL
;
2429 can_filter_in_kernel
= 0;
2431 #endif /* USHRT_MAX */
2434 * Oh joy, the Linux kernel uses struct sock_fprog instead
2435 * of struct bpf_program and of course the length field is
2436 * of different size. Pointed out by Sebastian
2438 * Oh, and we also need to fix it up so that all "ret"
2439 * instructions with non-zero operands have 65535 as the
2440 * operand if we're not capturing in memory-mapped modee,
2441 * and so that, if we're in cooked mode, all memory-reference
2442 * instructions use special magic offsets in references to
2443 * the link-layer header and assume that the link-layer
2444 * payload begins at 0; "fix_program()" will do that.
2446 switch (fix_program(handle
, &fcode
, is_mmapped
)) {
2451 * Fatal error; just quit.
2452 * (The "default" case shouldn't happen; we
2453 * return -1 for that reason.)
2459 * The program performed checks that we can't make
2460 * work in the kernel.
2462 can_filter_in_kernel
= 0;
2467 * We have a filter that'll work in the kernel.
2469 can_filter_in_kernel
= 1;
2475 * NOTE: at this point, we've set both the "len" and "filter"
2476 * fields of "fcode". As of the 2.6.32.4 kernel, at least,
2477 * those are the only members of the "sock_fprog" structure,
2478 * so we initialize every member of that structure.
2480 * If there is anything in "fcode" that is not initialized,
2481 * it is either a field added in a later kernel, or it's
2484 * If a new field is added, this code needs to be updated
2485 * to set it correctly.
2487 * If there are no other fields, then:
2489 * if the Linux kernel looks at the padding, it's
2492 * if the Linux kernel doesn't look at the padding,
2493 * then if some tool complains that we're passing
2494 * uninitialized data to the kernel, then the tool
2495 * is buggy and needs to understand that it's just
2498 if (can_filter_in_kernel
) {
2499 if ((err
= set_kernel_filter(handle
, &fcode
)) == 0)
2501 /* Installation succeded - using kernel filter. */
2502 handle
->md
.use_bpf
= 1;
2504 else if (err
== -1) /* Non-fatal error */
2507 * Print a warning if we weren't able to install
2508 * the filter for a reason other than "this kernel
2509 * isn't configured to support socket filters.
2511 if (errno
!= ENOPROTOOPT
&& errno
!= EOPNOTSUPP
) {
2513 "Warning: Kernel filter failed: %s\n",
2514 pcap_strerror(errno
));
2520 * If we're not using the kernel filter, get rid of any kernel
2521 * filter that might've been there before, e.g. because the
2522 * previous filter could work in the kernel, or because some other
2523 * code attached a filter to the socket by some means other than
2524 * calling "pcap_setfilter()". Otherwise, the kernel filter may
2525 * filter out packets that would pass the new userland filter.
2527 if (!handle
->md
.use_bpf
)
2528 reset_kernel_filter(handle
);
2531 * Free up the copy of the filter that was made by "fix_program()".
2533 if (fcode
.filter
!= NULL
)
2539 #endif /* SO_ATTACH_FILTER */
2545 pcap_setfilter_linux(pcap_t
*handle
, struct bpf_program
*filter
)
2547 return pcap_setfilter_linux_common(handle
, filter
, 0);
2552 * Set direction flag: Which packets do we accept on a forwarding
2553 * single device? IN, OUT or both?
2556 pcap_setdirection_linux(pcap_t
*handle
, pcap_direction_t d
)
2558 #ifdef HAVE_PF_PACKET_SOCKETS
2559 if (!handle
->md
.sock_packet
) {
2560 handle
->direction
= d
;
2565 * We're not using PF_PACKET sockets, so we can't determine
2566 * the direction of the packet.
2568 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2569 "Setting direction is not supported on SOCK_PACKET sockets");
2573 #ifdef HAVE_PF_PACKET_SOCKETS
2575 * Map the PACKET_ value to a LINUX_SLL_ value; we
2576 * want the same numerical value to be used in
2577 * the link-layer header even if the numerical values
2578 * for the PACKET_ #defines change, so that programs
2579 * that look at the packet type field will always be
2580 * able to handle DLT_LINUX_SLL captures.
2583 map_packet_type_to_sll_type(short int sll_pkttype
)
2585 switch (sll_pkttype
) {
2588 return htons(LINUX_SLL_HOST
);
2590 case PACKET_BROADCAST
:
2591 return htons(LINUX_SLL_BROADCAST
);
2593 case PACKET_MULTICAST
:
2594 return htons(LINUX_SLL_MULTICAST
);
2596 case PACKET_OTHERHOST
:
2597 return htons(LINUX_SLL_OTHERHOST
);
2599 case PACKET_OUTGOING
:
2600 return htons(LINUX_SLL_OUTGOING
);
2609 * Linux uses the ARP hardware type to identify the type of an
2610 * interface. pcap uses the DLT_xxx constants for this. This
2611 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
2612 * constant, as arguments, and sets "handle->linktype" to the
2613 * appropriate DLT_XXX constant and sets "handle->offset" to
2614 * the appropriate value (to make "handle->offset" plus link-layer
2615 * header length be a multiple of 4, so that the link-layer payload
2616 * will be aligned on a 4-byte boundary when capturing packets).
2617 * (If the offset isn't set here, it'll be 0; add code as appropriate
2618 * for cases where it shouldn't be 0.)
2620 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
2621 * in cooked mode; otherwise, we can't use cooked mode, so we have
2622 * to pick some type that works in raw mode, or fail.
2624 * Sets the link type to -1 if unable to map the type.
2626 static void map_arphrd_to_dlt(pcap_t
*handle
, int arptype
, int cooked_ok
)
2632 * This is (presumably) a real Ethernet capture; give it a
2633 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
2634 * that an application can let you choose it, in case you're
2635 * capturing DOCSIS traffic that a Cisco Cable Modem
2636 * Termination System is putting out onto an Ethernet (it
2637 * doesn't put an Ethernet header onto the wire, it puts raw
2638 * DOCSIS frames out on the wire inside the low-level
2639 * Ethernet framing).
2641 * XXX - are there any sorts of "fake Ethernet" that have
2642 * ARPHRD_ETHER but that *shouldn't offer DLT_DOCSIS as
2643 * a Cisco CMTS won't put traffic onto it or get traffic
2644 * bridged onto it? ISDN is handled in "activate_new()",
2645 * as we fall back on cooked mode there; are there any
2648 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
2650 * If that fails, just leave the list empty.
2652 if (handle
->dlt_list
!= NULL
) {
2653 handle
->dlt_list
[0] = DLT_EN10MB
;
2654 handle
->dlt_list
[1] = DLT_DOCSIS
;
2655 handle
->dlt_count
= 2;
2659 case ARPHRD_METRICOM
:
2660 case ARPHRD_LOOPBACK
:
2661 handle
->linktype
= DLT_EN10MB
;
2666 handle
->linktype
= DLT_EN3MB
;
2670 handle
->linktype
= DLT_AX25_KISS
;
2674 handle
->linktype
= DLT_PRONET
;
2678 handle
->linktype
= DLT_CHAOS
;
2681 #define ARPHRD_CAN 280
2684 handle
->linktype
= DLT_CAN_SOCKETCAN
;
2687 #ifndef ARPHRD_IEEE802_TR
2688 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
2690 case ARPHRD_IEEE802_TR
:
2691 case ARPHRD_IEEE802
:
2692 handle
->linktype
= DLT_IEEE802
;
2697 handle
->linktype
= DLT_ARCNET_LINUX
;
2700 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
2701 #define ARPHRD_FDDI 774
2704 handle
->linktype
= DLT_FDDI
;
2708 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
2709 #define ARPHRD_ATM 19
2713 * The Classical IP implementation in ATM for Linux
2714 * supports both what RFC 1483 calls "LLC Encapsulation",
2715 * in which each packet has an LLC header, possibly
2716 * with a SNAP header as well, prepended to it, and
2717 * what RFC 1483 calls "VC Based Multiplexing", in which
2718 * different virtual circuits carry different network
2719 * layer protocols, and no header is prepended to packets.
2721 * They both have an ARPHRD_ type of ARPHRD_ATM, so
2722 * you can't use the ARPHRD_ type to find out whether
2723 * captured packets will have an LLC header, and,
2724 * while there's a socket ioctl to *set* the encapsulation
2725 * type, there's no ioctl to *get* the encapsulation type.
2729 * programs that dissect Linux Classical IP frames
2730 * would have to check for an LLC header and,
2731 * depending on whether they see one or not, dissect
2732 * the frame as LLC-encapsulated or as raw IP (I
2733 * don't know whether there's any traffic other than
2734 * IP that would show up on the socket, or whether
2735 * there's any support for IPv6 in the Linux
2736 * Classical IP code);
2738 * filter expressions would have to compile into
2739 * code that checks for an LLC header and does
2742 * Both of those are a nuisance - and, at least on systems
2743 * that support PF_PACKET sockets, we don't have to put
2744 * up with those nuisances; instead, we can just capture
2745 * in cooked mode. That's what we'll do, if we can.
2746 * Otherwise, we'll just fail.
2749 handle
->linktype
= DLT_LINUX_SLL
;
2751 handle
->linktype
= -1;
2754 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
2755 #define ARPHRD_IEEE80211 801
2757 case ARPHRD_IEEE80211
:
2758 handle
->linktype
= DLT_IEEE802_11
;
2761 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
2762 #define ARPHRD_IEEE80211_PRISM 802
2764 case ARPHRD_IEEE80211_PRISM
:
2765 handle
->linktype
= DLT_PRISM_HEADER
;
2768 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
2769 #define ARPHRD_IEEE80211_RADIOTAP 803
2771 case ARPHRD_IEEE80211_RADIOTAP
:
2772 handle
->linktype
= DLT_IEEE802_11_RADIO
;
2777 * Some PPP code in the kernel supplies no link-layer
2778 * header whatsoever to PF_PACKET sockets; other PPP
2779 * code supplies PPP link-layer headers ("syncppp.c");
2780 * some PPP code might supply random link-layer
2781 * headers (PPP over ISDN - there's code in Ethereal,
2782 * for example, to cope with PPP-over-ISDN captures
2783 * with which the Ethereal developers have had to cope,
2784 * heuristically trying to determine which of the
2785 * oddball link-layer headers particular packets have).
2787 * As such, we just punt, and run all PPP interfaces
2788 * in cooked mode, if we can; otherwise, we just treat
2789 * it as DLT_RAW, for now - if somebody needs to capture,
2790 * on a 2.0[.x] kernel, on PPP devices that supply a
2791 * link-layer header, they'll have to add code here to
2792 * map to the appropriate DLT_ type (possibly adding a
2793 * new DLT_ type, if necessary).
2796 handle
->linktype
= DLT_LINUX_SLL
;
2799 * XXX - handle ISDN types here? We can't fall
2800 * back on cooked sockets, so we'd have to
2801 * figure out from the device name what type of
2802 * link-layer encapsulation it's using, and map
2803 * that to an appropriate DLT_ value, meaning
2804 * we'd map "isdnN" devices to DLT_RAW (they
2805 * supply raw IP packets with no link-layer
2806 * header) and "isdY" devices to a new DLT_I4L_IP
2807 * type that has only an Ethernet packet type as
2808 * a link-layer header.
2810 * But sometimes we seem to get random crap
2811 * in the link-layer header when capturing on
2814 handle
->linktype
= DLT_RAW
;
2818 #ifndef ARPHRD_CISCO
2819 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
2822 handle
->linktype
= DLT_C_HDLC
;
2825 /* Not sure if this is correct for all tunnels, but it
2829 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
2837 #ifndef ARPHRD_RAWHDLC
2838 #define ARPHRD_RAWHDLC 518
2840 case ARPHRD_RAWHDLC
:
2842 #define ARPHRD_DLCI 15
2846 * XXX - should some of those be mapped to DLT_LINUX_SLL
2847 * instead? Should we just map all of them to DLT_LINUX_SLL?
2849 handle
->linktype
= DLT_RAW
;
2853 #define ARPHRD_FRAD 770
2856 handle
->linktype
= DLT_FRELAY
;
2859 case ARPHRD_LOCALTLK
:
2860 handle
->linktype
= DLT_LTALK
;
2864 #define ARPHRD_FCPP 784
2868 #define ARPHRD_FCAL 785
2872 #define ARPHRD_FCPL 786
2875 #ifndef ARPHRD_FCFABRIC
2876 #define ARPHRD_FCFABRIC 787
2878 case ARPHRD_FCFABRIC
:
2880 * We assume that those all mean RFC 2625 IP-over-
2881 * Fibre Channel, with the RFC 2625 header at
2882 * the beginning of the packet.
2884 handle
->linktype
= DLT_IP_OVER_FC
;
2888 #define ARPHRD_IRDA 783
2891 /* Don't expect IP packet out of this interfaces... */
2892 handle
->linktype
= DLT_LINUX_IRDA
;
2893 /* We need to save packet direction for IrDA decoding,
2894 * so let's use "Linux-cooked" mode. Jean II */
2895 //handle->md.cooked = 1;
2898 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
2899 * is needed, please report it to <daniele@orlandi.com> */
2901 #define ARPHRD_LAPD 8445
2904 /* Don't expect IP packet out of this interfaces... */
2905 handle
->linktype
= DLT_LINUX_LAPD
;
2909 #define ARPHRD_NONE 0xFFFE
2913 * No link-layer header; packets are just IP
2914 * packets, so use DLT_RAW.
2916 handle
->linktype
= DLT_RAW
;
2919 #ifndef ARPHRD_IEEE802154
2920 #define ARPHRD_IEEE802154 804
2922 case ARPHRD_IEEE802154
:
2923 handle
->linktype
= DLT_IEEE802_15_4_NOFCS
;
2927 handle
->linktype
= -1;
2932 /* ===== Functions to interface to the newer kernels ================== */
2935 * Try to open a packet socket using the new kernel PF_PACKET interface.
2936 * Returns 1 on success, 0 on an error that means the new interface isn't
2937 * present (so the old SOCK_PACKET interface should be tried), and a
2938 * PCAP_ERROR_ value on an error that means that the old mechanism won't
2939 * work either (so it shouldn't be tried).
2942 activate_new(pcap_t
*handle
)
2944 #ifdef HAVE_PF_PACKET_SOCKETS
2945 const char *device
= handle
->opt
.source
;
2946 int is_any_device
= (strcmp(device
, "any") == 0);
2947 int sock_fd
= -1, arptype
;
2948 #ifdef HAVE_PACKET_AUXDATA
2952 struct packet_mreq mr
;
2955 * Open a socket with protocol family packet. If the
2956 * "any" device was specified, we open a SOCK_DGRAM
2957 * socket for the cooked interface, otherwise we first
2958 * try a SOCK_RAW socket for the raw interface.
2960 sock_fd
= is_any_device
?
2961 socket(PF_PACKET
, SOCK_DGRAM
, htons(ETH_P_ALL
)) :
2962 socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
));
2964 if (sock_fd
== -1) {
2965 if (errno
== EINVAL
|| errno
== EAFNOSUPPORT
) {
2967 * We don't support PF_PACKET/SOCK_whatever
2968 * sockets; try the old mechanism.
2973 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "socket: %s",
2974 pcap_strerror(errno
) );
2975 if (errno
== EPERM
|| errno
== EACCES
) {
2977 * You don't have permission to open the
2980 return PCAP_ERROR_PERM_DENIED
;
2989 /* It seems the kernel supports the new interface. */
2990 handle
->md
.sock_packet
= 0;
2993 * Get the interface index of the loopback device.
2994 * If the attempt fails, don't fail, just set the
2995 * "md.lo_ifindex" to -1.
2997 * XXX - can there be more than one device that loops
2998 * packets back, i.e. devices other than "lo"? If so,
2999 * we'd need to find them all, and have an array of
3000 * indices for them, and check all of them in
3001 * "pcap_read_packet()".
3003 handle
->md
.lo_ifindex
= iface_get_id(sock_fd
, "lo", handle
->errbuf
);
3006 * Default value for offset to align link-layer payload
3007 * on a 4-byte boundary.
3012 * What kind of frames do we have to deal with? Fall back
3013 * to cooked mode if we have an unknown interface type
3014 * or a type we know doesn't work well in raw mode.
3016 if (!is_any_device
) {
3017 /* Assume for now we don't need cooked mode. */
3018 handle
->md
.cooked
= 0;
3020 if (handle
->opt
.rfmon
) {
3022 * We were asked to turn on monitor mode.
3023 * Do so before we get the link-layer type,
3024 * because entering monitor mode could change
3025 * the link-layer type.
3027 err
= enter_rfmon_mode(handle
, sock_fd
, device
);
3035 * Nothing worked for turning monitor mode
3039 return PCAP_ERROR_RFMON_NOTSUP
;
3043 * Either monitor mode has been turned on for
3044 * the device, or we've been given a different
3045 * device to open for monitor mode. If we've
3046 * been given a different device, use it.
3048 if (handle
->md
.mondevice
!= NULL
)
3049 device
= handle
->md
.mondevice
;
3051 arptype
= iface_get_arptype(sock_fd
, device
, handle
->errbuf
);
3056 map_arphrd_to_dlt(handle
, arptype
, 1);
3057 if (handle
->linktype
== -1 ||
3058 handle
->linktype
== DLT_LINUX_SLL
||
3059 handle
->linktype
== DLT_LINUX_IRDA
||
3060 handle
->linktype
== DLT_LINUX_LAPD
||
3061 (handle
->linktype
== DLT_EN10MB
&&
3062 (strncmp("isdn", device
, 4) == 0 ||
3063 strncmp("isdY", device
, 4) == 0))) {
3065 * Unknown interface type (-1), or a
3066 * device we explicitly chose to run
3067 * in cooked mode (e.g., PPP devices),
3068 * or an ISDN device (whose link-layer
3069 * type we can only determine by using
3070 * APIs that may be different on different
3071 * kernels) - reopen in cooked mode.
3073 if (close(sock_fd
) == -1) {
3074 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3075 "close: %s", pcap_strerror(errno
));
3078 sock_fd
= socket(PF_PACKET
, SOCK_DGRAM
,
3080 if (sock_fd
== -1) {
3081 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3082 "socket: %s", pcap_strerror(errno
));
3083 if (errno
== EPERM
|| errno
== EACCES
) {
3085 * You don't have permission to
3088 return PCAP_ERROR_PERM_DENIED
;
3096 handle
->md
.cooked
= 1;
3099 * Get rid of any link-layer type list
3100 * we allocated - this only supports cooked
3103 if (handle
->dlt_list
!= NULL
) {
3104 free(handle
->dlt_list
);
3105 handle
->dlt_list
= NULL
;
3106 handle
->dlt_count
= 0;
3109 if (handle
->linktype
== -1) {
3111 * Warn that we're falling back on
3112 * cooked mode; we may want to
3113 * update "map_arphrd_to_dlt()"
3114 * to handle the new type.
3116 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3118 "supported by libpcap - "
3119 "falling back to cooked "
3125 * IrDA capture is not a real "cooked" capture,
3126 * it's IrLAP frames, not IP packets. The
3127 * same applies to LAPD capture.
3129 if (handle
->linktype
!= DLT_LINUX_IRDA
&&
3130 handle
->linktype
!= DLT_LINUX_LAPD
)
3131 handle
->linktype
= DLT_LINUX_SLL
;
3134 handle
->md
.ifindex
= iface_get_id(sock_fd
, device
,
3136 if (handle
->md
.ifindex
== -1) {
3141 if ((err
= iface_bind(sock_fd
, handle
->md
.ifindex
,
3142 handle
->errbuf
)) != 1) {
3147 return 0; /* try old mechanism */
3153 if (handle
->opt
.rfmon
) {
3155 * It doesn't support monitor mode.
3157 return PCAP_ERROR_RFMON_NOTSUP
;
3161 * It uses cooked mode.
3163 handle
->md
.cooked
= 1;
3164 handle
->linktype
= DLT_LINUX_SLL
;
3167 * We're not bound to a device.
3168 * For now, we're using this as an indication
3169 * that we can't transmit; stop doing that only
3170 * if we figure out how to transmit in cooked
3173 handle
->md
.ifindex
= -1;
3177 * Select promiscuous mode on if "promisc" is set.
3179 * Do not turn allmulti mode on if we don't select
3180 * promiscuous mode - on some devices (e.g., Orinoco
3181 * wireless interfaces), allmulti mode isn't supported
3182 * and the driver implements it by turning promiscuous
3183 * mode on, and that screws up the operation of the
3184 * card as a normal networking interface, and on no
3185 * other platform I know of does starting a non-
3186 * promiscuous capture affect which multicast packets
3187 * are received by the interface.
3191 * Hmm, how can we set promiscuous mode on all interfaces?
3192 * I am not sure if that is possible at all. For now, we
3193 * silently ignore attempts to turn promiscuous mode on
3194 * for the "any" device (so you don't have to explicitly
3195 * disable it in programs such as tcpdump).
3198 if (!is_any_device
&& handle
->opt
.promisc
) {
3199 memset(&mr
, 0, sizeof(mr
));
3200 mr
.mr_ifindex
= handle
->md
.ifindex
;
3201 mr
.mr_type
= PACKET_MR_PROMISC
;
3202 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_ADD_MEMBERSHIP
,
3203 &mr
, sizeof(mr
)) == -1) {
3204 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3205 "setsockopt: %s", pcap_strerror(errno
));
3211 /* Enable auxillary data if supported and reserve room for
3212 * reconstructing VLAN headers. */
3213 #ifdef HAVE_PACKET_AUXDATA
3215 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_AUXDATA
, &val
,
3216 sizeof(val
)) == -1 && errno
!= ENOPROTOOPT
) {
3217 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3218 "setsockopt: %s", pcap_strerror(errno
));
3222 handle
->offset
+= VLAN_TAG_LEN
;
3223 #endif /* HAVE_PACKET_AUXDATA */
3226 * This is a 2.2[.x] or later kernel (we know that
3227 * because we're not using a SOCK_PACKET socket -
3228 * PF_PACKET is supported only in 2.2 and later
3231 * We can safely pass "recvfrom()" a byte count
3232 * based on the snapshot length.
3234 * If we're in cooked mode, make the snapshot length
3235 * large enough to hold a "cooked mode" header plus
3236 * 1 byte of packet data (so we don't pass a byte
3237 * count of 0 to "recvfrom()").
3239 if (handle
->md
.cooked
) {
3240 if (handle
->snapshot
< SLL_HDR_LEN
+ 1)
3241 handle
->snapshot
= SLL_HDR_LEN
+ 1;
3243 handle
->bufsize
= handle
->snapshot
;
3245 /* Save the socket FD in the pcap structure */
3246 handle
->fd
= sock_fd
;
3251 "New packet capturing interface not supported by build "
3252 "environment", PCAP_ERRBUF_SIZE
);
3257 #ifdef HAVE_PACKET_RING
3259 * Attempt to activate with memory-mapped access.
3261 * On success, returns 1, and sets *status to 0 if there are no warnings
3262 * or to a PCAP_WARNING_ code if there is a warning.
3264 * On failure due to lack of support for memory-mapped capture, returns
3267 * On error, returns -1, and sets *status to the appropriate error code;
3268 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3271 activate_mmap(pcap_t
*handle
, int *status
)
3276 * Attempt to allocate a buffer to hold the contents of one
3277 * packet, for use by the oneshot callback.
3279 handle
->md
.oneshot_buffer
= malloc(handle
->snapshot
);
3280 if (handle
->md
.oneshot_buffer
== NULL
) {
3281 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3282 "can't allocate oneshot buffer: %s",
3283 pcap_strerror(errno
));
3284 *status
= PCAP_ERROR
;
3288 if (handle
->opt
.buffer_size
== 0) {
3289 /* by default request 2M for the ring buffer */
3290 handle
->opt
.buffer_size
= 2*1024*1024;
3292 ret
= prepare_tpacket_socket(handle
);
3294 free(handle
->md
.oneshot_buffer
);
3295 *status
= PCAP_ERROR
;
3298 ret
= create_ring(handle
, status
);
3301 * We don't support memory-mapped capture; our caller
3302 * will fall back on reading from the socket.
3304 free(handle
->md
.oneshot_buffer
);
3309 * Error attempting to enable memory-mapped capture;
3310 * fail. create_ring() has set *status.
3312 free(handle
->md
.oneshot_buffer
);
3317 * Success. *status has been set either to 0 if there are no
3318 * warnings or to a PCAP_WARNING_ value if there is a warning.
3320 * Override some defaults and inherit the other fields from
3322 * handle->offset is used to get the current position into the rx ring.
3323 * handle->cc is used to store the ring size.
3325 handle
->read_op
= pcap_read_linux_mmap
;
3326 handle
->cleanup_op
= pcap_cleanup_linux_mmap
;
3327 handle
->setfilter_op
= pcap_setfilter_linux_mmap
;
3328 handle
->setnonblock_op
= pcap_setnonblock_mmap
;
3329 handle
->getnonblock_op
= pcap_getnonblock_mmap
;
3330 handle
->oneshot_callback
= pcap_oneshot_mmap
;
3331 handle
->selectable_fd
= handle
->fd
;
3334 #else /* HAVE_PACKET_RING */
3336 activate_mmap(pcap_t
*handle _U_
, int *status _U_
)
3340 #endif /* HAVE_PACKET_RING */
3342 #ifdef HAVE_PACKET_RING
3344 * Attempt to set the socket to version 2 of the memory-mapped header.
3345 * Return 1 if we succeed or if we fail because version 2 isn't
3346 * supported; return -1 on any other error, and set handle->errbuf.
3349 prepare_tpacket_socket(pcap_t
*handle
)
3351 #ifdef HAVE_TPACKET2
3356 handle
->md
.tp_version
= TPACKET_V1
;
3357 handle
->md
.tp_hdrlen
= sizeof(struct tpacket_hdr
);
3359 #ifdef HAVE_TPACKET2
3360 /* Probe whether kernel supports TPACKET_V2 */
3363 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_HDRLEN
, &val
, &len
) < 0) {
3364 if (errno
== ENOPROTOOPT
)
3365 return 1; /* no - just drive on */
3367 /* Yes - treat as a failure. */
3368 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3369 "can't get TPACKET_V2 header len on packet socket: %s",
3370 pcap_strerror(errno
));
3373 handle
->md
.tp_hdrlen
= val
;
3376 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_VERSION
, &val
,
3378 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3379 "can't activate TPACKET_V2 on packet socket: %s",
3380 pcap_strerror(errno
));
3383 handle
->md
.tp_version
= TPACKET_V2
;
3385 /* Reserve space for VLAN tag reconstruction */
3387 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
, &val
,
3389 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3390 "can't set up reserve on packet socket: %s",
3391 pcap_strerror(errno
));
3395 #endif /* HAVE_TPACKET2 */
3400 * Attempt to set up memory-mapped access.
3402 * On success, returns 1, and sets *status to 0 if there are no warnings
3403 * or to a PCAP_WARNING_ code if there is a warning.
3405 * On failure due to lack of support for memory-mapped capture, returns
3408 * On error, returns -1, and sets *status to the appropriate error code;
3409 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3412 create_ring(pcap_t
*handle
, int *status
)
3414 unsigned i
, j
, frames_per_block
;
3415 struct tpacket_req req
;
3417 unsigned int sk_type
, tp_reserve
, maclen
, tp_hdrlen
, netoff
, macoff
;
3418 unsigned int frame_size
;
3421 * Start out assuming no warnings or errors.
3425 /* Note that with large snapshot length (say 64K, which is the default
3426 * for recent versions of tcpdump, the value that "-s 0" has given
3427 * for a long time with tcpdump, and the default in Wireshark/TShark),
3428 * if we use the snapshot length to calculate the frame length,
3429 * only a few frames will be available in the ring even with pretty
3430 * large ring size (and a lot of memory will be unused).
3432 * Ideally, we should choose a frame length based on the
3433 * minimum of the specified snapshot length and the maximum
3434 * packet size. That's not as easy as it sounds; consider, for
3435 * example, an 802.11 interface in monitor mode, where the
3436 * frame would include a radiotap header, where the maximum
3437 * radiotap header length is device-dependent.
3439 * So, for now, we just do this for Ethernet devices, where
3440 * there's no metadata header, and the link-layer header is
3441 * fixed length. We can get the maximum packet size by
3442 * adding 18, the Ethernet header length plus the CRC length
3443 * (just in case we happen to get the CRC in the packet), to
3444 * the MTU of the interface; we fetch the MTU in the hopes
3445 * that it reflects support for jumbo frames. (Even if the
3446 * interface is just being used for passive snooping, the driver
3447 * might set the size of buffers in the receive ring based on
3448 * the MTU, so that the MTU limits the maximum size of packets
3449 * that we can receive.)
3451 * We don't do that if segmentation/fragmentation or receive
3452 * offload are enabled, so we don't get rudely surprised by
3453 * "packets" bigger than the MTU. */
3454 frame_size
= handle
->snapshot
;
3455 if (handle
->linktype
== DLT_EN10MB
) {
3459 offload
= iface_get_offload(handle
);
3460 if (offload
== -1) {
3461 *status
= PCAP_ERROR
;
3465 mtu
= iface_get_mtu(handle
->fd
, handle
->opt
.source
,
3468 *status
= PCAP_ERROR
;
3471 if (frame_size
> mtu
+ 18)
3472 frame_size
= mtu
+ 18;
3476 /* NOTE: calculus matching those in tpacket_rcv()
3477 * in linux-2.6/net/packet/af_packet.c
3479 len
= sizeof(sk_type
);
3480 if (getsockopt(handle
->fd
, SOL_SOCKET
, SO_TYPE
, &sk_type
, &len
) < 0) {
3481 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "getsockopt: %s", pcap_strerror(errno
));
3482 *status
= PCAP_ERROR
;
3485 #ifdef PACKET_RESERVE
3486 len
= sizeof(tp_reserve
);
3487 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
, &tp_reserve
, &len
) < 0) {
3488 if (errno
!= ENOPROTOOPT
) {
3490 * ENOPROTOOPT means "kernel doesn't support
3491 * PACKET_RESERVE", in which case we fall back
3494 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "getsockopt: %s", pcap_strerror(errno
));
3495 *status
= PCAP_ERROR
;
3498 tp_reserve
= 0; /* older kernel, reserve not supported */
3501 tp_reserve
= 0; /* older kernel, reserve not supported */
3503 maclen
= (sk_type
== SOCK_DGRAM
) ? 0 : MAX_LINKHEADER_SIZE
;
3504 /* XXX: in the kernel maclen is calculated from
3505 * LL_ALLOCATED_SPACE(dev) and vnet_hdr.hdr_len
3506 * in: packet_snd() in linux-2.6/net/packet/af_packet.c
3507 * then packet_alloc_skb() in linux-2.6/net/packet/af_packet.c
3508 * then sock_alloc_send_pskb() in linux-2.6/net/core/sock.c
3509 * but I see no way to get those sizes in userspace,
3510 * like for instance with an ifreq ioctl();
3511 * the best thing I've found so far is MAX_HEADER in the kernel
3512 * part of linux-2.6/include/linux/netdevice.h
3513 * which goes up to 128+48=176; since pcap-linux.c defines
3514 * a MAX_LINKHEADER_SIZE of 256 which is greater than that,
3515 * let's use it.. maybe is it even large enough to directly
3518 tp_hdrlen
= TPACKET_ALIGN(handle
->md
.tp_hdrlen
) + sizeof(struct sockaddr_ll
) ;
3519 netoff
= TPACKET_ALIGN(tp_hdrlen
+ (maclen
< 16 ? 16 : maclen
)) + tp_reserve
;
3520 /* NOTE: AFAICS tp_reserve may break the TPACKET_ALIGN of
3521 * netoff, which contradicts
3522 * linux-2.6/Documentation/networking/packet_mmap.txt
3524 * "- Gap, chosen so that packet data (Start+tp_net)
3525 * aligns to TPACKET_ALIGNMENT=16"
3527 /* NOTE: in linux-2.6/include/linux/skbuff.h:
3528 * "CPUs often take a performance hit
3529 * when accessing unaligned memory locations"
3531 macoff
= netoff
- maclen
;
3532 req
.tp_frame_size
= TPACKET_ALIGN(macoff
+ frame_size
);
3533 req
.tp_frame_nr
= handle
->opt
.buffer_size
/req
.tp_frame_size
;
3535 /* compute the minumum block size that will handle this frame.
3536 * The block has to be page size aligned.
3537 * The max block size allowed by the kernel is arch-dependent and
3538 * it's not explicitly checked here. */
3539 req
.tp_block_size
= getpagesize();
3540 while (req
.tp_block_size
< req
.tp_frame_size
)
3541 req
.tp_block_size
<<= 1;
3543 frames_per_block
= req
.tp_block_size
/req
.tp_frame_size
;
3546 * PACKET_TIMESTAMP was added after linux/net_tstamp.h was,
3547 * so we check for PACKET_TIMESTAMP. We check for
3548 * linux/net_tstamp.h just in case a system somehow has
3549 * PACKET_TIMESTAMP but not linux/net_tstamp.h; that might
3552 * SIOCSHWTSTAMP was introduced in the patch that introduced
3553 * linux/net_tstamp.h, so we don't bother checking whether
3554 * SIOCSHWTSTAMP is defined (if your Linux system has
3555 * linux/net_tstamp.h but doesn't define SIOCSHWTSTAMP, your
3556 * Linux system is badly broken).
3558 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
3560 * If we were told to do so, ask the kernel and the driver
3561 * to use hardware timestamps.
3563 * Hardware timestamps are only supported with mmapped
3566 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
||
3567 handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER_UNSYNCED
) {
3568 struct hwtstamp_config hwconfig
;
3573 * Ask for hardware time stamps on all packets,
3574 * including transmitted packets.
3576 memset(&hwconfig
, 0, sizeof(hwconfig
));
3577 hwconfig
.tx_type
= HWTSTAMP_TX_ON
;
3578 hwconfig
.rx_filter
= HWTSTAMP_FILTER_ALL
;
3580 memset(&ifr
, 0, sizeof(ifr
));
3581 strcpy(ifr
.ifr_name
, handle
->opt
.source
);
3582 ifr
.ifr_data
= (void *)&hwconfig
;
3584 if (ioctl(handle
->fd
, SIOCSHWTSTAMP
, &ifr
) < 0) {
3589 * Treat this as an error, as the
3590 * user should try to run this
3591 * with the appropriate privileges -
3592 * and, if they can't, shouldn't
3593 * try requesting hardware time stamps.
3595 *status
= PCAP_ERROR_PERM_DENIED
;
3600 * Treat this as a warning, as the
3601 * only way to fix the warning is to
3602 * get an adapter that supports hardware
3603 * time stamps. We'll just fall back
3604 * on the standard host time stamps.
3606 *status
= PCAP_WARNING_TSTAMP_TYPE_NOTSUP
;
3610 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3611 "SIOCSHWTSTAMP failed: %s",
3612 pcap_strerror(errno
));
3613 *status
= PCAP_ERROR
;
3618 * Well, that worked. Now specify the type of
3619 * hardware time stamp we want for this
3622 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
) {
3624 * Hardware timestamp, synchronized
3625 * with the system clock.
3627 timesource
= SOF_TIMESTAMPING_SYS_HARDWARE
;
3630 * PCAP_TSTAMP_ADAPTER_UNSYNCED - hardware
3631 * timestamp, not synchronized with the
3634 timesource
= SOF_TIMESTAMPING_RAW_HARDWARE
;
3636 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_TIMESTAMP
,
3637 (void *)×ource
, sizeof(timesource
))) {
3638 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3639 "can't set PACKET_TIMESTAMP: %s",
3640 pcap_strerror(errno
));
3641 *status
= PCAP_ERROR
;
3646 #endif /* HAVE_LINUX_NET_TSTAMP_H && PACKET_TIMESTAMP */
3648 /* ask the kernel to create the ring */
3650 req
.tp_block_nr
= req
.tp_frame_nr
/ frames_per_block
;
3652 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
3653 req
.tp_frame_nr
= req
.tp_block_nr
* frames_per_block
;
3655 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
3656 (void *) &req
, sizeof(req
))) {
3657 if ((errno
== ENOMEM
) && (req
.tp_block_nr
> 1)) {
3659 * Memory failure; try to reduce the requested ring
3662 * We used to reduce this by half -- do 5% instead.
3663 * That may result in more iterations and a longer
3664 * startup, but the user will be much happier with
3665 * the resulting buffer size.
3667 if (req
.tp_frame_nr
< 20)
3668 req
.tp_frame_nr
-= 1;
3670 req
.tp_frame_nr
-= req
.tp_frame_nr
/20;
3673 if (errno
== ENOPROTOOPT
) {
3675 * We don't have ring buffer support in this kernel.
3679 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3680 "can't create rx ring on packet socket: %s",
3681 pcap_strerror(errno
));
3682 *status
= PCAP_ERROR
;
3686 /* memory map the rx ring */
3687 handle
->md
.mmapbuflen
= req
.tp_block_nr
* req
.tp_block_size
;
3688 handle
->md
.mmapbuf
= mmap(0, handle
->md
.mmapbuflen
,
3689 PROT_READ
|PROT_WRITE
, MAP_SHARED
, handle
->fd
, 0);
3690 if (handle
->md
.mmapbuf
== MAP_FAILED
) {
3691 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3692 "can't mmap rx ring: %s", pcap_strerror(errno
));
3694 /* clear the allocated ring on error*/
3695 destroy_ring(handle
);
3696 *status
= PCAP_ERROR
;
3700 /* allocate a ring for each frame header pointer*/
3701 handle
->cc
= req
.tp_frame_nr
;
3702 handle
->buffer
= malloc(handle
->cc
* sizeof(union thdr
*));
3703 if (!handle
->buffer
) {
3704 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3705 "can't allocate ring of frame headers: %s",
3706 pcap_strerror(errno
));
3708 destroy_ring(handle
);
3709 *status
= PCAP_ERROR
;
3713 /* fill the header ring with proper frame ptr*/
3715 for (i
=0; i
<req
.tp_block_nr
; ++i
) {
3716 void *base
= &handle
->md
.mmapbuf
[i
*req
.tp_block_size
];
3717 for (j
=0; j
<frames_per_block
; ++j
, ++handle
->offset
) {
3718 RING_GET_FRAME(handle
) = base
;
3719 base
+= req
.tp_frame_size
;
3723 handle
->bufsize
= req
.tp_frame_size
;
3728 /* free all ring related resources*/
3730 destroy_ring(pcap_t
*handle
)
3732 /* tell the kernel to destroy the ring*/
3733 struct tpacket_req req
;
3734 memset(&req
, 0, sizeof(req
));
3735 setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
3736 (void *) &req
, sizeof(req
));
3738 /* if ring is mapped, unmap it*/
3739 if (handle
->md
.mmapbuf
) {
3740 /* do not test for mmap failure, as we can't recover from any error */
3741 munmap(handle
->md
.mmapbuf
, handle
->md
.mmapbuflen
);
3742 handle
->md
.mmapbuf
= NULL
;
3747 * Special one-shot callback, used for pcap_next() and pcap_next_ex(),
3748 * for Linux mmapped capture.
3750 * The problem is that pcap_next() and pcap_next_ex() expect the packet
3751 * data handed to the callback to be valid after the callback returns,
3752 * but pcap_read_linux_mmap() has to release that packet as soon as
3753 * the callback returns (otherwise, the kernel thinks there's still
3754 * at least one unprocessed packet available in the ring, so a select()
3755 * will immediately return indicating that there's data to process), so,
3756 * in the callback, we have to make a copy of the packet.
3758 * Yes, this means that, if the capture is using the ring buffer, using
3759 * pcap_next() or pcap_next_ex() requires more copies than using
3760 * pcap_loop() or pcap_dispatch(). If that bothers you, don't use
3761 * pcap_next() or pcap_next_ex().
3764 pcap_oneshot_mmap(u_char
*user
, const struct pcap_pkthdr
*h
,
3765 const u_char
*bytes
)
3767 struct oneshot_userdata
*sp
= (struct oneshot_userdata
*)user
;
3770 memcpy(sp
->pd
->md
.oneshot_buffer
, bytes
, h
->caplen
);
3771 *sp
->pkt
= sp
->pd
->md
.oneshot_buffer
;
3775 pcap_cleanup_linux_mmap( pcap_t
*handle
)
3777 destroy_ring(handle
);
3778 if (handle
->md
.oneshot_buffer
!= NULL
) {
3779 free(handle
->md
.oneshot_buffer
);
3780 handle
->md
.oneshot_buffer
= NULL
;
3782 pcap_cleanup_linux(handle
);
3787 pcap_getnonblock_mmap(pcap_t
*p
, char *errbuf
)
3789 /* use negative value of timeout to indicate non blocking ops */
3790 return (p
->md
.timeout
<0);
3794 pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
, char *errbuf
)
3796 /* map each value to the corresponding 2's complement, to
3797 * preserve the timeout value provided with pcap_set_timeout */
3799 if (p
->md
.timeout
>= 0) {
3801 * Timeout is non-negative, so we're not already
3802 * in non-blocking mode; set it to the 2's
3803 * complement, to make it negative, as an
3804 * indication that we're in non-blocking mode.
3806 p
->md
.timeout
= p
->md
.timeout
*-1 - 1;
3809 if (p
->md
.timeout
< 0) {
3811 * Timeout is negative, so we're not already
3812 * in blocking mode; reverse the previous
3813 * operation, to make the timeout non-negative
3816 p
->md
.timeout
= (p
->md
.timeout
+1)*-1;
3822 static inline union thdr
*
3823 pcap_get_ring_frame(pcap_t
*handle
, int status
)
3827 h
.raw
= RING_GET_FRAME(handle
);
3828 switch (handle
->md
.tp_version
) {
3830 if (status
!= (h
.h1
->tp_status
? TP_STATUS_USER
:
3834 #ifdef HAVE_TPACKET2
3836 if (status
!= (h
.h2
->tp_status
? TP_STATUS_USER
:
3850 pcap_read_linux_mmap(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
3857 /* wait for frames availability.*/
3858 if (!pcap_get_ring_frame(handle
, TP_STATUS_USER
)) {
3859 struct pollfd pollinfo
;
3862 pollinfo
.fd
= handle
->fd
;
3863 pollinfo
.events
= POLLIN
;
3865 if (handle
->md
.timeout
== 0)
3866 timeout
= -1; /* block forever */
3867 else if (handle
->md
.timeout
> 0)
3868 timeout
= handle
->md
.timeout
; /* block for that amount of time */
3870 timeout
= 0; /* non-blocking mode - poll to pick up errors */
3872 ret
= poll(&pollinfo
, 1, timeout
);
3873 if (ret
< 0 && errno
!= EINTR
) {
3874 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3875 "can't poll on packet socket: %s",
3876 pcap_strerror(errno
));
3878 } else if (ret
> 0 &&
3879 (pollinfo
.revents
& (POLLHUP
|POLLRDHUP
|POLLERR
|POLLNVAL
))) {
3881 * There's some indication other than
3882 * "you can read on this descriptor" on
3885 if (pollinfo
.revents
& (POLLHUP
| POLLRDHUP
)) {
3886 snprintf(handle
->errbuf
,
3888 "Hangup on packet socket");
3891 if (pollinfo
.revents
& POLLERR
) {
3893 * A recv() will give us the
3894 * actual error code.
3896 * XXX - make the socket non-blocking?
3898 if (recv(handle
->fd
, &c
, sizeof c
,
3900 continue; /* what, no error? */
3901 if (errno
== ENETDOWN
) {
3903 * The device on which we're
3904 * capturing went away.
3906 * XXX - we should really return
3907 * PCAP_ERROR_IFACE_NOT_UP,
3908 * but pcap_dispatch() etc.
3909 * aren't defined to return
3912 snprintf(handle
->errbuf
,
3914 "The interface went down");
3916 snprintf(handle
->errbuf
,
3918 "Error condition on packet socket: %s",
3923 if (pollinfo
.revents
& POLLNVAL
) {
3924 snprintf(handle
->errbuf
,
3926 "Invalid polling request on packet socket");
3930 /* check for break loop condition on interrupted syscall*/
3931 if (handle
->break_loop
) {
3932 handle
->break_loop
= 0;
3933 return PCAP_ERROR_BREAK
;
3938 /* non-positive values of max_packets are used to require all
3939 * packets currently available in the ring */
3940 while ((pkts
< max_packets
) || (max_packets
<= 0)) {
3942 struct sockaddr_ll
*sll
;
3943 struct pcap_pkthdr pcaphdr
;
3946 unsigned int tp_len
;
3947 unsigned int tp_mac
;
3948 unsigned int tp_snaplen
;
3949 unsigned int tp_sec
;
3950 unsigned int tp_usec
;
3952 h
.raw
= pcap_get_ring_frame(handle
, TP_STATUS_USER
);
3956 switch (handle
->md
.tp_version
) {
3958 tp_len
= h
.h1
->tp_len
;
3959 tp_mac
= h
.h1
->tp_mac
;
3960 tp_snaplen
= h
.h1
->tp_snaplen
;
3961 tp_sec
= h
.h1
->tp_sec
;
3962 tp_usec
= h
.h1
->tp_usec
;
3964 #ifdef HAVE_TPACKET2
3966 tp_len
= h
.h2
->tp_len
;
3967 tp_mac
= h
.h2
->tp_mac
;
3968 tp_snaplen
= h
.h2
->tp_snaplen
;
3969 tp_sec
= h
.h2
->tp_sec
;
3970 tp_usec
= h
.h2
->tp_nsec
/ 1000;
3974 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3975 "unsupported tpacket version %d",
3976 handle
->md
.tp_version
);
3979 /* perform sanity check on internal offset. */
3980 if (tp_mac
+ tp_snaplen
> handle
->bufsize
) {
3981 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3982 "corrupted frame on kernel ring mac "
3983 "offset %d + caplen %d > frame len %d",
3984 tp_mac
, tp_snaplen
, handle
->bufsize
);
3988 /* run filter on received packet
3989 * If the kernel filtering is enabled we need to run the
3990 * filter until all the frames present into the ring
3991 * at filter creation time are processed.
3992 * In such case md.use_bpf is used as a counter for the
3993 * packet we need to filter.
3994 * Note: alternatively it could be possible to stop applying
3995 * the filter when the ring became empty, but it can possibly
3996 * happen a lot later... */
3997 bp
= (unsigned char*)h
.raw
+ tp_mac
;
3998 run_bpf
= (!handle
->md
.use_bpf
) ||
3999 ((handle
->md
.use_bpf
>1) && handle
->md
.use_bpf
--);
4000 if (run_bpf
&& handle
->fcode
.bf_insns
&&
4001 (bpf_filter(handle
->fcode
.bf_insns
, bp
,
4002 tp_len
, tp_snaplen
) == 0))
4006 * Do checks based on packet direction.
4008 sll
= (void *)h
.raw
+ TPACKET_ALIGN(handle
->md
.tp_hdrlen
);
4009 if (sll
->sll_pkttype
== PACKET_OUTGOING
) {
4012 * If this is from the loopback device, reject it;
4013 * we'll see the packet as an incoming packet as well,
4014 * and we don't want to see it twice.
4016 if (sll
->sll_ifindex
== handle
->md
.lo_ifindex
)
4020 * If the user only wants incoming packets, reject it.
4022 if (handle
->direction
== PCAP_D_IN
)
4027 * If the user only wants outgoing packets, reject it.
4029 if (handle
->direction
== PCAP_D_OUT
)
4033 /* get required packet info from ring header */
4034 pcaphdr
.ts
.tv_sec
= tp_sec
;
4035 pcaphdr
.ts
.tv_usec
= tp_usec
;
4036 pcaphdr
.caplen
= tp_snaplen
;
4037 pcaphdr
.len
= tp_len
;
4039 /* if required build in place the sll header*/
4040 if (handle
->md
.cooked
) {
4041 struct sll_header
*hdrp
;
4044 * The kernel should have left us with enough
4045 * space for an sll header; back up the packet
4046 * data pointer into that space, as that'll be
4047 * the beginning of the packet we pass to the
4053 * Let's make sure that's past the end of
4054 * the tpacket header, i.e. >=
4055 * ((u_char *)thdr + TPACKET_HDRLEN), so we
4056 * don't step on the header when we construct
4059 if (bp
< (u_char
*)h
.raw
+
4060 TPACKET_ALIGN(handle
->md
.tp_hdrlen
) +
4061 sizeof(struct sockaddr_ll
)) {
4062 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4063 "cooked-mode frame doesn't have room for sll header");
4068 * OK, that worked; construct the sll header.
4070 hdrp
= (struct sll_header
*)bp
;
4071 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(
4073 hdrp
->sll_hatype
= htons(sll
->sll_hatype
);
4074 hdrp
->sll_halen
= htons(sll
->sll_halen
);
4075 memcpy(hdrp
->sll_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
4076 hdrp
->sll_protocol
= sll
->sll_protocol
;
4078 /* update packet len */
4079 pcaphdr
.caplen
+= SLL_HDR_LEN
;
4080 pcaphdr
.len
+= SLL_HDR_LEN
;
4083 #ifdef HAVE_TPACKET2
4084 if (handle
->md
.tp_version
== TPACKET_V2
&& h
.h2
->tp_vlan_tci
&&
4085 tp_snaplen
>= 2 * ETH_ALEN
) {
4086 struct vlan_tag
*tag
;
4089 memmove(bp
, bp
+ VLAN_TAG_LEN
, 2 * ETH_ALEN
);
4091 tag
= (struct vlan_tag
*)(bp
+ 2 * ETH_ALEN
);
4092 tag
->vlan_tpid
= htons(ETH_P_8021Q
);
4093 tag
->vlan_tci
= htons(h
.h2
->tp_vlan_tci
);
4095 pcaphdr
.caplen
+= VLAN_TAG_LEN
;
4096 pcaphdr
.len
+= VLAN_TAG_LEN
;
4101 * The only way to tell the kernel to cut off the
4102 * packet at a snapshot length is with a filter program;
4103 * if there's no filter program, the kernel won't cut
4106 * Trim the snapshot length to be no longer than the
4107 * specified snapshot length.
4109 if (pcaphdr
.caplen
> handle
->snapshot
)
4110 pcaphdr
.caplen
= handle
->snapshot
;
4112 /* pass the packet to the user */
4114 callback(user
, &pcaphdr
, bp
);
4115 handle
->md
.packets_read
++;
4119 switch (handle
->md
.tp_version
) {
4121 h
.h1
->tp_status
= TP_STATUS_KERNEL
;
4123 #ifdef HAVE_TPACKET2
4125 h
.h2
->tp_status
= TP_STATUS_KERNEL
;
4129 if (++handle
->offset
>= handle
->cc
)
4132 /* check for break loop condition*/
4133 if (handle
->break_loop
) {
4134 handle
->break_loop
= 0;
4135 return PCAP_ERROR_BREAK
;
4142 pcap_setfilter_linux_mmap(pcap_t
*handle
, struct bpf_program
*filter
)
4148 * Don't rewrite "ret" instructions; we don't need to, as
4149 * we're not reading packets with recvmsg(), and we don't
4150 * want to, as, by not rewriting them, the kernel can avoid
4151 * copying extra data.
4153 ret
= pcap_setfilter_linux_common(handle
, filter
, 1);
4157 /* if the kernel filter is enabled, we need to apply the filter on
4158 * all packets present into the ring. Get an upper bound of their number
4160 if (!handle
->md
.use_bpf
)
4163 /* walk the ring backward and count the free slot */
4164 offset
= handle
->offset
;
4165 if (--handle
->offset
< 0)
4166 handle
->offset
= handle
->cc
- 1;
4167 for (n
=0; n
< handle
->cc
; ++n
) {
4168 if (--handle
->offset
< 0)
4169 handle
->offset
= handle
->cc
- 1;
4170 if (!pcap_get_ring_frame(handle
, TP_STATUS_KERNEL
))
4174 /* be careful to not change current ring position */
4175 handle
->offset
= offset
;
4177 /* store the number of packets currently present in the ring */
4178 handle
->md
.use_bpf
= 1 + (handle
->cc
- n
);
4182 #endif /* HAVE_PACKET_RING */
4185 #ifdef HAVE_PF_PACKET_SOCKETS
4187 * Return the index of the given device name. Fill ebuf and return
4191 iface_get_id(int fd
, const char *device
, char *ebuf
)
4195 memset(&ifr
, 0, sizeof(ifr
));
4196 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4198 if (ioctl(fd
, SIOCGIFINDEX
, &ifr
) == -1) {
4199 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4200 "SIOCGIFINDEX: %s", pcap_strerror(errno
));
4204 return ifr
.ifr_ifindex
;
4208 * Bind the socket associated with FD to the given device.
4209 * Return 1 on success, 0 if we should try a SOCK_PACKET socket,
4210 * or a PCAP_ERROR_ value on a hard error.
4213 iface_bind(int fd
, int ifindex
, char *ebuf
)
4215 struct sockaddr_ll sll
;
4217 socklen_t errlen
= sizeof(err
);
4219 memset(&sll
, 0, sizeof(sll
));
4220 sll
.sll_family
= AF_PACKET
;
4221 sll
.sll_ifindex
= ifindex
;
4222 sll
.sll_protocol
= htons(ETH_P_ALL
);
4224 if (bind(fd
, (struct sockaddr
*) &sll
, sizeof(sll
)) == -1) {
4225 if (errno
== ENETDOWN
) {
4227 * Return a "network down" indication, so that
4228 * the application can report that rather than
4229 * saying we had a mysterious failure and
4230 * suggest that they report a problem to the
4231 * libpcap developers.
4233 return PCAP_ERROR_IFACE_NOT_UP
;
4235 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4236 "bind: %s", pcap_strerror(errno
));
4241 /* Any pending errors, e.g., network is down? */
4243 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
4244 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4245 "getsockopt: %s", pcap_strerror(errno
));
4249 if (err
== ENETDOWN
) {
4251 * Return a "network down" indication, so that
4252 * the application can report that rather than
4253 * saying we had a mysterious failure and
4254 * suggest that they report a problem to the
4255 * libpcap developers.
4257 return PCAP_ERROR_IFACE_NOT_UP
;
4258 } else if (err
> 0) {
4259 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4260 "bind: %s", pcap_strerror(err
));
4267 #ifdef IW_MODE_MONITOR
4269 * Check whether the device supports the Wireless Extensions.
4270 * Returns 1 if it does, 0 if it doesn't, PCAP_ERROR_NO_SUCH_DEVICE
4271 * if the device doesn't even exist.
4274 has_wext(int sock_fd
, const char *device
, char *ebuf
)
4278 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4279 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4280 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4281 if (ioctl(sock_fd
, SIOCGIWNAME
, &ireq
) >= 0)
4283 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4284 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
4285 if (errno
== ENODEV
)
4286 return PCAP_ERROR_NO_SUCH_DEVICE
;
4291 * Per me si va ne la citta dolente,
4292 * Per me si va ne l'etterno dolore,
4294 * Lasciate ogne speranza, voi ch'intrate.
4296 * XXX - airmon-ng does special stuff with the Orinoco driver and the
4312 * Use the Wireless Extensions, if we have them, to try to turn monitor mode
4313 * on if it's not already on.
4315 * Returns 1 on success, 0 if we don't support the Wireless Extensions
4316 * on this device, or a PCAP_ERROR_ value if we do support them but
4317 * we weren't able to turn monitor mode on.
4320 enter_rfmon_mode_wext(pcap_t
*handle
, int sock_fd
, const char *device
)
4323 * XXX - at least some adapters require non-Wireless Extensions
4324 * mechanisms to turn monitor mode on.
4326 * Atheros cards might require that a separate "monitor virtual access
4327 * point" be created, with later versions of the madwifi driver.
4328 * airmon-ng does "wlanconfig ath create wlandev {if} wlanmode
4329 * monitor -bssid", which apparently spits out a line "athN"
4330 * where "athN" is the monitor mode device. To leave monitor
4331 * mode, it destroys the monitor mode device.
4333 * Some Intel Centrino adapters might require private ioctls to get
4334 * radio headers; the ipw2200 and ipw3945 drivers allow you to
4335 * configure a separate "rtapN" interface to capture in monitor
4336 * mode without preventing the adapter from operating normally.
4337 * (airmon-ng doesn't appear to use that, though.)
4339 * It would be Truly Wonderful if mac80211 and nl80211 cleaned this
4340 * up, and if all drivers were converted to mac80211 drivers.
4342 * If interface {if} is a mac80211 driver, the file
4343 * /sys/class/net/{if}/phy80211 is a symlink to
4344 * /sys/class/ieee80211/{phydev}, for some {phydev}.
4346 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
4347 * least, has a "wmaster0" device and a "wlan0" device; the
4348 * latter is the one with the IP address. Both show up in
4349 * "tcpdump -D" output. Capturing on the wmaster0 device
4350 * captures with 802.11 headers.
4352 * airmon-ng searches through /sys/class/net for devices named
4353 * monN, starting with mon0; as soon as one *doesn't* exist,
4354 * it chooses that as the monitor device name. If the "iw"
4355 * command exists, it does "iw dev {if} interface add {monif}
4356 * type monitor", where {monif} is the monitor device. It
4357 * then (sigh) sleeps .1 second, and then configures the
4358 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
4359 * is a file, it writes {mondev}, without a newline, to that file,
4360 * and again (sigh) sleeps .1 second, and then iwconfig's that
4361 * device into monitor mode and configures it up. Otherwise,
4362 * you can't do monitor mode.
4364 * All these devices are "glued" together by having the
4365 * /sys/class/net/{device}/phy80211 links pointing to the same
4366 * place, so, given a wmaster, wlan, or mon device, you can
4367 * find the other devices by looking for devices with
4368 * the same phy80211 link.
4370 * To turn monitor mode off, delete the monitor interface,
4371 * either with "iw dev {monif} interface del" or by sending
4372 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
4374 * Note: if you try to create a monitor device named "monN", and
4375 * there's already a "monN" device, it fails, as least with
4376 * the netlink interface (which is what iw uses), with a return
4377 * value of -ENFILE. (Return values are negative errnos.) We
4378 * could probably use that to find an unused device.
4382 struct iw_priv_args
*priv
;
4383 monitor_type montype
;
4392 * Does this device *support* the Wireless Extensions?
4394 err
= has_wext(sock_fd
, device
, handle
->errbuf
);
4396 return err
; /* either it doesn't or the device doesn't even exist */
4398 * Start out assuming we have no private extensions to control
4401 montype
= MONITOR_WEXT
;
4405 * Try to get all the Wireless Extensions private ioctls
4406 * supported by this device.
4408 * First, get the size of the buffer we need, by supplying no
4409 * buffer and a length of 0. If the device supports private
4410 * ioctls, it should return E2BIG, with ireq.u.data.length set
4411 * to the length we need. If it doesn't support them, it should
4412 * return EOPNOTSUPP.
4414 memset(&ireq
, 0, sizeof ireq
);
4415 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4416 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4417 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4418 ireq
.u
.data
.pointer
= (void *)args
;
4419 ireq
.u
.data
.length
= 0;
4420 ireq
.u
.data
.flags
= 0;
4421 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) != -1) {
4422 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4423 "%s: SIOCGIWPRIV with a zero-length buffer didn't fail!",
4427 if (errno
!= EOPNOTSUPP
) {
4429 * OK, it's not as if there are no private ioctls.
4431 if (errno
!= E2BIG
) {
4435 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4436 "%s: SIOCGIWPRIV: %s", device
,
4437 pcap_strerror(errno
));
4442 * OK, try to get the list of private ioctls.
4444 priv
= malloc(ireq
.u
.data
.length
* sizeof (struct iw_priv_args
));
4446 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4447 "malloc: %s", pcap_strerror(errno
));
4450 ireq
.u
.data
.pointer
= (void *)priv
;
4451 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) == -1) {
4452 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4453 "%s: SIOCGIWPRIV: %s", device
,
4454 pcap_strerror(errno
));
4460 * Look for private ioctls to turn monitor mode on or, if
4461 * monitor mode is on, to set the header type.
4463 for (i
= 0; i
< ireq
.u
.data
.length
; i
++) {
4464 if (strcmp(priv
[i
].name
, "monitor_type") == 0) {
4466 * Hostap driver, use this one.
4467 * Set monitor mode first.
4468 * You can set it to 0 to get DLT_IEEE80211,
4469 * 1 to get DLT_PRISM, 2 to get
4470 * DLT_IEEE80211_RADIO_AVS, and, with more
4471 * recent versions of the driver, 3 to get
4472 * DLT_IEEE80211_RADIO.
4474 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4476 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4478 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
4480 montype
= MONITOR_HOSTAP
;
4484 if (strcmp(priv
[i
].name
, "set_prismhdr") == 0) {
4486 * Prism54 driver, use this one.
4487 * Set monitor mode first.
4488 * You can set it to 2 to get DLT_IEEE80211
4489 * or 3 or get DLT_PRISM.
4491 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4493 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4495 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
4497 montype
= MONITOR_PRISM54
;
4501 if (strcmp(priv
[i
].name
, "forceprismheader") == 0) {
4503 * RT2570 driver, use this one.
4504 * Do this after turning monitor mode on.
4505 * You can set it to 1 to get DLT_PRISM or 2
4506 * to get DLT_IEEE80211.
4508 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4510 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4512 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
4514 montype
= MONITOR_RT2570
;
4518 if (strcmp(priv
[i
].name
, "forceprism") == 0) {
4520 * RT73 driver, use this one.
4521 * Do this after turning monitor mode on.
4522 * Its argument is a *string*; you can
4523 * set it to "1" to get DLT_PRISM or "2"
4524 * to get DLT_IEEE80211.
4526 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_CHAR
)
4528 if (priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
)
4530 montype
= MONITOR_RT73
;
4534 if (strcmp(priv
[i
].name
, "prismhdr") == 0) {
4536 * One of the RTL8xxx drivers, use this one.
4537 * It can only be done after monitor mode
4538 * has been turned on. You can set it to 1
4539 * to get DLT_PRISM or 0 to get DLT_IEEE80211.
4541 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4543 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4545 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
4547 montype
= MONITOR_RTL8XXX
;
4551 if (strcmp(priv
[i
].name
, "rfmontx") == 0) {
4553 * RT2500 or RT61 driver, use this one.
4554 * It has one one-byte parameter; set
4555 * u.data.length to 1 and u.data.pointer to
4556 * point to the parameter.
4557 * It doesn't itself turn monitor mode on.
4558 * You can set it to 1 to allow transmitting
4559 * in monitor mode(?) and get DLT_IEEE80211,
4560 * or set it to 0 to disallow transmitting in
4561 * monitor mode(?) and get DLT_PRISM.
4563 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4565 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 2)
4567 montype
= MONITOR_RT2500
;
4571 if (strcmp(priv
[i
].name
, "monitor") == 0) {
4573 * Either ACX100 or hostap, use this one.
4574 * It turns monitor mode on.
4575 * If it takes two arguments, it's ACX100;
4576 * the first argument is 1 for DLT_PRISM
4577 * or 2 for DLT_IEEE80211, and the second
4578 * argument is the channel on which to
4579 * run. If it takes one argument, it's
4580 * HostAP, and the argument is 2 for
4581 * DLT_IEEE80211 and 3 for DLT_PRISM.
4583 * If we see this, we don't quit, as this
4584 * might be a version of the hostap driver
4585 * that also supports "monitor_type".
4587 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4589 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4591 switch (priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) {
4594 montype
= MONITOR_PRISM
;
4599 montype
= MONITOR_ACX100
;
4612 * XXX - ipw3945? islism?
4618 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4619 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4620 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4621 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) == -1) {
4623 * We probably won't be able to set the mode, either.
4625 return PCAP_ERROR_RFMON_NOTSUP
;
4629 * Is it currently in monitor mode?
4631 if (ireq
.u
.mode
== IW_MODE_MONITOR
) {
4633 * Yes. Just leave things as they are.
4634 * We don't offer multiple link-layer types, as
4635 * changing the link-layer type out from under
4636 * somebody else capturing in monitor mode would
4637 * be considered rude.
4642 * No. We have to put the adapter into rfmon mode.
4646 * If we haven't already done so, arrange to have
4647 * "pcap_close_all()" called when we exit.
4649 if (!pcap_do_addexit(handle
)) {
4651 * "atexit()" failed; don't put the interface
4652 * in rfmon mode, just give up.
4654 return PCAP_ERROR_RFMON_NOTSUP
;
4658 * Save the old mode.
4660 handle
->md
.oldmode
= ireq
.u
.mode
;
4663 * Put the adapter in rfmon mode. How we do this depends
4664 * on whether we have a special private ioctl or not.
4666 if (montype
== MONITOR_PRISM
) {
4668 * We have the "monitor" private ioctl, but none of
4669 * the other private ioctls. Use this, and select
4672 * If it fails, just fall back on SIOCSIWMODE.
4674 memset(&ireq
, 0, sizeof ireq
);
4675 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4676 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4677 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4678 ireq
.u
.data
.length
= 1; /* 1 argument */
4679 args
[0] = 3; /* request Prism header */
4680 memcpy(ireq
.u
.name
, args
, IFNAMSIZ
);
4681 if (ioctl(sock_fd
, cmd
, &ireq
) != -1) {
4684 * Note that we have to put the old mode back
4685 * when we close the device.
4687 handle
->md
.must_do_on_close
|= MUST_CLEAR_RFMON
;
4690 * Add this to the list of pcaps to close
4693 pcap_add_to_pcaps_to_close(handle
);
4699 * Failure. Fall back on SIOCSIWMODE.
4704 * First, take the interface down if it's up; otherwise, we
4707 memset(&ifr
, 0, sizeof(ifr
));
4708 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4709 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
4710 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4711 "%s: Can't get flags: %s", device
, strerror(errno
));
4715 if (ifr
.ifr_flags
& IFF_UP
) {
4716 oldflags
= ifr
.ifr_flags
;
4717 ifr
.ifr_flags
&= ~IFF_UP
;
4718 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
4719 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4720 "%s: Can't set flags: %s", device
, strerror(errno
));
4726 * Then turn monitor mode on.
4728 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4729 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4730 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4731 ireq
.u
.mode
= IW_MODE_MONITOR
;
4732 if (ioctl(sock_fd
, SIOCSIWMODE
, &ireq
) == -1) {
4734 * Scientist, you've failed.
4735 * Bring the interface back up if we shut it down.
4737 ifr
.ifr_flags
= oldflags
;
4738 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
4739 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4740 "%s: Can't set flags: %s", device
, strerror(errno
));
4743 return PCAP_ERROR_RFMON_NOTSUP
;
4747 * XXX - airmon-ng does "iwconfig {if} key off" after setting
4748 * monitor mode and setting the channel, and then does
4753 * Now select the appropriate radio header.
4759 * We don't have any private ioctl to set the header.
4763 case MONITOR_HOSTAP
:
4765 * Try to select the radiotap header.
4767 memset(&ireq
, 0, sizeof ireq
);
4768 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4769 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4770 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4771 args
[0] = 3; /* request radiotap header */
4772 memcpy(ireq
.u
.name
, args
, sizeof (int));
4773 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
4774 break; /* success */
4777 * That failed. Try to select the AVS header.
4779 memset(&ireq
, 0, sizeof ireq
);
4780 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4781 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4782 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4783 args
[0] = 2; /* request AVS header */
4784 memcpy(ireq
.u
.name
, args
, sizeof (int));
4785 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
4786 break; /* success */
4789 * That failed. Try to select the Prism header.
4791 memset(&ireq
, 0, sizeof ireq
);
4792 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4793 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4794 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4795 args
[0] = 1; /* request Prism header */
4796 memcpy(ireq
.u
.name
, args
, sizeof (int));
4797 ioctl(sock_fd
, cmd
, &ireq
);
4802 * The private ioctl failed.
4806 case MONITOR_PRISM54
:
4808 * Select the Prism header.
4810 memset(&ireq
, 0, sizeof ireq
);
4811 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4812 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4813 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4814 args
[0] = 3; /* request Prism header */
4815 memcpy(ireq
.u
.name
, args
, sizeof (int));
4816 ioctl(sock_fd
, cmd
, &ireq
);
4819 case MONITOR_ACX100
:
4821 * Get the current channel.
4823 memset(&ireq
, 0, sizeof ireq
);
4824 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4825 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4826 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4827 if (ioctl(sock_fd
, SIOCGIWFREQ
, &ireq
) == -1) {
4828 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4829 "%s: SIOCGIWFREQ: %s", device
,
4830 pcap_strerror(errno
));
4833 channel
= ireq
.u
.freq
.m
;
4836 * Select the Prism header, and set the channel to the
4839 memset(&ireq
, 0, sizeof ireq
);
4840 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4841 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4842 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4843 args
[0] = 1; /* request Prism header */
4844 args
[1] = channel
; /* set channel */
4845 memcpy(ireq
.u
.name
, args
, 2*sizeof (int));
4846 ioctl(sock_fd
, cmd
, &ireq
);
4849 case MONITOR_RT2500
:
4851 * Disallow transmission - that turns on the
4854 memset(&ireq
, 0, sizeof ireq
);
4855 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4856 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4857 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4858 args
[0] = 0; /* disallow transmitting */
4859 memcpy(ireq
.u
.name
, args
, sizeof (int));
4860 ioctl(sock_fd
, cmd
, &ireq
);
4863 case MONITOR_RT2570
:
4865 * Force the Prism header.
4867 memset(&ireq
, 0, sizeof ireq
);
4868 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4869 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4870 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4871 args
[0] = 1; /* request Prism header */
4872 memcpy(ireq
.u
.name
, args
, sizeof (int));
4873 ioctl(sock_fd
, cmd
, &ireq
);
4878 * Force the Prism header.
4880 memset(&ireq
, 0, sizeof ireq
);
4881 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4882 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4883 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4884 ireq
.u
.data
.length
= 1; /* 1 argument */
4885 ireq
.u
.data
.pointer
= "1";
4886 ireq
.u
.data
.flags
= 0;
4887 ioctl(sock_fd
, cmd
, &ireq
);
4890 case MONITOR_RTL8XXX
:
4892 * Force the Prism header.
4894 memset(&ireq
, 0, sizeof ireq
);
4895 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4896 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4897 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4898 args
[0] = 1; /* request Prism header */
4899 memcpy(ireq
.u
.name
, args
, sizeof (int));
4900 ioctl(sock_fd
, cmd
, &ireq
);
4905 * Now bring the interface back up if we brought it down.
4907 if (oldflags
!= 0) {
4908 ifr
.ifr_flags
= oldflags
;
4909 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
4910 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4911 "%s: Can't set flags: %s", device
, strerror(errno
));
4914 * At least try to restore the old mode on the
4917 if (ioctl(handle
->fd
, SIOCSIWMODE
, &ireq
) == -1) {
4919 * Scientist, you've failed.
4922 "Can't restore interface wireless mode (SIOCSIWMODE failed: %s).\n"
4923 "Please adjust manually.\n",
4931 * Note that we have to put the old mode back when we
4934 handle
->md
.must_do_on_close
|= MUST_CLEAR_RFMON
;
4937 * Add this to the list of pcaps to close when we exit.
4939 pcap_add_to_pcaps_to_close(handle
);
4943 #endif /* IW_MODE_MONITOR */
4946 * Try various mechanisms to enter monitor mode.
4949 enter_rfmon_mode(pcap_t
*handle
, int sock_fd
, const char *device
)
4951 #if defined(HAVE_LIBNL) || defined(IW_MODE_MONITOR)
4956 ret
= enter_rfmon_mode_mac80211(handle
, sock_fd
, device
);
4958 return ret
; /* error attempting to do so */
4960 return 1; /* success */
4961 #endif /* HAVE_LIBNL */
4963 #ifdef IW_MODE_MONITOR
4964 ret
= enter_rfmon_mode_wext(handle
, sock_fd
, device
);
4966 return ret
; /* error attempting to do so */
4968 return 1; /* success */
4969 #endif /* IW_MODE_MONITOR */
4972 * Either none of the mechanisms we know about work or none
4973 * of those mechanisms are available, so we can't do monitor
4980 * Find out if we have any form of fragmentation/reassembly offloading.
4982 * We do so using SIOCETHTOOL checking for various types of offloading;
4983 * if SIOCETHTOOL isn't defined, or we don't have any #defines for any
4984 * of the types of offloading, there's nothing we can do to check, so
4985 * we just say "no, we don't".
4987 #if defined(SIOCETHTOOL) && (defined(ETHTOOL_GTSO) || defined(ETHTOOL_GUFO) || defined(ETHTOOL_GGSO) || defined(ETHTOOL_GFLAGS) || defined(ETHTOOL_GGRO))
4989 iface_ethtool_ioctl(pcap_t
*handle
, int cmd
, const char *cmdname
)
4992 struct ethtool_value eval
;
4994 memset(&ifr
, 0, sizeof(ifr
));
4995 strncpy(ifr
.ifr_name
, handle
->opt
.source
, sizeof(ifr
.ifr_name
));
4997 ifr
.ifr_data
= (caddr_t
)&eval
;
4998 if (ioctl(handle
->fd
, SIOCETHTOOL
, &ifr
) == -1) {
4999 if (errno
== EOPNOTSUPP
) {
5001 * OK, let's just return 0, which, in our
5002 * case, either means "no, what we're asking
5003 * about is not enabled" or "all the flags
5004 * are clear (i.e., nothing is enabled)".
5008 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5009 "%s: SIOETHTOOL(%s) ioctl failed: %s", handle
->opt
.source
,
5010 cmdname
, strerror(errno
));
5017 iface_get_offload(pcap_t
*handle
)
5022 ret
= iface_ethtool_ioctl(handle
, ETHTOOL_GTSO
, "ETHTOOL_GTSO");
5026 return 1; /* TCP segmentation offloading on */
5030 ret
= iface_ethtool_ioctl(handle
, ETHTOOL_GUFO
, "ETHTOOL_GUFO");
5034 return 1; /* UDP fragmentation offloading on */
5039 * XXX - will this cause large unsegmented packets to be
5040 * handed to PF_PACKET sockets on transmission? If not,
5041 * this need not be checked.
5043 ret
= iface_ethtool_ioctl(handle
, ETHTOOL_GGSO
, "ETHTOOL_GGSO");
5047 return 1; /* generic segmentation offloading on */
5050 #ifdef ETHTOOL_GFLAGS
5051 ret
= iface_ethtool_ioctl(handle
, ETHTOOL_GFLAGS
, "ETHTOOL_GFLAGS");
5054 if (ret
& ETH_FLAG_LRO
)
5055 return 1; /* large receive offloading on */
5060 * XXX - will this cause large reassembled packets to be
5061 * handed to PF_PACKET sockets on receipt? If not,
5062 * this need not be checked.
5064 ret
= iface_ethtool_ioctl(handle
, ETHTOOL_GGRO
, "ETHTOOL_GGRO");
5068 return 1; /* generic (large) receive offloading on */
5073 #else /* SIOCETHTOOL */
5075 iface_get_offload(pcap_t
*handle _U_
)
5078 * XXX - do we need to get this information if we don't
5079 * have the ethtool ioctls? If so, how do we do that?
5083 #endif /* SIOCETHTOOL */
5085 #endif /* HAVE_PF_PACKET_SOCKETS */
5087 /* ===== Functions to interface to the older kernels ================== */
5090 * Try to open a packet socket using the old kernel interface.
5091 * Returns 1 on success and a PCAP_ERROR_ value on an error.
5094 activate_old(pcap_t
*handle
)
5098 const char *device
= handle
->opt
.source
;
5099 struct utsname utsname
;
5102 /* Open the socket */
5104 handle
->fd
= socket(PF_INET
, SOCK_PACKET
, htons(ETH_P_ALL
));
5105 if (handle
->fd
== -1) {
5106 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5107 "socket: %s", pcap_strerror(errno
));
5108 if (errno
== EPERM
|| errno
== EACCES
) {
5110 * You don't have permission to open the
5113 return PCAP_ERROR_PERM_DENIED
;
5122 /* It worked - we are using the old interface */
5123 handle
->md
.sock_packet
= 1;
5125 /* ...which means we get the link-layer header. */
5126 handle
->md
.cooked
= 0;
5128 /* Bind to the given device */
5130 if (strcmp(device
, "any") == 0) {
5131 strncpy(handle
->errbuf
, "pcap_activate: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
5135 if (iface_bind_old(handle
->fd
, device
, handle
->errbuf
) == -1)
5139 * Try to get the link-layer type.
5141 arptype
= iface_get_arptype(handle
->fd
, device
, handle
->errbuf
);
5146 * Try to find the DLT_ type corresponding to that
5149 map_arphrd_to_dlt(handle
, arptype
, 0);
5150 if (handle
->linktype
== -1) {
5151 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5152 "unknown arptype %d", arptype
);
5156 /* Go to promisc mode if requested */
5158 if (handle
->opt
.promisc
) {
5159 memset(&ifr
, 0, sizeof(ifr
));
5160 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5161 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
5162 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5163 "SIOCGIFFLAGS: %s", pcap_strerror(errno
));
5166 if ((ifr
.ifr_flags
& IFF_PROMISC
) == 0) {
5168 * Promiscuous mode isn't currently on,
5169 * so turn it on, and remember that
5170 * we should turn it off when the
5175 * If we haven't already done so, arrange
5176 * to have "pcap_close_all()" called when
5179 if (!pcap_do_addexit(handle
)) {
5181 * "atexit()" failed; don't put
5182 * the interface in promiscuous
5183 * mode, just give up.
5188 ifr
.ifr_flags
|= IFF_PROMISC
;
5189 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
5190 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5192 pcap_strerror(errno
));
5195 handle
->md
.must_do_on_close
|= MUST_CLEAR_PROMISC
;
5198 * Add this to the list of pcaps
5199 * to close when we exit.
5201 pcap_add_to_pcaps_to_close(handle
);
5206 * Compute the buffer size.
5208 * We're using SOCK_PACKET, so this might be a 2.0[.x]
5209 * kernel, and might require special handling - check.
5211 if (uname(&utsname
) < 0 ||
5212 strncmp(utsname
.release
, "2.0", 3) == 0) {
5214 * Either we couldn't find out what kernel release
5215 * this is, or it's a 2.0[.x] kernel.
5217 * In the 2.0[.x] kernel, a "recvfrom()" on
5218 * a SOCK_PACKET socket, with MSG_TRUNC set, will
5219 * return the number of bytes read, so if we pass
5220 * a length based on the snapshot length, it'll
5221 * return the number of bytes from the packet
5222 * copied to userland, not the actual length
5225 * This means that, for example, the IP dissector
5226 * in tcpdump will get handed a packet length less
5227 * than the length in the IP header, and will
5228 * complain about "truncated-ip".
5230 * So we don't bother trying to copy from the
5231 * kernel only the bytes in which we're interested,
5232 * but instead copy them all, just as the older
5233 * versions of libpcap for Linux did.
5235 * The buffer therefore needs to be big enough to
5236 * hold the largest packet we can get from this
5237 * device. Unfortunately, we can't get the MRU
5238 * of the network; we can only get the MTU. The
5239 * MTU may be too small, in which case a packet larger
5240 * than the buffer size will be truncated *and* we
5241 * won't get the actual packet size.
5243 * However, if the snapshot length is larger than
5244 * the buffer size based on the MTU, we use the
5245 * snapshot length as the buffer size, instead;
5246 * this means that with a sufficiently large snapshot
5247 * length we won't artificially truncate packets
5248 * to the MTU-based size.
5250 * This mess just one of many problems with packet
5251 * capture on 2.0[.x] kernels; you really want a
5252 * 2.2[.x] or later kernel if you want packet capture
5255 mtu
= iface_get_mtu(handle
->fd
, device
, handle
->errbuf
);
5258 handle
->bufsize
= MAX_LINKHEADER_SIZE
+ mtu
;
5259 if (handle
->bufsize
< handle
->snapshot
)
5260 handle
->bufsize
= handle
->snapshot
;
5263 * This is a 2.2[.x] or later kernel.
5265 * We can safely pass "recvfrom()" a byte count
5266 * based on the snapshot length.
5268 handle
->bufsize
= handle
->snapshot
;
5272 * Default value for offset to align link-layer payload
5273 * on a 4-byte boundary.
5281 * Bind the socket associated with FD to the given device using the
5282 * interface of the old kernels.
5285 iface_bind_old(int fd
, const char *device
, char *ebuf
)
5287 struct sockaddr saddr
;
5289 socklen_t errlen
= sizeof(err
);
5291 memset(&saddr
, 0, sizeof(saddr
));
5292 strncpy(saddr
.sa_data
, device
, sizeof(saddr
.sa_data
));
5293 if (bind(fd
, &saddr
, sizeof(saddr
)) == -1) {
5294 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5295 "bind: %s", pcap_strerror(errno
));
5299 /* Any pending errors, e.g., network is down? */
5301 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
5302 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5303 "getsockopt: %s", pcap_strerror(errno
));
5308 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5309 "bind: %s", pcap_strerror(err
));
5317 /* ===== System calls available on all supported kernels ============== */
5320 * Query the kernel for the MTU of the given interface.
5323 iface_get_mtu(int fd
, const char *device
, char *ebuf
)
5328 return BIGGER_THAN_ALL_MTUS
;
5330 memset(&ifr
, 0, sizeof(ifr
));
5331 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5333 if (ioctl(fd
, SIOCGIFMTU
, &ifr
) == -1) {
5334 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5335 "SIOCGIFMTU: %s", pcap_strerror(errno
));
5343 * Get the hardware type of the given interface as ARPHRD_xxx constant.
5346 iface_get_arptype(int fd
, const char *device
, char *ebuf
)
5350 memset(&ifr
, 0, sizeof(ifr
));
5351 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5353 if (ioctl(fd
, SIOCGIFHWADDR
, &ifr
) == -1) {
5354 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5355 "SIOCGIFHWADDR: %s", pcap_strerror(errno
));
5356 if (errno
== ENODEV
) {
5360 return PCAP_ERROR_NO_SUCH_DEVICE
;
5365 return ifr
.ifr_hwaddr
.sa_family
;
5368 #ifdef SO_ATTACH_FILTER
5370 fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
, int is_mmapped
)
5374 register struct bpf_insn
*p
;
5379 * Make a copy of the filter, and modify that copy if
5382 prog_size
= sizeof(*handle
->fcode
.bf_insns
) * handle
->fcode
.bf_len
;
5383 len
= handle
->fcode
.bf_len
;
5384 f
= (struct bpf_insn
*)malloc(prog_size
);
5386 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5387 "malloc: %s", pcap_strerror(errno
));
5390 memcpy(f
, handle
->fcode
.bf_insns
, prog_size
);
5392 fcode
->filter
= (struct sock_filter
*) f
;
5394 for (i
= 0; i
< len
; ++i
) {
5397 * What type of instruction is this?
5399 switch (BPF_CLASS(p
->code
)) {
5403 * It's a return instruction; are we capturing
5404 * in memory-mapped mode?
5408 * No; is the snapshot length a constant,
5409 * rather than the contents of the
5412 if (BPF_MODE(p
->code
) == BPF_K
) {
5414 * Yes - if the value to be returned,
5415 * i.e. the snapshot length, is
5416 * anything other than 0, make it
5417 * 65535, so that the packet is
5418 * truncated by "recvfrom()",
5419 * not by the filter.
5421 * XXX - there's nothing we can
5422 * easily do if it's getting the
5423 * value from the accumulator; we'd
5424 * have to insert code to force
5425 * non-zero values to be 65535.
5436 * It's a load instruction; is it loading
5439 switch (BPF_MODE(p
->code
)) {
5445 * Yes; are we in cooked mode?
5447 if (handle
->md
.cooked
) {
5449 * Yes, so we need to fix this
5452 if (fix_offset(p
) < 0) {
5454 * We failed to do so.
5455 * Return 0, so our caller
5456 * knows to punt to userland.
5466 return 1; /* we succeeded */
5470 fix_offset(struct bpf_insn
*p
)
5473 * What's the offset?
5475 if (p
->k
>= SLL_HDR_LEN
) {
5477 * It's within the link-layer payload; that starts at an
5478 * offset of 0, as far as the kernel packet filter is
5479 * concerned, so subtract the length of the link-layer
5482 p
->k
-= SLL_HDR_LEN
;
5483 } else if (p
->k
== 0) {
5485 * It's the packet type field; map it to the special magic
5486 * kernel offset for that field.
5488 p
->k
= SKF_AD_OFF
+ SKF_AD_PKTTYPE
;
5489 } else if (p
->k
== 14) {
5491 * It's the protocol field; map it to the special magic
5492 * kernel offset for that field.
5494 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
5495 } else if ((bpf_int32
)(p
->k
) > 0) {
5497 * It's within the header, but it's not one of those
5498 * fields; we can't do that in the kernel, so punt
5507 set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
)
5509 int total_filter_on
= 0;
5515 * The socket filter code doesn't discard all packets queued
5516 * up on the socket when the filter is changed; this means
5517 * that packets that don't match the new filter may show up
5518 * after the new filter is put onto the socket, if those
5519 * packets haven't yet been read.
5521 * This means, for example, that if you do a tcpdump capture
5522 * with a filter, the first few packets in the capture might
5523 * be packets that wouldn't have passed the filter.
5525 * We therefore discard all packets queued up on the socket
5526 * when setting a kernel filter. (This isn't an issue for
5527 * userland filters, as the userland filtering is done after
5528 * packets are queued up.)
5530 * To flush those packets, we put the socket in read-only mode,
5531 * and read packets from the socket until there are no more to
5534 * In order to keep that from being an infinite loop - i.e.,
5535 * to keep more packets from arriving while we're draining
5536 * the queue - we put the "total filter", which is a filter
5537 * that rejects all packets, onto the socket before draining
5540 * This code deliberately ignores any errors, so that you may
5541 * get bogus packets if an error occurs, rather than having
5542 * the filtering done in userland even if it could have been
5543 * done in the kernel.
5545 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
5546 &total_fcode
, sizeof(total_fcode
)) == 0) {
5550 * Note that we've put the total filter onto the socket.
5552 total_filter_on
= 1;
5555 * Save the socket's current mode, and put it in
5556 * non-blocking mode; we drain it by reading packets
5557 * until we get an error (which is normally a
5558 * "nothing more to be read" error).
5560 save_mode
= fcntl(handle
->fd
, F_GETFL
, 0);
5561 if (save_mode
!= -1 &&
5562 fcntl(handle
->fd
, F_SETFL
, save_mode
| O_NONBLOCK
) >= 0) {
5563 while (recv(handle
->fd
, &drain
, sizeof drain
,
5567 fcntl(handle
->fd
, F_SETFL
, save_mode
);
5568 if (save_errno
!= EAGAIN
) {
5570 reset_kernel_filter(handle
);
5571 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5572 "recv: %s", pcap_strerror(save_errno
));
5579 * Now attach the new filter.
5581 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
5582 fcode
, sizeof(*fcode
));
5583 if (ret
== -1 && total_filter_on
) {
5585 * Well, we couldn't set that filter on the socket,
5586 * but we could set the total filter on the socket.
5588 * This could, for example, mean that the filter was
5589 * too big to put into the kernel, so we'll have to
5590 * filter in userland; in any case, we'll be doing
5591 * filtering in userland, so we need to remove the
5592 * total filter so we see packets.
5597 * XXX - if this fails, we're really screwed;
5598 * we have the total filter on the socket,
5599 * and it won't come off. What do we do then?
5601 reset_kernel_filter(handle
);
5609 reset_kernel_filter(pcap_t
*handle
)
5612 * setsockopt() barfs unless it get a dummy parameter.
5613 * valgrind whines unless the value is initialized,
5614 * as it has no idea that setsockopt() ignores its
5619 return setsockopt(handle
->fd
, SOL_SOCKET
, SO_DETACH_FILTER
,
5620 &dummy
, sizeof(dummy
));