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/stat.h>
131 #include <sys/socket.h>
132 #include <sys/ioctl.h>
133 #include <sys/utsname.h>
134 #include <sys/mman.h>
135 #include <linux/if.h>
136 #include <linux/if_packet.h>
137 #include <netinet/in.h>
138 #include <linux/if_ether.h>
139 #include <net/if_arp.h>
143 #include "pcap-int.h"
144 #include "pcap/sll.h"
145 #include "pcap/vlan.h"
148 * If PF_PACKET is defined, we can use {SOCK_RAW,SOCK_DGRAM}/PF_PACKET
149 * sockets rather than SOCK_PACKET sockets.
151 * To use them, we include <linux/if_packet.h> rather than
152 * <netpacket/packet.h>; we do so because
154 * some Linux distributions (e.g., Slackware 4.0) have 2.2 or
155 * later kernels and libc5, and don't provide a <netpacket/packet.h>
158 * not all versions of glibc2 have a <netpacket/packet.h> file
159 * that defines stuff needed for some of the 2.4-or-later-kernel
160 * features, so if the system has a 2.4 or later kernel, we
161 * still can't use those features.
163 * We're already including a number of other <linux/XXX.h> headers, and
164 * this code is Linux-specific (no other OS has PF_PACKET sockets as
165 * a raw packet capture mechanism), so it's not as if you gain any
166 * useful portability by using <netpacket/packet.h>
168 * XXX - should we just include <linux/if_packet.h> even if PF_PACKET
169 * isn't defined? It only defines one data structure in 2.0.x, so
170 * it shouldn't cause any problems.
173 # include <linux/if_packet.h>
176 * On at least some Linux distributions (for example, Red Hat 5.2),
177 * there's no <netpacket/packet.h> file, but PF_PACKET is defined if
178 * you include <sys/socket.h>, but <linux/if_packet.h> doesn't define
179 * any of the PF_PACKET stuff such as "struct sockaddr_ll" or any of
180 * the PACKET_xxx stuff.
182 * So we check whether PACKET_HOST is defined, and assume that we have
183 * PF_PACKET sockets only if it is defined.
186 # define HAVE_PF_PACKET_SOCKETS
187 # ifdef PACKET_AUXDATA
188 # define HAVE_PACKET_AUXDATA
189 # endif /* PACKET_AUXDATA */
190 # endif /* PACKET_HOST */
193 /* check for memory mapped access avaibility. We assume every needed
194 * struct is defined if the macro TPACKET_HDRLEN is defined, because it
195 * uses many ring related structs and macros */
196 # ifdef TPACKET_HDRLEN
197 # define HAVE_PACKET_RING
198 # ifdef TPACKET2_HDRLEN
199 # define HAVE_TPACKET2
201 # define TPACKET_V1 0
202 # endif /* TPACKET2_HDRLEN */
203 # endif /* TPACKET_HDRLEN */
204 #endif /* PF_PACKET */
206 #ifdef SO_ATTACH_FILTER
207 #include <linux/types.h>
208 #include <linux/filter.h>
212 * We need linux/sockios.h if we have linux/net_tstamp.h (for time stamp
213 * specification) or linux/ethtool.h (for ethtool ioctls to get offloading
216 #if defined(HAVE_LINUX_NET_TSTAMP_H) || defined(HAVE_LINUX_ETHTOOL_H)
217 #include <linux/sockios.h>
220 #ifdef HAVE_LINUX_NET_TSTAMP_H
221 #include <linux/net_tstamp.h>
225 * Got Wireless Extensions?
227 #ifdef HAVE_LINUX_WIRELESS_H
228 #include <linux/wireless.h>
229 #endif /* HAVE_LINUX_WIRELESS_H */
235 #include <linux/nl80211.h>
237 #include <netlink/genl/genl.h>
238 #include <netlink/genl/family.h>
239 #include <netlink/genl/ctrl.h>
240 #include <netlink/msg.h>
241 #include <netlink/attr.h>
242 #endif /* HAVE_LIBNL */
245 * Got ethtool support?
247 #ifdef HAVE_LINUX_ETHTOOL_H
248 #include <linux/ethtool.h>
251 #ifndef HAVE_SOCKLEN_T
252 typedef int socklen_t
;
257 * This is being compiled on a system that lacks MSG_TRUNC; define it
258 * with the value it has in the 2.2 and later kernels, so that, on
259 * those kernels, when we pass it in the flags argument to "recvfrom()"
260 * we're passing the right value and thus get the MSG_TRUNC behavior
261 * we want. (We don't get that behavior on 2.0[.x] kernels, because
262 * they didn't support MSG_TRUNC.)
264 #define MSG_TRUNC 0x20
269 * This is being compiled on a system that lacks SOL_PACKET; define it
270 * with the value it has in the 2.2 and later kernels, so that we can
271 * set promiscuous mode in the good modern way rather than the old
272 * 2.0-kernel crappy way.
274 #define SOL_PACKET 263
277 #define MAX_LINKHEADER_SIZE 256
280 * When capturing on all interfaces we use this as the buffer size.
281 * Should be bigger then all MTUs that occur in real life.
282 * 64kB should be enough for now.
284 #define BIGGER_THAN_ALL_MTUS (64*1024)
287 * Private data for capturing on Linux SOCK_PACKET or PF_PACKET sockets.
290 u_int packets_read
; /* count of packets read with recvfrom() */
291 long proc_dropped
; /* packets reported dropped by /proc/net/dev */
292 struct pcap_stat stat
;
294 char *device
; /* device name */
295 int filtering_in_kernel
; /* using kernel filter */
296 int must_do_on_close
; /* stuff we must do when we close */
297 int timeout
; /* timeout for buffering */
298 int sock_packet
; /* using Linux 2.0 compatible interface */
299 int cooked
; /* using SOCK_DGRAM rather than SOCK_RAW */
300 int ifindex
; /* interface index of device we're bound to */
301 int lo_ifindex
; /* interface index of the loopback device */
302 bpf_u_int32 oldmode
; /* mode to restore when turning monitor mode off */
303 char *mondevice
; /* mac80211 monitor device we created */
304 u_char
*mmapbuf
; /* memory-mapped region pointer */
305 size_t mmapbuflen
; /* size of region */
306 int vlan_offset
; /* offset at which to insert vlan tags; if -1, don't insert */
307 u_int tp_version
; /* version of tpacket_hdr for mmaped ring */
308 u_int tp_hdrlen
; /* hdrlen of tpacket_hdr for mmaped ring */
309 u_char
*oneshot_buffer
; /* buffer for copy of packet */
313 * Stuff to do when we close.
315 #define MUST_CLEAR_PROMISC 0x00000001 /* clear promiscuous mode */
316 #define MUST_CLEAR_RFMON 0x00000002 /* clear rfmon (monitor) mode */
317 #define MUST_DELETE_MONIF 0x00000004 /* delete monitor-mode interface */
320 * Prototypes for internal functions and methods.
322 static void map_arphrd_to_dlt(pcap_t
*, int, int);
323 #ifdef HAVE_PF_PACKET_SOCKETS
324 static short int map_packet_type_to_sll_type(short int);
326 static int pcap_activate_linux(pcap_t
*);
327 static int activate_old(pcap_t
*);
328 static int activate_new(pcap_t
*);
329 static int activate_mmap(pcap_t
*, int *);
330 static int pcap_can_set_rfmon_linux(pcap_t
*);
331 static int pcap_read_linux(pcap_t
*, int, pcap_handler
, u_char
*);
332 static int pcap_read_packet(pcap_t
*, pcap_handler
, u_char
*);
333 static int pcap_inject_linux(pcap_t
*, const void *, size_t);
334 static int pcap_stats_linux(pcap_t
*, struct pcap_stat
*);
335 static int pcap_setfilter_linux(pcap_t
*, struct bpf_program
*);
336 static int pcap_setdirection_linux(pcap_t
*, pcap_direction_t
);
337 static int pcap_set_datalink_linux(pcap_t
*, int);
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_interface(const char *device
, char *ebuf
)
398 handle
= pcap_create_common(device
, ebuf
, sizeof (struct pcap_linux
));
402 handle
->activate_op
= pcap_activate_linux
;
403 handle
->can_set_rfmon_op
= pcap_can_set_rfmon_linux
;
404 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
406 * We claim that we support:
408 * software time stamps, with no details about their precision;
409 * hardware time stamps, synced to the host time;
410 * hardware time stamps, not synced to the host time.
412 * XXX - we can't ask a device whether it supports
413 * hardware time stamps, so we just claim all devices do.
415 handle
->tstamp_type_count
= 3;
416 handle
->tstamp_type_list
= malloc(3 * sizeof(u_int
));
417 if (handle
->tstamp_type_list
== NULL
) {
421 handle
->tstamp_type_list
[0] = PCAP_TSTAMP_HOST
;
422 handle
->tstamp_type_list
[1] = PCAP_TSTAMP_ADAPTER
;
423 handle
->tstamp_type_list
[2] = PCAP_TSTAMP_ADAPTER_UNSYNCED
;
431 * If interface {if} is a mac80211 driver, the file
432 * /sys/class/net/{if}/phy80211 is a symlink to
433 * /sys/class/ieee80211/{phydev}, for some {phydev}.
435 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
436 * least, has a "wmaster0" device and a "wlan0" device; the
437 * latter is the one with the IP address. Both show up in
438 * "tcpdump -D" output. Capturing on the wmaster0 device
439 * captures with 802.11 headers.
441 * airmon-ng searches through /sys/class/net for devices named
442 * monN, starting with mon0; as soon as one *doesn't* exist,
443 * it chooses that as the monitor device name. If the "iw"
444 * command exists, it does "iw dev {if} interface add {monif}
445 * type monitor", where {monif} is the monitor device. It
446 * then (sigh) sleeps .1 second, and then configures the
447 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
448 * is a file, it writes {mondev}, without a newline, to that file,
449 * and again (sigh) sleeps .1 second, and then iwconfig's that
450 * device into monitor mode and configures it up. Otherwise,
451 * you can't do monitor mode.
453 * All these devices are "glued" together by having the
454 * /sys/class/net/{device}/phy80211 links pointing to the same
455 * place, so, given a wmaster, wlan, or mon device, you can
456 * find the other devices by looking for devices with
457 * the same phy80211 link.
459 * To turn monitor mode off, delete the monitor interface,
460 * either with "iw dev {monif} interface del" or by sending
461 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
463 * Note: if you try to create a monitor device named "monN", and
464 * there's already a "monN" device, it fails, as least with
465 * the netlink interface (which is what iw uses), with a return
466 * value of -ENFILE. (Return values are negative errnos.) We
467 * could probably use that to find an unused device.
469 * Yes, you can have multiple monitor devices for a given
474 * Is this a mac80211 device? If so, fill in the physical device path and
475 * return 1; if not, return 0. On an error, fill in handle->errbuf and
479 get_mac80211_phydev(pcap_t
*handle
, const char *device
, char *phydev_path
,
480 size_t phydev_max_pathlen
)
486 * Generate the path string for the symlink to the physical device.
488 if (asprintf(&pathstr
, "/sys/class/net/%s/phy80211", device
) == -1) {
489 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
490 "%s: Can't generate path name string for /sys/class/net device",
494 bytes_read
= readlink(pathstr
, phydev_path
, phydev_max_pathlen
);
495 if (bytes_read
== -1) {
496 if (errno
== ENOENT
|| errno
== EINVAL
) {
498 * Doesn't exist, or not a symlink; assume that
499 * means it's not a mac80211 device.
504 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
505 "%s: Can't readlink %s: %s", device
, pathstr
,
511 phydev_path
[bytes_read
] = '\0';
515 #ifdef HAVE_LIBNL_SOCKETS
516 #define get_nl_errmsg nl_geterror
518 /* libnl 2.x compatibility code */
520 #define nl_sock nl_handle
522 static inline struct nl_handle
*
523 nl_socket_alloc(void)
525 return nl_handle_alloc();
529 nl_socket_free(struct nl_handle
*h
)
531 nl_handle_destroy(h
);
534 #define get_nl_errmsg strerror
537 __genl_ctrl_alloc_cache(struct nl_handle
*h
, struct nl_cache
**cache
)
539 struct nl_cache
*tmp
= genl_ctrl_alloc_cache(h
);
545 #define genl_ctrl_alloc_cache __genl_ctrl_alloc_cache
546 #endif /* !HAVE_LIBNL_SOCKETS */
548 struct nl80211_state
{
549 struct nl_sock
*nl_sock
;
550 struct nl_cache
*nl_cache
;
551 struct genl_family
*nl80211
;
555 nl80211_init(pcap_t
*handle
, struct nl80211_state
*state
, const char *device
)
559 state
->nl_sock
= nl_socket_alloc();
560 if (!state
->nl_sock
) {
561 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
562 "%s: failed to allocate netlink handle", device
);
566 if (genl_connect(state
->nl_sock
)) {
567 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
568 "%s: failed to connect to generic netlink", device
);
569 goto out_handle_destroy
;
572 err
= genl_ctrl_alloc_cache(state
->nl_sock
, &state
->nl_cache
);
574 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
575 "%s: failed to allocate generic netlink cache: %s",
576 device
, get_nl_errmsg(-err
));
577 goto out_handle_destroy
;
580 state
->nl80211
= genl_ctrl_search_by_name(state
->nl_cache
, "nl80211");
581 if (!state
->nl80211
) {
582 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
583 "%s: nl80211 not found", device
);
590 nl_cache_free(state
->nl_cache
);
592 nl_socket_free(state
->nl_sock
);
597 nl80211_cleanup(struct nl80211_state
*state
)
599 genl_family_put(state
->nl80211
);
600 nl_cache_free(state
->nl_cache
);
601 nl_socket_free(state
->nl_sock
);
605 add_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
606 const char *device
, const char *mondevice
)
612 ifindex
= iface_get_id(sock_fd
, device
, handle
->errbuf
);
618 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
619 "%s: failed to allocate netlink msg", device
);
623 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
624 0, NL80211_CMD_NEW_INTERFACE
, 0);
625 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
626 NLA_PUT_STRING(msg
, NL80211_ATTR_IFNAME
, mondevice
);
627 NLA_PUT_U32(msg
, NL80211_ATTR_IFTYPE
, NL80211_IFTYPE_MONITOR
);
629 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
631 #if defined HAVE_LIBNL_NLE
632 if (err
== -NLE_FAILURE
) {
634 if (err
== -ENFILE
) {
637 * Device not available; our caller should just
638 * keep trying. (libnl 2.x maps ENFILE to
639 * NLE_FAILURE; it can also map other errors
640 * to that, but there's not much we can do
647 * Real failure, not just "that device is not
650 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
651 "%s: nl_send_auto_complete failed adding %s interface: %s",
652 device
, mondevice
, get_nl_errmsg(-err
));
657 err
= nl_wait_for_ack(state
->nl_sock
);
659 #if defined HAVE_LIBNL_NLE
660 if (err
== -NLE_FAILURE
) {
662 if (err
== -ENFILE
) {
665 * Device not available; our caller should just
666 * keep trying. (libnl 2.x maps ENFILE to
667 * NLE_FAILURE; it can also map other errors
668 * to that, but there's not much we can do
675 * Real failure, not just "that device is not
678 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
679 "%s: nl_wait_for_ack failed adding %s interface: %s",
680 device
, mondevice
, get_nl_errmsg(-err
));
693 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
694 "%s: nl_put failed adding %s interface",
701 del_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
702 const char *device
, const char *mondevice
)
708 ifindex
= iface_get_id(sock_fd
, mondevice
, handle
->errbuf
);
714 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
715 "%s: failed to allocate netlink msg", device
);
719 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
720 0, NL80211_CMD_DEL_INTERFACE
, 0);
721 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
723 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
725 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
726 "%s: nl_send_auto_complete failed deleting %s interface: %s",
727 device
, mondevice
, get_nl_errmsg(-err
));
731 err
= nl_wait_for_ack(state
->nl_sock
);
733 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
734 "%s: nl_wait_for_ack failed adding %s interface: %s",
735 device
, mondevice
, get_nl_errmsg(-err
));
747 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
748 "%s: nl_put failed deleting %s interface",
755 enter_rfmon_mode_mac80211(pcap_t
*handle
, int sock_fd
, const char *device
)
757 struct pcap_linux
*handlep
= handle
->private;
759 char phydev_path
[PATH_MAX
+1];
760 struct nl80211_state nlstate
;
765 * Is this a mac80211 device?
767 ret
= get_mac80211_phydev(handle
, device
, phydev_path
, PATH_MAX
);
769 return ret
; /* error */
771 return 0; /* no error, but not mac80211 device */
774 * XXX - is this already a monN device?
776 * Is that determined by old Wireless Extensions ioctls?
780 * OK, it's apparently a mac80211 device.
781 * Try to find an unused monN device for it.
783 ret
= nl80211_init(handle
, &nlstate
, device
);
786 for (n
= 0; n
< UINT_MAX
; n
++) {
790 char mondevice
[3+10+1]; /* mon{UINT_MAX}\0 */
792 snprintf(mondevice
, sizeof mondevice
, "mon%u", n
);
793 ret
= add_mon_if(handle
, sock_fd
, &nlstate
, device
, mondevice
);
795 handlep
->mondevice
= strdup(mondevice
);
800 * Hard failure. Just return ret; handle->errbuf
801 * has already been set.
803 nl80211_cleanup(&nlstate
);
808 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
809 "%s: No free monN interfaces", device
);
810 nl80211_cleanup(&nlstate
);
817 * Sleep for .1 seconds.
820 delay
.tv_nsec
= 500000000;
821 nanosleep(&delay
, NULL
);
825 * If we haven't already done so, arrange to have
826 * "pcap_close_all()" called when we exit.
828 if (!pcap_do_addexit(handle
)) {
830 * "atexit()" failed; don't put the interface
831 * in rfmon mode, just give up.
833 return PCAP_ERROR_RFMON_NOTSUP
;
837 * Now configure the monitor interface up.
839 memset(&ifr
, 0, sizeof(ifr
));
840 strncpy(ifr
.ifr_name
, handlep
->mondevice
, sizeof(ifr
.ifr_name
));
841 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
842 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
843 "%s: Can't get flags for %s: %s", device
,
844 handlep
->mondevice
, strerror(errno
));
845 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
847 nl80211_cleanup(&nlstate
);
850 ifr
.ifr_flags
|= IFF_UP
|IFF_RUNNING
;
851 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
852 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
853 "%s: Can't set flags for %s: %s", device
,
854 handlep
->mondevice
, strerror(errno
));
855 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
857 nl80211_cleanup(&nlstate
);
862 * Success. Clean up the libnl state.
864 nl80211_cleanup(&nlstate
);
867 * Note that we have to delete the monitor device when we close
870 handlep
->must_do_on_close
|= MUST_DELETE_MONIF
;
873 * Add this to the list of pcaps to close when we exit.
875 pcap_add_to_pcaps_to_close(handle
);
879 #endif /* HAVE_LIBNL */
882 pcap_can_set_rfmon_linux(pcap_t
*handle
)
885 char phydev_path
[PATH_MAX
+1];
888 #ifdef IW_MODE_MONITOR
893 if (strcmp(handle
->opt
.source
, "any") == 0) {
895 * Monitor mode makes no sense on the "any" device.
902 * Bleah. There doesn't seem to be a way to ask a mac80211
903 * device, through libnl, whether it supports monitor mode;
904 * we'll just check whether the device appears to be a
905 * mac80211 device and, if so, assume the device supports
908 * wmaster devices don't appear to support the Wireless
909 * Extensions, but we can create a mon device for a
910 * wmaster device, so we don't bother checking whether
911 * a mac80211 device supports the Wireless Extensions.
913 ret
= get_mac80211_phydev(handle
, handle
->opt
.source
, phydev_path
,
916 return ret
; /* error */
918 return 1; /* mac80211 device */
921 #ifdef IW_MODE_MONITOR
923 * Bleah. There doesn't appear to be an ioctl to use to ask
924 * whether a device supports monitor mode; we'll just do
925 * SIOCGIWMODE and, if it succeeds, assume the device supports
928 * Open a socket on which to attempt to get the mode.
929 * (We assume that if we have Wireless Extensions support
930 * we also have PF_PACKET support.)
932 sock_fd
= socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
));
934 (void)snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
935 "socket: %s", pcap_strerror(errno
));
940 * Attempt to get the current mode.
942 strncpy(ireq
.ifr_ifrn
.ifrn_name
, handle
->opt
.source
,
943 sizeof ireq
.ifr_ifrn
.ifrn_name
);
944 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
945 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) != -1) {
947 * Well, we got the mode; assume we can set it.
952 if (errno
== ENODEV
) {
953 /* The device doesn't even exist. */
954 (void)snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
955 "SIOCGIWMODE failed: %s", pcap_strerror(errno
));
957 return PCAP_ERROR_NO_SUCH_DEVICE
;
965 * Grabs the number of dropped packets by the interface from /proc/net/dev.
967 * XXX - what about /sys/class/net/{interface name}/rx_*? There are
968 * individual devices giving, in ASCII, various rx_ and tx_ statistics.
970 * Or can we get them in binary form from netlink?
973 linux_if_drops(const char * if_name
)
978 int field_to_convert
= 3, if_name_sz
= strlen(if_name
);
979 long int dropped_pkts
= 0;
981 file
= fopen("/proc/net/dev", "r");
985 while (!dropped_pkts
&& fgets( buffer
, sizeof(buffer
), file
))
987 /* search for 'bytes' -- if its in there, then
988 that means we need to grab the fourth field. otherwise
989 grab the third field. */
990 if (field_to_convert
!= 4 && strstr(buffer
, "bytes"))
992 field_to_convert
= 4;
996 /* find iface and make sure it actually matches -- space before the name and : after it */
997 if ((bufptr
= strstr(buffer
, if_name
)) &&
998 (bufptr
== buffer
|| *(bufptr
-1) == ' ') &&
999 *(bufptr
+ if_name_sz
) == ':')
1001 bufptr
= bufptr
+ if_name_sz
+ 1;
1003 /* grab the nth field from it */
1004 while( --field_to_convert
&& *bufptr
!= '\0')
1006 while (*bufptr
!= '\0' && *(bufptr
++) == ' ');
1007 while (*bufptr
!= '\0' && *(bufptr
++) != ' ');
1010 /* get rid of any final spaces */
1011 while (*bufptr
!= '\0' && *bufptr
== ' ') bufptr
++;
1013 if (*bufptr
!= '\0')
1014 dropped_pkts
= strtol(bufptr
, NULL
, 10);
1021 return dropped_pkts
;
1026 * With older kernels promiscuous mode is kind of interesting because we
1027 * have to reset the interface before exiting. The problem can't really
1028 * be solved without some daemon taking care of managing usage counts.
1029 * If we put the interface into promiscuous mode, we set a flag indicating
1030 * that we must take it out of that mode when the interface is closed,
1031 * and, when closing the interface, if that flag is set we take it out
1032 * of promiscuous mode.
1034 * Even with newer kernels, we have the same issue with rfmon mode.
1037 static void pcap_cleanup_linux( pcap_t
*handle
)
1039 struct pcap_linux
*handlep
= handle
->private;
1042 struct nl80211_state nlstate
;
1044 #endif /* HAVE_LIBNL */
1045 #ifdef IW_MODE_MONITOR
1048 #endif /* IW_MODE_MONITOR */
1050 if (handlep
->must_do_on_close
!= 0) {
1052 * There's something we have to do when closing this
1055 if (handlep
->must_do_on_close
& MUST_CLEAR_PROMISC
) {
1057 * We put the interface into promiscuous mode;
1058 * take it out of promiscuous mode.
1060 * XXX - if somebody else wants it in promiscuous
1061 * mode, this code cannot know that, so it'll take
1062 * it out of promiscuous mode. That's not fixable
1063 * in 2.0[.x] kernels.
1065 memset(&ifr
, 0, sizeof(ifr
));
1066 strncpy(ifr
.ifr_name
, handlep
->device
,
1067 sizeof(ifr
.ifr_name
));
1068 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
1070 "Can't restore interface %s flags (SIOCGIFFLAGS failed: %s).\n"
1071 "Please adjust manually.\n"
1072 "Hint: This can't happen with Linux >= 2.2.0.\n",
1073 handlep
->device
, strerror(errno
));
1075 if (ifr
.ifr_flags
& IFF_PROMISC
) {
1077 * Promiscuous mode is currently on;
1080 ifr
.ifr_flags
&= ~IFF_PROMISC
;
1081 if (ioctl(handle
->fd
, SIOCSIFFLAGS
,
1084 "Can't restore interface %s flags (SIOCSIFFLAGS failed: %s).\n"
1085 "Please adjust manually.\n"
1086 "Hint: This can't happen with Linux >= 2.2.0.\n",
1095 if (handlep
->must_do_on_close
& MUST_DELETE_MONIF
) {
1096 ret
= nl80211_init(handle
, &nlstate
, handlep
->device
);
1098 ret
= del_mon_if(handle
, handle
->fd
, &nlstate
,
1099 handlep
->device
, handlep
->mondevice
);
1100 nl80211_cleanup(&nlstate
);
1104 "Can't delete monitor interface %s (%s).\n"
1105 "Please delete manually.\n",
1106 handlep
->mondevice
, handle
->errbuf
);
1109 #endif /* HAVE_LIBNL */
1111 #ifdef IW_MODE_MONITOR
1112 if (handlep
->must_do_on_close
& MUST_CLEAR_RFMON
) {
1114 * We put the interface into rfmon mode;
1115 * take it out of rfmon mode.
1117 * XXX - if somebody else wants it in rfmon
1118 * mode, this code cannot know that, so it'll take
1119 * it out of rfmon mode.
1123 * First, take the interface down if it's up;
1124 * otherwise, we might get EBUSY.
1125 * If we get errors, just drive on and print
1126 * a warning if we can't restore the mode.
1129 memset(&ifr
, 0, sizeof(ifr
));
1130 strncpy(ifr
.ifr_name
, handlep
->device
,
1131 sizeof(ifr
.ifr_name
));
1132 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) != -1) {
1133 if (ifr
.ifr_flags
& IFF_UP
) {
1134 oldflags
= ifr
.ifr_flags
;
1135 ifr
.ifr_flags
&= ~IFF_UP
;
1136 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1)
1137 oldflags
= 0; /* didn't set, don't restore */
1142 * Now restore the mode.
1144 strncpy(ireq
.ifr_ifrn
.ifrn_name
, handlep
->device
,
1145 sizeof ireq
.ifr_ifrn
.ifrn_name
);
1146 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1]
1148 ireq
.u
.mode
= handlep
->oldmode
;
1149 if (ioctl(handle
->fd
, SIOCSIWMODE
, &ireq
) == -1) {
1151 * Scientist, you've failed.
1154 "Can't restore interface %s wireless mode (SIOCSIWMODE failed: %s).\n"
1155 "Please adjust manually.\n",
1156 handlep
->device
, strerror(errno
));
1160 * Now bring the interface back up if we brought
1163 if (oldflags
!= 0) {
1164 ifr
.ifr_flags
= oldflags
;
1165 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
1167 "Can't bring interface %s back up (SIOCSIFFLAGS failed: %s).\n"
1168 "Please adjust manually.\n",
1169 handlep
->device
, strerror(errno
));
1173 #endif /* IW_MODE_MONITOR */
1176 * Take this pcap out of the list of pcaps for which we
1177 * have to take the interface out of some mode.
1179 pcap_remove_from_pcaps_to_close(handle
);
1182 if (handlep
->mondevice
!= NULL
) {
1183 free(handlep
->mondevice
);
1184 handlep
->mondevice
= NULL
;
1186 if (handlep
->device
!= NULL
) {
1187 free(handlep
->device
);
1188 handlep
->device
= NULL
;
1190 pcap_cleanup_live_common(handle
);
1194 * Get a handle for a live capture from the given device. You can
1195 * pass NULL as device to get all packages (without link level
1196 * information of course). If you pass 1 as promisc the interface
1197 * will be set to promiscous mode (XXX: I think this usage should
1198 * be deprecated and functions be added to select that later allow
1199 * modification of that values -- Torsten).
1202 pcap_activate_linux(pcap_t
*handle
)
1204 struct pcap_linux
*handlep
= handle
->private;
1208 device
= handle
->opt
.source
;
1210 handle
->inject_op
= pcap_inject_linux
;
1211 handle
->setfilter_op
= pcap_setfilter_linux
;
1212 handle
->setdirection_op
= pcap_setdirection_linux
;
1213 handle
->set_datalink_op
= pcap_set_datalink_linux
;
1214 handle
->getnonblock_op
= pcap_getnonblock_fd
;
1215 handle
->setnonblock_op
= pcap_setnonblock_fd
;
1216 handle
->cleanup_op
= pcap_cleanup_linux
;
1217 handle
->read_op
= pcap_read_linux
;
1218 handle
->stats_op
= pcap_stats_linux
;
1221 * The "any" device is a special device which causes us not
1222 * to bind to a particular device and thus to look at all
1225 if (strcmp(device
, "any") == 0) {
1226 if (handle
->opt
.promisc
) {
1227 handle
->opt
.promisc
= 0;
1228 /* Just a warning. */
1229 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1230 "Promiscuous mode not supported on the \"any\" device");
1231 status
= PCAP_WARNING_PROMISC_NOTSUP
;
1235 handlep
->device
= strdup(device
);
1236 if (handlep
->device
== NULL
) {
1237 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "strdup: %s",
1238 pcap_strerror(errno
) );
1242 /* copy timeout value */
1243 handlep
->timeout
= handle
->opt
.timeout
;
1246 * If we're in promiscuous mode, then we probably want
1247 * to see when the interface drops packets too, so get an
1248 * initial count from /proc/net/dev
1250 if (handle
->opt
.promisc
)
1251 handlep
->proc_dropped
= linux_if_drops(handlep
->device
);
1254 * Current Linux kernels use the protocol family PF_PACKET to
1255 * allow direct access to all packets on the network while
1256 * older kernels had a special socket type SOCK_PACKET to
1257 * implement this feature.
1258 * While this old implementation is kind of obsolete we need
1259 * to be compatible with older kernels for a while so we are
1260 * trying both methods with the newer method preferred.
1262 status
= activate_new(handle
);
1265 * Fatal error with the new way; just fail.
1266 * status has the error return; if it's PCAP_ERROR,
1267 * handle->errbuf has been set appropriately.
1274 * Try to use memory-mapped access.
1276 switch (activate_mmap(handle
, &status
)) {
1280 * We succeeded. status has been
1281 * set to the status to return,
1282 * which might be 0, or might be
1283 * a PCAP_WARNING_ value.
1289 * Kernel doesn't support it - just continue
1290 * with non-memory-mapped access.
1296 * We failed to set up to use it, or the kernel
1297 * supports it, but we failed to enable it.
1298 * status has been set to the error status to
1299 * return and, if it's PCAP_ERROR, handle->errbuf
1300 * contains the error message.
1305 else if (status
== 0) {
1306 /* Non-fatal error; try old way */
1307 if ((status
= activate_old(handle
)) != 1) {
1309 * Both methods to open the packet socket failed.
1310 * Tidy up and report our failure (handle->errbuf
1311 * is expected to be set by the functions above).
1318 * We set up the socket, but not with memory-mapped access.
1321 if (handle
->opt
.buffer_size
!= 0) {
1323 * Set the socket buffer size to the specified value.
1325 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_RCVBUF
,
1326 &handle
->opt
.buffer_size
,
1327 sizeof(handle
->opt
.buffer_size
)) == -1) {
1328 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1329 "SO_RCVBUF: %s", pcap_strerror(errno
));
1330 status
= PCAP_ERROR
;
1335 /* Allocate the buffer */
1337 handle
->buffer
= malloc(handle
->bufsize
+ handle
->offset
);
1338 if (!handle
->buffer
) {
1339 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1340 "malloc: %s", pcap_strerror(errno
));
1341 status
= PCAP_ERROR
;
1346 * "handle->fd" is a socket, so "select()" and "poll()"
1347 * should work on it.
1349 handle
->selectable_fd
= handle
->fd
;
1354 pcap_cleanup_linux(handle
);
1359 * Read at most max_packets from the capture stream and call the callback
1360 * for each of them. Returns the number of packets handled or -1 if an
1364 pcap_read_linux(pcap_t
*handle
, int max_packets
, pcap_handler callback
, u_char
*user
)
1367 * Currently, on Linux only one packet is delivered per read,
1370 return pcap_read_packet(handle
, callback
, user
);
1374 pcap_set_datalink_linux(pcap_t
*handle
, int dlt
)
1376 handle
->linktype
= dlt
;
1381 * Read a packet from the socket calling the handler provided by
1382 * the user. Returns the number of packets received or -1 if an
1386 pcap_read_packet(pcap_t
*handle
, pcap_handler callback
, u_char
*userdata
)
1388 struct pcap_linux
*handlep
= handle
->private;
1391 #ifdef HAVE_PF_PACKET_SOCKETS
1392 struct sockaddr_ll from
;
1393 struct sll_header
*hdrp
;
1395 struct sockaddr from
;
1397 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1400 struct cmsghdr
*cmsg
;
1402 struct cmsghdr cmsg
;
1403 char buf
[CMSG_SPACE(sizeof(struct tpacket_auxdata
))];
1405 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1407 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1408 int packet_len
, caplen
;
1409 struct pcap_pkthdr pcap_header
;
1411 #ifdef HAVE_PF_PACKET_SOCKETS
1413 * If this is a cooked device, leave extra room for a
1414 * fake packet header.
1416 if (handlep
->cooked
)
1417 offset
= SLL_HDR_LEN
;
1422 * This system doesn't have PF_PACKET sockets, so it doesn't
1423 * support cooked devices.
1429 * Receive a single packet from the kernel.
1430 * We ignore EINTR, as that might just be due to a signal
1431 * being delivered - if the signal should interrupt the
1432 * loop, the signal handler should call pcap_breakloop()
1433 * to set handle->break_loop (we ignore it on other
1434 * platforms as well).
1435 * We also ignore ENETDOWN, so that we can continue to
1436 * capture traffic if the interface goes down and comes
1437 * back up again; comments in the kernel indicate that
1438 * we'll just block waiting for packets if we try to
1439 * receive from a socket that delivered ENETDOWN, and,
1440 * if we're using a memory-mapped buffer, we won't even
1441 * get notified of "network down" events.
1443 bp
= handle
->buffer
+ handle
->offset
;
1445 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1446 msg
.msg_name
= &from
;
1447 msg
.msg_namelen
= sizeof(from
);
1450 msg
.msg_control
= &cmsg_buf
;
1451 msg
.msg_controllen
= sizeof(cmsg_buf
);
1454 iov
.iov_len
= handle
->bufsize
- offset
;
1455 iov
.iov_base
= bp
+ offset
;
1456 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1460 * Has "pcap_breakloop()" been called?
1462 if (handle
->break_loop
) {
1464 * Yes - clear the flag that indicates that it has,
1465 * and return PCAP_ERROR_BREAK as an indication that
1466 * we were told to break out of the loop.
1468 handle
->break_loop
= 0;
1469 return PCAP_ERROR_BREAK
;
1472 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1473 packet_len
= recvmsg(handle
->fd
, &msg
, MSG_TRUNC
);
1474 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1475 fromlen
= sizeof(from
);
1476 packet_len
= recvfrom(
1477 handle
->fd
, bp
+ offset
,
1478 handle
->bufsize
- offset
, MSG_TRUNC
,
1479 (struct sockaddr
*) &from
, &fromlen
);
1480 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1481 } while (packet_len
== -1 && errno
== EINTR
);
1483 /* Check if an error occured */
1485 if (packet_len
== -1) {
1489 return 0; /* no packet there */
1493 * The device on which we're capturing went away.
1495 * XXX - we should really return
1496 * PCAP_ERROR_IFACE_NOT_UP, but pcap_dispatch()
1497 * etc. aren't defined to return that.
1499 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1500 "The interface went down");
1504 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1505 "recvfrom: %s", pcap_strerror(errno
));
1510 #ifdef HAVE_PF_PACKET_SOCKETS
1511 if (!handlep
->sock_packet
) {
1513 * Unfortunately, there is a window between socket() and
1514 * bind() where the kernel may queue packets from any
1515 * interface. If we're bound to a particular interface,
1516 * discard packets not from that interface.
1518 * (If socket filters are supported, we could do the
1519 * same thing we do when changing the filter; however,
1520 * that won't handle packet sockets without socket
1521 * filter support, and it's a bit more complicated.
1522 * It would save some instructions per packet, however.)
1524 if (handlep
->ifindex
!= -1 &&
1525 from
.sll_ifindex
!= handlep
->ifindex
)
1529 * Do checks based on packet direction.
1530 * We can only do this if we're using PF_PACKET; the
1531 * address returned for SOCK_PACKET is a "sockaddr_pkt"
1532 * which lacks the relevant packet type information.
1534 if (from
.sll_pkttype
== PACKET_OUTGOING
) {
1537 * If this is from the loopback device, reject it;
1538 * we'll see the packet as an incoming packet as well,
1539 * and we don't want to see it twice.
1541 if (from
.sll_ifindex
== handlep
->lo_ifindex
)
1545 * If the user only wants incoming packets, reject it.
1547 if (handle
->direction
== PCAP_D_IN
)
1552 * If the user only wants outgoing packets, reject it.
1554 if (handle
->direction
== PCAP_D_OUT
)
1560 #ifdef HAVE_PF_PACKET_SOCKETS
1562 * If this is a cooked device, fill in the fake packet header.
1564 if (handlep
->cooked
) {
1566 * Add the length of the fake header to the length
1567 * of packet data we read.
1569 packet_len
+= SLL_HDR_LEN
;
1571 hdrp
= (struct sll_header
*)bp
;
1572 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(from
.sll_pkttype
);
1573 hdrp
->sll_hatype
= htons(from
.sll_hatype
);
1574 hdrp
->sll_halen
= htons(from
.sll_halen
);
1575 memcpy(hdrp
->sll_addr
, from
.sll_addr
,
1576 (from
.sll_halen
> SLL_ADDRLEN
) ?
1579 hdrp
->sll_protocol
= from
.sll_protocol
;
1582 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1583 if (handlep
->vlan_offset
!= -1) {
1584 for (cmsg
= CMSG_FIRSTHDR(&msg
); cmsg
; cmsg
= CMSG_NXTHDR(&msg
, cmsg
)) {
1585 struct tpacket_auxdata
*aux
;
1587 struct vlan_tag
*tag
;
1589 if (cmsg
->cmsg_len
< CMSG_LEN(sizeof(struct tpacket_auxdata
)) ||
1590 cmsg
->cmsg_level
!= SOL_PACKET
||
1591 cmsg
->cmsg_type
!= PACKET_AUXDATA
)
1594 aux
= (struct tpacket_auxdata
*)CMSG_DATA(cmsg
);
1595 #if defined(TP_STATUS_VLAN_VALID)
1596 if ((aux
->tp_vlan_tci
== 0) && !(aux
->tp_status
& TP_STATUS_VLAN_VALID
))
1598 if (aux
->tp_vlan_tci
== 0) /* this is ambigious but without the
1599 TP_STATUS_VLAN_VALID flag, there is
1600 nothing that we can do */
1604 len
= packet_len
> iov
.iov_len
? iov
.iov_len
: packet_len
;
1605 if (len
< (unsigned int) handlep
->vlan_offset
)
1609 memmove(bp
, bp
+ VLAN_TAG_LEN
, handlep
->vlan_offset
);
1611 tag
= (struct vlan_tag
*)(bp
+ handlep
->vlan_offset
);
1612 tag
->vlan_tpid
= htons(ETH_P_8021Q
);
1613 tag
->vlan_tci
= htons(aux
->tp_vlan_tci
);
1615 packet_len
+= VLAN_TAG_LEN
;
1618 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1619 #endif /* HAVE_PF_PACKET_SOCKETS */
1622 * XXX: According to the kernel source we should get the real
1623 * packet len if calling recvfrom with MSG_TRUNC set. It does
1624 * not seem to work here :(, but it is supported by this code
1626 * To be honest the code RELIES on that feature so this is really
1627 * broken with 2.2.x kernels.
1628 * I spend a day to figure out what's going on and I found out
1629 * that the following is happening:
1631 * The packet comes from a random interface and the packet_rcv
1632 * hook is called with a clone of the packet. That code inserts
1633 * the packet into the receive queue of the packet socket.
1634 * If a filter is attached to that socket that filter is run
1635 * first - and there lies the problem. The default filter always
1636 * cuts the packet at the snaplen:
1641 * So the packet filter cuts down the packet. The recvfrom call
1642 * says "hey, it's only 68 bytes, it fits into the buffer" with
1643 * the result that we don't get the real packet length. This
1644 * is valid at least until kernel 2.2.17pre6.
1646 * We currently handle this by making a copy of the filter
1647 * program, fixing all "ret" instructions with non-zero
1648 * operands to have an operand of 65535 so that the filter
1649 * doesn't truncate the packet, and supplying that modified
1650 * filter to the kernel.
1653 caplen
= packet_len
;
1654 if (caplen
> handle
->snapshot
)
1655 caplen
= handle
->snapshot
;
1657 /* Run the packet filter if not using kernel filter */
1658 if (!handlep
->filtering_in_kernel
&& handle
->fcode
.bf_insns
) {
1659 if (bpf_filter(handle
->fcode
.bf_insns
, bp
,
1660 packet_len
, caplen
) == 0)
1662 /* rejected by filter */
1667 /* Fill in our own header data */
1669 if (ioctl(handle
->fd
, SIOCGSTAMP
, &pcap_header
.ts
) == -1) {
1670 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1671 "SIOCGSTAMP: %s", pcap_strerror(errno
));
1674 pcap_header
.caplen
= caplen
;
1675 pcap_header
.len
= packet_len
;
1680 * Arguably, we should count them before we check the filter,
1681 * as on many other platforms "ps_recv" counts packets
1682 * handed to the filter rather than packets that passed
1683 * the filter, but if filtering is done in the kernel, we
1684 * can't get a count of packets that passed the filter,
1685 * and that would mean the meaning of "ps_recv" wouldn't
1686 * be the same on all Linux systems.
1688 * XXX - it's not the same on all systems in any case;
1689 * ideally, we should have a "get the statistics" call
1690 * that supplies more counts and indicates which of them
1691 * it supplies, so that we supply a count of packets
1692 * handed to the filter only on platforms where that
1693 * information is available.
1695 * We count them here even if we can get the packet count
1696 * from the kernel, as we can only determine at run time
1697 * whether we'll be able to get it from the kernel (if
1698 * HAVE_TPACKET_STATS isn't defined, we can't get it from
1699 * the kernel, but if it is defined, the library might
1700 * have been built with a 2.4 or later kernel, but we
1701 * might be running on a 2.2[.x] kernel without Alexey
1702 * Kuznetzov's turbopacket patches, and thus the kernel
1703 * might not be able to supply those statistics). We
1704 * could, I guess, try, when opening the socket, to get
1705 * the statistics, and if we can not increment the count
1706 * here, but it's not clear that always incrementing
1707 * the count is more expensive than always testing a flag
1710 * We keep the count in "handlep->packets_read", and use that
1711 * for "ps_recv" if we can't get the statistics from the kernel.
1712 * We do that because, if we *can* get the statistics from
1713 * the kernel, we use "handlep->stat.ps_recv" and
1714 * "handlep->stat.ps_drop" as running counts, as reading the
1715 * statistics from the kernel resets the kernel statistics,
1716 * and if we directly increment "handlep->stat.ps_recv" here,
1717 * that means it will count packets *twice* on systems where
1718 * we can get kernel statistics - once here, and once in
1719 * pcap_stats_linux().
1721 handlep
->packets_read
++;
1723 /* Call the user supplied callback function */
1724 callback(userdata
, &pcap_header
, bp
);
1730 pcap_inject_linux(pcap_t
*handle
, const void *buf
, size_t size
)
1732 struct pcap_linux
*handlep
= handle
->private;
1735 #ifdef HAVE_PF_PACKET_SOCKETS
1736 if (!handlep
->sock_packet
) {
1737 /* PF_PACKET socket */
1738 if (handlep
->ifindex
== -1) {
1740 * We don't support sending on the "any" device.
1742 strlcpy(handle
->errbuf
,
1743 "Sending packets isn't supported on the \"any\" device",
1748 if (handlep
->cooked
) {
1750 * We don't support sending on the "any" device.
1752 * XXX - how do you send on a bound cooked-mode
1754 * Is a "sendto()" required there?
1756 strlcpy(handle
->errbuf
,
1757 "Sending packets isn't supported in cooked mode",
1764 ret
= send(handle
->fd
, buf
, size
, 0);
1766 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "send: %s",
1767 pcap_strerror(errno
));
1774 * Get the statistics for the given packet capture handle.
1775 * Reports the number of dropped packets iff the kernel supports
1776 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
1777 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
1778 * patches); otherwise, that information isn't available, and we lie
1779 * and report 0 as the count of dropped packets.
1782 pcap_stats_linux(pcap_t
*handle
, struct pcap_stat
*stats
)
1784 struct pcap_linux
*handlep
= handle
->private;
1785 #ifdef HAVE_TPACKET_STATS
1786 struct tpacket_stats kstats
;
1787 socklen_t len
= sizeof (struct tpacket_stats
);
1790 long if_dropped
= 0;
1793 * To fill in ps_ifdrop, we parse /proc/net/dev for the number
1795 if (handle
->opt
.promisc
)
1797 if_dropped
= handlep
->proc_dropped
;
1798 handlep
->proc_dropped
= linux_if_drops(handlep
->device
);
1799 handlep
->stat
.ps_ifdrop
+= (handlep
->proc_dropped
- if_dropped
);
1802 #ifdef HAVE_TPACKET_STATS
1804 * Try to get the packet counts from the kernel.
1806 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_STATISTICS
,
1807 &kstats
, &len
) > -1) {
1809 * On systems where the PACKET_STATISTICS "getsockopt()"
1810 * argument is supported on PF_PACKET sockets:
1812 * "ps_recv" counts only packets that *passed* the
1813 * filter, not packets that didn't pass the filter.
1814 * This includes packets later dropped because we
1815 * ran out of buffer space.
1817 * "ps_drop" counts packets dropped because we ran
1818 * out of buffer space. It doesn't count packets
1819 * dropped by the interface driver. It counts only
1820 * packets that passed the filter.
1822 * See above for ps_ifdrop.
1824 * Both statistics include packets not yet read from
1825 * the kernel by libpcap, and thus not yet seen by
1828 * In "linux/net/packet/af_packet.c", at least in the
1829 * 2.4.9 kernel, "tp_packets" is incremented for every
1830 * packet that passes the packet filter *and* is
1831 * successfully queued on the socket; "tp_drops" is
1832 * incremented for every packet dropped because there's
1833 * not enough free space in the socket buffer.
1835 * When the statistics are returned for a PACKET_STATISTICS
1836 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
1837 * so that "tp_packets" counts all packets handed to
1838 * the PF_PACKET socket, including packets dropped because
1839 * there wasn't room on the socket buffer - but not
1840 * including packets that didn't pass the filter.
1842 * In the BSD BPF, the count of received packets is
1843 * incremented for every packet handed to BPF, regardless
1844 * of whether it passed the filter.
1846 * We can't make "pcap_stats()" work the same on both
1847 * platforms, but the best approximation is to return
1848 * "tp_packets" as the count of packets and "tp_drops"
1849 * as the count of drops.
1851 * Keep a running total because each call to
1852 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
1853 * resets the counters to zero.
1855 handlep
->stat
.ps_recv
+= kstats
.tp_packets
;
1856 handlep
->stat
.ps_drop
+= kstats
.tp_drops
;
1857 *stats
= handlep
->stat
;
1863 * If the error was EOPNOTSUPP, fall through, so that
1864 * if you build the library on a system with
1865 * "struct tpacket_stats" and run it on a system
1866 * that doesn't, it works as it does if the library
1867 * is built on a system without "struct tpacket_stats".
1869 if (errno
!= EOPNOTSUPP
) {
1870 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1871 "pcap_stats: %s", pcap_strerror(errno
));
1877 * On systems where the PACKET_STATISTICS "getsockopt()" argument
1878 * is not supported on PF_PACKET sockets:
1880 * "ps_recv" counts only packets that *passed* the filter,
1881 * not packets that didn't pass the filter. It does not
1882 * count packets dropped because we ran out of buffer
1885 * "ps_drop" is not supported.
1887 * "ps_ifdrop" is supported. It will return the number
1888 * of drops the interface reports in /proc/net/dev,
1889 * if that is available.
1891 * "ps_recv" doesn't include packets not yet read from
1892 * the kernel by libpcap.
1894 * We maintain the count of packets processed by libpcap in
1895 * "handlep->packets_read", for reasons described in the comment
1896 * at the end of pcap_read_packet(). We have no idea how many
1897 * packets were dropped by the kernel buffers -- but we know
1898 * how many the interface dropped, so we can return that.
1901 stats
->ps_recv
= handlep
->packets_read
;
1903 stats
->ps_ifdrop
= handlep
->stat
.ps_ifdrop
;
1908 * Get from "/sys/class/net" all interfaces listed there; if they're
1909 * already in the list of interfaces we have, that won't add another
1910 * instance, but if they're not, that'll add them.
1912 * We don't bother getting any addresses for them; it appears you can't
1913 * use SIOCGIFADDR on Linux to get IPv6 addresses for interfaces, and,
1914 * although some other types of addresses can be fetched with SIOCGIFADDR,
1915 * we don't bother with them for now.
1917 * We also don't fail if we couldn't open "/sys/class/net"; we just leave
1918 * the list of interfaces as is, and return 0, so that we can try
1919 * scanning /proc/net/dev.
1922 scan_sys_class_net(pcap_if_t
**devlistp
, char *errbuf
)
1924 DIR *sys_class_net_d
;
1927 char subsystem_path
[PATH_MAX
+1];
1930 char name
[512]; /* XXX - pick a size */
1932 struct ifreq ifrflags
;
1935 sys_class_net_d
= opendir("/sys/class/net");
1936 if (sys_class_net_d
== NULL
) {
1938 * Don't fail if it doesn't exist at all.
1940 if (errno
== ENOENT
)
1944 * Fail if we got some other error.
1946 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1947 "Can't open /sys/class/net: %s", pcap_strerror(errno
));
1952 * Create a socket from which to fetch interface information.
1954 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
1956 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1957 "socket: %s", pcap_strerror(errno
));
1958 (void)closedir(sys_class_net_d
);
1964 ent
= readdir(sys_class_net_d
);
1967 * Error or EOF; if errno != 0, it's an error.
1973 * Ignore "." and "..".
1975 if (strcmp(ent
->d_name
, ".") == 0 ||
1976 strcmp(ent
->d_name
, "..") == 0)
1980 * Ignore plain files; they do not have subdirectories
1981 * and thus have no attributes.
1983 if (ent
->d_type
== DT_REG
)
1987 * Is there an "ifindex" file under that name?
1988 * (We don't care whether it's a directory or
1989 * a symlink; older kernels have directories
1990 * for devices, newer kernels have symlinks to
1993 snprintf(subsystem_path
, sizeof subsystem_path
,
1994 "/sys/class/net/%s/ifindex", ent
->d_name
);
1995 if (lstat(subsystem_path
, &statb
) != 0) {
1997 * Stat failed. Either there was an error
1998 * other than ENOENT, and we don't know if
1999 * this is an interface, or it's ENOENT,
2000 * and either some part of "/sys/class/net/{if}"
2001 * disappeared, in which case it probably means
2002 * the interface disappeared, or there's no
2003 * "ifindex" file, which means it's not a
2004 * network interface.
2010 * Get the interface name.
2012 p
= &ent
->d_name
[0];
2014 while (*p
!= '\0' && isascii(*p
) && !isspace(*p
)) {
2017 * This could be the separator between a
2018 * name and an alias number, or it could be
2019 * the separator between a name with no
2020 * alias number and the next field.
2022 * If there's a colon after digits, it
2023 * separates the name and the alias number,
2024 * otherwise it separates the name and the
2028 while (isascii(*p
) && isdigit(*p
))
2032 * That was the next field,
2033 * not the alias number.
2044 * Get the flags for this interface, and skip it if
2047 strncpy(ifrflags
.ifr_name
, name
, sizeof(ifrflags
.ifr_name
));
2048 if (ioctl(fd
, SIOCGIFFLAGS
, (char *)&ifrflags
) < 0) {
2049 if (errno
== ENXIO
|| errno
== ENODEV
)
2051 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2052 "SIOCGIFFLAGS: %.*s: %s",
2053 (int)sizeof(ifrflags
.ifr_name
),
2055 pcap_strerror(errno
));
2059 if (!(ifrflags
.ifr_flags
& IFF_UP
))
2063 * Add an entry for this interface, with no addresses.
2065 if (pcap_add_if(devlistp
, name
, ifrflags
.ifr_flags
, NULL
,
2076 * Well, we didn't fail for any other reason; did we
2077 * fail due to an error reading the directory?
2080 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2081 "Error reading /sys/class/net: %s",
2082 pcap_strerror(errno
));
2088 (void)closedir(sys_class_net_d
);
2093 * Get from "/proc/net/dev" all interfaces listed there; if they're
2094 * already in the list of interfaces we have, that won't add another
2095 * instance, but if they're not, that'll add them.
2097 * See comments from scan_sys_class_net().
2100 scan_proc_net_dev(pcap_if_t
**devlistp
, char *errbuf
)
2107 char name
[512]; /* XXX - pick a size */
2109 struct ifreq ifrflags
;
2112 proc_net_f
= fopen("/proc/net/dev", "r");
2113 if (proc_net_f
== NULL
) {
2115 * Don't fail if it doesn't exist at all.
2117 if (errno
== ENOENT
)
2121 * Fail if we got some other error.
2123 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2124 "Can't open /proc/net/dev: %s", pcap_strerror(errno
));
2129 * Create a socket from which to fetch interface information.
2131 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
2133 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2134 "socket: %s", pcap_strerror(errno
));
2135 (void)fclose(proc_net_f
);
2140 fgets(linebuf
, sizeof linebuf
, proc_net_f
) != NULL
; linenum
++) {
2142 * Skip the first two lines - they're headers.
2150 * Skip leading white space.
2152 while (*p
!= '\0' && isascii(*p
) && isspace(*p
))
2154 if (*p
== '\0' || *p
== '\n')
2155 continue; /* blank line */
2158 * Get the interface name.
2161 while (*p
!= '\0' && isascii(*p
) && !isspace(*p
)) {
2164 * This could be the separator between a
2165 * name and an alias number, or it could be
2166 * the separator between a name with no
2167 * alias number and the next field.
2169 * If there's a colon after digits, it
2170 * separates the name and the alias number,
2171 * otherwise it separates the name and the
2175 while (isascii(*p
) && isdigit(*p
))
2179 * That was the next field,
2180 * not the alias number.
2191 * Get the flags for this interface, and skip it if
2194 strncpy(ifrflags
.ifr_name
, name
, sizeof(ifrflags
.ifr_name
));
2195 if (ioctl(fd
, SIOCGIFFLAGS
, (char *)&ifrflags
) < 0) {
2198 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2199 "SIOCGIFFLAGS: %.*s: %s",
2200 (int)sizeof(ifrflags
.ifr_name
),
2202 pcap_strerror(errno
));
2206 if (!(ifrflags
.ifr_flags
& IFF_UP
))
2210 * Add an entry for this interface, with no addresses.
2212 if (pcap_add_if(devlistp
, name
, ifrflags
.ifr_flags
, NULL
,
2223 * Well, we didn't fail for any other reason; did we
2224 * fail due to an error reading the file?
2226 if (ferror(proc_net_f
)) {
2227 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2228 "Error reading /proc/net/dev: %s",
2229 pcap_strerror(errno
));
2235 (void)fclose(proc_net_f
);
2240 * Description string for the "any" device.
2242 static const char any_descr
[] = "Pseudo-device that captures on all interfaces";
2245 pcap_platform_finddevs(pcap_if_t
**alldevsp
, char *errbuf
)
2250 * Read "/sys/class/net", and add to the list of interfaces all
2251 * interfaces listed there that we don't already have, because,
2252 * on Linux, SIOCGIFCONF reports only interfaces with IPv4 addresses,
2253 * and even getifaddrs() won't return information about
2254 * interfaces with no addresses, so you need to read "/sys/class/net"
2255 * to get the names of the rest of the interfaces.
2257 ret
= scan_sys_class_net(alldevsp
, errbuf
);
2259 return (-1); /* failed */
2262 * No /sys/class/net; try reading /proc/net/dev instead.
2264 if (scan_proc_net_dev(alldevsp
, errbuf
) == -1)
2269 * Add the "any" device.
2271 if (pcap_add_if(alldevsp
, "any", 0, any_descr
, errbuf
) < 0)
2278 * Attach the given BPF code to the packet capture device.
2281 pcap_setfilter_linux_common(pcap_t
*handle
, struct bpf_program
*filter
,
2284 struct pcap_linux
*handlep
;
2285 #ifdef SO_ATTACH_FILTER
2286 struct sock_fprog fcode
;
2287 int can_filter_in_kernel
;
2294 strncpy(handle
->errbuf
, "setfilter: No filter specified",
2299 handlep
= handle
->private;
2301 /* Make our private copy of the filter */
2303 if (install_bpf_program(handle
, filter
) < 0)
2304 /* install_bpf_program() filled in errbuf */
2308 * Run user level packet filter by default. Will be overriden if
2309 * installing a kernel filter succeeds.
2311 handlep
->filtering_in_kernel
= 0;
2313 /* Install kernel level filter if possible */
2315 #ifdef SO_ATTACH_FILTER
2317 if (handle
->fcode
.bf_len
> USHRT_MAX
) {
2319 * fcode.len is an unsigned short for current kernel.
2320 * I have yet to see BPF-Code with that much
2321 * instructions but still it is possible. So for the
2322 * sake of correctness I added this check.
2324 fprintf(stderr
, "Warning: Filter too complex for kernel\n");
2326 fcode
.filter
= NULL
;
2327 can_filter_in_kernel
= 0;
2329 #endif /* USHRT_MAX */
2332 * Oh joy, the Linux kernel uses struct sock_fprog instead
2333 * of struct bpf_program and of course the length field is
2334 * of different size. Pointed out by Sebastian
2336 * Oh, and we also need to fix it up so that all "ret"
2337 * instructions with non-zero operands have 65535 as the
2338 * operand if we're not capturing in memory-mapped modee,
2339 * and so that, if we're in cooked mode, all memory-reference
2340 * instructions use special magic offsets in references to
2341 * the link-layer header and assume that the link-layer
2342 * payload begins at 0; "fix_program()" will do that.
2344 switch (fix_program(handle
, &fcode
, is_mmapped
)) {
2349 * Fatal error; just quit.
2350 * (The "default" case shouldn't happen; we
2351 * return -1 for that reason.)
2357 * The program performed checks that we can't make
2358 * work in the kernel.
2360 can_filter_in_kernel
= 0;
2365 * We have a filter that'll work in the kernel.
2367 can_filter_in_kernel
= 1;
2373 * NOTE: at this point, we've set both the "len" and "filter"
2374 * fields of "fcode". As of the 2.6.32.4 kernel, at least,
2375 * those are the only members of the "sock_fprog" structure,
2376 * so we initialize every member of that structure.
2378 * If there is anything in "fcode" that is not initialized,
2379 * it is either a field added in a later kernel, or it's
2382 * If a new field is added, this code needs to be updated
2383 * to set it correctly.
2385 * If there are no other fields, then:
2387 * if the Linux kernel looks at the padding, it's
2390 * if the Linux kernel doesn't look at the padding,
2391 * then if some tool complains that we're passing
2392 * uninitialized data to the kernel, then the tool
2393 * is buggy and needs to understand that it's just
2396 if (can_filter_in_kernel
) {
2397 if ((err
= set_kernel_filter(handle
, &fcode
)) == 0)
2399 /* Installation succeded - using kernel filter. */
2400 handlep
->filtering_in_kernel
= 1;
2402 else if (err
== -1) /* Non-fatal error */
2405 * Print a warning if we weren't able to install
2406 * the filter for a reason other than "this kernel
2407 * isn't configured to support socket filters.
2409 if (errno
!= ENOPROTOOPT
&& errno
!= EOPNOTSUPP
) {
2411 "Warning: Kernel filter failed: %s\n",
2412 pcap_strerror(errno
));
2418 * If we're not using the kernel filter, get rid of any kernel
2419 * filter that might've been there before, e.g. because the
2420 * previous filter could work in the kernel, or because some other
2421 * code attached a filter to the socket by some means other than
2422 * calling "pcap_setfilter()". Otherwise, the kernel filter may
2423 * filter out packets that would pass the new userland filter.
2425 if (!handlep
->filtering_in_kernel
)
2426 reset_kernel_filter(handle
);
2429 * Free up the copy of the filter that was made by "fix_program()".
2431 if (fcode
.filter
!= NULL
)
2437 #endif /* SO_ATTACH_FILTER */
2443 pcap_setfilter_linux(pcap_t
*handle
, struct bpf_program
*filter
)
2445 return pcap_setfilter_linux_common(handle
, filter
, 0);
2450 * Set direction flag: Which packets do we accept on a forwarding
2451 * single device? IN, OUT or both?
2454 pcap_setdirection_linux(pcap_t
*handle
, pcap_direction_t d
)
2456 #ifdef HAVE_PF_PACKET_SOCKETS
2457 struct pcap_linux
*handlep
= handle
->private;
2459 if (!handlep
->sock_packet
) {
2460 handle
->direction
= d
;
2465 * We're not using PF_PACKET sockets, so we can't determine
2466 * the direction of the packet.
2468 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2469 "Setting direction is not supported on SOCK_PACKET sockets");
2473 #ifdef HAVE_PF_PACKET_SOCKETS
2475 * Map the PACKET_ value to a LINUX_SLL_ value; we
2476 * want the same numerical value to be used in
2477 * the link-layer header even if the numerical values
2478 * for the PACKET_ #defines change, so that programs
2479 * that look at the packet type field will always be
2480 * able to handle DLT_LINUX_SLL captures.
2483 map_packet_type_to_sll_type(short int sll_pkttype
)
2485 switch (sll_pkttype
) {
2488 return htons(LINUX_SLL_HOST
);
2490 case PACKET_BROADCAST
:
2491 return htons(LINUX_SLL_BROADCAST
);
2493 case PACKET_MULTICAST
:
2494 return htons(LINUX_SLL_MULTICAST
);
2496 case PACKET_OTHERHOST
:
2497 return htons(LINUX_SLL_OTHERHOST
);
2499 case PACKET_OUTGOING
:
2500 return htons(LINUX_SLL_OUTGOING
);
2509 * Linux uses the ARP hardware type to identify the type of an
2510 * interface. pcap uses the DLT_xxx constants for this. This
2511 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
2512 * constant, as arguments, and sets "handle->linktype" to the
2513 * appropriate DLT_XXX constant and sets "handle->offset" to
2514 * the appropriate value (to make "handle->offset" plus link-layer
2515 * header length be a multiple of 4, so that the link-layer payload
2516 * will be aligned on a 4-byte boundary when capturing packets).
2517 * (If the offset isn't set here, it'll be 0; add code as appropriate
2518 * for cases where it shouldn't be 0.)
2520 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
2521 * in cooked mode; otherwise, we can't use cooked mode, so we have
2522 * to pick some type that works in raw mode, or fail.
2524 * Sets the link type to -1 if unable to map the type.
2526 static void map_arphrd_to_dlt(pcap_t
*handle
, int arptype
, int cooked_ok
)
2532 * This is (presumably) a real Ethernet capture; give it a
2533 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
2534 * that an application can let you choose it, in case you're
2535 * capturing DOCSIS traffic that a Cisco Cable Modem
2536 * Termination System is putting out onto an Ethernet (it
2537 * doesn't put an Ethernet header onto the wire, it puts raw
2538 * DOCSIS frames out on the wire inside the low-level
2539 * Ethernet framing).
2541 * XXX - are there any sorts of "fake Ethernet" that have
2542 * ARPHRD_ETHER but that *shouldn't offer DLT_DOCSIS as
2543 * a Cisco CMTS won't put traffic onto it or get traffic
2544 * bridged onto it? ISDN is handled in "activate_new()",
2545 * as we fall back on cooked mode there; are there any
2548 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
2550 * If that fails, just leave the list empty.
2552 if (handle
->dlt_list
!= NULL
) {
2553 handle
->dlt_list
[0] = DLT_EN10MB
;
2554 handle
->dlt_list
[1] = DLT_DOCSIS
;
2555 handle
->dlt_count
= 2;
2559 case ARPHRD_METRICOM
:
2560 case ARPHRD_LOOPBACK
:
2561 handle
->linktype
= DLT_EN10MB
;
2566 handle
->linktype
= DLT_EN3MB
;
2570 handle
->linktype
= DLT_AX25_KISS
;
2574 handle
->linktype
= DLT_PRONET
;
2578 handle
->linktype
= DLT_CHAOS
;
2581 #define ARPHRD_CAN 280
2584 handle
->linktype
= DLT_CAN_SOCKETCAN
;
2587 #ifndef ARPHRD_IEEE802_TR
2588 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
2590 case ARPHRD_IEEE802_TR
:
2591 case ARPHRD_IEEE802
:
2592 handle
->linktype
= DLT_IEEE802
;
2597 handle
->linktype
= DLT_ARCNET_LINUX
;
2600 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
2601 #define ARPHRD_FDDI 774
2604 handle
->linktype
= DLT_FDDI
;
2608 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
2609 #define ARPHRD_ATM 19
2613 * The Classical IP implementation in ATM for Linux
2614 * supports both what RFC 1483 calls "LLC Encapsulation",
2615 * in which each packet has an LLC header, possibly
2616 * with a SNAP header as well, prepended to it, and
2617 * what RFC 1483 calls "VC Based Multiplexing", in which
2618 * different virtual circuits carry different network
2619 * layer protocols, and no header is prepended to packets.
2621 * They both have an ARPHRD_ type of ARPHRD_ATM, so
2622 * you can't use the ARPHRD_ type to find out whether
2623 * captured packets will have an LLC header, and,
2624 * while there's a socket ioctl to *set* the encapsulation
2625 * type, there's no ioctl to *get* the encapsulation type.
2629 * programs that dissect Linux Classical IP frames
2630 * would have to check for an LLC header and,
2631 * depending on whether they see one or not, dissect
2632 * the frame as LLC-encapsulated or as raw IP (I
2633 * don't know whether there's any traffic other than
2634 * IP that would show up on the socket, or whether
2635 * there's any support for IPv6 in the Linux
2636 * Classical IP code);
2638 * filter expressions would have to compile into
2639 * code that checks for an LLC header and does
2642 * Both of those are a nuisance - and, at least on systems
2643 * that support PF_PACKET sockets, we don't have to put
2644 * up with those nuisances; instead, we can just capture
2645 * in cooked mode. That's what we'll do, if we can.
2646 * Otherwise, we'll just fail.
2649 handle
->linktype
= DLT_LINUX_SLL
;
2651 handle
->linktype
= -1;
2654 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
2655 #define ARPHRD_IEEE80211 801
2657 case ARPHRD_IEEE80211
:
2658 handle
->linktype
= DLT_IEEE802_11
;
2661 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
2662 #define ARPHRD_IEEE80211_PRISM 802
2664 case ARPHRD_IEEE80211_PRISM
:
2665 handle
->linktype
= DLT_PRISM_HEADER
;
2668 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
2669 #define ARPHRD_IEEE80211_RADIOTAP 803
2671 case ARPHRD_IEEE80211_RADIOTAP
:
2672 handle
->linktype
= DLT_IEEE802_11_RADIO
;
2677 * Some PPP code in the kernel supplies no link-layer
2678 * header whatsoever to PF_PACKET sockets; other PPP
2679 * code supplies PPP link-layer headers ("syncppp.c");
2680 * some PPP code might supply random link-layer
2681 * headers (PPP over ISDN - there's code in Ethereal,
2682 * for example, to cope with PPP-over-ISDN captures
2683 * with which the Ethereal developers have had to cope,
2684 * heuristically trying to determine which of the
2685 * oddball link-layer headers particular packets have).
2687 * As such, we just punt, and run all PPP interfaces
2688 * in cooked mode, if we can; otherwise, we just treat
2689 * it as DLT_RAW, for now - if somebody needs to capture,
2690 * on a 2.0[.x] kernel, on PPP devices that supply a
2691 * link-layer header, they'll have to add code here to
2692 * map to the appropriate DLT_ type (possibly adding a
2693 * new DLT_ type, if necessary).
2696 handle
->linktype
= DLT_LINUX_SLL
;
2699 * XXX - handle ISDN types here? We can't fall
2700 * back on cooked sockets, so we'd have to
2701 * figure out from the device name what type of
2702 * link-layer encapsulation it's using, and map
2703 * that to an appropriate DLT_ value, meaning
2704 * we'd map "isdnN" devices to DLT_RAW (they
2705 * supply raw IP packets with no link-layer
2706 * header) and "isdY" devices to a new DLT_I4L_IP
2707 * type that has only an Ethernet packet type as
2708 * a link-layer header.
2710 * But sometimes we seem to get random crap
2711 * in the link-layer header when capturing on
2714 handle
->linktype
= DLT_RAW
;
2718 #ifndef ARPHRD_CISCO
2719 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
2722 handle
->linktype
= DLT_C_HDLC
;
2725 /* Not sure if this is correct for all tunnels, but it
2729 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
2737 #ifndef ARPHRD_RAWHDLC
2738 #define ARPHRD_RAWHDLC 518
2740 case ARPHRD_RAWHDLC
:
2742 #define ARPHRD_DLCI 15
2746 * XXX - should some of those be mapped to DLT_LINUX_SLL
2747 * instead? Should we just map all of them to DLT_LINUX_SLL?
2749 handle
->linktype
= DLT_RAW
;
2753 #define ARPHRD_FRAD 770
2756 handle
->linktype
= DLT_FRELAY
;
2759 case ARPHRD_LOCALTLK
:
2760 handle
->linktype
= DLT_LTALK
;
2765 * RFC 4338 defines an encapsulation for IP and ARP
2766 * packets that's compatible with the RFC 2625
2767 * encapsulation, but that uses a different ARP
2768 * hardware type and hardware addresses. That
2769 * ARP hardware type is 18; Linux doesn't define
2770 * any ARPHRD_ value as 18, but if it ever officially
2771 * supports RFC 4338-style IP-over-FC, it should define
2774 * For now, we map it to DLT_IP_OVER_FC, in the hopes
2775 * that this will encourage its use in the future,
2776 * should Linux ever officially support RFC 4338-style
2779 handle
->linktype
= DLT_IP_OVER_FC
;
2783 #define ARPHRD_FCPP 784
2787 #define ARPHRD_FCAL 785
2791 #define ARPHRD_FCPL 786
2794 #ifndef ARPHRD_FCFABRIC
2795 #define ARPHRD_FCFABRIC 787
2797 case ARPHRD_FCFABRIC
:
2799 * Back in 2002, Donald Lee at Cray wanted a DLT_ for
2802 * http://www.mail-archive.com/tcpdump-workers@sandelman.ottawa.on.ca/msg01043.html
2804 * and one was assigned.
2806 * In a later private discussion (spun off from a message
2807 * on the ethereal-users list) on how to get that DLT_
2808 * value in libpcap on Linux, I ended up deciding that
2809 * the best thing to do would be to have him tweak the
2810 * driver to set the ARPHRD_ value to some ARPHRD_FCxx
2811 * type, and map all those types to DLT_IP_OVER_FC:
2813 * I've checked into the libpcap and tcpdump CVS tree
2814 * support for DLT_IP_OVER_FC. In order to use that,
2815 * you'd have to modify your modified driver to return
2816 * one of the ARPHRD_FCxxx types, in "fcLINUXfcp.c" -
2817 * change it to set "dev->type" to ARPHRD_FCFABRIC, for
2818 * example (the exact value doesn't matter, it can be
2819 * any of ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL, or
2822 * 11 years later, Christian Svensson wanted to map
2823 * various ARPHRD_ values to DLT_FC_2 and
2824 * DLT_FC_2_WITH_FRAME_DELIMS for raw Fibre Channel
2827 * https://github.com/mcr/libpcap/pull/29
2829 * There doesn't seem to be any network drivers that uses
2830 * any of the ARPHRD_FC* values for IP-over-FC, and
2831 * it's not exactly clear what the "Dummy types for non
2832 * ARP hardware" are supposed to mean (link-layer
2833 * header type? Physical network type?), so it's
2834 * not exactly clear why the ARPHRD_FC* types exist
2835 * in the first place.
2837 * For now, we map them to DLT_FC_2, and provide an
2838 * option of DLT_FC_2_WITH_FRAME_DELIMS, as well as
2839 * DLT_IP_OVER_FC just in case there's some old
2840 * driver out there that uses one of those types for
2841 * IP-over-FC on which somebody wants to capture
2844 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
2846 * If that fails, just leave the list empty.
2848 if (handle
->dlt_list
!= NULL
) {
2849 handle
->dlt_list
[0] = DLT_FC_2
;
2850 handle
->dlt_list
[1] = DLT_FC_2_WITH_FRAME_DELIMS
;
2851 handle
->dlt_list
[2] = DLT_IP_OVER_FC
;
2852 handle
->dlt_count
= 3;
2854 handle
->linktype
= DLT_FC_2
;
2858 #define ARPHRD_IRDA 783
2861 /* Don't expect IP packet out of this interfaces... */
2862 handle
->linktype
= DLT_LINUX_IRDA
;
2863 /* We need to save packet direction for IrDA decoding,
2864 * so let's use "Linux-cooked" mode. Jean II */
2865 //handlep->cooked = 1;
2868 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
2869 * is needed, please report it to <daniele@orlandi.com> */
2871 #define ARPHRD_LAPD 8445
2874 /* Don't expect IP packet out of this interfaces... */
2875 handle
->linktype
= DLT_LINUX_LAPD
;
2879 #define ARPHRD_NONE 0xFFFE
2883 * No link-layer header; packets are just IP
2884 * packets, so use DLT_RAW.
2886 handle
->linktype
= DLT_RAW
;
2889 #ifndef ARPHRD_IEEE802154
2890 #define ARPHRD_IEEE802154 804
2892 case ARPHRD_IEEE802154
:
2893 handle
->linktype
= DLT_IEEE802_15_4_NOFCS
;
2897 handle
->linktype
= -1;
2902 /* ===== Functions to interface to the newer kernels ================== */
2905 * Try to open a packet socket using the new kernel PF_PACKET interface.
2906 * Returns 1 on success, 0 on an error that means the new interface isn't
2907 * present (so the old SOCK_PACKET interface should be tried), and a
2908 * PCAP_ERROR_ value on an error that means that the old mechanism won't
2909 * work either (so it shouldn't be tried).
2912 activate_new(pcap_t
*handle
)
2914 #ifdef HAVE_PF_PACKET_SOCKETS
2915 struct pcap_linux
*handlep
= handle
->private;
2916 const char *device
= handle
->opt
.source
;
2917 int is_any_device
= (strcmp(device
, "any") == 0);
2918 int sock_fd
= -1, arptype
;
2919 #ifdef HAVE_PACKET_AUXDATA
2923 struct packet_mreq mr
;
2926 * Open a socket with protocol family packet. If the
2927 * "any" device was specified, we open a SOCK_DGRAM
2928 * socket for the cooked interface, otherwise we first
2929 * try a SOCK_RAW socket for the raw interface.
2931 sock_fd
= is_any_device
?
2932 socket(PF_PACKET
, SOCK_DGRAM
, htons(ETH_P_ALL
)) :
2933 socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
));
2935 if (sock_fd
== -1) {
2936 if (errno
== EINVAL
|| errno
== EAFNOSUPPORT
) {
2938 * We don't support PF_PACKET/SOCK_whatever
2939 * sockets; try the old mechanism.
2944 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "socket: %s",
2945 pcap_strerror(errno
) );
2946 if (errno
== EPERM
|| errno
== EACCES
) {
2948 * You don't have permission to open the
2951 return PCAP_ERROR_PERM_DENIED
;
2960 /* It seems the kernel supports the new interface. */
2961 handlep
->sock_packet
= 0;
2964 * Get the interface index of the loopback device.
2965 * If the attempt fails, don't fail, just set the
2966 * "handlep->lo_ifindex" to -1.
2968 * XXX - can there be more than one device that loops
2969 * packets back, i.e. devices other than "lo"? If so,
2970 * we'd need to find them all, and have an array of
2971 * indices for them, and check all of them in
2972 * "pcap_read_packet()".
2974 handlep
->lo_ifindex
= iface_get_id(sock_fd
, "lo", handle
->errbuf
);
2977 * Default value for offset to align link-layer payload
2978 * on a 4-byte boundary.
2983 * What kind of frames do we have to deal with? Fall back
2984 * to cooked mode if we have an unknown interface type
2985 * or a type we know doesn't work well in raw mode.
2987 if (!is_any_device
) {
2988 /* Assume for now we don't need cooked mode. */
2989 handlep
->cooked
= 0;
2991 if (handle
->opt
.rfmon
) {
2993 * We were asked to turn on monitor mode.
2994 * Do so before we get the link-layer type,
2995 * because entering monitor mode could change
2996 * the link-layer type.
2998 err
= enter_rfmon_mode(handle
, sock_fd
, device
);
3006 * Nothing worked for turning monitor mode
3010 return PCAP_ERROR_RFMON_NOTSUP
;
3014 * Either monitor mode has been turned on for
3015 * the device, or we've been given a different
3016 * device to open for monitor mode. If we've
3017 * been given a different device, use it.
3019 if (handlep
->mondevice
!= NULL
)
3020 device
= handlep
->mondevice
;
3022 arptype
= iface_get_arptype(sock_fd
, device
, handle
->errbuf
);
3027 map_arphrd_to_dlt(handle
, arptype
, 1);
3028 if (handle
->linktype
== -1 ||
3029 handle
->linktype
== DLT_LINUX_SLL
||
3030 handle
->linktype
== DLT_LINUX_IRDA
||
3031 handle
->linktype
== DLT_LINUX_LAPD
||
3032 (handle
->linktype
== DLT_EN10MB
&&
3033 (strncmp("isdn", device
, 4) == 0 ||
3034 strncmp("isdY", device
, 4) == 0))) {
3036 * Unknown interface type (-1), or a
3037 * device we explicitly chose to run
3038 * in cooked mode (e.g., PPP devices),
3039 * or an ISDN device (whose link-layer
3040 * type we can only determine by using
3041 * APIs that may be different on different
3042 * kernels) - reopen in cooked mode.
3044 if (close(sock_fd
) == -1) {
3045 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3046 "close: %s", pcap_strerror(errno
));
3049 sock_fd
= socket(PF_PACKET
, SOCK_DGRAM
,
3051 if (sock_fd
== -1) {
3052 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3053 "socket: %s", pcap_strerror(errno
));
3054 if (errno
== EPERM
|| errno
== EACCES
) {
3056 * You don't have permission to
3059 return PCAP_ERROR_PERM_DENIED
;
3067 handlep
->cooked
= 1;
3070 * Get rid of any link-layer type list
3071 * we allocated - this only supports cooked
3074 if (handle
->dlt_list
!= NULL
) {
3075 free(handle
->dlt_list
);
3076 handle
->dlt_list
= NULL
;
3077 handle
->dlt_count
= 0;
3080 if (handle
->linktype
== -1) {
3082 * Warn that we're falling back on
3083 * cooked mode; we may want to
3084 * update "map_arphrd_to_dlt()"
3085 * to handle the new type.
3087 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3089 "supported by libpcap - "
3090 "falling back to cooked "
3096 * IrDA capture is not a real "cooked" capture,
3097 * it's IrLAP frames, not IP packets. The
3098 * same applies to LAPD capture.
3100 if (handle
->linktype
!= DLT_LINUX_IRDA
&&
3101 handle
->linktype
!= DLT_LINUX_LAPD
)
3102 handle
->linktype
= DLT_LINUX_SLL
;
3105 handlep
->ifindex
= iface_get_id(sock_fd
, device
,
3107 if (handlep
->ifindex
== -1) {
3112 if ((err
= iface_bind(sock_fd
, handlep
->ifindex
,
3113 handle
->errbuf
)) != 1) {
3118 return 0; /* try old mechanism */
3124 if (handle
->opt
.rfmon
) {
3126 * It doesn't support monitor mode.
3128 return PCAP_ERROR_RFMON_NOTSUP
;
3132 * It uses cooked mode.
3134 handlep
->cooked
= 1;
3135 handle
->linktype
= DLT_LINUX_SLL
;
3138 * We're not bound to a device.
3139 * For now, we're using this as an indication
3140 * that we can't transmit; stop doing that only
3141 * if we figure out how to transmit in cooked
3144 handlep
->ifindex
= -1;
3148 * Select promiscuous mode on if "promisc" is set.
3150 * Do not turn allmulti mode on if we don't select
3151 * promiscuous mode - on some devices (e.g., Orinoco
3152 * wireless interfaces), allmulti mode isn't supported
3153 * and the driver implements it by turning promiscuous
3154 * mode on, and that screws up the operation of the
3155 * card as a normal networking interface, and on no
3156 * other platform I know of does starting a non-
3157 * promiscuous capture affect which multicast packets
3158 * are received by the interface.
3162 * Hmm, how can we set promiscuous mode on all interfaces?
3163 * I am not sure if that is possible at all. For now, we
3164 * silently ignore attempts to turn promiscuous mode on
3165 * for the "any" device (so you don't have to explicitly
3166 * disable it in programs such as tcpdump).
3169 if (!is_any_device
&& handle
->opt
.promisc
) {
3170 memset(&mr
, 0, sizeof(mr
));
3171 mr
.mr_ifindex
= handlep
->ifindex
;
3172 mr
.mr_type
= PACKET_MR_PROMISC
;
3173 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_ADD_MEMBERSHIP
,
3174 &mr
, sizeof(mr
)) == -1) {
3175 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3176 "setsockopt: %s", pcap_strerror(errno
));
3182 /* Enable auxillary data if supported and reserve room for
3183 * reconstructing VLAN headers. */
3184 #ifdef HAVE_PACKET_AUXDATA
3186 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_AUXDATA
, &val
,
3187 sizeof(val
)) == -1 && errno
!= ENOPROTOOPT
) {
3188 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3189 "setsockopt: %s", pcap_strerror(errno
));
3193 handle
->offset
+= VLAN_TAG_LEN
;
3194 #endif /* HAVE_PACKET_AUXDATA */
3197 * This is a 2.2[.x] or later kernel (we know that
3198 * because we're not using a SOCK_PACKET socket -
3199 * PF_PACKET is supported only in 2.2 and later
3202 * We can safely pass "recvfrom()" a byte count
3203 * based on the snapshot length.
3205 * If we're in cooked mode, make the snapshot length
3206 * large enough to hold a "cooked mode" header plus
3207 * 1 byte of packet data (so we don't pass a byte
3208 * count of 0 to "recvfrom()").
3210 if (handlep
->cooked
) {
3211 if (handle
->snapshot
< SLL_HDR_LEN
+ 1)
3212 handle
->snapshot
= SLL_HDR_LEN
+ 1;
3214 handle
->bufsize
= handle
->snapshot
;
3217 * Set the offset at which to insert VLAN tags.
3219 switch (handle
->linktype
) {
3222 handlep
->vlan_offset
= 2 * ETH_ALEN
;
3226 handlep
->vlan_offset
= 14;
3230 handlep
->vlan_offset
= -1; /* unknown */
3234 /* Save the socket FD in the pcap structure */
3235 handle
->fd
= sock_fd
;
3240 "New packet capturing interface not supported by build "
3241 "environment", PCAP_ERRBUF_SIZE
);
3246 #ifdef HAVE_PACKET_RING
3248 * Attempt to activate with memory-mapped access.
3250 * On success, returns 1, and sets *status to 0 if there are no warnings
3251 * or to a PCAP_WARNING_ code if there is a warning.
3253 * On failure due to lack of support for memory-mapped capture, returns
3256 * On error, returns -1, and sets *status to the appropriate error code;
3257 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3260 activate_mmap(pcap_t
*handle
, int *status
)
3262 struct pcap_linux
*handlep
= handle
->private;
3266 * Attempt to allocate a buffer to hold the contents of one
3267 * packet, for use by the oneshot callback.
3269 handlep
->oneshot_buffer
= malloc(handle
->snapshot
);
3270 if (handlep
->oneshot_buffer
== NULL
) {
3271 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3272 "can't allocate oneshot buffer: %s",
3273 pcap_strerror(errno
));
3274 *status
= PCAP_ERROR
;
3278 if (handle
->opt
.buffer_size
== 0) {
3279 /* by default request 2M for the ring buffer */
3280 handle
->opt
.buffer_size
= 2*1024*1024;
3282 ret
= prepare_tpacket_socket(handle
);
3284 free(handlep
->oneshot_buffer
);
3285 *status
= PCAP_ERROR
;
3288 ret
= create_ring(handle
, status
);
3291 * We don't support memory-mapped capture; our caller
3292 * will fall back on reading from the socket.
3294 free(handlep
->oneshot_buffer
);
3299 * Error attempting to enable memory-mapped capture;
3300 * fail. create_ring() has set *status.
3302 free(handlep
->oneshot_buffer
);
3307 * Success. *status has been set either to 0 if there are no
3308 * warnings or to a PCAP_WARNING_ value if there is a warning.
3310 * Override some defaults and inherit the other fields from
3312 * handle->offset is used to get the current position into the rx ring.
3313 * handle->cc is used to store the ring size.
3315 handle
->read_op
= pcap_read_linux_mmap
;
3316 handle
->cleanup_op
= pcap_cleanup_linux_mmap
;
3317 handle
->setfilter_op
= pcap_setfilter_linux_mmap
;
3318 handle
->setnonblock_op
= pcap_setnonblock_mmap
;
3319 handle
->getnonblock_op
= pcap_getnonblock_mmap
;
3320 handle
->oneshot_callback
= pcap_oneshot_mmap
;
3321 handle
->selectable_fd
= handle
->fd
;
3324 #else /* HAVE_PACKET_RING */
3326 activate_mmap(pcap_t
*handle _U_
, int *status _U_
)
3330 #endif /* HAVE_PACKET_RING */
3332 #ifdef HAVE_PACKET_RING
3334 * Attempt to set the socket to version 2 of the memory-mapped header.
3335 * Return 1 if we succeed or if we fail because version 2 isn't
3336 * supported; return -1 on any other error, and set handle->errbuf.
3339 prepare_tpacket_socket(pcap_t
*handle
)
3341 struct pcap_linux
*handlep
= handle
->private;
3342 #ifdef HAVE_TPACKET2
3347 handlep
->tp_version
= TPACKET_V1
;
3348 handlep
->tp_hdrlen
= sizeof(struct tpacket_hdr
);
3350 #ifdef HAVE_TPACKET2
3351 /* Probe whether kernel supports TPACKET_V2 */
3354 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_HDRLEN
, &val
, &len
) < 0) {
3355 if (errno
== ENOPROTOOPT
)
3356 return 1; /* no - just drive on */
3358 /* Yes - treat as a failure. */
3359 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3360 "can't get TPACKET_V2 header len on packet socket: %s",
3361 pcap_strerror(errno
));
3364 handlep
->tp_hdrlen
= val
;
3367 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_VERSION
, &val
,
3369 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3370 "can't activate TPACKET_V2 on packet socket: %s",
3371 pcap_strerror(errno
));
3374 handlep
->tp_version
= TPACKET_V2
;
3376 /* Reserve space for VLAN tag reconstruction */
3378 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
, &val
,
3380 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3381 "can't set up reserve on packet socket: %s",
3382 pcap_strerror(errno
));
3386 #endif /* HAVE_TPACKET2 */
3391 * Attempt to set up memory-mapped access.
3393 * On success, returns 1, and sets *status to 0 if there are no warnings
3394 * or to a PCAP_WARNING_ code if there is a warning.
3396 * On failure due to lack of support for memory-mapped capture, returns
3399 * On error, returns -1, and sets *status to the appropriate error code;
3400 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3403 create_ring(pcap_t
*handle
, int *status
)
3405 struct pcap_linux
*handlep
= handle
->private;
3406 unsigned i
, j
, frames_per_block
;
3407 struct tpacket_req req
;
3409 unsigned int sk_type
, tp_reserve
, maclen
, tp_hdrlen
, netoff
, macoff
;
3410 unsigned int frame_size
;
3413 * Start out assuming no warnings or errors.
3417 /* Note that with large snapshot length (say 64K, which is the default
3418 * for recent versions of tcpdump, the value that "-s 0" has given
3419 * for a long time with tcpdump, and the default in Wireshark/TShark),
3420 * if we use the snapshot length to calculate the frame length,
3421 * only a few frames will be available in the ring even with pretty
3422 * large ring size (and a lot of memory will be unused).
3424 * Ideally, we should choose a frame length based on the
3425 * minimum of the specified snapshot length and the maximum
3426 * packet size. That's not as easy as it sounds; consider, for
3427 * example, an 802.11 interface in monitor mode, where the
3428 * frame would include a radiotap header, where the maximum
3429 * radiotap header length is device-dependent.
3431 * So, for now, we just do this for Ethernet devices, where
3432 * there's no metadata header, and the link-layer header is
3433 * fixed length. We can get the maximum packet size by
3434 * adding 18, the Ethernet header length plus the CRC length
3435 * (just in case we happen to get the CRC in the packet), to
3436 * the MTU of the interface; we fetch the MTU in the hopes
3437 * that it reflects support for jumbo frames. (Even if the
3438 * interface is just being used for passive snooping, the driver
3439 * might set the size of buffers in the receive ring based on
3440 * the MTU, so that the MTU limits the maximum size of packets
3441 * that we can receive.)
3443 * We don't do that if segmentation/fragmentation or receive
3444 * offload are enabled, so we don't get rudely surprised by
3445 * "packets" bigger than the MTU. */
3446 frame_size
= handle
->snapshot
;
3447 if (handle
->linktype
== DLT_EN10MB
) {
3451 offload
= iface_get_offload(handle
);
3452 if (offload
== -1) {
3453 *status
= PCAP_ERROR
;
3457 mtu
= iface_get_mtu(handle
->fd
, handle
->opt
.source
,
3460 *status
= PCAP_ERROR
;
3463 if (frame_size
> mtu
+ 18)
3464 frame_size
= mtu
+ 18;
3468 /* NOTE: calculus matching those in tpacket_rcv()
3469 * in linux-2.6/net/packet/af_packet.c
3471 len
= sizeof(sk_type
);
3472 if (getsockopt(handle
->fd
, SOL_SOCKET
, SO_TYPE
, &sk_type
, &len
) < 0) {
3473 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "getsockopt: %s", pcap_strerror(errno
));
3474 *status
= PCAP_ERROR
;
3477 #ifdef PACKET_RESERVE
3478 len
= sizeof(tp_reserve
);
3479 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
, &tp_reserve
, &len
) < 0) {
3480 if (errno
!= ENOPROTOOPT
) {
3482 * ENOPROTOOPT means "kernel doesn't support
3483 * PACKET_RESERVE", in which case we fall back
3486 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "getsockopt: %s", pcap_strerror(errno
));
3487 *status
= PCAP_ERROR
;
3490 tp_reserve
= 0; /* older kernel, reserve not supported */
3493 tp_reserve
= 0; /* older kernel, reserve not supported */
3495 maclen
= (sk_type
== SOCK_DGRAM
) ? 0 : MAX_LINKHEADER_SIZE
;
3496 /* XXX: in the kernel maclen is calculated from
3497 * LL_ALLOCATED_SPACE(dev) and vnet_hdr.hdr_len
3498 * in: packet_snd() in linux-2.6/net/packet/af_packet.c
3499 * then packet_alloc_skb() in linux-2.6/net/packet/af_packet.c
3500 * then sock_alloc_send_pskb() in linux-2.6/net/core/sock.c
3501 * but I see no way to get those sizes in userspace,
3502 * like for instance with an ifreq ioctl();
3503 * the best thing I've found so far is MAX_HEADER in the kernel
3504 * part of linux-2.6/include/linux/netdevice.h
3505 * which goes up to 128+48=176; since pcap-linux.c defines
3506 * a MAX_LINKHEADER_SIZE of 256 which is greater than that,
3507 * let's use it.. maybe is it even large enough to directly
3510 tp_hdrlen
= TPACKET_ALIGN(handlep
->tp_hdrlen
) + sizeof(struct sockaddr_ll
) ;
3511 netoff
= TPACKET_ALIGN(tp_hdrlen
+ (maclen
< 16 ? 16 : maclen
)) + tp_reserve
;
3512 /* NOTE: AFAICS tp_reserve may break the TPACKET_ALIGN of
3513 * netoff, which contradicts
3514 * linux-2.6/Documentation/networking/packet_mmap.txt
3516 * "- Gap, chosen so that packet data (Start+tp_net)
3517 * aligns to TPACKET_ALIGNMENT=16"
3519 /* NOTE: in linux-2.6/include/linux/skbuff.h:
3520 * "CPUs often take a performance hit
3521 * when accessing unaligned memory locations"
3523 macoff
= netoff
- maclen
;
3524 req
.tp_frame_size
= TPACKET_ALIGN(macoff
+ frame_size
);
3525 req
.tp_frame_nr
= handle
->opt
.buffer_size
/req
.tp_frame_size
;
3527 /* compute the minumum block size that will handle this frame.
3528 * The block has to be page size aligned.
3529 * The max block size allowed by the kernel is arch-dependent and
3530 * it's not explicitly checked here. */
3531 req
.tp_block_size
= getpagesize();
3532 while (req
.tp_block_size
< req
.tp_frame_size
)
3533 req
.tp_block_size
<<= 1;
3535 frames_per_block
= req
.tp_block_size
/req
.tp_frame_size
;
3538 * PACKET_TIMESTAMP was added after linux/net_tstamp.h was,
3539 * so we check for PACKET_TIMESTAMP. We check for
3540 * linux/net_tstamp.h just in case a system somehow has
3541 * PACKET_TIMESTAMP but not linux/net_tstamp.h; that might
3544 * SIOCSHWTSTAMP was introduced in the patch that introduced
3545 * linux/net_tstamp.h, so we don't bother checking whether
3546 * SIOCSHWTSTAMP is defined (if your Linux system has
3547 * linux/net_tstamp.h but doesn't define SIOCSHWTSTAMP, your
3548 * Linux system is badly broken).
3550 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
3552 * If we were told to do so, ask the kernel and the driver
3553 * to use hardware timestamps.
3555 * Hardware timestamps are only supported with mmapped
3558 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
||
3559 handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER_UNSYNCED
) {
3560 struct hwtstamp_config hwconfig
;
3565 * Ask for hardware time stamps on all packets,
3566 * including transmitted packets.
3568 memset(&hwconfig
, 0, sizeof(hwconfig
));
3569 hwconfig
.tx_type
= HWTSTAMP_TX_ON
;
3570 hwconfig
.rx_filter
= HWTSTAMP_FILTER_ALL
;
3572 memset(&ifr
, 0, sizeof(ifr
));
3573 strcpy(ifr
.ifr_name
, handle
->opt
.source
);
3574 ifr
.ifr_data
= (void *)&hwconfig
;
3576 if (ioctl(handle
->fd
, SIOCSHWTSTAMP
, &ifr
) < 0) {
3581 * Treat this as an error, as the
3582 * user should try to run this
3583 * with the appropriate privileges -
3584 * and, if they can't, shouldn't
3585 * try requesting hardware time stamps.
3587 *status
= PCAP_ERROR_PERM_DENIED
;
3592 * Treat this as a warning, as the
3593 * only way to fix the warning is to
3594 * get an adapter that supports hardware
3595 * time stamps. We'll just fall back
3596 * on the standard host time stamps.
3598 *status
= PCAP_WARNING_TSTAMP_TYPE_NOTSUP
;
3602 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3603 "SIOCSHWTSTAMP failed: %s",
3604 pcap_strerror(errno
));
3605 *status
= PCAP_ERROR
;
3610 * Well, that worked. Now specify the type of
3611 * hardware time stamp we want for this
3614 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
) {
3616 * Hardware timestamp, synchronized
3617 * with the system clock.
3619 timesource
= SOF_TIMESTAMPING_SYS_HARDWARE
;
3622 * PCAP_TSTAMP_ADAPTER_UNSYNCED - hardware
3623 * timestamp, not synchronized with the
3626 timesource
= SOF_TIMESTAMPING_RAW_HARDWARE
;
3628 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_TIMESTAMP
,
3629 (void *)×ource
, sizeof(timesource
))) {
3630 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3631 "can't set PACKET_TIMESTAMP: %s",
3632 pcap_strerror(errno
));
3633 *status
= PCAP_ERROR
;
3638 #endif /* HAVE_LINUX_NET_TSTAMP_H && PACKET_TIMESTAMP */
3640 /* ask the kernel to create the ring */
3642 req
.tp_block_nr
= req
.tp_frame_nr
/ frames_per_block
;
3644 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
3645 req
.tp_frame_nr
= req
.tp_block_nr
* frames_per_block
;
3647 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
3648 (void *) &req
, sizeof(req
))) {
3649 if ((errno
== ENOMEM
) && (req
.tp_block_nr
> 1)) {
3651 * Memory failure; try to reduce the requested ring
3654 * We used to reduce this by half -- do 5% instead.
3655 * That may result in more iterations and a longer
3656 * startup, but the user will be much happier with
3657 * the resulting buffer size.
3659 if (req
.tp_frame_nr
< 20)
3660 req
.tp_frame_nr
-= 1;
3662 req
.tp_frame_nr
-= req
.tp_frame_nr
/20;
3665 if (errno
== ENOPROTOOPT
) {
3667 * We don't have ring buffer support in this kernel.
3671 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3672 "can't create rx ring on packet socket: %s",
3673 pcap_strerror(errno
));
3674 *status
= PCAP_ERROR
;
3678 /* memory map the rx ring */
3679 handlep
->mmapbuflen
= req
.tp_block_nr
* req
.tp_block_size
;
3680 handlep
->mmapbuf
= mmap(0, handlep
->mmapbuflen
,
3681 PROT_READ
|PROT_WRITE
, MAP_SHARED
, handle
->fd
, 0);
3682 if (handlep
->mmapbuf
== MAP_FAILED
) {
3683 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3684 "can't mmap rx ring: %s", pcap_strerror(errno
));
3686 /* clear the allocated ring on error*/
3687 destroy_ring(handle
);
3688 *status
= PCAP_ERROR
;
3692 /* allocate a ring for each frame header pointer*/
3693 handle
->cc
= req
.tp_frame_nr
;
3694 handle
->buffer
= malloc(handle
->cc
* sizeof(union thdr
*));
3695 if (!handle
->buffer
) {
3696 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3697 "can't allocate ring of frame headers: %s",
3698 pcap_strerror(errno
));
3700 destroy_ring(handle
);
3701 *status
= PCAP_ERROR
;
3705 /* fill the header ring with proper frame ptr*/
3707 for (i
=0; i
<req
.tp_block_nr
; ++i
) {
3708 void *base
= &handlep
->mmapbuf
[i
*req
.tp_block_size
];
3709 for (j
=0; j
<frames_per_block
; ++j
, ++handle
->offset
) {
3710 RING_GET_FRAME(handle
) = base
;
3711 base
+= req
.tp_frame_size
;
3715 handle
->bufsize
= req
.tp_frame_size
;
3720 /* free all ring related resources*/
3722 destroy_ring(pcap_t
*handle
)
3724 struct pcap_linux
*handlep
= handle
->private;
3726 /* tell the kernel to destroy the ring*/
3727 struct tpacket_req req
;
3728 memset(&req
, 0, sizeof(req
));
3729 setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
3730 (void *) &req
, sizeof(req
));
3732 /* if ring is mapped, unmap it*/
3733 if (handlep
->mmapbuf
) {
3734 /* do not test for mmap failure, as we can't recover from any error */
3735 munmap(handlep
->mmapbuf
, handlep
->mmapbuflen
);
3736 handlep
->mmapbuf
= NULL
;
3741 * Special one-shot callback, used for pcap_next() and pcap_next_ex(),
3742 * for Linux mmapped capture.
3744 * The problem is that pcap_next() and pcap_next_ex() expect the packet
3745 * data handed to the callback to be valid after the callback returns,
3746 * but pcap_read_linux_mmap() has to release that packet as soon as
3747 * the callback returns (otherwise, the kernel thinks there's still
3748 * at least one unprocessed packet available in the ring, so a select()
3749 * will immediately return indicating that there's data to process), so,
3750 * in the callback, we have to make a copy of the packet.
3752 * Yes, this means that, if the capture is using the ring buffer, using
3753 * pcap_next() or pcap_next_ex() requires more copies than using
3754 * pcap_loop() or pcap_dispatch(). If that bothers you, don't use
3755 * pcap_next() or pcap_next_ex().
3758 pcap_oneshot_mmap(u_char
*user
, const struct pcap_pkthdr
*h
,
3759 const u_char
*bytes
)
3761 struct oneshot_userdata
*sp
= (struct oneshot_userdata
*)user
;
3762 pcap_t
*handle
= sp
->pd
;
3763 struct pcap_linux
*handlep
= handle
->private;
3766 memcpy(handlep
->oneshot_buffer
, bytes
, h
->caplen
);
3767 *sp
->pkt
= handlep
->oneshot_buffer
;
3771 pcap_cleanup_linux_mmap( pcap_t
*handle
)
3773 struct pcap_linux
*handlep
= handle
->private;
3775 destroy_ring(handle
);
3776 if (handlep
->oneshot_buffer
!= NULL
) {
3777 free(handlep
->oneshot_buffer
);
3778 handlep
->oneshot_buffer
= NULL
;
3780 pcap_cleanup_linux(handle
);
3785 pcap_getnonblock_mmap(pcap_t
*p
, char *errbuf
)
3787 struct pcap_linux
*handlep
= p
->private;
3789 /* use negative value of timeout to indicate non blocking ops */
3790 return (handlep
->timeout
<0);
3794 pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
, char *errbuf
)
3796 struct pcap_linux
*handlep
= p
->private;
3799 * Map each value to their corresponding negation to
3800 * preserve the timeout value provided with pcap_set_timeout.
3803 if (handlep
->timeout
>= 0) {
3805 * Indicate that we're switching to
3806 * non-blocking mode.
3808 handlep
->timeout
= ~handlep
->timeout
;
3811 if (handlep
->timeout
< 0) {
3812 handlep
->timeout
= ~handlep
->timeout
;
3818 static inline union thdr
*
3819 pcap_get_ring_frame(pcap_t
*handle
, int status
)
3821 struct pcap_linux
*handlep
= handle
->private;
3824 h
.raw
= RING_GET_FRAME(handle
);
3825 switch (handlep
->tp_version
) {
3827 if (status
!= (h
.h1
->tp_status
? TP_STATUS_USER
:
3831 #ifdef HAVE_TPACKET2
3833 if (status
!= (h
.h2
->tp_status
? TP_STATUS_USER
:
3847 pcap_read_linux_mmap(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
3850 struct pcap_linux
*handlep
= handle
->private;
3855 /* wait for frames availability.*/
3856 if (!pcap_get_ring_frame(handle
, TP_STATUS_USER
)) {
3857 struct pollfd pollinfo
;
3860 pollinfo
.fd
= handle
->fd
;
3861 pollinfo
.events
= POLLIN
;
3863 if (handlep
->timeout
== 0)
3864 timeout
= -1; /* block forever */
3865 else if (handlep
->timeout
> 0)
3866 timeout
= handlep
->timeout
; /* block for that amount of time */
3868 timeout
= 0; /* non-blocking mode - poll to pick up errors */
3870 ret
= poll(&pollinfo
, 1, timeout
);
3871 if (ret
< 0 && errno
!= EINTR
) {
3872 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3873 "can't poll on packet socket: %s",
3874 pcap_strerror(errno
));
3876 } else if (ret
> 0 &&
3877 (pollinfo
.revents
& (POLLHUP
|POLLRDHUP
|POLLERR
|POLLNVAL
))) {
3879 * There's some indication other than
3880 * "you can read on this descriptor" on
3883 if (pollinfo
.revents
& (POLLHUP
| POLLRDHUP
)) {
3884 snprintf(handle
->errbuf
,
3886 "Hangup on packet socket");
3889 if (pollinfo
.revents
& POLLERR
) {
3891 * A recv() will give us the
3892 * actual error code.
3894 * XXX - make the socket non-blocking?
3896 if (recv(handle
->fd
, &c
, sizeof c
,
3898 continue; /* what, no error? */
3899 if (errno
== ENETDOWN
) {
3901 * The device on which we're
3902 * capturing went away.
3904 * XXX - we should really return
3905 * PCAP_ERROR_IFACE_NOT_UP,
3906 * but pcap_dispatch() etc.
3907 * aren't defined to return
3910 snprintf(handle
->errbuf
,
3912 "The interface went down");
3914 snprintf(handle
->errbuf
,
3916 "Error condition on packet socket: %s",
3921 if (pollinfo
.revents
& POLLNVAL
) {
3922 snprintf(handle
->errbuf
,
3924 "Invalid polling request on packet socket");
3928 /* check for break loop condition on interrupted syscall*/
3929 if (handle
->break_loop
) {
3930 handle
->break_loop
= 0;
3931 return PCAP_ERROR_BREAK
;
3936 /* non-positive values of max_packets are used to require all
3937 * packets currently available in the ring */
3938 while ((pkts
< max_packets
) || (max_packets
<= 0)) {
3940 struct sockaddr_ll
*sll
;
3941 struct pcap_pkthdr pcaphdr
;
3944 unsigned int tp_len
;
3945 unsigned int tp_mac
;
3946 unsigned int tp_snaplen
;
3947 unsigned int tp_sec
;
3948 unsigned int tp_usec
;
3950 h
.raw
= pcap_get_ring_frame(handle
, TP_STATUS_USER
);
3954 switch (handlep
->tp_version
) {
3956 tp_len
= h
.h1
->tp_len
;
3957 tp_mac
= h
.h1
->tp_mac
;
3958 tp_snaplen
= h
.h1
->tp_snaplen
;
3959 tp_sec
= h
.h1
->tp_sec
;
3960 tp_usec
= h
.h1
->tp_usec
;
3962 #ifdef HAVE_TPACKET2
3964 tp_len
= h
.h2
->tp_len
;
3965 tp_mac
= h
.h2
->tp_mac
;
3966 tp_snaplen
= h
.h2
->tp_snaplen
;
3967 tp_sec
= h
.h2
->tp_sec
;
3968 tp_usec
= h
.h2
->tp_nsec
/ 1000;
3972 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3973 "unsupported tpacket version %d",
3974 handlep
->tp_version
);
3977 /* perform sanity check on internal offset. */
3978 if (tp_mac
+ tp_snaplen
> handle
->bufsize
) {
3979 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3980 "corrupted frame on kernel ring mac "
3981 "offset %d + caplen %d > frame len %d",
3982 tp_mac
, tp_snaplen
, handle
->bufsize
);
3986 /* run filter on received packet
3987 * If the kernel filtering is enabled we need to run the
3988 * filter until all the frames present into the ring
3989 * at filter creation time are processed.
3990 * In such case filtering_in_kernel is used as a counter for the
3991 * packet we need to filter.
3992 * Note: alternatively it could be possible to stop applying
3993 * the filter when the ring became empty, but it can possibly
3994 * happen a lot later... */
3995 bp
= (unsigned char*)h
.raw
+ tp_mac
;
3996 run_bpf
= (!handlep
->filtering_in_kernel
) ||
3997 ((handlep
->filtering_in_kernel
>1) && handlep
->filtering_in_kernel
--);
3998 if (run_bpf
&& handle
->fcode
.bf_insns
&&
3999 (bpf_filter(handle
->fcode
.bf_insns
, bp
,
4000 tp_len
, tp_snaplen
) == 0))
4004 * Do checks based on packet direction.
4006 sll
= (void *)h
.raw
+ TPACKET_ALIGN(handlep
->tp_hdrlen
);
4007 if (sll
->sll_pkttype
== PACKET_OUTGOING
) {
4010 * If this is from the loopback device, reject it;
4011 * we'll see the packet as an incoming packet as well,
4012 * and we don't want to see it twice.
4014 if (sll
->sll_ifindex
== handlep
->lo_ifindex
)
4018 * If the user only wants incoming packets, reject it.
4020 if (handle
->direction
== PCAP_D_IN
)
4025 * If the user only wants outgoing packets, reject it.
4027 if (handle
->direction
== PCAP_D_OUT
)
4031 /* get required packet info from ring header */
4032 pcaphdr
.ts
.tv_sec
= tp_sec
;
4033 pcaphdr
.ts
.tv_usec
= tp_usec
;
4034 pcaphdr
.caplen
= tp_snaplen
;
4035 pcaphdr
.len
= tp_len
;
4037 /* if required build in place the sll header*/
4038 if (handlep
->cooked
) {
4039 struct sll_header
*hdrp
;
4042 * The kernel should have left us with enough
4043 * space for an sll header; back up the packet
4044 * data pointer into that space, as that'll be
4045 * the beginning of the packet we pass to the
4051 * Let's make sure that's past the end of
4052 * the tpacket header, i.e. >=
4053 * ((u_char *)thdr + TPACKET_HDRLEN), so we
4054 * don't step on the header when we construct
4057 if (bp
< (u_char
*)h
.raw
+
4058 TPACKET_ALIGN(handlep
->tp_hdrlen
) +
4059 sizeof(struct sockaddr_ll
)) {
4060 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4061 "cooked-mode frame doesn't have room for sll header");
4066 * OK, that worked; construct the sll header.
4068 hdrp
= (struct sll_header
*)bp
;
4069 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(
4071 hdrp
->sll_hatype
= htons(sll
->sll_hatype
);
4072 hdrp
->sll_halen
= htons(sll
->sll_halen
);
4073 memcpy(hdrp
->sll_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
4074 hdrp
->sll_protocol
= sll
->sll_protocol
;
4076 /* update packet len */
4077 pcaphdr
.caplen
+= SLL_HDR_LEN
;
4078 pcaphdr
.len
+= SLL_HDR_LEN
;
4081 #ifdef HAVE_TPACKET2
4082 if ((handlep
->tp_version
== TPACKET_V2
) &&
4083 #if defined(TP_STATUS_VLAN_VALID)
4084 (h
.h2
->tp_vlan_tci
|| (h
.h2
->tp_status
& TP_STATUS_VLAN_VALID
)) &&
4086 h
.h2
->tp_vlan_tci
&&
4088 handlep
->vlan_offset
!= -1 &&
4089 tp_snaplen
>= (unsigned int) handlep
->vlan_offset
) {
4090 struct vlan_tag
*tag
;
4093 memmove(bp
, bp
+ VLAN_TAG_LEN
, handlep
->vlan_offset
);
4095 tag
= (struct vlan_tag
*)(bp
+ handlep
->vlan_offset
);
4096 tag
->vlan_tpid
= htons(ETH_P_8021Q
);
4097 tag
->vlan_tci
= htons(h
.h2
->tp_vlan_tci
);
4099 pcaphdr
.caplen
+= VLAN_TAG_LEN
;
4100 pcaphdr
.len
+= VLAN_TAG_LEN
;
4105 * The only way to tell the kernel to cut off the
4106 * packet at a snapshot length is with a filter program;
4107 * if there's no filter program, the kernel won't cut
4110 * Trim the snapshot length to be no longer than the
4111 * specified snapshot length.
4113 if (pcaphdr
.caplen
> handle
->snapshot
)
4114 pcaphdr
.caplen
= handle
->snapshot
;
4116 /* pass the packet to the user */
4118 callback(user
, &pcaphdr
, bp
);
4119 handlep
->packets_read
++;
4123 switch (handlep
->tp_version
) {
4125 h
.h1
->tp_status
= TP_STATUS_KERNEL
;
4127 #ifdef HAVE_TPACKET2
4129 h
.h2
->tp_status
= TP_STATUS_KERNEL
;
4133 if (++handle
->offset
>= handle
->cc
)
4136 /* check for break loop condition*/
4137 if (handle
->break_loop
) {
4138 handle
->break_loop
= 0;
4139 return PCAP_ERROR_BREAK
;
4146 pcap_setfilter_linux_mmap(pcap_t
*handle
, struct bpf_program
*filter
)
4148 struct pcap_linux
*handlep
= handle
->private;
4153 * Don't rewrite "ret" instructions; we don't need to, as
4154 * we're not reading packets with recvmsg(), and we don't
4155 * want to, as, by not rewriting them, the kernel can avoid
4156 * copying extra data.
4158 ret
= pcap_setfilter_linux_common(handle
, filter
, 1);
4162 /* if the kernel filter is enabled, we need to apply the filter on
4163 * all packets present into the ring. Get an upper bound of their number
4165 if (!handlep
->filtering_in_kernel
)
4168 /* walk the ring backward and count the free slot */
4169 offset
= handle
->offset
;
4170 if (--handle
->offset
< 0)
4171 handle
->offset
= handle
->cc
- 1;
4172 for (n
=0; n
< handle
->cc
; ++n
) {
4173 if (--handle
->offset
< 0)
4174 handle
->offset
= handle
->cc
- 1;
4175 if (!pcap_get_ring_frame(handle
, TP_STATUS_KERNEL
))
4179 /* be careful to not change current ring position */
4180 handle
->offset
= offset
;
4182 /* store the number of packets currently present in the ring */
4183 handlep
->filtering_in_kernel
= 1 + (handle
->cc
- n
);
4187 #endif /* HAVE_PACKET_RING */
4190 #ifdef HAVE_PF_PACKET_SOCKETS
4192 * Return the index of the given device name. Fill ebuf and return
4196 iface_get_id(int fd
, const char *device
, char *ebuf
)
4200 memset(&ifr
, 0, sizeof(ifr
));
4201 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4203 if (ioctl(fd
, SIOCGIFINDEX
, &ifr
) == -1) {
4204 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4205 "SIOCGIFINDEX: %s", pcap_strerror(errno
));
4209 return ifr
.ifr_ifindex
;
4213 * Bind the socket associated with FD to the given device.
4214 * Return 1 on success, 0 if we should try a SOCK_PACKET socket,
4215 * or a PCAP_ERROR_ value on a hard error.
4218 iface_bind(int fd
, int ifindex
, char *ebuf
)
4220 struct sockaddr_ll sll
;
4222 socklen_t errlen
= sizeof(err
);
4224 memset(&sll
, 0, sizeof(sll
));
4225 sll
.sll_family
= AF_PACKET
;
4226 sll
.sll_ifindex
= ifindex
;
4227 sll
.sll_protocol
= htons(ETH_P_ALL
);
4229 if (bind(fd
, (struct sockaddr
*) &sll
, sizeof(sll
)) == -1) {
4230 if (errno
== ENETDOWN
) {
4232 * Return a "network down" indication, so that
4233 * the application can report that rather than
4234 * saying we had a mysterious failure and
4235 * suggest that they report a problem to the
4236 * libpcap developers.
4238 return PCAP_ERROR_IFACE_NOT_UP
;
4240 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4241 "bind: %s", pcap_strerror(errno
));
4246 /* Any pending errors, e.g., network is down? */
4248 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
4249 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4250 "getsockopt: %s", pcap_strerror(errno
));
4254 if (err
== ENETDOWN
) {
4256 * Return a "network down" indication, so that
4257 * the application can report that rather than
4258 * saying we had a mysterious failure and
4259 * suggest that they report a problem to the
4260 * libpcap developers.
4262 return PCAP_ERROR_IFACE_NOT_UP
;
4263 } else if (err
> 0) {
4264 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4265 "bind: %s", pcap_strerror(err
));
4272 #ifdef IW_MODE_MONITOR
4274 * Check whether the device supports the Wireless Extensions.
4275 * Returns 1 if it does, 0 if it doesn't, PCAP_ERROR_NO_SUCH_DEVICE
4276 * if the device doesn't even exist.
4279 has_wext(int sock_fd
, const char *device
, char *ebuf
)
4283 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4284 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4285 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4286 if (ioctl(sock_fd
, SIOCGIWNAME
, &ireq
) >= 0)
4288 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4289 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
4290 if (errno
== ENODEV
)
4291 return PCAP_ERROR_NO_SUCH_DEVICE
;
4296 * Per me si va ne la citta dolente,
4297 * Per me si va ne l'etterno dolore,
4299 * Lasciate ogne speranza, voi ch'intrate.
4301 * XXX - airmon-ng does special stuff with the Orinoco driver and the
4317 * Use the Wireless Extensions, if we have them, to try to turn monitor mode
4318 * on if it's not already on.
4320 * Returns 1 on success, 0 if we don't support the Wireless Extensions
4321 * on this device, or a PCAP_ERROR_ value if we do support them but
4322 * we weren't able to turn monitor mode on.
4325 enter_rfmon_mode_wext(pcap_t
*handle
, int sock_fd
, const char *device
)
4328 * XXX - at least some adapters require non-Wireless Extensions
4329 * mechanisms to turn monitor mode on.
4331 * Atheros cards might require that a separate "monitor virtual access
4332 * point" be created, with later versions of the madwifi driver.
4333 * airmon-ng does "wlanconfig ath create wlandev {if} wlanmode
4334 * monitor -bssid", which apparently spits out a line "athN"
4335 * where "athN" is the monitor mode device. To leave monitor
4336 * mode, it destroys the monitor mode device.
4338 * Some Intel Centrino adapters might require private ioctls to get
4339 * radio headers; the ipw2200 and ipw3945 drivers allow you to
4340 * configure a separate "rtapN" interface to capture in monitor
4341 * mode without preventing the adapter from operating normally.
4342 * (airmon-ng doesn't appear to use that, though.)
4344 * It would be Truly Wonderful if mac80211 and nl80211 cleaned this
4345 * up, and if all drivers were converted to mac80211 drivers.
4347 * If interface {if} is a mac80211 driver, the file
4348 * /sys/class/net/{if}/phy80211 is a symlink to
4349 * /sys/class/ieee80211/{phydev}, for some {phydev}.
4351 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
4352 * least, has a "wmaster0" device and a "wlan0" device; the
4353 * latter is the one with the IP address. Both show up in
4354 * "tcpdump -D" output. Capturing on the wmaster0 device
4355 * captures with 802.11 headers.
4357 * airmon-ng searches through /sys/class/net for devices named
4358 * monN, starting with mon0; as soon as one *doesn't* exist,
4359 * it chooses that as the monitor device name. If the "iw"
4360 * command exists, it does "iw dev {if} interface add {monif}
4361 * type monitor", where {monif} is the monitor device. It
4362 * then (sigh) sleeps .1 second, and then configures the
4363 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
4364 * is a file, it writes {mondev}, without a newline, to that file,
4365 * and again (sigh) sleeps .1 second, and then iwconfig's that
4366 * device into monitor mode and configures it up. Otherwise,
4367 * you can't do monitor mode.
4369 * All these devices are "glued" together by having the
4370 * /sys/class/net/{device}/phy80211 links pointing to the same
4371 * place, so, given a wmaster, wlan, or mon device, you can
4372 * find the other devices by looking for devices with
4373 * the same phy80211 link.
4375 * To turn monitor mode off, delete the monitor interface,
4376 * either with "iw dev {monif} interface del" or by sending
4377 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
4379 * Note: if you try to create a monitor device named "monN", and
4380 * there's already a "monN" device, it fails, as least with
4381 * the netlink interface (which is what iw uses), with a return
4382 * value of -ENFILE. (Return values are negative errnos.) We
4383 * could probably use that to find an unused device.
4385 struct pcap_linux
*handlep
= handle
->private;
4388 struct iw_priv_args
*priv
;
4389 monitor_type montype
;
4398 * Does this device *support* the Wireless Extensions?
4400 err
= has_wext(sock_fd
, device
, handle
->errbuf
);
4402 return err
; /* either it doesn't or the device doesn't even exist */
4404 * Start out assuming we have no private extensions to control
4407 montype
= MONITOR_WEXT
;
4411 * Try to get all the Wireless Extensions private ioctls
4412 * supported by this device.
4414 * First, get the size of the buffer we need, by supplying no
4415 * buffer and a length of 0. If the device supports private
4416 * ioctls, it should return E2BIG, with ireq.u.data.length set
4417 * to the length we need. If it doesn't support them, it should
4418 * return EOPNOTSUPP.
4420 memset(&ireq
, 0, sizeof ireq
);
4421 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4422 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4423 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4424 ireq
.u
.data
.pointer
= (void *)args
;
4425 ireq
.u
.data
.length
= 0;
4426 ireq
.u
.data
.flags
= 0;
4427 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) != -1) {
4428 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4429 "%s: SIOCGIWPRIV with a zero-length buffer didn't fail!",
4433 if (errno
!= EOPNOTSUPP
) {
4435 * OK, it's not as if there are no private ioctls.
4437 if (errno
!= E2BIG
) {
4441 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4442 "%s: SIOCGIWPRIV: %s", device
,
4443 pcap_strerror(errno
));
4448 * OK, try to get the list of private ioctls.
4450 priv
= malloc(ireq
.u
.data
.length
* sizeof (struct iw_priv_args
));
4452 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4453 "malloc: %s", pcap_strerror(errno
));
4456 ireq
.u
.data
.pointer
= (void *)priv
;
4457 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) == -1) {
4458 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4459 "%s: SIOCGIWPRIV: %s", device
,
4460 pcap_strerror(errno
));
4466 * Look for private ioctls to turn monitor mode on or, if
4467 * monitor mode is on, to set the header type.
4469 for (i
= 0; i
< ireq
.u
.data
.length
; i
++) {
4470 if (strcmp(priv
[i
].name
, "monitor_type") == 0) {
4472 * Hostap driver, use this one.
4473 * Set monitor mode first.
4474 * You can set it to 0 to get DLT_IEEE80211,
4475 * 1 to get DLT_PRISM, 2 to get
4476 * DLT_IEEE80211_RADIO_AVS, and, with more
4477 * recent versions of the driver, 3 to get
4478 * DLT_IEEE80211_RADIO.
4480 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4482 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4484 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
4486 montype
= MONITOR_HOSTAP
;
4490 if (strcmp(priv
[i
].name
, "set_prismhdr") == 0) {
4492 * Prism54 driver, use this one.
4493 * Set monitor mode first.
4494 * You can set it to 2 to get DLT_IEEE80211
4495 * or 3 or get DLT_PRISM.
4497 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4499 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4501 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
4503 montype
= MONITOR_PRISM54
;
4507 if (strcmp(priv
[i
].name
, "forceprismheader") == 0) {
4509 * RT2570 driver, use this one.
4510 * Do this after turning monitor mode on.
4511 * You can set it to 1 to get DLT_PRISM or 2
4512 * to get DLT_IEEE80211.
4514 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4516 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4518 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
4520 montype
= MONITOR_RT2570
;
4524 if (strcmp(priv
[i
].name
, "forceprism") == 0) {
4526 * RT73 driver, use this one.
4527 * Do this after turning monitor mode on.
4528 * Its argument is a *string*; you can
4529 * set it to "1" to get DLT_PRISM or "2"
4530 * to get DLT_IEEE80211.
4532 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_CHAR
)
4534 if (priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
)
4536 montype
= MONITOR_RT73
;
4540 if (strcmp(priv
[i
].name
, "prismhdr") == 0) {
4542 * One of the RTL8xxx drivers, use this one.
4543 * It can only be done after monitor mode
4544 * has been turned on. You can set it to 1
4545 * to get DLT_PRISM or 0 to get DLT_IEEE80211.
4547 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4549 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4551 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
4553 montype
= MONITOR_RTL8XXX
;
4557 if (strcmp(priv
[i
].name
, "rfmontx") == 0) {
4559 * RT2500 or RT61 driver, use this one.
4560 * It has one one-byte parameter; set
4561 * u.data.length to 1 and u.data.pointer to
4562 * point to the parameter.
4563 * It doesn't itself turn monitor mode on.
4564 * You can set it to 1 to allow transmitting
4565 * in monitor mode(?) and get DLT_IEEE80211,
4566 * or set it to 0 to disallow transmitting in
4567 * monitor mode(?) and get DLT_PRISM.
4569 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4571 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 2)
4573 montype
= MONITOR_RT2500
;
4577 if (strcmp(priv
[i
].name
, "monitor") == 0) {
4579 * Either ACX100 or hostap, use this one.
4580 * It turns monitor mode on.
4581 * If it takes two arguments, it's ACX100;
4582 * the first argument is 1 for DLT_PRISM
4583 * or 2 for DLT_IEEE80211, and the second
4584 * argument is the channel on which to
4585 * run. If it takes one argument, it's
4586 * HostAP, and the argument is 2 for
4587 * DLT_IEEE80211 and 3 for DLT_PRISM.
4589 * If we see this, we don't quit, as this
4590 * might be a version of the hostap driver
4591 * that also supports "monitor_type".
4593 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4595 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4597 switch (priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) {
4600 montype
= MONITOR_PRISM
;
4605 montype
= MONITOR_ACX100
;
4618 * XXX - ipw3945? islism?
4624 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4625 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4626 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4627 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) == -1) {
4629 * We probably won't be able to set the mode, either.
4631 return PCAP_ERROR_RFMON_NOTSUP
;
4635 * Is it currently in monitor mode?
4637 if (ireq
.u
.mode
== IW_MODE_MONITOR
) {
4639 * Yes. Just leave things as they are.
4640 * We don't offer multiple link-layer types, as
4641 * changing the link-layer type out from under
4642 * somebody else capturing in monitor mode would
4643 * be considered rude.
4648 * No. We have to put the adapter into rfmon mode.
4652 * If we haven't already done so, arrange to have
4653 * "pcap_close_all()" called when we exit.
4655 if (!pcap_do_addexit(handle
)) {
4657 * "atexit()" failed; don't put the interface
4658 * in rfmon mode, just give up.
4660 return PCAP_ERROR_RFMON_NOTSUP
;
4664 * Save the old mode.
4666 handlep
->oldmode
= ireq
.u
.mode
;
4669 * Put the adapter in rfmon mode. How we do this depends
4670 * on whether we have a special private ioctl or not.
4672 if (montype
== MONITOR_PRISM
) {
4674 * We have the "monitor" private ioctl, but none of
4675 * the other private ioctls. Use this, and select
4678 * If it fails, just fall back on SIOCSIWMODE.
4680 memset(&ireq
, 0, sizeof ireq
);
4681 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4682 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4683 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4684 ireq
.u
.data
.length
= 1; /* 1 argument */
4685 args
[0] = 3; /* request Prism header */
4686 memcpy(ireq
.u
.name
, args
, IFNAMSIZ
);
4687 if (ioctl(sock_fd
, cmd
, &ireq
) != -1) {
4690 * Note that we have to put the old mode back
4691 * when we close the device.
4693 handlep
->must_do_on_close
|= MUST_CLEAR_RFMON
;
4696 * Add this to the list of pcaps to close
4699 pcap_add_to_pcaps_to_close(handle
);
4705 * Failure. Fall back on SIOCSIWMODE.
4710 * First, take the interface down if it's up; otherwise, we
4713 memset(&ifr
, 0, sizeof(ifr
));
4714 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4715 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
4716 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4717 "%s: Can't get flags: %s", device
, strerror(errno
));
4721 if (ifr
.ifr_flags
& IFF_UP
) {
4722 oldflags
= ifr
.ifr_flags
;
4723 ifr
.ifr_flags
&= ~IFF_UP
;
4724 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
4725 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4726 "%s: Can't set flags: %s", device
, strerror(errno
));
4732 * Then turn monitor mode on.
4734 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4735 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4736 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4737 ireq
.u
.mode
= IW_MODE_MONITOR
;
4738 if (ioctl(sock_fd
, SIOCSIWMODE
, &ireq
) == -1) {
4740 * Scientist, you've failed.
4741 * Bring the interface back up if we shut it down.
4743 ifr
.ifr_flags
= oldflags
;
4744 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
4745 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4746 "%s: Can't set flags: %s", device
, strerror(errno
));
4749 return PCAP_ERROR_RFMON_NOTSUP
;
4753 * XXX - airmon-ng does "iwconfig {if} key off" after setting
4754 * monitor mode and setting the channel, and then does
4759 * Now select the appropriate radio header.
4765 * We don't have any private ioctl to set the header.
4769 case MONITOR_HOSTAP
:
4771 * Try to select the radiotap header.
4773 memset(&ireq
, 0, sizeof ireq
);
4774 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4775 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4776 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4777 args
[0] = 3; /* request radiotap header */
4778 memcpy(ireq
.u
.name
, args
, sizeof (int));
4779 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
4780 break; /* success */
4783 * That failed. Try to select the AVS header.
4785 memset(&ireq
, 0, sizeof ireq
);
4786 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4787 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4788 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4789 args
[0] = 2; /* request AVS header */
4790 memcpy(ireq
.u
.name
, args
, sizeof (int));
4791 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
4792 break; /* success */
4795 * That failed. Try to select the Prism header.
4797 memset(&ireq
, 0, sizeof ireq
);
4798 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4799 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4800 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4801 args
[0] = 1; /* request Prism header */
4802 memcpy(ireq
.u
.name
, args
, sizeof (int));
4803 ioctl(sock_fd
, cmd
, &ireq
);
4808 * The private ioctl failed.
4812 case MONITOR_PRISM54
:
4814 * Select the Prism header.
4816 memset(&ireq
, 0, sizeof ireq
);
4817 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4818 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4819 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4820 args
[0] = 3; /* request Prism header */
4821 memcpy(ireq
.u
.name
, args
, sizeof (int));
4822 ioctl(sock_fd
, cmd
, &ireq
);
4825 case MONITOR_ACX100
:
4827 * Get the current channel.
4829 memset(&ireq
, 0, sizeof ireq
);
4830 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4831 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4832 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4833 if (ioctl(sock_fd
, SIOCGIWFREQ
, &ireq
) == -1) {
4834 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4835 "%s: SIOCGIWFREQ: %s", device
,
4836 pcap_strerror(errno
));
4839 channel
= ireq
.u
.freq
.m
;
4842 * Select the Prism header, and set the channel to the
4845 memset(&ireq
, 0, sizeof ireq
);
4846 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4847 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4848 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4849 args
[0] = 1; /* request Prism header */
4850 args
[1] = channel
; /* set channel */
4851 memcpy(ireq
.u
.name
, args
, 2*sizeof (int));
4852 ioctl(sock_fd
, cmd
, &ireq
);
4855 case MONITOR_RT2500
:
4857 * Disallow transmission - that turns on the
4860 memset(&ireq
, 0, sizeof ireq
);
4861 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4862 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4863 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4864 args
[0] = 0; /* disallow transmitting */
4865 memcpy(ireq
.u
.name
, args
, sizeof (int));
4866 ioctl(sock_fd
, cmd
, &ireq
);
4869 case MONITOR_RT2570
:
4871 * Force the Prism header.
4873 memset(&ireq
, 0, sizeof ireq
);
4874 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4875 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4876 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4877 args
[0] = 1; /* request Prism header */
4878 memcpy(ireq
.u
.name
, args
, sizeof (int));
4879 ioctl(sock_fd
, cmd
, &ireq
);
4884 * Force the Prism header.
4886 memset(&ireq
, 0, sizeof ireq
);
4887 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4888 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4889 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4890 ireq
.u
.data
.length
= 1; /* 1 argument */
4891 ireq
.u
.data
.pointer
= "1";
4892 ireq
.u
.data
.flags
= 0;
4893 ioctl(sock_fd
, cmd
, &ireq
);
4896 case MONITOR_RTL8XXX
:
4898 * Force the Prism header.
4900 memset(&ireq
, 0, sizeof ireq
);
4901 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4902 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4903 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4904 args
[0] = 1; /* request Prism header */
4905 memcpy(ireq
.u
.name
, args
, sizeof (int));
4906 ioctl(sock_fd
, cmd
, &ireq
);
4911 * Now bring the interface back up if we brought it down.
4913 if (oldflags
!= 0) {
4914 ifr
.ifr_flags
= oldflags
;
4915 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
4916 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4917 "%s: Can't set flags: %s", device
, strerror(errno
));
4920 * At least try to restore the old mode on the
4923 if (ioctl(handle
->fd
, SIOCSIWMODE
, &ireq
) == -1) {
4925 * Scientist, you've failed.
4928 "Can't restore interface wireless mode (SIOCSIWMODE failed: %s).\n"
4929 "Please adjust manually.\n",
4937 * Note that we have to put the old mode back when we
4940 handlep
->must_do_on_close
|= MUST_CLEAR_RFMON
;
4943 * Add this to the list of pcaps to close when we exit.
4945 pcap_add_to_pcaps_to_close(handle
);
4949 #endif /* IW_MODE_MONITOR */
4952 * Try various mechanisms to enter monitor mode.
4955 enter_rfmon_mode(pcap_t
*handle
, int sock_fd
, const char *device
)
4957 #if defined(HAVE_LIBNL) || defined(IW_MODE_MONITOR)
4962 ret
= enter_rfmon_mode_mac80211(handle
, sock_fd
, device
);
4964 return ret
; /* error attempting to do so */
4966 return 1; /* success */
4967 #endif /* HAVE_LIBNL */
4969 #ifdef IW_MODE_MONITOR
4970 ret
= enter_rfmon_mode_wext(handle
, sock_fd
, device
);
4972 return ret
; /* error attempting to do so */
4974 return 1; /* success */
4975 #endif /* IW_MODE_MONITOR */
4978 * Either none of the mechanisms we know about work or none
4979 * of those mechanisms are available, so we can't do monitor
4986 * Find out if we have any form of fragmentation/reassembly offloading.
4988 * We do so using SIOCETHTOOL checking for various types of offloading;
4989 * if SIOCETHTOOL isn't defined, or we don't have any #defines for any
4990 * of the types of offloading, there's nothing we can do to check, so
4991 * we just say "no, we don't".
4993 #if defined(SIOCETHTOOL) && (defined(ETHTOOL_GTSO) || defined(ETHTOOL_GUFO) || defined(ETHTOOL_GGSO) || defined(ETHTOOL_GFLAGS) || defined(ETHTOOL_GGRO))
4995 iface_ethtool_ioctl(pcap_t
*handle
, int cmd
, const char *cmdname
)
4998 struct ethtool_value eval
;
5000 memset(&ifr
, 0, sizeof(ifr
));
5001 strncpy(ifr
.ifr_name
, handle
->opt
.source
, sizeof(ifr
.ifr_name
));
5004 ifr
.ifr_data
= (caddr_t
)&eval
;
5005 if (ioctl(handle
->fd
, SIOCETHTOOL
, &ifr
) == -1) {
5006 if (errno
== EOPNOTSUPP
|| errno
== EINVAL
) {
5008 * OK, let's just return 0, which, in our
5009 * case, either means "no, what we're asking
5010 * about is not enabled" or "all the flags
5011 * are clear (i.e., nothing is enabled)".
5015 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5016 "%s: SIOETHTOOL(%s) ioctl failed: %s", handle
->opt
.source
,
5017 cmdname
, strerror(errno
));
5024 iface_get_offload(pcap_t
*handle
)
5029 ret
= iface_ethtool_ioctl(handle
, ETHTOOL_GTSO
, "ETHTOOL_GTSO");
5033 return 1; /* TCP segmentation offloading on */
5037 ret
= iface_ethtool_ioctl(handle
, ETHTOOL_GUFO
, "ETHTOOL_GUFO");
5041 return 1; /* UDP fragmentation offloading on */
5046 * XXX - will this cause large unsegmented packets to be
5047 * handed to PF_PACKET sockets on transmission? If not,
5048 * this need not be checked.
5050 ret
= iface_ethtool_ioctl(handle
, ETHTOOL_GGSO
, "ETHTOOL_GGSO");
5054 return 1; /* generic segmentation offloading on */
5057 #ifdef ETHTOOL_GFLAGS
5058 ret
= iface_ethtool_ioctl(handle
, ETHTOOL_GFLAGS
, "ETHTOOL_GFLAGS");
5061 if (ret
& ETH_FLAG_LRO
)
5062 return 1; /* large receive offloading on */
5067 * XXX - will this cause large reassembled packets to be
5068 * handed to PF_PACKET sockets on receipt? If not,
5069 * this need not be checked.
5071 ret
= iface_ethtool_ioctl(handle
, ETHTOOL_GGRO
, "ETHTOOL_GGRO");
5075 return 1; /* generic (large) receive offloading on */
5080 #else /* SIOCETHTOOL */
5082 iface_get_offload(pcap_t
*handle _U_
)
5085 * XXX - do we need to get this information if we don't
5086 * have the ethtool ioctls? If so, how do we do that?
5090 #endif /* SIOCETHTOOL */
5092 #endif /* HAVE_PF_PACKET_SOCKETS */
5094 /* ===== Functions to interface to the older kernels ================== */
5097 * Try to open a packet socket using the old kernel interface.
5098 * Returns 1 on success and a PCAP_ERROR_ value on an error.
5101 activate_old(pcap_t
*handle
)
5103 struct pcap_linux
*handlep
= handle
->private;
5106 const char *device
= handle
->opt
.source
;
5107 struct utsname utsname
;
5110 /* Open the socket */
5112 handle
->fd
= socket(PF_INET
, SOCK_PACKET
, htons(ETH_P_ALL
));
5113 if (handle
->fd
== -1) {
5114 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5115 "socket: %s", pcap_strerror(errno
));
5116 if (errno
== EPERM
|| errno
== EACCES
) {
5118 * You don't have permission to open the
5121 return PCAP_ERROR_PERM_DENIED
;
5130 /* It worked - we are using the old interface */
5131 handlep
->sock_packet
= 1;
5133 /* ...which means we get the link-layer header. */
5134 handlep
->cooked
= 0;
5136 /* Bind to the given device */
5138 if (strcmp(device
, "any") == 0) {
5139 strncpy(handle
->errbuf
, "pcap_activate: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
5143 if (iface_bind_old(handle
->fd
, device
, handle
->errbuf
) == -1)
5147 * Try to get the link-layer type.
5149 arptype
= iface_get_arptype(handle
->fd
, device
, handle
->errbuf
);
5154 * Try to find the DLT_ type corresponding to that
5157 map_arphrd_to_dlt(handle
, arptype
, 0);
5158 if (handle
->linktype
== -1) {
5159 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5160 "unknown arptype %d", arptype
);
5164 /* Go to promisc mode if requested */
5166 if (handle
->opt
.promisc
) {
5167 memset(&ifr
, 0, sizeof(ifr
));
5168 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5169 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
5170 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5171 "SIOCGIFFLAGS: %s", pcap_strerror(errno
));
5174 if ((ifr
.ifr_flags
& IFF_PROMISC
) == 0) {
5176 * Promiscuous mode isn't currently on,
5177 * so turn it on, and remember that
5178 * we should turn it off when the
5183 * If we haven't already done so, arrange
5184 * to have "pcap_close_all()" called when
5187 if (!pcap_do_addexit(handle
)) {
5189 * "atexit()" failed; don't put
5190 * the interface in promiscuous
5191 * mode, just give up.
5196 ifr
.ifr_flags
|= IFF_PROMISC
;
5197 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
5198 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5200 pcap_strerror(errno
));
5203 handlep
->must_do_on_close
|= MUST_CLEAR_PROMISC
;
5206 * Add this to the list of pcaps
5207 * to close when we exit.
5209 pcap_add_to_pcaps_to_close(handle
);
5214 * Compute the buffer size.
5216 * We're using SOCK_PACKET, so this might be a 2.0[.x]
5217 * kernel, and might require special handling - check.
5219 if (uname(&utsname
) < 0 ||
5220 strncmp(utsname
.release
, "2.0", 3) == 0) {
5222 * Either we couldn't find out what kernel release
5223 * this is, or it's a 2.0[.x] kernel.
5225 * In the 2.0[.x] kernel, a "recvfrom()" on
5226 * a SOCK_PACKET socket, with MSG_TRUNC set, will
5227 * return the number of bytes read, so if we pass
5228 * a length based on the snapshot length, it'll
5229 * return the number of bytes from the packet
5230 * copied to userland, not the actual length
5233 * This means that, for example, the IP dissector
5234 * in tcpdump will get handed a packet length less
5235 * than the length in the IP header, and will
5236 * complain about "truncated-ip".
5238 * So we don't bother trying to copy from the
5239 * kernel only the bytes in which we're interested,
5240 * but instead copy them all, just as the older
5241 * versions of libpcap for Linux did.
5243 * The buffer therefore needs to be big enough to
5244 * hold the largest packet we can get from this
5245 * device. Unfortunately, we can't get the MRU
5246 * of the network; we can only get the MTU. The
5247 * MTU may be too small, in which case a packet larger
5248 * than the buffer size will be truncated *and* we
5249 * won't get the actual packet size.
5251 * However, if the snapshot length is larger than
5252 * the buffer size based on the MTU, we use the
5253 * snapshot length as the buffer size, instead;
5254 * this means that with a sufficiently large snapshot
5255 * length we won't artificially truncate packets
5256 * to the MTU-based size.
5258 * This mess just one of many problems with packet
5259 * capture on 2.0[.x] kernels; you really want a
5260 * 2.2[.x] or later kernel if you want packet capture
5263 mtu
= iface_get_mtu(handle
->fd
, device
, handle
->errbuf
);
5266 handle
->bufsize
= MAX_LINKHEADER_SIZE
+ mtu
;
5267 if (handle
->bufsize
< handle
->snapshot
)
5268 handle
->bufsize
= handle
->snapshot
;
5271 * This is a 2.2[.x] or later kernel.
5273 * We can safely pass "recvfrom()" a byte count
5274 * based on the snapshot length.
5276 handle
->bufsize
= handle
->snapshot
;
5280 * Default value for offset to align link-layer payload
5281 * on a 4-byte boundary.
5286 * SOCK_PACKET sockets don't supply information from
5287 * stripped VLAN tags.
5289 handlep
->vlan_offset
= -1; /* unknown */
5295 * Bind the socket associated with FD to the given device using the
5296 * interface of the old kernels.
5299 iface_bind_old(int fd
, const char *device
, char *ebuf
)
5301 struct sockaddr saddr
;
5303 socklen_t errlen
= sizeof(err
);
5305 memset(&saddr
, 0, sizeof(saddr
));
5306 strncpy(saddr
.sa_data
, device
, sizeof(saddr
.sa_data
));
5307 if (bind(fd
, &saddr
, sizeof(saddr
)) == -1) {
5308 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5309 "bind: %s", pcap_strerror(errno
));
5313 /* Any pending errors, e.g., network is down? */
5315 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
5316 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5317 "getsockopt: %s", pcap_strerror(errno
));
5322 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5323 "bind: %s", pcap_strerror(err
));
5331 /* ===== System calls available on all supported kernels ============== */
5334 * Query the kernel for the MTU of the given interface.
5337 iface_get_mtu(int fd
, const char *device
, char *ebuf
)
5342 return BIGGER_THAN_ALL_MTUS
;
5344 memset(&ifr
, 0, sizeof(ifr
));
5345 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5347 if (ioctl(fd
, SIOCGIFMTU
, &ifr
) == -1) {
5348 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5349 "SIOCGIFMTU: %s", pcap_strerror(errno
));
5357 * Get the hardware type of the given interface as ARPHRD_xxx constant.
5360 iface_get_arptype(int fd
, const char *device
, char *ebuf
)
5364 memset(&ifr
, 0, sizeof(ifr
));
5365 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5367 if (ioctl(fd
, SIOCGIFHWADDR
, &ifr
) == -1) {
5368 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5369 "SIOCGIFHWADDR: %s", pcap_strerror(errno
));
5370 if (errno
== ENODEV
) {
5374 return PCAP_ERROR_NO_SUCH_DEVICE
;
5379 return ifr
.ifr_hwaddr
.sa_family
;
5382 #ifdef SO_ATTACH_FILTER
5384 fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
, int is_mmapped
)
5386 struct pcap_linux
*handlep
= handle
->private;
5389 register struct bpf_insn
*p
;
5394 * Make a copy of the filter, and modify that copy if
5397 prog_size
= sizeof(*handle
->fcode
.bf_insns
) * handle
->fcode
.bf_len
;
5398 len
= handle
->fcode
.bf_len
;
5399 f
= (struct bpf_insn
*)malloc(prog_size
);
5401 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5402 "malloc: %s", pcap_strerror(errno
));
5405 memcpy(f
, handle
->fcode
.bf_insns
, prog_size
);
5407 fcode
->filter
= (struct sock_filter
*) f
;
5409 for (i
= 0; i
< len
; ++i
) {
5412 * What type of instruction is this?
5414 switch (BPF_CLASS(p
->code
)) {
5418 * It's a return instruction; are we capturing
5419 * in memory-mapped mode?
5423 * No; is the snapshot length a constant,
5424 * rather than the contents of the
5427 if (BPF_MODE(p
->code
) == BPF_K
) {
5429 * Yes - if the value to be returned,
5430 * i.e. the snapshot length, is
5431 * anything other than 0, make it
5432 * 65535, so that the packet is
5433 * truncated by "recvfrom()",
5434 * not by the filter.
5436 * XXX - there's nothing we can
5437 * easily do if it's getting the
5438 * value from the accumulator; we'd
5439 * have to insert code to force
5440 * non-zero values to be 65535.
5451 * It's a load instruction; is it loading
5454 switch (BPF_MODE(p
->code
)) {
5460 * Yes; are we in cooked mode?
5462 if (handlep
->cooked
) {
5464 * Yes, so we need to fix this
5467 if (fix_offset(p
) < 0) {
5469 * We failed to do so.
5470 * Return 0, so our caller
5471 * knows to punt to userland.
5481 return 1; /* we succeeded */
5485 fix_offset(struct bpf_insn
*p
)
5488 * What's the offset?
5490 if (p
->k
>= SLL_HDR_LEN
) {
5492 * It's within the link-layer payload; that starts at an
5493 * offset of 0, as far as the kernel packet filter is
5494 * concerned, so subtract the length of the link-layer
5497 p
->k
-= SLL_HDR_LEN
;
5498 } else if (p
->k
== 0) {
5500 * It's the packet type field; map it to the special magic
5501 * kernel offset for that field.
5503 p
->k
= SKF_AD_OFF
+ SKF_AD_PKTTYPE
;
5504 } else if (p
->k
== 14) {
5506 * It's the protocol field; map it to the special magic
5507 * kernel offset for that field.
5509 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
5510 } else if ((bpf_int32
)(p
->k
) > 0) {
5512 * It's within the header, but it's not one of those
5513 * fields; we can't do that in the kernel, so punt
5522 set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
)
5524 int total_filter_on
= 0;
5530 * The socket filter code doesn't discard all packets queued
5531 * up on the socket when the filter is changed; this means
5532 * that packets that don't match the new filter may show up
5533 * after the new filter is put onto the socket, if those
5534 * packets haven't yet been read.
5536 * This means, for example, that if you do a tcpdump capture
5537 * with a filter, the first few packets in the capture might
5538 * be packets that wouldn't have passed the filter.
5540 * We therefore discard all packets queued up on the socket
5541 * when setting a kernel filter. (This isn't an issue for
5542 * userland filters, as the userland filtering is done after
5543 * packets are queued up.)
5545 * To flush those packets, we put the socket in read-only mode,
5546 * and read packets from the socket until there are no more to
5549 * In order to keep that from being an infinite loop - i.e.,
5550 * to keep more packets from arriving while we're draining
5551 * the queue - we put the "total filter", which is a filter
5552 * that rejects all packets, onto the socket before draining
5555 * This code deliberately ignores any errors, so that you may
5556 * get bogus packets if an error occurs, rather than having
5557 * the filtering done in userland even if it could have been
5558 * done in the kernel.
5560 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
5561 &total_fcode
, sizeof(total_fcode
)) == 0) {
5565 * Note that we've put the total filter onto the socket.
5567 total_filter_on
= 1;
5570 * Save the socket's current mode, and put it in
5571 * non-blocking mode; we drain it by reading packets
5572 * until we get an error (which is normally a
5573 * "nothing more to be read" error).
5575 save_mode
= fcntl(handle
->fd
, F_GETFL
, 0);
5576 if (save_mode
!= -1 &&
5577 fcntl(handle
->fd
, F_SETFL
, save_mode
| O_NONBLOCK
) >= 0) {
5578 while (recv(handle
->fd
, &drain
, sizeof drain
,
5582 fcntl(handle
->fd
, F_SETFL
, save_mode
);
5583 if (save_errno
!= EAGAIN
) {
5585 reset_kernel_filter(handle
);
5586 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5587 "recv: %s", pcap_strerror(save_errno
));
5594 * Now attach the new filter.
5596 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
5597 fcode
, sizeof(*fcode
));
5598 if (ret
== -1 && total_filter_on
) {
5600 * Well, we couldn't set that filter on the socket,
5601 * but we could set the total filter on the socket.
5603 * This could, for example, mean that the filter was
5604 * too big to put into the kernel, so we'll have to
5605 * filter in userland; in any case, we'll be doing
5606 * filtering in userland, so we need to remove the
5607 * total filter so we see packets.
5612 * XXX - if this fails, we're really screwed;
5613 * we have the total filter on the socket,
5614 * and it won't come off. What do we do then?
5616 reset_kernel_filter(handle
);
5624 reset_kernel_filter(pcap_t
*handle
)
5627 * setsockopt() barfs unless it get a dummy parameter.
5628 * valgrind whines unless the value is initialized,
5629 * as it has no idea that setsockopt() ignores its
5634 return setsockopt(handle
->fd
, SOL_SOCKET
, SO_DETACH_FILTER
,
5635 &dummy
, sizeof(dummy
));