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>
29 * Added TPACKET_V3 support
30 * Gabor Tatarka <gabor.tatarka@ericsson.com>
32 * based on previous works of:
33 * Simon Patarin <patarin@cs.unibo.it>
34 * Phil Wood <cpw@lanl.gov>
36 * Monitor-mode support for mac80211 includes code taken from the iw
37 * command; the copyright notice for that code is
39 * Copyright (c) 2007, 2008 Johannes Berg
40 * Copyright (c) 2007 Andy Lutomirski
41 * Copyright (c) 2007 Mike Kershaw
42 * Copyright (c) 2008 Gábor Stefanik
44 * All rights reserved.
46 * Redistribution and use in source and binary forms, with or without
47 * modification, are permitted provided that the following conditions
49 * 1. Redistributions of source code must retain the above copyright
50 * notice, this list of conditions and the following disclaimer.
51 * 2. Redistributions in binary form must reproduce the above copyright
52 * notice, this list of conditions and the following disclaimer in the
53 * documentation and/or other materials provided with the distribution.
54 * 3. The name of the author may not be used to endorse or promote products
55 * derived from this software without specific prior written permission.
57 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
58 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
59 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
60 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
61 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
62 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
63 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
64 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
65 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
66 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
85 #include <sys/socket.h>
86 #include <sys/ioctl.h>
87 #include <sys/utsname.h>
90 #include <linux/if_packet.h>
91 #include <linux/sockios.h>
92 #include <netinet/in.h>
93 #include <linux/if_ether.h>
94 #include <linux/if_arp.h>
97 #ifdef HAVE_SYS_EVENTFD_H
98 #include <sys/eventfd.h>
101 #include "pcap-int.h"
102 #include "pcap/sll.h"
103 #include "pcap/vlan.h"
105 #include "diag-control.h"
108 /* check for memory mapped access avaibility. We assume every needed
109 * struct is defined if the macro TPACKET_HDRLEN is defined, because it
110 * uses many ring related structs and macros */
111 #ifdef PCAP_SUPPORT_PACKET_RING
112 #ifdef TPACKET_HDRLEN
113 # define HAVE_PACKET_RING
114 # ifdef TPACKET3_HDRLEN
115 # define HAVE_TPACKET3
116 # endif /* TPACKET3_HDRLEN */
117 # ifdef TPACKET2_HDRLEN
118 # define HAVE_TPACKET2
119 # else /* TPACKET2_HDRLEN */
120 # define TPACKET_V1 0 /* Old kernel with only V1, so no TPACKET_Vn defined */
121 # endif /* TPACKET2_HDRLEN */
122 #endif /* TPACKET_HDRLEN */
123 #endif /* PCAP_SUPPORT_PACKET_RING */
125 #ifdef SO_ATTACH_FILTER
126 #include <linux/types.h>
127 #include <linux/filter.h>
130 #ifdef HAVE_LINUX_NET_TSTAMP_H
131 #include <linux/net_tstamp.h>
134 #ifdef HAVE_LINUX_SOCKIOS_H
135 #include <linux/sockios.h>
138 #ifdef HAVE_LINUX_IF_BONDING_H
139 #include <linux/if_bonding.h>
142 * The ioctl code to use to check whether a device is a bonding device.
144 #if defined(SIOCBONDINFOQUERY)
145 #define BOND_INFO_QUERY_IOCTL SIOCBONDINFOQUERY
146 #elif defined(BOND_INFO_QUERY_OLD)
147 #define BOND_INFO_QUERY_IOCTL BOND_INFO_QUERY_OLD
149 #endif /* HAVE_LINUX_IF_BONDING_H */
152 * Got Wireless Extensions?
154 #ifdef HAVE_LINUX_WIRELESS_H
155 #include <linux/wireless.h>
156 #endif /* HAVE_LINUX_WIRELESS_H */
162 #include <linux/nl80211.h>
164 #include <netlink/genl/genl.h>
165 #include <netlink/genl/family.h>
166 #include <netlink/genl/ctrl.h>
167 #include <netlink/msg.h>
168 #include <netlink/attr.h>
169 #endif /* HAVE_LIBNL */
172 * Got ethtool support?
174 #ifdef HAVE_LINUX_ETHTOOL_H
175 #include <linux/ethtool.h>
178 #ifndef HAVE_SOCKLEN_T
179 typedef int socklen_t
;
182 #define MAX_LINKHEADER_SIZE 256
185 * When capturing on all interfaces we use this as the buffer size.
186 * Should be bigger then all MTUs that occur in real life.
187 * 64kB should be enough for now.
189 #define BIGGER_THAN_ALL_MTUS (64*1024)
192 * Private data for capturing on Linux PF_PACKET sockets.
195 u_int packets_read
; /* count of packets read with recvfrom() */
196 long long sysfs_dropped
; /* packets reported dropped by /sys/class/net/{if_name}/statistics/rx_{missed,fifo}_errors */
197 struct pcap_stat stat
;
199 char *device
; /* device name */
200 int filter_in_userland
; /* must filter in userland */
201 int blocks_to_filter_in_userland
;
202 int must_do_on_close
; /* stuff we must do when we close */
203 int timeout
; /* timeout for buffering */
204 int cooked
; /* using SOCK_DGRAM rather than SOCK_RAW */
205 int ifindex
; /* interface index of device we're bound to */
206 int lo_ifindex
; /* interface index of the loopback device */
207 bpf_u_int32 oldmode
; /* mode to restore when turning monitor mode off */
208 char *mondevice
; /* mac80211 monitor device we created */
209 u_char
*mmapbuf
; /* memory-mapped region pointer */
210 size_t mmapbuflen
; /* size of region */
211 int vlan_offset
; /* offset at which to insert vlan tags; if -1, don't insert */
212 u_int tp_version
; /* version of tpacket_hdr for mmaped ring */
213 u_int tp_hdrlen
; /* hdrlen of tpacket_hdr for mmaped ring */
214 u_char
*oneshot_buffer
; /* buffer for copy of packet */
215 int poll_timeout
; /* timeout to use in poll() */
217 unsigned char *current_packet
; /* Current packet within the TPACKET_V3 block. Move to next block if NULL. */
218 int packets_left
; /* Unhandled packets left within the block from previous call to pcap_read_linux_mmap_v3 in case of TPACKET_V3. */
220 #ifdef HAVE_SYS_EVENTFD_H
221 int poll_breakloop_fd
; /* fd to an eventfd to break from blocking operations */
226 * Stuff to do when we close.
228 #define MUST_CLEAR_RFMON 0x00000001 /* clear rfmon (monitor) mode */
229 #define MUST_DELETE_MONIF 0x00000002 /* delete monitor-mode interface */
232 * Prototypes for internal functions and methods.
234 static int get_if_flags(const char *, bpf_u_int32
*, char *);
235 static int is_wifi(int, const char *);
236 static void map_arphrd_to_dlt(pcap_t
*, int, int, const char *, int);
237 static int pcap_activate_linux(pcap_t
*);
238 static int activate_sock(pcap_t
*, int);
239 #ifdef HAVE_PACKET_RING
240 static int activate_mmap(pcap_t
*, int *);
242 static int pcap_can_set_rfmon_linux(pcap_t
*);
243 static int pcap_read_linux(pcap_t
*, int, pcap_handler
, u_char
*);
244 static int pcap_read_packet(pcap_t
*, pcap_handler
, u_char
*);
245 static int pcap_inject_linux(pcap_t
*, const void *, int);
246 static int pcap_stats_linux(pcap_t
*, struct pcap_stat
*);
247 static int pcap_setfilter_linux(pcap_t
*, struct bpf_program
*);
248 static int pcap_setdirection_linux(pcap_t
*, pcap_direction_t
);
249 static int pcap_set_datalink_linux(pcap_t
*, int);
250 static void pcap_cleanup_linux(pcap_t
*);
253 * This is what the header structure looks like in a 64-bit kernel;
254 * we use this, rather than struct tpacket_hdr, if we're using
255 * TPACKET_V1 in 32-bit code running on a 64-bit kernel.
257 struct tpacket_hdr_64
{
260 unsigned int tp_snaplen
;
261 unsigned short tp_mac
;
262 unsigned short tp_net
;
264 unsigned int tp_usec
;
268 * We use this internally as the tpacket version for TPACKET_V1 in
269 * 32-bit code on a 64-bit kernel.
271 #define TPACKET_V1_64 99
274 struct tpacket_hdr
*h1
;
275 struct tpacket_hdr_64
*h1_64
;
277 struct tpacket2_hdr
*h2
;
280 struct tpacket_block_desc
*h3
;
285 #ifdef HAVE_PACKET_RING
286 #define RING_GET_FRAME_AT(h, offset) (((u_char **)h->buffer)[(offset)])
287 #define RING_GET_CURRENT_FRAME(h) RING_GET_FRAME_AT(h, h->offset)
289 static void destroy_ring(pcap_t
*handle
);
290 static int create_ring(pcap_t
*handle
, int *status
);
291 static int prepare_tpacket_socket(pcap_t
*handle
);
292 static void pcap_cleanup_linux_mmap(pcap_t
*);
293 static int pcap_read_linux_mmap_v1(pcap_t
*, int, pcap_handler
, u_char
*);
294 static int pcap_read_linux_mmap_v1_64(pcap_t
*, int, pcap_handler
, u_char
*);
296 static int pcap_read_linux_mmap_v2(pcap_t
*, int, pcap_handler
, u_char
*);
299 static int pcap_read_linux_mmap_v3(pcap_t
*, int, pcap_handler
, u_char
*);
301 static int pcap_setfilter_linux_mmap(pcap_t
*, struct bpf_program
*);
302 static int pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
);
303 static int pcap_getnonblock_mmap(pcap_t
*p
);
304 static void pcap_oneshot_mmap(u_char
*user
, const struct pcap_pkthdr
*h
,
305 const u_char
*bytes
);
309 * In pre-3.0 kernels, the tp_vlan_tci field is set to whatever the
310 * vlan_tci field in the skbuff is. 0 can either mean "not on a VLAN"
311 * or "on VLAN 0". There is no flag set in the tp_status field to
312 * distinguish between them.
314 * In 3.0 and later kernels, if there's a VLAN tag present, the tp_vlan_tci
315 * field is set to the VLAN tag, and the TP_STATUS_VLAN_VALID flag is set
316 * in the tp_status field, otherwise the tp_vlan_tci field is set to 0 and
317 * the TP_STATUS_VLAN_VALID flag isn't set in the tp_status field.
319 * With a pre-3.0 kernel, we cannot distinguish between packets with no
320 * VLAN tag and packets on VLAN 0, so we will mishandle some packets, and
321 * there's nothing we can do about that.
323 * So, on those systems, which never set the TP_STATUS_VLAN_VALID flag, we
324 * continue the behavior of earlier libpcaps, wherein we treated packets
325 * with a VLAN tag of 0 as being packets without a VLAN tag rather than packets
326 * on VLAN 0. We do this by treating packets with a tp_vlan_tci of 0 and
327 * with the TP_STATUS_VLAN_VALID flag not set in tp_status as not having
328 * VLAN tags. This does the right thing on 3.0 and later kernels, and
329 * continues the old unfixably-imperfect behavior on pre-3.0 kernels.
331 * If TP_STATUS_VLAN_VALID isn't defined, we test it as the 0x10 bit; it
332 * has that value in 3.0 and later kernels.
334 #ifdef TP_STATUS_VLAN_VALID
335 #define VLAN_VALID(hdr, hv) ((hv)->tp_vlan_tci != 0 || ((hdr)->tp_status & TP_STATUS_VLAN_VALID))
338 * This is being compiled on a system that lacks TP_STATUS_VLAN_VALID,
339 * so we testwith the value it has in the 3.0 and later kernels, so
340 * we can test it if we're running on a system that has it. (If we're
341 * running on a system that doesn't have it, it won't be set in the
342 * tp_status field, so the tests of it will always fail; that means
343 * we behave the way we did before we introduced this macro.)
345 #define VLAN_VALID(hdr, hv) ((hv)->tp_vlan_tci != 0 || ((hdr)->tp_status & 0x10))
348 #ifdef TP_STATUS_VLAN_TPID_VALID
349 # define VLAN_TPID(hdr, hv) (((hv)->tp_vlan_tpid || ((hdr)->tp_status & TP_STATUS_VLAN_TPID_VALID)) ? (hv)->tp_vlan_tpid : ETH_P_8021Q)
351 # define VLAN_TPID(hdr, hv) ETH_P_8021Q
355 * Wrap some ioctl calls
357 static int iface_get_id(int fd
, const char *device
, char *ebuf
);
358 static int iface_get_mtu(int fd
, const char *device
, char *ebuf
);
359 static int iface_get_arptype(int fd
, const char *device
, char *ebuf
);
360 static int iface_bind(int fd
, int ifindex
, char *ebuf
, int protocol
);
361 #ifdef IW_MODE_MONITOR
362 static int has_wext(int sock_fd
, const char *device
, char *ebuf
);
363 #endif /* IW_MODE_MONITOR */
364 static int enter_rfmon_mode(pcap_t
*handle
, int sock_fd
,
366 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
367 static int iface_ethtool_get_ts_info(const char *device
, pcap_t
*handle
,
370 #ifdef HAVE_PACKET_RING
371 static int iface_get_offload(pcap_t
*handle
);
374 #ifdef SO_ATTACH_FILTER
375 static int fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
,
377 static int fix_offset(pcap_t
*handle
, struct bpf_insn
*p
);
378 static int set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
);
379 static int reset_kernel_filter(pcap_t
*handle
);
381 static struct sock_filter total_insn
382 = BPF_STMT(BPF_RET
| BPF_K
, 0);
383 static struct sock_fprog total_fcode
384 = { 1, &total_insn
};
385 #endif /* SO_ATTACH_FILTER */
387 static int iface_dsa_get_proto_info(const char *device
, pcap_t
*handle
);
390 pcap_create_interface(const char *device
, char *ebuf
)
394 handle
= pcap_create_common(ebuf
, sizeof (struct pcap_linux
));
398 handle
->activate_op
= pcap_activate_linux
;
399 handle
->can_set_rfmon_op
= pcap_can_set_rfmon_linux
;
401 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
403 * See what time stamp types we support.
405 if (iface_ethtool_get_ts_info(device
, handle
, ebuf
) == -1) {
411 #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
413 * We claim that we support microsecond and nanosecond time
416 * XXX - with adapter-supplied time stamps, can we choose
417 * microsecond or nanosecond time stamps on arbitrary
420 handle
->tstamp_precision_count
= 2;
421 handle
->tstamp_precision_list
= malloc(2 * sizeof(u_int
));
422 if (handle
->tstamp_precision_list
== NULL
) {
423 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
428 handle
->tstamp_precision_list
[0] = PCAP_TSTAMP_PRECISION_MICRO
;
429 handle
->tstamp_precision_list
[1] = PCAP_TSTAMP_PRECISION_NANO
;
430 #endif /* defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS) */
432 #ifdef HAVE_SYS_EVENTFD_H
433 struct pcap_linux
*handlep
= handle
->priv
;
434 handlep
->poll_breakloop_fd
= eventfd(0, EFD_NONBLOCK
);
442 * If interface {if_name} is a mac80211 driver, the file
443 * /sys/class/net/{if_name}/phy80211 is a symlink to
444 * /sys/class/ieee80211/{phydev_name}, for some {phydev_name}.
446 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
447 * least, has a "wmaster0" device and a "wlan0" device; the
448 * latter is the one with the IP address. Both show up in
449 * "tcpdump -D" output. Capturing on the wmaster0 device
450 * captures with 802.11 headers.
452 * airmon-ng searches through /sys/class/net for devices named
453 * monN, starting with mon0; as soon as one *doesn't* exist,
454 * it chooses that as the monitor device name. If the "iw"
455 * command exists, it does
457 * iw dev {if_name} interface add {monif_name} type monitor
459 * where {monif_name} is the monitor device. It then (sigh) sleeps
460 * .1 second, and then configures the device up. Otherwise, if
461 * /sys/class/ieee80211/{phydev_name}/add_iface is a file, it writes
462 * {mondev_name}, without a newline, to that file, and again (sigh)
463 * sleeps .1 second, and then iwconfig's that device into monitor
464 * mode and configures it up. Otherwise, you can't do monitor mode.
466 * All these devices are "glued" together by having the
467 * /sys/class/net/{if_name}/phy80211 links pointing to the same
468 * place, so, given a wmaster, wlan, or mon device, you can
469 * find the other devices by looking for devices with
470 * the same phy80211 link.
472 * To turn monitor mode off, delete the monitor interface,
475 * iw dev {monif_name} interface del
477 * or by sending {monif_name}, with no NL, down
478 * /sys/class/ieee80211/{phydev_name}/remove_iface
480 * Note: if you try to create a monitor device named "monN", and
481 * there's already a "monN" device, it fails, as least with
482 * the netlink interface (which is what iw uses), with a return
483 * value of -ENFILE. (Return values are negative errnos.) We
484 * could probably use that to find an unused device.
486 * Yes, you can have multiple monitor devices for a given
491 * Is this a mac80211 device? If so, fill in the physical device path and
492 * return 1; if not, return 0. On an error, fill in handle->errbuf and
496 get_mac80211_phydev(pcap_t
*handle
, const char *device
, char *phydev_path
,
497 size_t phydev_max_pathlen
)
503 * Generate the path string for the symlink to the physical device.
505 if (asprintf(&pathstr
, "/sys/class/net/%s/phy80211", device
) == -1) {
506 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
507 "%s: Can't generate path name string for /sys/class/net device",
511 bytes_read
= readlink(pathstr
, phydev_path
, phydev_max_pathlen
);
512 if (bytes_read
== -1) {
513 if (errno
== ENOENT
|| errno
== EINVAL
) {
515 * Doesn't exist, or not a symlink; assume that
516 * means it's not a mac80211 device.
521 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
522 errno
, "%s: Can't readlink %s", device
, pathstr
);
527 phydev_path
[bytes_read
] = '\0';
531 #ifdef HAVE_LIBNL_SOCKETS
532 #define get_nl_errmsg nl_geterror
534 /* libnl 2.x compatibility code */
536 #define nl_sock nl_handle
538 static inline struct nl_handle
*
539 nl_socket_alloc(void)
541 return nl_handle_alloc();
545 nl_socket_free(struct nl_handle
*h
)
547 nl_handle_destroy(h
);
550 #define get_nl_errmsg strerror
553 __genl_ctrl_alloc_cache(struct nl_handle
*h
, struct nl_cache
**cache
)
555 struct nl_cache
*tmp
= genl_ctrl_alloc_cache(h
);
561 #define genl_ctrl_alloc_cache __genl_ctrl_alloc_cache
562 #endif /* !HAVE_LIBNL_SOCKETS */
564 struct nl80211_state
{
565 struct nl_sock
*nl_sock
;
566 struct nl_cache
*nl_cache
;
567 struct genl_family
*nl80211
;
571 nl80211_init(pcap_t
*handle
, struct nl80211_state
*state
, const char *device
)
575 state
->nl_sock
= nl_socket_alloc();
576 if (!state
->nl_sock
) {
577 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
578 "%s: failed to allocate netlink handle", device
);
582 if (genl_connect(state
->nl_sock
)) {
583 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
584 "%s: failed to connect to generic netlink", device
);
585 goto out_handle_destroy
;
588 err
= genl_ctrl_alloc_cache(state
->nl_sock
, &state
->nl_cache
);
590 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
591 "%s: failed to allocate generic netlink cache: %s",
592 device
, get_nl_errmsg(-err
));
593 goto out_handle_destroy
;
596 state
->nl80211
= genl_ctrl_search_by_name(state
->nl_cache
, "nl80211");
597 if (!state
->nl80211
) {
598 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
599 "%s: nl80211 not found", device
);
606 nl_cache_free(state
->nl_cache
);
608 nl_socket_free(state
->nl_sock
);
613 nl80211_cleanup(struct nl80211_state
*state
)
615 genl_family_put(state
->nl80211
);
616 nl_cache_free(state
->nl_cache
);
617 nl_socket_free(state
->nl_sock
);
621 del_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
622 const char *device
, const char *mondevice
);
625 add_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
626 const char *device
, const char *mondevice
)
628 struct pcap_linux
*handlep
= handle
->priv
;
633 ifindex
= iface_get_id(sock_fd
, device
, handle
->errbuf
);
639 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
640 "%s: failed to allocate netlink msg", device
);
644 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
645 0, NL80211_CMD_NEW_INTERFACE
, 0);
646 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
648 NLA_PUT_STRING(msg
, NL80211_ATTR_IFNAME
, mondevice
);
650 NLA_PUT_U32(msg
, NL80211_ATTR_IFTYPE
, NL80211_IFTYPE_MONITOR
);
652 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
654 #if defined HAVE_LIBNL_NLE
655 if (err
== -NLE_FAILURE
) {
657 if (err
== -ENFILE
) {
660 * Device not available; our caller should just
661 * keep trying. (libnl 2.x maps ENFILE to
662 * NLE_FAILURE; it can also map other errors
663 * to that, but there's not much we can do
670 * Real failure, not just "that device is not
673 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
674 "%s: nl_send_auto_complete failed adding %s interface: %s",
675 device
, mondevice
, get_nl_errmsg(-err
));
680 err
= nl_wait_for_ack(state
->nl_sock
);
682 #if defined HAVE_LIBNL_NLE
683 if (err
== -NLE_FAILURE
) {
685 if (err
== -ENFILE
) {
688 * Device not available; our caller should just
689 * keep trying. (libnl 2.x maps ENFILE to
690 * NLE_FAILURE; it can also map other errors
691 * to that, but there's not much we can do
698 * Real failure, not just "that device is not
701 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
702 "%s: nl_wait_for_ack failed adding %s interface: %s",
703 device
, mondevice
, get_nl_errmsg(-err
));
715 * Try to remember the monitor device.
717 handlep
->mondevice
= strdup(mondevice
);
718 if (handlep
->mondevice
== NULL
) {
719 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
722 * Get rid of the monitor device.
724 del_mon_if(handle
, sock_fd
, state
, device
, mondevice
);
730 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
731 "%s: nl_put failed adding %s interface",
738 del_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
739 const char *device
, const char *mondevice
)
745 ifindex
= iface_get_id(sock_fd
, mondevice
, handle
->errbuf
);
751 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
752 "%s: failed to allocate netlink msg", device
);
756 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
757 0, NL80211_CMD_DEL_INTERFACE
, 0);
758 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
760 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
762 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
763 "%s: nl_send_auto_complete failed deleting %s interface: %s",
764 device
, mondevice
, get_nl_errmsg(-err
));
768 err
= nl_wait_for_ack(state
->nl_sock
);
770 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
771 "%s: nl_wait_for_ack failed adding %s interface: %s",
772 device
, mondevice
, get_nl_errmsg(-err
));
784 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
785 "%s: nl_put failed deleting %s interface",
792 enter_rfmon_mode_mac80211(pcap_t
*handle
, int sock_fd
, const char *device
)
794 struct pcap_linux
*handlep
= handle
->priv
;
796 char phydev_path
[PATH_MAX
+1];
797 struct nl80211_state nlstate
;
802 * Is this a mac80211 device?
804 ret
= get_mac80211_phydev(handle
, device
, phydev_path
, PATH_MAX
);
806 return ret
; /* error */
808 return 0; /* no error, but not mac80211 device */
811 * XXX - is this already a monN device?
813 * Is that determined by old Wireless Extensions ioctls?
817 * OK, it's apparently a mac80211 device.
818 * Try to find an unused monN device for it.
820 ret
= nl80211_init(handle
, &nlstate
, device
);
823 for (n
= 0; n
< UINT_MAX
; n
++) {
827 char mondevice
[3+10+1]; /* mon{UINT_MAX}\0 */
829 snprintf(mondevice
, sizeof mondevice
, "mon%u", n
);
830 ret
= add_mon_if(handle
, sock_fd
, &nlstate
, device
, mondevice
);
833 * Success. We don't clean up the libnl state
834 * yet, as we'll be using it later.
840 * Hard failure. Just return ret; handle->errbuf
841 * has already been set.
843 nl80211_cleanup(&nlstate
);
848 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
849 "%s: No free monN interfaces", device
);
850 nl80211_cleanup(&nlstate
);
857 * Sleep for .1 seconds.
860 delay
.tv_nsec
= 500000000;
861 nanosleep(&delay
, NULL
);
865 * If we haven't already done so, arrange to have
866 * "pcap_close_all()" called when we exit.
868 if (!pcap_do_addexit(handle
)) {
870 * "atexit()" failed; don't put the interface
871 * in rfmon mode, just give up.
873 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
875 nl80211_cleanup(&nlstate
);
880 * Now configure the monitor interface up.
882 memset(&ifr
, 0, sizeof(ifr
));
883 pcap_strlcpy(ifr
.ifr_name
, handlep
->mondevice
, sizeof(ifr
.ifr_name
));
884 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
885 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
886 errno
, "%s: Can't get flags for %s", device
,
888 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
890 nl80211_cleanup(&nlstate
);
893 ifr
.ifr_flags
|= IFF_UP
|IFF_RUNNING
;
894 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
895 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
896 errno
, "%s: Can't set flags for %s", device
,
898 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
900 nl80211_cleanup(&nlstate
);
905 * Success. Clean up the libnl state.
907 nl80211_cleanup(&nlstate
);
910 * Note that we have to delete the monitor device when we close
913 handlep
->must_do_on_close
|= MUST_DELETE_MONIF
;
916 * Add this to the list of pcaps to close when we exit.
918 pcap_add_to_pcaps_to_close(handle
);
922 #endif /* HAVE_LIBNL */
924 #ifdef IW_MODE_MONITOR
926 * Bonding devices mishandle unknown ioctls; they fail with ENODEV
927 * rather than ENOTSUP, EOPNOTSUPP, or ENOTTY, so Wireless Extensions
928 * will fail with ENODEV if we try to do them on a bonding device,
929 * making us return a "no such device" indication rather than just
930 * saying "no Wireless Extensions".
932 * So we check for bonding devices, if we can, before trying those
933 * ioctls, by trying a bonding device information query ioctl to see
934 * whether it succeeds.
937 is_bonding_device(int fd
, const char *device
)
939 #ifdef BOND_INFO_QUERY_IOCTL
943 memset(&ifr
, 0, sizeof ifr
);
944 pcap_strlcpy(ifr
.ifr_name
, device
, sizeof ifr
.ifr_name
);
945 memset(&ifb
, 0, sizeof ifb
);
946 ifr
.ifr_data
= (caddr_t
)&ifb
;
947 if (ioctl(fd
, BOND_INFO_QUERY_IOCTL
, &ifr
) == 0)
948 return 1; /* success, so it's a bonding device */
949 #endif /* BOND_INFO_QUERY_IOCTL */
951 return 0; /* no, it's not a bonding device */
953 #endif /* IW_MODE_MONITOR */
955 static int pcap_protocol(pcap_t
*handle
)
959 protocol
= handle
->opt
.protocol
;
961 protocol
= ETH_P_ALL
;
963 return htons(protocol
);
967 pcap_can_set_rfmon_linux(pcap_t
*handle
)
970 char phydev_path
[PATH_MAX
+1];
973 #ifdef IW_MODE_MONITOR
978 if (strcmp(handle
->opt
.device
, "any") == 0) {
980 * Monitor mode makes no sense on the "any" device.
987 * Bleah. There doesn't seem to be a way to ask a mac80211
988 * device, through libnl, whether it supports monitor mode;
989 * we'll just check whether the device appears to be a
990 * mac80211 device and, if so, assume the device supports
993 * wmaster devices don't appear to support the Wireless
994 * Extensions, but we can create a mon device for a
995 * wmaster device, so we don't bother checking whether
996 * a mac80211 device supports the Wireless Extensions.
998 ret
= get_mac80211_phydev(handle
, handle
->opt
.device
, phydev_path
,
1001 return ret
; /* error */
1003 return 1; /* mac80211 device */
1006 #ifdef IW_MODE_MONITOR
1008 * Bleah. There doesn't appear to be an ioctl to use to ask
1009 * whether a device supports monitor mode; we'll just do
1010 * SIOCGIWMODE and, if it succeeds, assume the device supports
1013 * Open a socket on which to attempt to get the mode.
1014 * (We assume that if we have Wireless Extensions support
1015 * we also have PF_PACKET support.)
1017 sock_fd
= socket(PF_PACKET
, SOCK_RAW
, pcap_protocol(handle
));
1018 if (sock_fd
== -1) {
1019 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1024 if (is_bonding_device(sock_fd
, handle
->opt
.device
)) {
1025 /* It's a bonding device, so don't even try. */
1031 * Attempt to get the current mode.
1033 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, handle
->opt
.device
,
1034 sizeof ireq
.ifr_ifrn
.ifrn_name
);
1035 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) != -1) {
1037 * Well, we got the mode; assume we can set it.
1042 if (errno
== ENODEV
) {
1043 /* The device doesn't even exist. */
1044 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1045 errno
, "SIOCGIWMODE failed");
1047 return PCAP_ERROR_NO_SUCH_DEVICE
;
1055 * Grabs the number of missed packets by the interface from
1056 * /sys/class/net/{if_name}/statistics/rx_{missed,fifo}_errors.
1058 * Compared to /proc/net/dev this avoids counting software drops,
1059 * but may be unimplemented and just return 0.
1060 * The author has found no straigthforward way to check for support.
1062 static long long int
1063 linux_get_stat(const char * if_name
, const char * stat
) {
1066 char buffer
[PATH_MAX
];
1068 snprintf(buffer
, sizeof(buffer
), "/sys/class/net/%s/statistics/%s", if_name
, stat
);
1069 fd
= open(buffer
, O_RDONLY
);
1073 bytes_read
= read(fd
, buffer
, sizeof(buffer
) - 1);
1075 if (bytes_read
== -1)
1077 buffer
[bytes_read
] = '\0';
1079 return strtoll(buffer
, NULL
, 10);
1082 static long long int
1083 linux_if_drops(const char * if_name
)
1085 long long int missed
= linux_get_stat(if_name
, "rx_missed_errors");
1086 long long int fifo
= linux_get_stat(if_name
, "rx_fifo_errors");
1087 return missed
+ fifo
;
1092 * Monitor mode is kind of interesting because we have to reset the
1093 * interface before exiting. The problem can't really be solved without
1094 * some daemon taking care of managing usage counts. If we put the
1095 * interface into monitor mode, we set a flag indicating that we must
1096 * take it out of that mode when the interface is closed, and, when
1097 * closing the interface, if that flag is set we take it out of monitor
1101 static void pcap_cleanup_linux( pcap_t
*handle
)
1103 struct pcap_linux
*handlep
= handle
->priv
;
1106 struct nl80211_state nlstate
;
1108 #endif /* HAVE_LIBNL */
1109 #ifdef IW_MODE_MONITOR
1112 #endif /* IW_MODE_MONITOR */
1114 if (handlep
->must_do_on_close
!= 0) {
1116 * There's something we have to do when closing this
1120 if (handlep
->must_do_on_close
& MUST_DELETE_MONIF
) {
1121 ret
= nl80211_init(handle
, &nlstate
, handlep
->device
);
1123 ret
= del_mon_if(handle
, handle
->fd
, &nlstate
,
1124 handlep
->device
, handlep
->mondevice
);
1125 nl80211_cleanup(&nlstate
);
1129 "Can't delete monitor interface %s (%s).\n"
1130 "Please delete manually.\n",
1131 handlep
->mondevice
, handle
->errbuf
);
1134 #endif /* HAVE_LIBNL */
1136 #ifdef IW_MODE_MONITOR
1137 if (handlep
->must_do_on_close
& MUST_CLEAR_RFMON
) {
1139 * We put the interface into rfmon mode;
1140 * take it out of rfmon mode.
1142 * XXX - if somebody else wants it in rfmon
1143 * mode, this code cannot know that, so it'll take
1144 * it out of rfmon mode.
1148 * First, take the interface down if it's up;
1149 * otherwise, we might get EBUSY.
1150 * If we get errors, just drive on and print
1151 * a warning if we can't restore the mode.
1154 memset(&ifr
, 0, sizeof(ifr
));
1155 pcap_strlcpy(ifr
.ifr_name
, handlep
->device
,
1156 sizeof(ifr
.ifr_name
));
1157 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) != -1) {
1158 if (ifr
.ifr_flags
& IFF_UP
) {
1159 oldflags
= ifr
.ifr_flags
;
1160 ifr
.ifr_flags
&= ~IFF_UP
;
1161 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1)
1162 oldflags
= 0; /* didn't set, don't restore */
1167 * Now restore the mode.
1169 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, handlep
->device
,
1170 sizeof ireq
.ifr_ifrn
.ifrn_name
);
1171 ireq
.u
.mode
= handlep
->oldmode
;
1172 if (ioctl(handle
->fd
, SIOCSIWMODE
, &ireq
) == -1) {
1174 * Scientist, you've failed.
1177 "Can't restore interface %s wireless mode (SIOCSIWMODE failed: %s).\n"
1178 "Please adjust manually.\n",
1179 handlep
->device
, strerror(errno
));
1183 * Now bring the interface back up if we brought
1186 if (oldflags
!= 0) {
1187 ifr
.ifr_flags
= oldflags
;
1188 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
1190 "Can't bring interface %s back up (SIOCSIFFLAGS failed: %s).\n"
1191 "Please adjust manually.\n",
1192 handlep
->device
, strerror(errno
));
1196 #endif /* IW_MODE_MONITOR */
1199 * Take this pcap out of the list of pcaps for which we
1200 * have to take the interface out of some mode.
1202 pcap_remove_from_pcaps_to_close(handle
);
1205 if (handlep
->mondevice
!= NULL
) {
1206 free(handlep
->mondevice
);
1207 handlep
->mondevice
= NULL
;
1209 if (handlep
->device
!= NULL
) {
1210 free(handlep
->device
);
1211 handlep
->device
= NULL
;
1214 #ifdef HAVE_SYS_EVENTFD_H
1215 close(handlep
->poll_breakloop_fd
);
1217 pcap_cleanup_live_common(handle
);
1221 * Set the timeout to be used in poll() with memory-mapped packet capture.
1224 set_poll_timeout(struct pcap_linux
*handlep
)
1226 #ifdef HAVE_TPACKET3
1227 struct utsname utsname
;
1228 char *version_component
, *endp
;
1230 int broken_tpacket_v3
= 1;
1233 * Some versions of TPACKET_V3 have annoying bugs/misfeatures
1234 * around which we have to work. Determine if we have those
1237 if (uname(&utsname
) == 0) {
1239 * 3.19 is the first release with a fixed version of
1240 * TPACKET_V3. We treat anything before that as
1241 * not haveing a fixed version; that may really mean
1242 * it has *no* version.
1244 version_component
= utsname
.release
;
1245 major
= strtol(version_component
, &endp
, 10);
1246 if (endp
!= version_component
&& *endp
== '.') {
1248 * OK, that was a valid major version.
1249 * Get the minor version.
1251 version_component
= endp
+ 1;
1252 minor
= strtol(version_component
, &endp
, 10);
1253 if (endp
!= version_component
&&
1254 (*endp
== '.' || *endp
== '\0')) {
1256 * OK, that was a valid minor version.
1257 * Is this 3.19 or newer?
1259 if (major
>= 4 || (major
== 3 && minor
>= 19)) {
1260 /* Yes. TPACKET_V3 works correctly. */
1261 broken_tpacket_v3
= 0;
1267 if (handlep
->timeout
== 0) {
1268 #ifdef HAVE_TPACKET3
1270 * XXX - due to a set of (mis)features in the TPACKET_V3
1271 * kernel code prior to the 3.19 kernel, blocking forever
1272 * with a TPACKET_V3 socket can, if few packets are
1273 * arriving and passing the socket filter, cause most
1274 * packets to be dropped. See libpcap issue #335 for the
1275 * full painful story.
1277 * The workaround is to have poll() time out very quickly,
1278 * so we grab the frames handed to us, and return them to
1281 if (handlep
->tp_version
== TPACKET_V3
&& broken_tpacket_v3
)
1282 handlep
->poll_timeout
= 1; /* don't block for very long */
1285 handlep
->poll_timeout
= -1; /* block forever */
1286 } else if (handlep
->timeout
> 0) {
1287 #ifdef HAVE_TPACKET3
1289 * For TPACKET_V3, the timeout is handled by the kernel,
1290 * so block forever; that way, we don't get extra timeouts.
1291 * Don't do that if we have a broken TPACKET_V3, though.
1293 if (handlep
->tp_version
== TPACKET_V3
&& !broken_tpacket_v3
)
1294 handlep
->poll_timeout
= -1; /* block forever, let TPACKET_V3 wake us up */
1297 handlep
->poll_timeout
= handlep
->timeout
; /* block for that amount of time */
1300 * Non-blocking mode; we call poll() to pick up error
1301 * indications, but we don't want it to wait for
1304 handlep
->poll_timeout
= 0;
1308 #ifdef HAVE_SYS_EVENTFD_H
1309 static void pcap_breakloop_linux(pcap_t
*handle
)
1311 pcap_breakloop_common(handle
);
1312 struct pcap_linux
*handlep
= handle
->priv
;
1315 /* XXX - what if this fails? */
1316 (void)write(handlep
->poll_breakloop_fd
, &value
, sizeof(value
));
1321 * Open a PF_PACKET socket.
1324 open_pf_packet_socket(pcap_t
*handle
, int cooked
)
1326 int protocol
= pcap_protocol(handle
);
1330 * Open a socket with protocol family packet. If cooked is true,
1331 * we open a SOCK_DGRAM socket for the cooked interface, otherwise
1332 * we open a SOCK_RAW socket for the raw interface.
1335 socket(PF_PACKET
, SOCK_DGRAM
, protocol
) :
1336 socket(PF_PACKET
, SOCK_RAW
, protocol
);
1338 if (sock_fd
== -1) {
1339 if (errno
== EPERM
|| errno
== EACCES
) {
1341 * You don't have permission to open the
1344 ret
= PCAP_ERROR_PERM_DENIED
;
1351 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1359 * Get a handle for a live capture from the given device. You can
1360 * pass NULL as device to get all packages (without link level
1361 * information of course). If you pass 1 as promisc the interface
1362 * will be set to promiscuous mode (XXX: I think this usage should
1363 * be deprecated and functions be added to select that later allow
1364 * modification of that values -- Torsten).
1367 pcap_activate_linux(pcap_t
*handle
)
1369 struct pcap_linux
*handlep
= handle
->priv
;
1376 device
= handle
->opt
.device
;
1379 * Make sure the name we were handed will fit into the ioctls we
1380 * might perform on the device; if not, return a "No such device"
1381 * indication, as the Linux kernel shouldn't support creating
1382 * a device whose name won't fit into those ioctls.
1384 * "Will fit" means "will fit, complete with a null terminator",
1385 * so if the length, which does *not* include the null terminator,
1386 * is greater than *or equal to* the size of the field into which
1387 * we'll be copying it, that won't fit.
1389 if (strlen(device
) >= sizeof(ifr
.ifr_name
)) {
1390 status
= PCAP_ERROR_NO_SUCH_DEVICE
;
1395 * Turn a negative snapshot value (invalid), a snapshot value of
1396 * 0 (unspecified), or a value bigger than the normal maximum
1397 * value, into the maximum allowed value.
1399 * If some application really *needs* a bigger snapshot
1400 * length, we should just increase MAXIMUM_SNAPLEN.
1402 if (handle
->snapshot
<= 0 || handle
->snapshot
> MAXIMUM_SNAPLEN
)
1403 handle
->snapshot
= MAXIMUM_SNAPLEN
;
1405 handle
->inject_op
= pcap_inject_linux
;
1406 handle
->setfilter_op
= pcap_setfilter_linux
;
1407 handle
->setdirection_op
= pcap_setdirection_linux
;
1408 handle
->set_datalink_op
= pcap_set_datalink_linux
;
1409 handle
->getnonblock_op
= pcap_getnonblock_fd
;
1410 handle
->setnonblock_op
= pcap_setnonblock_fd
;
1411 handle
->cleanup_op
= pcap_cleanup_linux
;
1412 handle
->read_op
= pcap_read_linux
;
1413 handle
->stats_op
= pcap_stats_linux
;
1414 #ifdef HAVE_SYS_EVENTFD_H
1415 handle
->breakloop_op
= pcap_breakloop_linux
;
1418 handlep
->device
= strdup(device
);
1419 if (handlep
->device
== NULL
) {
1420 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1422 status
= PCAP_ERROR
;
1427 * The "any" device is a special device which causes us not
1428 * to bind to a particular device and thus to look at all
1431 is_any_device
= (strcmp(device
, "any") == 0);
1432 if (is_any_device
) {
1433 if (handle
->opt
.promisc
) {
1434 handle
->opt
.promisc
= 0;
1435 /* Just a warning. */
1436 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1437 "Promiscuous mode not supported on the \"any\" device");
1438 status
= PCAP_WARNING_PROMISC_NOTSUP
;
1442 /* copy timeout value */
1443 handlep
->timeout
= handle
->opt
.timeout
;
1446 * If we're in promiscuous mode, then we probably want
1447 * to see when the interface drops packets too, so get an
1448 * initial count from
1449 * /sys/class/net/{if_name}/statistics/rx_{missed,fifo}_errors
1451 if (handle
->opt
.promisc
)
1452 handlep
->sysfs_dropped
= linux_if_drops(handlep
->device
);
1455 * If the "any" device is specified, try to open a SOCK_DGRAM.
1456 * Otherwise, open a SOCK_RAW.
1458 ret
= activate_sock(handle
, is_any_device
);
1461 * Fatal error; the return value is the error code,
1462 * and handle->errbuf has been set to an appropriate
1467 #ifdef HAVE_PACKET_RING
1470 * Try to use memory-mapped access.
1472 switch (activate_mmap(handle
, &status
)) {
1476 * We succeeded. status has been
1477 * set to the status to return,
1478 * which might be 0, or might be
1479 * a PCAP_WARNING_ value.
1481 * Set the timeout to use in poll() before
1484 set_poll_timeout(handlep
);
1489 * Kernel doesn't support it - just continue
1490 * with non-memory-mapped access.
1496 * We failed to set up to use it, or the
1497 * kernel supports it, but we failed to
1498 * enable it. status has been set to the
1499 * error status to return and, if it's
1500 * PCAP_ERROR, handle->errbuf contains
1501 * the error message.
1505 #endif /* HAVE_PACKET_RING */
1509 * We set up the socket, but not with memory-mapped access.
1511 if (handle
->opt
.buffer_size
!= 0) {
1513 * Set the socket buffer size to the specified value.
1515 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_RCVBUF
,
1516 &handle
->opt
.buffer_size
,
1517 sizeof(handle
->opt
.buffer_size
)) == -1) {
1518 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
1519 PCAP_ERRBUF_SIZE
, errno
, "SO_RCVBUF");
1520 status
= PCAP_ERROR
;
1525 /* Allocate the buffer */
1527 handle
->buffer
= malloc(handle
->bufsize
+ handle
->offset
);
1528 if (!handle
->buffer
) {
1529 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1531 status
= PCAP_ERROR
;
1536 * "handle->fd" is a socket, so "select()" and "poll()"
1537 * should work on it.
1539 handle
->selectable_fd
= handle
->fd
;
1544 pcap_cleanup_linux(handle
);
1549 * Read at most max_packets from the capture stream and call the callback
1550 * for each of them. Returns the number of packets handled or -1 if an
1554 pcap_read_linux(pcap_t
*handle
, int max_packets _U_
, pcap_handler callback
, u_char
*user
)
1557 * Currently, on Linux only one packet is delivered per read,
1560 return pcap_read_packet(handle
, callback
, user
);
1564 pcap_set_datalink_linux(pcap_t
*handle
, int dlt
)
1566 handle
->linktype
= dlt
;
1571 * linux_check_direction()
1573 * Do checks based on packet direction.
1576 linux_check_direction(const pcap_t
*handle
, const struct sockaddr_ll
*sll
)
1578 struct pcap_linux
*handlep
= handle
->priv
;
1580 if (sll
->sll_pkttype
== PACKET_OUTGOING
) {
1583 * If this is from the loopback device, reject it;
1584 * we'll see the packet as an incoming packet as well,
1585 * and we don't want to see it twice.
1587 if (sll
->sll_ifindex
== handlep
->lo_ifindex
)
1591 * If this is an outgoing CAN or CAN FD frame, and
1592 * the user doesn't only want outgoing packets,
1593 * reject it; CAN devices and drivers, and the CAN
1594 * stack, always arrange to loop back transmitted
1595 * packets, so they also appear as incoming packets.
1596 * We don't want duplicate packets, and we can't
1597 * easily distinguish packets looped back by the CAN
1598 * layer than those received by the CAN layer, so we
1599 * eliminate this packet instead.
1601 if ((sll
->sll_protocol
== LINUX_SLL_P_CAN
||
1602 sll
->sll_protocol
== LINUX_SLL_P_CANFD
) &&
1603 handle
->direction
!= PCAP_D_OUT
)
1607 * If the user only wants incoming packets, reject it.
1609 if (handle
->direction
== PCAP_D_IN
)
1614 * If the user only wants outgoing packets, reject it.
1616 if (handle
->direction
== PCAP_D_OUT
)
1623 * Read a packet from the socket calling the handler provided by
1624 * the user. Returns the number of packets received or -1 if an
1628 pcap_read_packet(pcap_t
*handle
, pcap_handler callback
, u_char
*userdata
)
1630 struct pcap_linux
*handlep
= handle
->priv
;
1633 struct sockaddr_ll from
;
1634 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI)
1637 struct cmsghdr
*cmsg
;
1639 struct cmsghdr cmsg
;
1640 char buf
[CMSG_SPACE(sizeof(struct tpacket_auxdata
))];
1642 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI) */
1644 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI) */
1647 struct pcap_pkthdr pcap_header
;
1649 struct bpf_aux_data aux_data
;
1651 * If this is a cooked device, leave extra room for a
1652 * fake packet header.
1654 if (handlep
->cooked
) {
1655 if (handle
->linktype
== DLT_LINUX_SLL2
)
1656 offset
= SLL2_HDR_LEN
;
1658 offset
= SLL_HDR_LEN
;
1663 * Receive a single packet from the kernel.
1664 * We ignore EINTR, as that might just be due to a signal
1665 * being delivered - if the signal should interrupt the
1666 * loop, the signal handler should call pcap_breakloop()
1667 * to set handle->break_loop (we ignore it on other
1668 * platforms as well).
1669 * We also ignore ENETDOWN, so that we can continue to
1670 * capture traffic if the interface goes down and comes
1671 * back up again; comments in the kernel indicate that
1672 * we'll just block waiting for packets if we try to
1673 * receive from a socket that delivered ENETDOWN, and,
1674 * if we're using a memory-mapped buffer, we won't even
1675 * get notified of "network down" events.
1677 bp
= (u_char
*)handle
->buffer
+ handle
->offset
;
1679 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI)
1680 msg
.msg_name
= &from
;
1681 msg
.msg_namelen
= sizeof(from
);
1684 msg
.msg_control
= &cmsg_buf
;
1685 msg
.msg_controllen
= sizeof(cmsg_buf
);
1688 iov
.iov_len
= handle
->bufsize
- offset
;
1689 iov
.iov_base
= bp
+ offset
;
1690 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI) */
1694 * Has "pcap_breakloop()" been called?
1696 if (handle
->break_loop
) {
1698 * Yes - clear the flag that indicates that it has,
1699 * and return PCAP_ERROR_BREAK as an indication that
1700 * we were told to break out of the loop.
1702 handle
->break_loop
= 0;
1703 return PCAP_ERROR_BREAK
;
1706 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI)
1707 packet_len
= recvmsg(handle
->fd
, &msg
, MSG_TRUNC
);
1708 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI) */
1709 fromlen
= sizeof(from
);
1710 packet_len
= recvfrom(
1711 handle
->fd
, bp
+ offset
,
1712 handle
->bufsize
- offset
, MSG_TRUNC
,
1713 (struct sockaddr
*) &from
, &fromlen
);
1714 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI) */
1715 } while (packet_len
== -1 && errno
== EINTR
);
1717 /* Check if an error occured */
1719 if (packet_len
== -1) {
1723 return 0; /* no packet there */
1727 * The device on which we're capturing went away.
1729 * XXX - we should really return
1730 * PCAP_ERROR_IFACE_NOT_UP, but pcap_dispatch()
1731 * etc. aren't defined to return that.
1733 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1734 "The interface went down");
1738 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
1739 PCAP_ERRBUF_SIZE
, errno
, "recvfrom");
1745 * Unfortunately, there is a window between socket() and
1746 * bind() where the kernel may queue packets from any
1747 * interface. If we're bound to a particular interface,
1748 * discard packets not from that interface.
1750 * (If socket filters are supported, we could do the
1751 * same thing we do when changing the filter; however,
1752 * that won't handle packet sockets without socket
1753 * filter support, and it's a bit more complicated.
1754 * It would save some instructions per packet, however.)
1756 if (handlep
->ifindex
!= -1 &&
1757 from
.sll_ifindex
!= handlep
->ifindex
)
1760 /* Do checks based on packet direction. */
1761 if (!linux_check_direction(handle
, &from
))
1765 * If this is a cooked device, fill in the fake packet header.
1767 if (handlep
->cooked
) {
1769 * Add the length of the fake header to the length
1770 * of packet data we read.
1772 if (handle
->linktype
== DLT_LINUX_SLL2
) {
1773 struct sll2_header
*hdrp
;
1775 packet_len
+= SLL2_HDR_LEN
;
1777 hdrp
= (struct sll2_header
*)bp
;
1778 hdrp
->sll2_protocol
= from
.sll_protocol
;
1779 hdrp
->sll2_reserved_mbz
= 0;
1780 hdrp
->sll2_if_index
= htonl(from
.sll_ifindex
);
1781 hdrp
->sll2_hatype
= htons(from
.sll_hatype
);
1782 hdrp
->sll2_pkttype
= from
.sll_pkttype
;
1783 hdrp
->sll2_halen
= from
.sll_halen
;
1784 memcpy(hdrp
->sll2_addr
, from
.sll_addr
,
1785 (from
.sll_halen
> SLL_ADDRLEN
) ?
1789 struct sll_header
*hdrp
;
1791 packet_len
+= SLL_HDR_LEN
;
1793 hdrp
= (struct sll_header
*)bp
;
1794 hdrp
->sll_pkttype
= htons(from
.sll_pkttype
);
1795 hdrp
->sll_hatype
= htons(from
.sll_hatype
);
1796 hdrp
->sll_halen
= htons(from
.sll_halen
);
1797 memcpy(hdrp
->sll_addr
, from
.sll_addr
,
1798 (from
.sll_halen
> SLL_ADDRLEN
) ?
1801 hdrp
->sll_protocol
= from
.sll_protocol
;
1806 * Start out with no VLAN information.
1808 aux_data
.vlan_tag_present
= 0;
1809 aux_data
.vlan_tag
= 0;
1810 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI)
1811 if (handlep
->vlan_offset
!= -1) {
1812 for (cmsg
= CMSG_FIRSTHDR(&msg
); cmsg
; cmsg
= CMSG_NXTHDR(&msg
, cmsg
)) {
1813 struct tpacket_auxdata
*aux
;
1815 struct vlan_tag
*tag
;
1817 if (cmsg
->cmsg_len
< CMSG_LEN(sizeof(struct tpacket_auxdata
)) ||
1818 cmsg
->cmsg_level
!= SOL_PACKET
||
1819 cmsg
->cmsg_type
!= PACKET_AUXDATA
) {
1821 * This isn't a PACKET_AUXDATA auxiliary
1827 aux
= (struct tpacket_auxdata
*)CMSG_DATA(cmsg
);
1828 if (!VLAN_VALID(aux
, aux
)) {
1830 * There is no VLAN information in the
1836 len
= (size_t)packet_len
> iov
.iov_len
? iov
.iov_len
: (u_int
)packet_len
;
1837 if (len
< (size_t)handlep
->vlan_offset
)
1841 * Move everything in the header, except the
1842 * type field, down VLAN_TAG_LEN bytes, to
1843 * allow us to insert the VLAN tag between
1844 * that stuff and the type field.
1847 memmove(bp
, bp
+ VLAN_TAG_LEN
, handlep
->vlan_offset
);
1850 * Now insert the tag.
1852 tag
= (struct vlan_tag
*)(bp
+ handlep
->vlan_offset
);
1853 tag
->vlan_tpid
= htons(VLAN_TPID(aux
, aux
));
1854 tag
->vlan_tci
= htons(aux
->tp_vlan_tci
);
1857 * Save a flag indicating that we have a VLAN tag,
1858 * and the VLAN TCI, to bpf_aux_data struct for
1859 * use by the BPF filter if we're doing the
1860 * filtering in userland.
1862 aux_data
.vlan_tag_present
= 1;
1863 aux_data
.vlan_tag
= htons(aux
->tp_vlan_tci
) & 0x0fff;
1866 * Add the tag to the packet lengths.
1868 packet_len
+= VLAN_TAG_LEN
;
1871 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI) */
1874 * XXX: According to the kernel source we should get the real
1875 * packet len if calling recvfrom with MSG_TRUNC set. It does
1876 * not seem to work here :(, but it is supported by this code
1878 * To be honest the code RELIES on that feature so this is really
1879 * broken with 2.2.x kernels.
1880 * I spend a day to figure out what's going on and I found out
1881 * that the following is happening:
1883 * The packet comes from a random interface and the packet_rcv
1884 * hook is called with a clone of the packet. That code inserts
1885 * the packet into the receive queue of the packet socket.
1886 * If a filter is attached to that socket that filter is run
1887 * first - and there lies the problem. The default filter always
1888 * cuts the packet at the snaplen:
1893 * So the packet filter cuts down the packet. The recvfrom call
1894 * says "hey, it's only 68 bytes, it fits into the buffer" with
1895 * the result that we don't get the real packet length. This
1896 * is valid at least until kernel 2.2.17pre6.
1898 * We currently handle this by making a copy of the filter
1899 * program, fixing all "ret" instructions with non-zero
1900 * operands to have an operand of MAXIMUM_SNAPLEN so that the
1901 * filter doesn't truncate the packet, and supplying that modified
1902 * filter to the kernel.
1905 caplen
= (int)packet_len
;
1906 if (caplen
> handle
->snapshot
)
1907 caplen
= handle
->snapshot
;
1909 /* Run the packet filter if not using kernel filter */
1910 if (handlep
->filter_in_userland
&& handle
->fcode
.bf_insns
) {
1911 if (pcap_filter_with_aux_data(handle
->fcode
.bf_insns
, bp
,
1912 (int)packet_len
, caplen
, &aux_data
) == 0) {
1913 /* rejected by filter */
1918 /* Fill in our own header data */
1920 /* get timestamp for this packet */
1921 #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
1922 if (handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
) {
1923 if (ioctl(handle
->fd
, SIOCGSTAMPNS
, &pcap_header
.ts
) == -1) {
1924 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
1925 PCAP_ERRBUF_SIZE
, errno
, "SIOCGSTAMPNS");
1931 if (ioctl(handle
->fd
, SIOCGSTAMP
, &pcap_header
.ts
) == -1) {
1932 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
1933 PCAP_ERRBUF_SIZE
, errno
, "SIOCGSTAMP");
1938 pcap_header
.caplen
= caplen
;
1939 pcap_header
.len
= (bpf_u_int32
)packet_len
;
1944 * Arguably, we should count them before we check the filter,
1945 * as on many other platforms "ps_recv" counts packets
1946 * handed to the filter rather than packets that passed
1947 * the filter, but if filtering is done in the kernel, we
1948 * can't get a count of packets that passed the filter,
1949 * and that would mean the meaning of "ps_recv" wouldn't
1950 * be the same on all Linux systems.
1952 * XXX - it's not the same on all systems in any case;
1953 * ideally, we should have a "get the statistics" call
1954 * that supplies more counts and indicates which of them
1955 * it supplies, so that we supply a count of packets
1956 * handed to the filter only on platforms where that
1957 * information is available.
1959 * We count them here even if we can get the packet count
1960 * from the kernel, as we can only determine at run time
1961 * whether we'll be able to get it from the kernel (if
1962 * HAVE_STRUCT_TPACKET_STATS isn't defined, we can't get it from
1963 * the kernel, but if it is defined, the library might
1964 * have been built with a 2.4 or later kernel, but we
1965 * might be running on a 2.2[.x] kernel without Alexey
1966 * Kuznetzov's turbopacket patches, and thus the kernel
1967 * might not be able to supply those statistics). We
1968 * could, I guess, try, when opening the socket, to get
1969 * the statistics, and if we can not increment the count
1970 * here, but it's not clear that always incrementing
1971 * the count is more expensive than always testing a flag
1974 * We keep the count in "handlep->packets_read", and use that
1975 * for "ps_recv" if we can't get the statistics from the kernel.
1976 * We do that because, if we *can* get the statistics from
1977 * the kernel, we use "handlep->stat.ps_recv" and
1978 * "handlep->stat.ps_drop" as running counts, as reading the
1979 * statistics from the kernel resets the kernel statistics,
1980 * and if we directly increment "handlep->stat.ps_recv" here,
1981 * that means it will count packets *twice* on systems where
1982 * we can get kernel statistics - once here, and once in
1983 * pcap_stats_linux().
1985 handlep
->packets_read
++;
1987 /* Call the user supplied callback function */
1988 callback(userdata
, &pcap_header
, bp
);
1994 pcap_inject_linux(pcap_t
*handle
, const void *buf
, int size
)
1996 struct pcap_linux
*handlep
= handle
->priv
;
1999 if (handlep
->ifindex
== -1) {
2001 * We don't support sending on the "any" device.
2003 pcap_strlcpy(handle
->errbuf
,
2004 "Sending packets isn't supported on the \"any\" device",
2009 if (handlep
->cooked
) {
2011 * We don't support sending on cooked-mode sockets.
2013 * XXX - how do you send on a bound cooked-mode
2015 * Is a "sendto()" required there?
2017 pcap_strlcpy(handle
->errbuf
,
2018 "Sending packets isn't supported in cooked mode",
2023 ret
= (int)send(handle
->fd
, buf
, size
, 0);
2025 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2033 * Get the statistics for the given packet capture handle.
2034 * Reports the number of dropped packets iff the kernel supports
2035 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
2036 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
2037 * patches); otherwise, that information isn't available, and we lie
2038 * and report 0 as the count of dropped packets.
2041 pcap_stats_linux(pcap_t
*handle
, struct pcap_stat
*stats
)
2043 struct pcap_linux
*handlep
= handle
->priv
;
2044 #ifdef HAVE_STRUCT_TPACKET_STATS
2045 #ifdef HAVE_TPACKET3
2047 * For sockets using TPACKET_V1 or TPACKET_V2, the extra
2048 * stuff at the end of a struct tpacket_stats_v3 will not
2049 * be filled in, and we don't look at it so this is OK even
2050 * for those sockets. In addition, the PF_PACKET socket
2051 * code in the kernel only uses the length parameter to
2052 * compute how much data to copy out and to indicate how
2053 * much data was copied out, so it's OK to base it on the
2054 * size of a struct tpacket_stats.
2056 * XXX - it's probably OK, in fact, to just use a
2057 * struct tpacket_stats for V3 sockets, as we don't
2058 * care about the tp_freeze_q_cnt stat.
2060 struct tpacket_stats_v3 kstats
;
2061 #else /* HAVE_TPACKET3 */
2062 struct tpacket_stats kstats
;
2063 #endif /* HAVE_TPACKET3 */
2064 socklen_t len
= sizeof (struct tpacket_stats
);
2065 #endif /* HAVE_STRUCT_TPACKET_STATS */
2067 long long if_dropped
= 0;
2070 * To fill in ps_ifdrop, we parse
2071 * /sys/class/net/{if_name}/statistics/rx_{missed,fifo}_errors
2074 if (handle
->opt
.promisc
)
2077 * XXX - is there any reason to do this by remembering
2078 * the last counts value, subtracting it from the
2079 * current counts value, and adding that to stat.ps_ifdrop,
2080 * maintaining stat.ps_ifdrop as a count, rather than just
2081 * saving the *initial* counts value and setting
2082 * stat.ps_ifdrop to the difference between the current
2083 * value and the initial value?
2085 * One reason might be to handle the count wrapping
2086 * around, on platforms where the count is 32 bits
2087 * and where you might get more than 2^32 dropped
2088 * packets; is there any other reason?
2090 * (We maintain the count as a long long int so that,
2091 * if the kernel maintains the counts as 64-bit even
2092 * on 32-bit platforms, we can handle the real count.
2094 * Unfortunately, we can't report 64-bit counts; we
2095 * need a better API for reporting statistics, such as
2096 * one that reports them in a style similar to the
2097 * pcapng Interface Statistics Block, so that 1) the
2098 * counts are 64-bit, 2) it's easier to add new statistics
2099 * without breaking the ABI, and 3) it's easier to
2100 * indicate to a caller that wants one particular
2101 * statistic that it's not available by just not supplying
2104 if_dropped
= handlep
->sysfs_dropped
;
2105 handlep
->sysfs_dropped
= linux_if_drops(handlep
->device
);
2106 handlep
->stat
.ps_ifdrop
+= (u_int
)(handlep
->sysfs_dropped
- if_dropped
);
2109 #ifdef HAVE_STRUCT_TPACKET_STATS
2111 * Try to get the packet counts from the kernel.
2113 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_STATISTICS
,
2114 &kstats
, &len
) > -1) {
2116 * On systems where the PACKET_STATISTICS "getsockopt()"
2117 * argument is supported on PF_PACKET sockets:
2119 * "ps_recv" counts only packets that *passed* the
2120 * filter, not packets that didn't pass the filter.
2121 * This includes packets later dropped because we
2122 * ran out of buffer space.
2124 * "ps_drop" counts packets dropped because we ran
2125 * out of buffer space. It doesn't count packets
2126 * dropped by the interface driver. It counts only
2127 * packets that passed the filter.
2129 * See above for ps_ifdrop.
2131 * Both statistics include packets not yet read from
2132 * the kernel by libpcap, and thus not yet seen by
2135 * In "linux/net/packet/af_packet.c", at least in the
2136 * 2.4.9 kernel, "tp_packets" is incremented for every
2137 * packet that passes the packet filter *and* is
2138 * successfully queued on the socket; "tp_drops" is
2139 * incremented for every packet dropped because there's
2140 * not enough free space in the socket buffer.
2142 * When the statistics are returned for a PACKET_STATISTICS
2143 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
2144 * so that "tp_packets" counts all packets handed to
2145 * the PF_PACKET socket, including packets dropped because
2146 * there wasn't room on the socket buffer - but not
2147 * including packets that didn't pass the filter.
2149 * In the BSD BPF, the count of received packets is
2150 * incremented for every packet handed to BPF, regardless
2151 * of whether it passed the filter.
2153 * We can't make "pcap_stats()" work the same on both
2154 * platforms, but the best approximation is to return
2155 * "tp_packets" as the count of packets and "tp_drops"
2156 * as the count of drops.
2158 * Keep a running total because each call to
2159 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
2160 * resets the counters to zero.
2162 handlep
->stat
.ps_recv
+= kstats
.tp_packets
;
2163 handlep
->stat
.ps_drop
+= kstats
.tp_drops
;
2164 *stats
= handlep
->stat
;
2170 * If the error was EOPNOTSUPP, fall through, so that
2171 * if you build the library on a system with
2172 * "struct tpacket_stats" and run it on a system
2173 * that doesn't, it works as it does if the library
2174 * is built on a system without "struct tpacket_stats".
2176 if (errno
!= EOPNOTSUPP
) {
2177 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
2178 PCAP_ERRBUF_SIZE
, errno
, "pcap_stats");
2184 * On systems where the PACKET_STATISTICS "getsockopt()" argument
2185 * is not supported on PF_PACKET sockets:
2187 * "ps_recv" counts only packets that *passed* the filter,
2188 * not packets that didn't pass the filter. It does not
2189 * count packets dropped because we ran out of buffer
2192 * "ps_drop" is not supported.
2194 * "ps_ifdrop" is supported. It will return the number
2195 * of drops the interface reports in
2196 * /sys/class/net/{if_name}/statistics/rx_{missed,fifo}_errors,
2197 * if that is available.
2199 * "ps_recv" doesn't include packets not yet read from
2200 * the kernel by libpcap.
2202 * We maintain the count of packets processed by libpcap in
2203 * "handlep->packets_read", for reasons described in the comment
2204 * at the end of pcap_read_packet(). We have no idea how many
2205 * packets were dropped by the kernel buffers -- but we know
2206 * how many the interface dropped, so we can return that.
2209 stats
->ps_recv
= handlep
->packets_read
;
2211 stats
->ps_ifdrop
= handlep
->stat
.ps_ifdrop
;
2216 add_linux_if(pcap_if_list_t
*devlistp
, const char *ifname
, int fd
, char *errbuf
)
2219 char name
[512]; /* XXX - pick a size */
2221 struct ifreq ifrflags
;
2224 * Get the interface name.
2228 while (*p
!= '\0' && *p
!= ' ' && *p
!= '\t' && *p
!= '\n') {
2231 * This could be the separator between a
2232 * name and an alias number, or it could be
2233 * the separator between a name with no
2234 * alias number and the next field.
2236 * If there's a colon after digits, it
2237 * separates the name and the alias number,
2238 * otherwise it separates the name and the
2242 while (PCAP_ISDIGIT(*p
))
2246 * That was the next field,
2247 * not the alias number.
2258 * Get the flags for this interface.
2260 pcap_strlcpy(ifrflags
.ifr_name
, name
, sizeof(ifrflags
.ifr_name
));
2261 if (ioctl(fd
, SIOCGIFFLAGS
, (char *)&ifrflags
) < 0) {
2262 if (errno
== ENXIO
|| errno
== ENODEV
)
2263 return (0); /* device doesn't actually exist - ignore it */
2264 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
2265 errno
, "SIOCGIFFLAGS: %.*s",
2266 (int)sizeof(ifrflags
.ifr_name
),
2272 * Add an entry for this interface, with no addresses, if it's
2273 * not already in the list.
2275 if (find_or_add_if(devlistp
, name
, ifrflags
.ifr_flags
,
2276 get_if_flags
, errbuf
) == NULL
) {
2287 * Get from "/sys/class/net" all interfaces listed there; if they're
2288 * already in the list of interfaces we have, that won't add another
2289 * instance, but if they're not, that'll add them.
2291 * We don't bother getting any addresses for them; it appears you can't
2292 * use SIOCGIFADDR on Linux to get IPv6 addresses for interfaces, and,
2293 * although some other types of addresses can be fetched with SIOCGIFADDR,
2294 * we don't bother with them for now.
2296 * We also don't fail if we couldn't open "/sys/class/net"; we just leave
2297 * the list of interfaces as is, and return 0, so that we can try
2298 * scanning /proc/net/dev.
2300 * Otherwise, we return 1 if we don't get an error and -1 if we do.
2303 scan_sys_class_net(pcap_if_list_t
*devlistp
, char *errbuf
)
2305 DIR *sys_class_net_d
;
2308 char subsystem_path
[PATH_MAX
+1];
2312 sys_class_net_d
= opendir("/sys/class/net");
2313 if (sys_class_net_d
== NULL
) {
2315 * Don't fail if it doesn't exist at all.
2317 if (errno
== ENOENT
)
2321 * Fail if we got some other error.
2323 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
2324 errno
, "Can't open /sys/class/net");
2329 * Create a socket from which to fetch interface information.
2331 fd
= socket(PF_UNIX
, SOCK_RAW
, 0);
2333 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
2335 (void)closedir(sys_class_net_d
);
2341 ent
= readdir(sys_class_net_d
);
2344 * Error or EOF; if errno != 0, it's an error.
2350 * Ignore "." and "..".
2352 if (strcmp(ent
->d_name
, ".") == 0 ||
2353 strcmp(ent
->d_name
, "..") == 0)
2357 * Ignore plain files; they do not have subdirectories
2358 * and thus have no attributes.
2360 if (ent
->d_type
== DT_REG
)
2364 * Is there an "ifindex" file under that name?
2365 * (We don't care whether it's a directory or
2366 * a symlink; older kernels have directories
2367 * for devices, newer kernels have symlinks to
2370 snprintf(subsystem_path
, sizeof subsystem_path
,
2371 "/sys/class/net/%s/ifindex", ent
->d_name
);
2372 if (lstat(subsystem_path
, &statb
) != 0) {
2374 * Stat failed. Either there was an error
2375 * other than ENOENT, and we don't know if
2376 * this is an interface, or it's ENOENT,
2377 * and either some part of "/sys/class/net/{if_name}"
2378 * disappeared, in which case it probably means
2379 * the interface disappeared, or there's no
2380 * "ifindex" file, which means it's not a
2381 * network interface.
2387 * Attempt to add the interface.
2389 if (add_linux_if(devlistp
, &ent
->d_name
[0], fd
, errbuf
) == -1) {
2397 * Well, we didn't fail for any other reason; did we
2398 * fail due to an error reading the directory?
2401 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
2402 errno
, "Error reading /sys/class/net");
2408 (void)closedir(sys_class_net_d
);
2413 * Get from "/proc/net/dev" all interfaces listed there; if they're
2414 * already in the list of interfaces we have, that won't add another
2415 * instance, but if they're not, that'll add them.
2417 * See comments from scan_sys_class_net().
2420 scan_proc_net_dev(pcap_if_list_t
*devlistp
, char *errbuf
)
2429 proc_net_f
= fopen("/proc/net/dev", "r");
2430 if (proc_net_f
== NULL
) {
2432 * Don't fail if it doesn't exist at all.
2434 if (errno
== ENOENT
)
2438 * Fail if we got some other error.
2440 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
2441 errno
, "Can't open /proc/net/dev");
2446 * Create a socket from which to fetch interface information.
2448 fd
= socket(PF_UNIX
, SOCK_RAW
, 0);
2450 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
2452 (void)fclose(proc_net_f
);
2457 fgets(linebuf
, sizeof linebuf
, proc_net_f
) != NULL
; linenum
++) {
2459 * Skip the first two lines - they're headers.
2467 * Skip leading white space.
2469 while (*p
== ' ' || *p
== '\t')
2471 if (*p
== '\0' || *p
== '\n')
2472 continue; /* blank line */
2475 * Attempt to add the interface.
2477 if (add_linux_if(devlistp
, p
, fd
, errbuf
) == -1) {
2485 * Well, we didn't fail for any other reason; did we
2486 * fail due to an error reading the file?
2488 if (ferror(proc_net_f
)) {
2489 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
2490 errno
, "Error reading /proc/net/dev");
2496 (void)fclose(proc_net_f
);
2501 * Description string for the "any" device.
2503 static const char any_descr
[] = "Pseudo-device that captures on all interfaces";
2506 * A PF_PACKET socket can be bound to any network interface.
2509 can_be_bound(const char *name _U_
)
2515 * Get additional flags for a device, using SIOCGIFMEDIA.
2518 get_if_flags(const char *name
, bpf_u_int32
*flags
, char *errbuf
)
2522 unsigned int arptype
;
2524 struct ethtool_value info
;
2526 if (*flags
& PCAP_IF_LOOPBACK
) {
2528 * Loopback devices aren't wireless, and "connected"/
2529 * "disconnected" doesn't apply to them.
2531 *flags
|= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
2535 sock
= socket(AF_INET
, SOCK_DGRAM
, 0);
2537 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
, errno
,
2538 "Can't create socket to get ethtool information for %s",
2544 * OK, what type of network is this?
2545 * In particular, is it wired or wireless?
2547 if (is_wifi(sock
, name
)) {
2549 * Wi-Fi, hence wireless.
2551 *flags
|= PCAP_IF_WIRELESS
;
2554 * OK, what does /sys/class/net/{if_name}/type contain?
2555 * (We don't use that for Wi-Fi, as it'll report
2556 * "Ethernet", i.e. ARPHRD_ETHER, for non-monitor-
2561 if (asprintf(&pathstr
, "/sys/class/net/%s/type", name
) == -1) {
2562 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2563 "%s: Can't generate path name string for /sys/class/net device",
2568 fh
= fopen(pathstr
, "r");
2570 if (fscanf(fh
, "%u", &arptype
) == 1) {
2572 * OK, we got an ARPHRD_ type; what is it?
2576 #ifdef ARPHRD_LOOPBACK
2577 case ARPHRD_LOOPBACK
:
2579 * These are types to which
2580 * "connected" and "disconnected"
2581 * don't apply, so don't bother
2584 * XXX - add other types?
2593 case ARPHRD_IEEE80211
:
2594 case ARPHRD_IEEE80211_PRISM
:
2595 case ARPHRD_IEEE80211_RADIOTAP
:
2596 #ifdef ARPHRD_IEEE802154
2597 case ARPHRD_IEEE802154
:
2599 #ifdef ARPHRD_IEEE802154_MONITOR
2600 case ARPHRD_IEEE802154_MONITOR
:
2602 #ifdef ARPHRD_6LOWPAN
2603 case ARPHRD_6LOWPAN
:
2606 * Various wireless types.
2608 *flags
|= PCAP_IF_WIRELESS
;
2617 #ifdef ETHTOOL_GLINK
2618 memset(&ifr
, 0, sizeof(ifr
));
2619 pcap_strlcpy(ifr
.ifr_name
, name
, sizeof(ifr
.ifr_name
));
2620 info
.cmd
= ETHTOOL_GLINK
;
2621 ifr
.ifr_data
= (caddr_t
)&info
;
2622 if (ioctl(sock
, SIOCETHTOOL
, &ifr
) == -1) {
2623 int save_errno
= errno
;
2625 switch (save_errno
) {
2630 * OK, this OS version or driver doesn't support
2631 * asking for this information.
2632 * XXX - distinguish between "this doesn't
2633 * support ethtool at all because it's not
2634 * that type of device" vs. "this doesn't
2635 * support ethtool even though it's that
2636 * type of device", and return "unknown".
2638 *flags
|= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
2644 * OK, no such device.
2645 * The user will find that out when they try to
2646 * activate the device; just say "OK" and
2647 * don't set anything.
2656 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
2658 "%s: SIOCETHTOOL(ETHTOOL_GLINK) ioctl failed",
2672 *flags
|= PCAP_IF_CONNECTION_STATUS_CONNECTED
;
2675 * It's disconnected.
2677 *flags
|= PCAP_IF_CONNECTION_STATUS_DISCONNECTED
;
2686 pcap_platform_finddevs(pcap_if_list_t
*devlistp
, char *errbuf
)
2691 * Get the list of regular interfaces first.
2693 if (pcap_findalldevs_interfaces(devlistp
, errbuf
, can_be_bound
,
2694 get_if_flags
) == -1)
2695 return (-1); /* failure */
2698 * Read "/sys/class/net", and add to the list of interfaces all
2699 * interfaces listed there that we don't already have, because,
2700 * on Linux, SIOCGIFCONF reports only interfaces with IPv4 addresses,
2701 * and even getifaddrs() won't return information about
2702 * interfaces with no addresses, so you need to read "/sys/class/net"
2703 * to get the names of the rest of the interfaces.
2705 ret
= scan_sys_class_net(devlistp
, errbuf
);
2707 return (-1); /* failed */
2710 * No /sys/class/net; try reading /proc/net/dev instead.
2712 if (scan_proc_net_dev(devlistp
, errbuf
) == -1)
2717 * Add the "any" device.
2718 * As it refers to all network devices, not to any particular
2719 * network device, the notion of "connected" vs. "disconnected"
2722 if (add_dev(devlistp
, "any",
2723 PCAP_IF_UP
|PCAP_IF_RUNNING
|PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
,
2724 any_descr
, errbuf
) == NULL
)
2731 * Attach the given BPF code to the packet capture device.
2734 pcap_setfilter_linux_common(pcap_t
*handle
, struct bpf_program
*filter
,
2737 struct pcap_linux
*handlep
;
2738 #ifdef SO_ATTACH_FILTER
2739 struct sock_fprog fcode
;
2740 int can_filter_in_kernel
;
2747 pcap_strlcpy(handle
->errbuf
, "setfilter: No filter specified",
2752 handlep
= handle
->priv
;
2754 /* Make our private copy of the filter */
2756 if (install_bpf_program(handle
, filter
) < 0)
2757 /* install_bpf_program() filled in errbuf */
2761 * Run user level packet filter by default. Will be overriden if
2762 * installing a kernel filter succeeds.
2764 handlep
->filter_in_userland
= 1;
2766 /* Install kernel level filter if possible */
2768 #ifdef SO_ATTACH_FILTER
2770 if (handle
->fcode
.bf_len
> USHRT_MAX
) {
2772 * fcode.len is an unsigned short for current kernel.
2773 * I have yet to see BPF-Code with that much
2774 * instructions but still it is possible. So for the
2775 * sake of correctness I added this check.
2777 fprintf(stderr
, "Warning: Filter too complex for kernel\n");
2779 fcode
.filter
= NULL
;
2780 can_filter_in_kernel
= 0;
2782 #endif /* USHRT_MAX */
2785 * Oh joy, the Linux kernel uses struct sock_fprog instead
2786 * of struct bpf_program and of course the length field is
2787 * of different size. Pointed out by Sebastian
2789 * Oh, and we also need to fix it up so that all "ret"
2790 * instructions with non-zero operands have MAXIMUM_SNAPLEN
2791 * as the operand if we're not capturing in memory-mapped
2792 * mode, and so that, if we're in cooked mode, all memory-
2793 * reference instructions use special magic offsets in
2794 * references to the link-layer header and assume that the
2795 * link-layer payload begins at 0; "fix_program()" will do
2798 switch (fix_program(handle
, &fcode
, is_mmapped
)) {
2803 * Fatal error; just quit.
2804 * (The "default" case shouldn't happen; we
2805 * return -1 for that reason.)
2811 * The program performed checks that we can't make
2812 * work in the kernel.
2814 can_filter_in_kernel
= 0;
2819 * We have a filter that'll work in the kernel.
2821 can_filter_in_kernel
= 1;
2827 * NOTE: at this point, we've set both the "len" and "filter"
2828 * fields of "fcode". As of the 2.6.32.4 kernel, at least,
2829 * those are the only members of the "sock_fprog" structure,
2830 * so we initialize every member of that structure.
2832 * If there is anything in "fcode" that is not initialized,
2833 * it is either a field added in a later kernel, or it's
2836 * If a new field is added, this code needs to be updated
2837 * to set it correctly.
2839 * If there are no other fields, then:
2841 * if the Linux kernel looks at the padding, it's
2844 * if the Linux kernel doesn't look at the padding,
2845 * then if some tool complains that we're passing
2846 * uninitialized data to the kernel, then the tool
2847 * is buggy and needs to understand that it's just
2850 if (can_filter_in_kernel
) {
2851 if ((err
= set_kernel_filter(handle
, &fcode
)) == 0)
2854 * Installation succeded - using kernel filter,
2855 * so userland filtering not needed.
2857 handlep
->filter_in_userland
= 0;
2859 else if (err
== -1) /* Non-fatal error */
2862 * Print a warning if we weren't able to install
2863 * the filter for a reason other than "this kernel
2864 * isn't configured to support socket filters.
2866 if (errno
!= ENOPROTOOPT
&& errno
!= EOPNOTSUPP
) {
2868 "Warning: Kernel filter failed: %s\n",
2869 pcap_strerror(errno
));
2875 * If we're not using the kernel filter, get rid of any kernel
2876 * filter that might've been there before, e.g. because the
2877 * previous filter could work in the kernel, or because some other
2878 * code attached a filter to the socket by some means other than
2879 * calling "pcap_setfilter()". Otherwise, the kernel filter may
2880 * filter out packets that would pass the new userland filter.
2882 if (handlep
->filter_in_userland
) {
2883 if (reset_kernel_filter(handle
) == -1) {
2884 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
2885 PCAP_ERRBUF_SIZE
, errno
,
2886 "can't remove kernel filter");
2887 err
= -2; /* fatal error */
2892 * Free up the copy of the filter that was made by "fix_program()".
2894 if (fcode
.filter
!= NULL
)
2900 #endif /* SO_ATTACH_FILTER */
2906 pcap_setfilter_linux(pcap_t
*handle
, struct bpf_program
*filter
)
2908 return pcap_setfilter_linux_common(handle
, filter
, 0);
2913 * Set direction flag: Which packets do we accept on a forwarding
2914 * single device? IN, OUT or both?
2917 pcap_setdirection_linux(pcap_t
*handle
, pcap_direction_t d
)
2919 handle
->direction
= d
;
2925 #ifndef IW_MODE_MONITOR
2928 , const char *device
)
2932 #ifdef IW_MODE_MONITOR
2933 char errbuf
[PCAP_ERRBUF_SIZE
];
2937 * See if there's a sysfs wireless directory for it.
2938 * If so, it's a wireless interface.
2940 if (asprintf(&pathstr
, "/sys/class/net/%s/wireless", device
) == -1) {
2942 * Just give up here.
2946 if (stat(pathstr
, &statb
) == 0) {
2952 #ifdef IW_MODE_MONITOR
2954 * OK, maybe it's not wireless, or maybe this kernel doesn't
2955 * support sysfs. Try the wireless extensions.
2957 if (has_wext(sock_fd
, device
, errbuf
) == 1) {
2959 * It supports the wireless extensions, so it's a Wi-Fi
2969 * Linux uses the ARP hardware type to identify the type of an
2970 * interface. pcap uses the DLT_xxx constants for this. This
2971 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
2972 * constant, as arguments, and sets "handle->linktype" to the
2973 * appropriate DLT_XXX constant and sets "handle->offset" to
2974 * the appropriate value (to make "handle->offset" plus link-layer
2975 * header length be a multiple of 4, so that the link-layer payload
2976 * will be aligned on a 4-byte boundary when capturing packets).
2977 * (If the offset isn't set here, it'll be 0; add code as appropriate
2978 * for cases where it shouldn't be 0.)
2980 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
2981 * in cooked mode; otherwise, we can't use cooked mode, so we have
2982 * to pick some type that works in raw mode, or fail.
2984 * Sets the link type to -1 if unable to map the type.
2986 static void map_arphrd_to_dlt(pcap_t
*handle
, int sock_fd
, int arptype
,
2987 const char *device
, int cooked_ok
)
2989 static const char cdma_rmnet
[] = "cdma_rmnet";
2995 * For various annoying reasons having to do with DHCP
2996 * software, some versions of Android give the mobile-
2997 * phone-network interface an ARPHRD_ value of
2998 * ARPHRD_ETHER, even though the packets supplied by
2999 * that interface have no link-layer header, and begin
3000 * with an IP header, so that the ARPHRD_ value should
3003 * Detect those devices by checking the device name, and
3004 * use DLT_RAW for them.
3006 if (strncmp(device
, cdma_rmnet
, sizeof cdma_rmnet
- 1) == 0) {
3007 handle
->linktype
= DLT_RAW
;
3012 * Is this a real Ethernet device? If so, give it a
3013 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
3014 * that an application can let you choose it, in case you're
3015 * capturing DOCSIS traffic that a Cisco Cable Modem
3016 * Termination System is putting out onto an Ethernet (it
3017 * doesn't put an Ethernet header onto the wire, it puts raw
3018 * DOCSIS frames out on the wire inside the low-level
3019 * Ethernet framing).
3021 * XXX - are there any other sorts of "fake Ethernet" that
3022 * have ARPHRD_ETHER but that shouldn't offer DLT_DOCSIS as
3023 * a Cisco CMTS won't put traffic onto it or get traffic
3024 * bridged onto it? ISDN is handled in "activate_sock()",
3025 * as we fall back on cooked mode there, and we use
3026 * is_wifi() to check for 802.11 devices; are there any
3029 if (!is_wifi(sock_fd
, device
)) {
3033 * This is not a Wi-Fi device but it could be
3034 * a DSA master/management network device.
3036 ret
= iface_dsa_get_proto_info(device
, handle
);
3042 * This is a DSA master/management network
3043 * device linktype is already set by
3044 * iface_dsa_get_proto_info() set an
3045 * appropriate offset here.
3052 * It's not a Wi-Fi device; offer DOCSIS.
3054 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
3056 * If that fails, just leave the list empty.
3058 if (handle
->dlt_list
!= NULL
) {
3059 handle
->dlt_list
[0] = DLT_EN10MB
;
3060 handle
->dlt_list
[1] = DLT_DOCSIS
;
3061 handle
->dlt_count
= 2;
3066 case ARPHRD_METRICOM
:
3067 case ARPHRD_LOOPBACK
:
3068 handle
->linktype
= DLT_EN10MB
;
3073 handle
->linktype
= DLT_EN3MB
;
3077 handle
->linktype
= DLT_AX25_KISS
;
3081 handle
->linktype
= DLT_PRONET
;
3085 handle
->linktype
= DLT_CHAOS
;
3088 #define ARPHRD_CAN 280
3092 * Map this to DLT_LINUX_SLL; that way, CAN frames will
3093 * have ETH_P_CAN/LINUX_SLL_P_CAN as the protocol and
3094 * CAN FD frames will have ETH_P_CANFD/LINUX_SLL_P_CANFD
3095 * as the protocol, so they can be distinguished by the
3096 * protocol in the SLL header.
3098 handle
->linktype
= DLT_LINUX_SLL
;
3101 #ifndef ARPHRD_IEEE802_TR
3102 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
3104 case ARPHRD_IEEE802_TR
:
3105 case ARPHRD_IEEE802
:
3106 handle
->linktype
= DLT_IEEE802
;
3111 handle
->linktype
= DLT_ARCNET_LINUX
;
3114 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
3115 #define ARPHRD_FDDI 774
3118 handle
->linktype
= DLT_FDDI
;
3122 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
3123 #define ARPHRD_ATM 19
3127 * The Classical IP implementation in ATM for Linux
3128 * supports both what RFC 1483 calls "LLC Encapsulation",
3129 * in which each packet has an LLC header, possibly
3130 * with a SNAP header as well, prepended to it, and
3131 * what RFC 1483 calls "VC Based Multiplexing", in which
3132 * different virtual circuits carry different network
3133 * layer protocols, and no header is prepended to packets.
3135 * They both have an ARPHRD_ type of ARPHRD_ATM, so
3136 * you can't use the ARPHRD_ type to find out whether
3137 * captured packets will have an LLC header, and,
3138 * while there's a socket ioctl to *set* the encapsulation
3139 * type, there's no ioctl to *get* the encapsulation type.
3143 * programs that dissect Linux Classical IP frames
3144 * would have to check for an LLC header and,
3145 * depending on whether they see one or not, dissect
3146 * the frame as LLC-encapsulated or as raw IP (I
3147 * don't know whether there's any traffic other than
3148 * IP that would show up on the socket, or whether
3149 * there's any support for IPv6 in the Linux
3150 * Classical IP code);
3152 * filter expressions would have to compile into
3153 * code that checks for an LLC header and does
3156 * Both of those are a nuisance - and, at least on systems
3157 * that support PF_PACKET sockets, we don't have to put
3158 * up with those nuisances; instead, we can just capture
3159 * in cooked mode. That's what we'll do, if we can.
3160 * Otherwise, we'll just fail.
3163 handle
->linktype
= DLT_LINUX_SLL
;
3165 handle
->linktype
= -1;
3168 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
3169 #define ARPHRD_IEEE80211 801
3171 case ARPHRD_IEEE80211
:
3172 handle
->linktype
= DLT_IEEE802_11
;
3175 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
3176 #define ARPHRD_IEEE80211_PRISM 802
3178 case ARPHRD_IEEE80211_PRISM
:
3179 handle
->linktype
= DLT_PRISM_HEADER
;
3182 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
3183 #define ARPHRD_IEEE80211_RADIOTAP 803
3185 case ARPHRD_IEEE80211_RADIOTAP
:
3186 handle
->linktype
= DLT_IEEE802_11_RADIO
;
3191 * Some PPP code in the kernel supplies no link-layer
3192 * header whatsoever to PF_PACKET sockets; other PPP
3193 * code supplies PPP link-layer headers ("syncppp.c");
3194 * some PPP code might supply random link-layer
3195 * headers (PPP over ISDN - there's code in Ethereal,
3196 * for example, to cope with PPP-over-ISDN captures
3197 * with which the Ethereal developers have had to cope,
3198 * heuristically trying to determine which of the
3199 * oddball link-layer headers particular packets have).
3201 * As such, we just punt, and run all PPP interfaces
3202 * in cooked mode, if we can; otherwise, we just treat
3203 * it as DLT_RAW, for now - if somebody needs to capture,
3204 * on a 2.0[.x] kernel, on PPP devices that supply a
3205 * link-layer header, they'll have to add code here to
3206 * map to the appropriate DLT_ type (possibly adding a
3207 * new DLT_ type, if necessary).
3210 handle
->linktype
= DLT_LINUX_SLL
;
3213 * XXX - handle ISDN types here? We can't fall
3214 * back on cooked sockets, so we'd have to
3215 * figure out from the device name what type of
3216 * link-layer encapsulation it's using, and map
3217 * that to an appropriate DLT_ value, meaning
3218 * we'd map "isdnN" devices to DLT_RAW (they
3219 * supply raw IP packets with no link-layer
3220 * header) and "isdY" devices to a new DLT_I4L_IP
3221 * type that has only an Ethernet packet type as
3222 * a link-layer header.
3224 * But sometimes we seem to get random crap
3225 * in the link-layer header when capturing on
3228 handle
->linktype
= DLT_RAW
;
3232 #ifndef ARPHRD_CISCO
3233 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
3236 handle
->linktype
= DLT_C_HDLC
;
3239 /* Not sure if this is correct for all tunnels, but it
3243 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
3251 #ifndef ARPHRD_RAWHDLC
3252 #define ARPHRD_RAWHDLC 518
3254 case ARPHRD_RAWHDLC
:
3256 #define ARPHRD_DLCI 15
3260 * XXX - should some of those be mapped to DLT_LINUX_SLL
3261 * instead? Should we just map all of them to DLT_LINUX_SLL?
3263 handle
->linktype
= DLT_RAW
;
3267 #define ARPHRD_FRAD 770
3270 handle
->linktype
= DLT_FRELAY
;
3273 case ARPHRD_LOCALTLK
:
3274 handle
->linktype
= DLT_LTALK
;
3279 * RFC 4338 defines an encapsulation for IP and ARP
3280 * packets that's compatible with the RFC 2625
3281 * encapsulation, but that uses a different ARP
3282 * hardware type and hardware addresses. That
3283 * ARP hardware type is 18; Linux doesn't define
3284 * any ARPHRD_ value as 18, but if it ever officially
3285 * supports RFC 4338-style IP-over-FC, it should define
3288 * For now, we map it to DLT_IP_OVER_FC, in the hopes
3289 * that this will encourage its use in the future,
3290 * should Linux ever officially support RFC 4338-style
3293 handle
->linktype
= DLT_IP_OVER_FC
;
3297 #define ARPHRD_FCPP 784
3301 #define ARPHRD_FCAL 785
3305 #define ARPHRD_FCPL 786
3308 #ifndef ARPHRD_FCFABRIC
3309 #define ARPHRD_FCFABRIC 787
3311 case ARPHRD_FCFABRIC
:
3313 * Back in 2002, Donald Lee at Cray wanted a DLT_ for
3316 * http://www.mail-archive.com/tcpdump-workers@sandelman.ottawa.on.ca/msg01043.html
3318 * and one was assigned.
3320 * In a later private discussion (spun off from a message
3321 * on the ethereal-users list) on how to get that DLT_
3322 * value in libpcap on Linux, I ended up deciding that
3323 * the best thing to do would be to have him tweak the
3324 * driver to set the ARPHRD_ value to some ARPHRD_FCxx
3325 * type, and map all those types to DLT_IP_OVER_FC:
3327 * I've checked into the libpcap and tcpdump CVS tree
3328 * support for DLT_IP_OVER_FC. In order to use that,
3329 * you'd have to modify your modified driver to return
3330 * one of the ARPHRD_FCxxx types, in "fcLINUXfcp.c" -
3331 * change it to set "dev->type" to ARPHRD_FCFABRIC, for
3332 * example (the exact value doesn't matter, it can be
3333 * any of ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL, or
3336 * 11 years later, Christian Svensson wanted to map
3337 * various ARPHRD_ values to DLT_FC_2 and
3338 * DLT_FC_2_WITH_FRAME_DELIMS for raw Fibre Channel
3341 * https://github.com/mcr/libpcap/pull/29
3343 * There doesn't seem to be any network drivers that uses
3344 * any of the ARPHRD_FC* values for IP-over-FC, and
3345 * it's not exactly clear what the "Dummy types for non
3346 * ARP hardware" are supposed to mean (link-layer
3347 * header type? Physical network type?), so it's
3348 * not exactly clear why the ARPHRD_FC* types exist
3349 * in the first place.
3351 * For now, we map them to DLT_FC_2, and provide an
3352 * option of DLT_FC_2_WITH_FRAME_DELIMS, as well as
3353 * DLT_IP_OVER_FC just in case there's some old
3354 * driver out there that uses one of those types for
3355 * IP-over-FC on which somebody wants to capture
3358 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 3);
3360 * If that fails, just leave the list empty.
3362 if (handle
->dlt_list
!= NULL
) {
3363 handle
->dlt_list
[0] = DLT_FC_2
;
3364 handle
->dlt_list
[1] = DLT_FC_2_WITH_FRAME_DELIMS
;
3365 handle
->dlt_list
[2] = DLT_IP_OVER_FC
;
3366 handle
->dlt_count
= 3;
3368 handle
->linktype
= DLT_FC_2
;
3372 #define ARPHRD_IRDA 783
3375 /* Don't expect IP packet out of this interfaces... */
3376 handle
->linktype
= DLT_LINUX_IRDA
;
3377 /* We need to save packet direction for IrDA decoding,
3378 * so let's use "Linux-cooked" mode. Jean II
3380 * XXX - this is handled in activate_sock(). */
3381 /* handlep->cooked = 1; */
3384 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
3385 * is needed, please report it to <daniele@orlandi.com> */
3387 #define ARPHRD_LAPD 8445
3390 /* Don't expect IP packet out of this interfaces... */
3391 handle
->linktype
= DLT_LINUX_LAPD
;
3395 #define ARPHRD_NONE 0xFFFE
3399 * No link-layer header; packets are just IP
3400 * packets, so use DLT_RAW.
3402 handle
->linktype
= DLT_RAW
;
3405 #ifndef ARPHRD_IEEE802154
3406 #define ARPHRD_IEEE802154 804
3408 case ARPHRD_IEEE802154
:
3409 handle
->linktype
= DLT_IEEE802_15_4_NOFCS
;
3412 #ifndef ARPHRD_NETLINK
3413 #define ARPHRD_NETLINK 824
3415 case ARPHRD_NETLINK
:
3416 handle
->linktype
= DLT_NETLINK
;
3418 * We need to use cooked mode, so that in sll_protocol we
3419 * pick up the netlink protocol type such as NETLINK_ROUTE,
3420 * NETLINK_GENERIC, NETLINK_FIB_LOOKUP, etc.
3422 * XXX - this is handled in activate_sock().
3424 /* handlep->cooked = 1; */
3427 #ifndef ARPHRD_VSOCKMON
3428 #define ARPHRD_VSOCKMON 826
3430 case ARPHRD_VSOCKMON
:
3431 handle
->linktype
= DLT_VSOCK
;
3435 handle
->linktype
= -1;
3440 #ifdef PACKET_RESERVE
3442 set_dlt_list_cooked(pcap_t
*handle
, int sock_fd
)
3445 unsigned int tp_reserve
;
3448 * If we can't do PACKET_RESERVE, we can't reserve extra space
3449 * for a DLL_LINUX_SLL2 header, so we can't support DLT_LINUX_SLL2.
3451 len
= sizeof(tp_reserve
);
3452 if (getsockopt(sock_fd
, SOL_PACKET
, PACKET_RESERVE
, &tp_reserve
,
3455 * Yes, we can do DLL_LINUX_SLL2.
3457 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
3459 * If that fails, just leave the list empty.
3461 if (handle
->dlt_list
!= NULL
) {
3462 handle
->dlt_list
[0] = DLT_LINUX_SLL
;
3463 handle
->dlt_list
[1] = DLT_LINUX_SLL2
;
3464 handle
->dlt_count
= 2;
3468 #else/* PACKET_RESERVE */
3470 * The build environment doesn't define PACKET_RESERVE, so we can't reserve
3471 * extra space for a DLL_LINUX_SLL2 header, so we can't support DLT_LINUX_SLL2.
3474 set_dlt_list_cooked(pcap_t
*handle _U_
, int sock_fd _U_
)
3477 #endif /* PACKET_RESERVE */
3480 * Try to set up a PF_PACKET socket.
3481 * Returns 0 on success and a PCAP_ERROR_ value on failure.
3484 activate_sock(pcap_t
*handle
, int is_any_device
)
3486 struct pcap_linux
*handlep
= handle
->priv
;
3487 const char *device
= handle
->opt
.device
;
3489 int sock_fd
, arptype
;
3490 #ifdef HAVE_PACKET_AUXDATA
3494 struct packet_mreq mr
;
3495 #if defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT)
3497 socklen_t len
= sizeof(bpf_extensions
);
3500 sock_fd
= open_pf_packet_socket(handle
, is_any_device
);
3503 * Failed; return its return value.
3509 * Get the interface index of the loopback device.
3510 * If the attempt fails, don't fail, just set the
3511 * "handlep->lo_ifindex" to -1.
3513 * XXX - can there be more than one device that loops
3514 * packets back, i.e. devices other than "lo"? If so,
3515 * we'd need to find them all, and have an array of
3516 * indices for them, and check all of them in
3517 * "pcap_read_packet()".
3519 handlep
->lo_ifindex
= iface_get_id(sock_fd
, "lo", handle
->errbuf
);
3522 * Default value for offset to align link-layer payload
3523 * on a 4-byte boundary.
3528 * What kind of frames do we have to deal with? Fall back
3529 * to cooked mode if we have an unknown interface type
3530 * or a type we know doesn't work well in raw mode.
3532 if (!is_any_device
) {
3533 /* Assume for now we don't need cooked mode. */
3534 handlep
->cooked
= 0;
3536 if (handle
->opt
.rfmon
) {
3538 * We were asked to turn on monitor mode.
3539 * Do so before we get the link-layer type,
3540 * because entering monitor mode could change
3541 * the link-layer type.
3543 err
= enter_rfmon_mode(handle
, sock_fd
, device
);
3551 * Nothing worked for turning monitor mode
3555 return PCAP_ERROR_RFMON_NOTSUP
;
3559 * Either monitor mode has been turned on for
3560 * the device, or we've been given a different
3561 * device to open for monitor mode. If we've
3562 * been given a different device, use it.
3564 if (handlep
->mondevice
!= NULL
)
3565 device
= handlep
->mondevice
;
3567 arptype
= iface_get_arptype(sock_fd
, device
, handle
->errbuf
);
3572 map_arphrd_to_dlt(handle
, sock_fd
, arptype
, device
, 1);
3573 if (handle
->linktype
== -1 ||
3574 handle
->linktype
== DLT_LINUX_SLL
||
3575 handle
->linktype
== DLT_LINUX_IRDA
||
3576 handle
->linktype
== DLT_LINUX_LAPD
||
3577 handle
->linktype
== DLT_NETLINK
||
3578 (handle
->linktype
== DLT_EN10MB
&&
3579 (strncmp("isdn", device
, 4) == 0 ||
3580 strncmp("isdY", device
, 4) == 0))) {
3582 * Unknown interface type (-1), or a
3583 * device we explicitly chose to run
3584 * in cooked mode (e.g., PPP devices),
3585 * or an ISDN device (whose link-layer
3586 * type we can only determine by using
3587 * APIs that may be different on different
3588 * kernels) - reopen in cooked mode.
3590 * If the type is unknown, return a warning;
3591 * map_arphrd_to_dlt() has already set the
3594 if (close(sock_fd
) == -1) {
3595 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
3596 PCAP_ERRBUF_SIZE
, errno
, "close");
3599 sock_fd
= open_pf_packet_socket(handle
, 1);
3602 * Fatal error; the return value is the
3603 * error code, and handle->errbuf has
3604 * been set to an appropriate error
3609 handlep
->cooked
= 1;
3612 * Get rid of any link-layer type list
3613 * we allocated - this only supports cooked
3616 if (handle
->dlt_list
!= NULL
) {
3617 free(handle
->dlt_list
);
3618 handle
->dlt_list
= NULL
;
3619 handle
->dlt_count
= 0;
3620 set_dlt_list_cooked(handle
, sock_fd
);
3623 if (handle
->linktype
== -1) {
3625 * Warn that we're falling back on
3626 * cooked mode; we may want to
3627 * update "map_arphrd_to_dlt()"
3628 * to handle the new type.
3630 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3632 "supported by libpcap - "
3633 "falling back to cooked "
3639 * IrDA capture is not a real "cooked" capture,
3640 * it's IrLAP frames, not IP packets. The
3641 * same applies to LAPD capture.
3643 if (handle
->linktype
!= DLT_LINUX_IRDA
&&
3644 handle
->linktype
!= DLT_LINUX_LAPD
&&
3645 handle
->linktype
!= DLT_NETLINK
)
3646 handle
->linktype
= DLT_LINUX_SLL
;
3647 if (handle
->linktype
== -1) {
3648 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3649 "unknown arptype %d, defaulting to cooked mode",
3651 status
= PCAP_WARNING
;
3655 handlep
->ifindex
= iface_get_id(sock_fd
, device
,
3657 if (handlep
->ifindex
== -1) {
3662 if ((err
= iface_bind(sock_fd
, handlep
->ifindex
,
3663 handle
->errbuf
, pcap_protocol(handle
))) != 0) {
3671 if (handle
->opt
.rfmon
) {
3673 * It doesn't support monitor mode.
3676 return PCAP_ERROR_RFMON_NOTSUP
;
3680 * It uses cooked mode.
3682 handlep
->cooked
= 1;
3683 handle
->linktype
= DLT_LINUX_SLL
;
3684 handle
->dlt_list
= NULL
;
3685 handle
->dlt_count
= 0;
3686 set_dlt_list_cooked(handle
, sock_fd
);
3689 * We're not bound to a device.
3690 * For now, we're using this as an indication
3691 * that we can't transmit; stop doing that only
3692 * if we figure out how to transmit in cooked
3695 handlep
->ifindex
= -1;
3699 * Select promiscuous mode on if "promisc" is set.
3701 * Do not turn allmulti mode on if we don't select
3702 * promiscuous mode - on some devices (e.g., Orinoco
3703 * wireless interfaces), allmulti mode isn't supported
3704 * and the driver implements it by turning promiscuous
3705 * mode on, and that screws up the operation of the
3706 * card as a normal networking interface, and on no
3707 * other platform I know of does starting a non-
3708 * promiscuous capture affect which multicast packets
3709 * are received by the interface.
3713 * Hmm, how can we set promiscuous mode on all interfaces?
3714 * I am not sure if that is possible at all. For now, we
3715 * silently ignore attempts to turn promiscuous mode on
3716 * for the "any" device (so you don't have to explicitly
3717 * disable it in programs such as tcpdump).
3720 if (!is_any_device
&& handle
->opt
.promisc
) {
3721 memset(&mr
, 0, sizeof(mr
));
3722 mr
.mr_ifindex
= handlep
->ifindex
;
3723 mr
.mr_type
= PACKET_MR_PROMISC
;
3724 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_ADD_MEMBERSHIP
,
3725 &mr
, sizeof(mr
)) == -1) {
3726 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
3727 PCAP_ERRBUF_SIZE
, errno
, "setsockopt (PACKET_ADD_MEMBERSHIP)");
3733 /* Enable auxillary data if supported and reserve room for
3734 * reconstructing VLAN headers. */
3735 #ifdef HAVE_PACKET_AUXDATA
3737 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_AUXDATA
, &val
,
3738 sizeof(val
)) == -1 && errno
!= ENOPROTOOPT
) {
3739 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3740 errno
, "setsockopt (PACKET_AUXDATA)");
3744 handle
->offset
+= VLAN_TAG_LEN
;
3745 #endif /* HAVE_PACKET_AUXDATA */
3748 * If we're in cooked mode, make the snapshot length
3749 * large enough to hold a "cooked mode" header plus
3750 * 1 byte of packet data (so we don't pass a byte
3751 * count of 0 to "recvfrom()").
3752 * XXX - we don't know whether this will be DLT_LINUX_SLL
3753 * or DLT_LINUX_SLL2, so make sure it's big enough for
3754 * a DLT_LINUX_SLL2 "cooked mode" header; a snapshot length
3755 * that small is silly anyway.
3757 if (handlep
->cooked
) {
3758 if (handle
->snapshot
< SLL2_HDR_LEN
+ 1)
3759 handle
->snapshot
= SLL2_HDR_LEN
+ 1;
3761 handle
->bufsize
= handle
->snapshot
;
3764 * Set the offset at which to insert VLAN tags.
3765 * That should be the offset of the type field.
3767 switch (handle
->linktype
) {
3771 * The type field is after the destination and source
3774 handlep
->vlan_offset
= 2 * ETH_ALEN
;
3779 * The type field is in the last 2 bytes of the
3780 * DLT_LINUX_SLL header.
3782 handlep
->vlan_offset
= SLL_HDR_LEN
- 2;
3786 handlep
->vlan_offset
= -1; /* unknown */
3790 #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
3791 if (handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
) {
3792 int nsec_tstamps
= 1;
3794 if (setsockopt(sock_fd
, SOL_SOCKET
, SO_TIMESTAMPNS
, &nsec_tstamps
, sizeof(nsec_tstamps
)) < 0) {
3795 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "setsockopt: unable to set SO_TIMESTAMPNS");
3800 #endif /* defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS) */
3803 * We've succeeded. Save the socket FD in the pcap structure.
3805 handle
->fd
= sock_fd
;
3807 #if defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT)
3809 * Can we generate special code for VLAN checks?
3810 * (XXX - what if we need the special code but it's not supported
3811 * by the OS? Is that possible?)
3813 if (getsockopt(sock_fd
, SOL_SOCKET
, SO_BPF_EXTENSIONS
,
3814 &bpf_extensions
, &len
) == 0) {
3815 if (bpf_extensions
>= SKF_AD_VLAN_TAG_PRESENT
) {
3817 * Yes, we can. Request that we do so.
3819 handle
->bpf_codegen_flags
|= BPF_SPECIAL_VLAN_HANDLING
;
3822 #endif /* defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT) */
3827 #ifdef HAVE_PACKET_RING
3829 * Attempt to activate with memory-mapped access.
3831 * On success, returns 1, and sets *status to 0 if there are no warnings
3832 * or to a PCAP_WARNING_ code if there is a warning.
3834 * On failure due to lack of support for memory-mapped capture, returns
3837 * On error, returns -1, and sets *status to the appropriate error code;
3838 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3841 activate_mmap(pcap_t
*handle
, int *status
)
3843 struct pcap_linux
*handlep
= handle
->priv
;
3847 * Attempt to allocate a buffer to hold the contents of one
3848 * packet, for use by the oneshot callback.
3850 handlep
->oneshot_buffer
= malloc(handle
->snapshot
);
3851 if (handlep
->oneshot_buffer
== NULL
) {
3852 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3853 errno
, "can't allocate oneshot buffer");
3854 *status
= PCAP_ERROR
;
3858 if (handle
->opt
.buffer_size
== 0) {
3859 /* by default request 2M for the ring buffer */
3860 handle
->opt
.buffer_size
= 2*1024*1024;
3862 ret
= prepare_tpacket_socket(handle
);
3864 free(handlep
->oneshot_buffer
);
3865 *status
= PCAP_ERROR
;
3868 ret
= create_ring(handle
, status
);
3871 * We don't support memory-mapped capture; our caller
3872 * will fall back on reading from the socket.
3874 free(handlep
->oneshot_buffer
);
3879 * Error attempting to enable memory-mapped capture;
3880 * fail. create_ring() has set *status.
3882 free(handlep
->oneshot_buffer
);
3887 * Success. *status has been set either to 0 if there are no
3888 * warnings or to a PCAP_WARNING_ value if there is a warning.
3890 * Override some defaults and inherit the other fields from
3892 * handle->offset is used to get the current position into the rx ring.
3893 * handle->cc is used to store the ring size.
3896 switch (handlep
->tp_version
) {
3898 handle
->read_op
= pcap_read_linux_mmap_v1
;
3901 handle
->read_op
= pcap_read_linux_mmap_v1_64
;
3903 #ifdef HAVE_TPACKET2
3905 handle
->read_op
= pcap_read_linux_mmap_v2
;
3908 #ifdef HAVE_TPACKET3
3910 handle
->read_op
= pcap_read_linux_mmap_v3
;
3914 handle
->cleanup_op
= pcap_cleanup_linux_mmap
;
3915 handle
->setfilter_op
= pcap_setfilter_linux_mmap
;
3916 handle
->setnonblock_op
= pcap_setnonblock_mmap
;
3917 handle
->getnonblock_op
= pcap_getnonblock_mmap
;
3918 handle
->oneshot_callback
= pcap_oneshot_mmap
;
3919 handle
->selectable_fd
= handle
->fd
;
3923 #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
3925 * Attempt to set the socket to the specified version of the memory-mapped
3928 * Return 0 if we succeed; return 1 if we fail because that version isn't
3929 * supported; return -1 on any other error, and set handle->errbuf.
3932 init_tpacket(pcap_t
*handle
, int version
, const char *version_str
)
3934 struct pcap_linux
*handlep
= handle
->priv
;
3936 socklen_t len
= sizeof(val
);
3939 * Probe whether kernel supports the specified TPACKET version;
3940 * this also gets the length of the header for that version.
3942 * This socket option was introduced in 2.6.27, which was
3943 * also the first release with TPACKET_V2 support.
3945 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_HDRLEN
, &val
, &len
) < 0) {
3946 if (errno
== ENOPROTOOPT
|| errno
== EINVAL
) {
3948 * ENOPROTOOPT means the kernel is too old to
3949 * support PACKET_HDRLEN at all, which means
3950 * it either doesn't support TPACKET at all
3951 * or supports only TPACKET_V1.
3956 /* Failed to even find out; this is a fatal error. */
3957 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3958 errno
, "can't get %s header len on packet socket",
3962 handlep
->tp_hdrlen
= val
;
3965 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_VERSION
, &val
,
3967 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3968 errno
, "can't activate %s on packet socket", version_str
);
3971 handlep
->tp_version
= version
;
3975 #endif /* defined HAVE_TPACKET2 || defined HAVE_TPACKET3 */
3978 * If the instruction set for which we're compiling has both 32-bit
3979 * and 64-bit versions, and Linux support for the 64-bit version
3980 * predates TPACKET_V2, define ISA_64_BIT as the .machine value
3981 * you get from uname() for the 64-bit version. Otherwise, leave
3982 * it undefined. (This includes ARM, which has a 64-bit version,
3983 * but Linux support for it appeared well after TPACKET_V2 support
3984 * did, so there should never be a case where 32-bit ARM code is
3985 * running o a 64-bit kernel that only supports TPACKET_V1.)
3987 * If we've omitted your favorite such architecture, please contribute
3988 * a patch. (No patch is needed for architectures that are 32-bit-only
3989 * or for which Linux has no support for 32-bit userland - or for which,
3990 * as noted, 64-bit support appeared in Linux after TPACKET_V2 support
3993 #if defined(__i386__)
3994 #define ISA_64_BIT "x86_64"
3995 #elif defined(__ppc__)
3996 #define ISA_64_BIT "ppc64"
3997 #elif defined(__sparc__)
3998 #define ISA_64_BIT "sparc64"
3999 #elif defined(__s390__)
4000 #define ISA_64_BIT "s390x"
4001 #elif defined(__mips__)
4002 #define ISA_64_BIT "mips64"
4003 #elif defined(__hppa__)
4004 #define ISA_64_BIT "parisc64"
4008 * Attempt to set the socket to version 3 of the memory-mapped header and,
4009 * if that fails because version 3 isn't supported, attempt to fall
4010 * back to version 2. If version 2 isn't supported, just leave it at
4013 * Return 1 if we succeed or if we fail because neither version 2 nor 3 is
4014 * supported; return -1 on any other error, and set handle->errbuf.
4017 prepare_tpacket_socket(pcap_t
*handle
)
4019 struct pcap_linux
*handlep
= handle
->priv
;
4020 #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
4024 #ifdef HAVE_TPACKET3
4026 * Try setting the version to TPACKET_V3.
4028 * The only mode in which buffering is done on PF_PACKET
4029 * sockets, so that packets might not be delivered
4030 * immediately, is TPACKET_V3 mode.
4032 * The buffering cannot be disabled in that mode, so
4033 * if the user has requested immediate mode, we don't
4036 if (!handle
->opt
.immediate
) {
4037 ret
= init_tpacket(handle
, TPACKET_V3
, "TPACKET_V3");
4046 * We failed for some reason other than "the
4047 * kernel doesn't support TPACKET_V3".
4052 #endif /* HAVE_TPACKET3 */
4054 #ifdef HAVE_TPACKET2
4056 * Try setting the version to TPACKET_V2.
4058 ret
= init_tpacket(handle
, TPACKET_V2
, "TPACKET_V2");
4067 * We failed for some reason other than "the
4068 * kernel doesn't support TPACKET_V2".
4072 #endif /* HAVE_TPACKET2 */
4075 * OK, we're using TPACKET_V1, as either that's all the kernel
4076 * supports or it doesn't support TPACKET at all. In the latter
4077 * case, create_ring() will fail, and we'll fall back on non-
4078 * memory-mapped capture.
4080 handlep
->tp_version
= TPACKET_V1
;
4081 handlep
->tp_hdrlen
= sizeof(struct tpacket_hdr
);
4085 * 32-bit userspace + 64-bit kernel + TPACKET_V1 are not compatible with
4086 * each other due to platform-dependent data type size differences.
4088 * If we have a 32-bit userland and a 64-bit kernel, use an
4089 * internally-defined TPACKET_V1_64, with which we use a 64-bit
4090 * version of the data structures.
4092 if (sizeof(long) == 4) {
4094 * This is 32-bit code.
4096 struct utsname utsname
;
4098 if (uname(&utsname
) == -1) {
4102 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
4103 PCAP_ERRBUF_SIZE
, errno
, "uname failed");
4106 if (strcmp(utsname
.machine
, ISA_64_BIT
) == 0) {
4108 * uname() tells us the machine is 64-bit,
4109 * so we presumably have a 64-bit kernel.
4111 * XXX - this presumes that uname() won't lie
4112 * in 32-bit code and claim that the machine
4113 * has the 32-bit version of the ISA.
4115 handlep
->tp_version
= TPACKET_V1_64
;
4116 handlep
->tp_hdrlen
= sizeof(struct tpacket_hdr_64
);
4124 #define MAX(a,b) ((a)>(b)?(a):(b))
4127 * Attempt to set up memory-mapped access.
4129 * On success, returns 1, and sets *status to 0 if there are no warnings
4130 * or to a PCAP_WARNING_ code if there is a warning.
4132 * On failure due to lack of support for memory-mapped capture, returns
4135 * On error, returns -1, and sets *status to the appropriate error code;
4136 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
4139 create_ring(pcap_t
*handle
, int *status
)
4141 struct pcap_linux
*handlep
= handle
->priv
;
4142 unsigned i
, j
, frames_per_block
;
4143 #ifdef HAVE_TPACKET3
4145 * For sockets using TPACKET_V1 or TPACKET_V2, the extra
4146 * stuff at the end of a struct tpacket_req3 will be
4147 * ignored, so this is OK even for those sockets.
4149 struct tpacket_req3 req
;
4151 struct tpacket_req req
;
4154 unsigned int sk_type
, tp_reserve
, maclen
, tp_hdrlen
, netoff
, macoff
;
4155 unsigned int frame_size
;
4158 * Start out assuming no warnings or errors.
4162 #ifdef TPACKET_RESERVE
4164 * TPACKET_V2 and PACKET_RESERVE were both introduced in
4165 * 2.6.27. If tp_version is for TPACKET_V1, that means
4166 * the kernel doesn't support TPACKET_V2, so it won't
4167 * support PACKET_RESERVE, either.
4169 if (handle
->tp_version
!= TPACKET_V1
&&
4170 handle
->tp_version
!= TPACKET_V1_64
) {
4172 * Reserve space for VLAN tag reconstruction.
4174 tp_reserve
= VLAN_TAG_LEN
;
4177 * If we're using DLT_LINUX_SLL2, reserve space for a
4178 * DLT_LINUX_SLL2 header.
4180 * XXX - we assume that the kernel is still adding
4181 * 16 bytes of extra space; that happens to
4182 * correspond to SLL_HDR_LEN (whether intentionally
4183 * or not - the kernel code has a raw "16" in
4184 * the expression), so we subtract SLL_HDR_LEN
4185 * from SLL2_HDR_LEN to get the additional space
4186 * needed. That also means we don't bother reserving
4187 * any additional space if we're using DLT_LINUX_SLL.
4189 * XXX - should we use TPACKET_ALIGN(SLL2_HDR_LEN - SLL_HDR_LEN)?
4191 if (handle
->linktype
== DLT_LINUX_SLL2
)
4192 tp_reserve
+= SLL2_HDR_LEN
- SLL_HDR_LEN
;
4195 * Try to request that amount of reserve space.
4196 * This must be done before creating the ring buffer.
4197 * If PACKET_RESERVE is supported, creating the ring
4198 * buffer should be, although if creating the ring
4199 * buffer fails, the PACKET_RESERVE call has no effect,
4200 * so falling back on read-from-the-socket capturing
4201 * won't be affected.
4203 len
= sizeof(tp_reserve
);
4204 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
,
4205 &tp_reserve
, len
) < 0) {
4207 * We treat ENOPROTOOPT as an error, as we
4208 * already determined that we support
4209 * TPACKET_V2 and later; see above.
4211 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
4212 PCAP_ERRBUF_SIZE
, errno
,
4213 "setsockopt (PACKET_RESERVE)");
4214 *status
= PCAP_ERROR
;
4219 * Older kernel, so we can't use PACKET_RESERVE;
4220 * this means we can't reserver extra space
4221 * for a DLT_LINUX_SLL2 header.
4223 * Those kernels don't supply the information
4224 * necessary to reconstruct the VLAN tag, so
4225 * that's not an issue here, and we don't allow
4226 * DLT_LINUX_SLL2 if we can't use PACKET_RESERVE,
4227 * so that shouldn't be an issue.
4229 tp_reserve
= 0; /* nothing reserved */
4233 * Build environment for an older kernel, so we can't use
4236 * Those kernels don't supply the information necessary
4237 * to reconstruct the VLAN tag, so that's not an issue
4238 * here, and we don't allow DLT_LINUX_SLL2 if we can't
4239 * use PACKET_RESERVE, so that shouldn't be an issue.
4241 tp_reserve
= 0; /* nothing reserved */
4244 switch (handlep
->tp_version
) {
4248 #ifdef HAVE_TPACKET2
4251 /* Note that with large snapshot length (say 256K, which is
4252 * the default for recent versions of tcpdump, Wireshark,
4253 * TShark, dumpcap or 64K, the value that "-s 0" has given for
4254 * a long time with tcpdump), if we use the snapshot
4255 * length to calculate the frame length, only a few frames
4256 * will be available in the ring even with pretty
4257 * large ring size (and a lot of memory will be unused).
4259 * Ideally, we should choose a frame length based on the
4260 * minimum of the specified snapshot length and the maximum
4261 * packet size. That's not as easy as it sounds; consider,
4262 * for example, an 802.11 interface in monitor mode, where
4263 * the frame would include a radiotap header, where the
4264 * maximum radiotap header length is device-dependent.
4266 * So, for now, we just do this for Ethernet devices, where
4267 * there's no metadata header, and the link-layer header is
4268 * fixed length. We can get the maximum packet size by
4269 * adding 18, the Ethernet header length plus the CRC length
4270 * (just in case we happen to get the CRC in the packet), to
4271 * the MTU of the interface; we fetch the MTU in the hopes
4272 * that it reflects support for jumbo frames. (Even if the
4273 * interface is just being used for passive snooping, the
4274 * driver might set the size of buffers in the receive ring
4275 * based on the MTU, so that the MTU limits the maximum size
4276 * of packets that we can receive.)
4278 * If segmentation/fragmentation or receive offload are
4279 * enabled, we can get reassembled/aggregated packets larger
4280 * than MTU, but bounded to 65535 plus the Ethernet overhead,
4281 * due to kernel and protocol constraints */
4282 frame_size
= handle
->snapshot
;
4283 if (handle
->linktype
== DLT_EN10MB
) {
4284 unsigned int max_frame_len
;
4288 mtu
= iface_get_mtu(handle
->fd
, handle
->opt
.device
,
4291 *status
= PCAP_ERROR
;
4294 offload
= iface_get_offload(handle
);
4295 if (offload
== -1) {
4296 *status
= PCAP_ERROR
;
4300 max_frame_len
= MAX(mtu
, 65535);
4302 max_frame_len
= mtu
;
4303 max_frame_len
+= 18;
4305 if (frame_size
> max_frame_len
)
4306 frame_size
= max_frame_len
;
4309 /* NOTE: calculus matching those in tpacket_rcv()
4310 * in linux-2.6/net/packet/af_packet.c
4312 len
= sizeof(sk_type
);
4313 if (getsockopt(handle
->fd
, SOL_SOCKET
, SO_TYPE
, &sk_type
,
4315 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
4316 PCAP_ERRBUF_SIZE
, errno
, "getsockopt (SO_TYPE)");
4317 *status
= PCAP_ERROR
;
4320 maclen
= (sk_type
== SOCK_DGRAM
) ? 0 : MAX_LINKHEADER_SIZE
;
4321 /* XXX: in the kernel maclen is calculated from
4322 * LL_ALLOCATED_SPACE(dev) and vnet_hdr.hdr_len
4323 * in: packet_snd() in linux-2.6/net/packet/af_packet.c
4324 * then packet_alloc_skb() in linux-2.6/net/packet/af_packet.c
4325 * then sock_alloc_send_pskb() in linux-2.6/net/core/sock.c
4326 * but I see no way to get those sizes in userspace,
4327 * like for instance with an ifreq ioctl();
4328 * the best thing I've found so far is MAX_HEADER in
4329 * the kernel part of linux-2.6/include/linux/netdevice.h
4330 * which goes up to 128+48=176; since pcap-linux.c
4331 * defines a MAX_LINKHEADER_SIZE of 256 which is
4332 * greater than that, let's use it.. maybe is it even
4333 * large enough to directly replace macoff..
4335 tp_hdrlen
= TPACKET_ALIGN(handlep
->tp_hdrlen
) + sizeof(struct sockaddr_ll
) ;
4336 netoff
= TPACKET_ALIGN(tp_hdrlen
+ (maclen
< 16 ? 16 : maclen
)) + tp_reserve
;
4337 /* NOTE: AFAICS tp_reserve may break the TPACKET_ALIGN
4338 * of netoff, which contradicts
4339 * linux-2.6/Documentation/networking/packet_mmap.txt
4341 * "- Gap, chosen so that packet data (Start+tp_net)
4342 * aligns to TPACKET_ALIGNMENT=16"
4344 /* NOTE: in linux-2.6/include/linux/skbuff.h:
4345 * "CPUs often take a performance hit
4346 * when accessing unaligned memory locations"
4348 macoff
= netoff
- maclen
;
4349 req
.tp_frame_size
= TPACKET_ALIGN(macoff
+ frame_size
);
4351 * Round the buffer size up to a multiple of the
4352 * frame size (rather than rounding down, which
4353 * would give a buffer smaller than our caller asked
4354 * for, and possibly give zero frames if the requested
4355 * buffer size is too small for one frame).
4357 req
.tp_frame_nr
= (handle
->opt
.buffer_size
+ req
.tp_frame_size
- 1)/req
.tp_frame_size
;
4360 #ifdef HAVE_TPACKET3
4362 /* The "frames" for this are actually buffers that
4363 * contain multiple variable-sized frames.
4365 * We pick a "frame" size of MAXIMUM_SNAPLEN to leave
4366 * enough room for at least one reasonably-sized packet
4367 * in the "frame". */
4368 req
.tp_frame_size
= MAXIMUM_SNAPLEN
;
4370 * Round the buffer size up to a multiple of the
4371 * "frame" size (rather than rounding down, which
4372 * would give a buffer smaller than our caller asked
4373 * for, and possibly give zero "frames" if the requested
4374 * buffer size is too small for one "frame").
4376 req
.tp_frame_nr
= (handle
->opt
.buffer_size
+ req
.tp_frame_size
- 1)/req
.tp_frame_size
;
4380 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4381 "Internal error: unknown TPACKET_ value %u",
4382 handlep
->tp_version
);
4383 *status
= PCAP_ERROR
;
4387 /* compute the minumum block size that will handle this frame.
4388 * The block has to be page size aligned.
4389 * The max block size allowed by the kernel is arch-dependent and
4390 * it's not explicitly checked here. */
4391 req
.tp_block_size
= getpagesize();
4392 while (req
.tp_block_size
< req
.tp_frame_size
)
4393 req
.tp_block_size
<<= 1;
4395 frames_per_block
= req
.tp_block_size
/req
.tp_frame_size
;
4398 * PACKET_TIMESTAMP was added after linux/net_tstamp.h was,
4399 * so we check for PACKET_TIMESTAMP. We check for
4400 * linux/net_tstamp.h just in case a system somehow has
4401 * PACKET_TIMESTAMP but not linux/net_tstamp.h; that might
4404 * SIOCSHWTSTAMP was introduced in the patch that introduced
4405 * linux/net_tstamp.h, so we don't bother checking whether
4406 * SIOCSHWTSTAMP is defined (if your Linux system has
4407 * linux/net_tstamp.h but doesn't define SIOCSHWTSTAMP, your
4408 * Linux system is badly broken).
4410 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
4412 * If we were told to do so, ask the kernel and the driver
4413 * to use hardware timestamps.
4415 * Hardware timestamps are only supported with mmapped
4418 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
||
4419 handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER_UNSYNCED
) {
4420 struct hwtstamp_config hwconfig
;
4425 * Ask for hardware time stamps on all packets,
4426 * including transmitted packets.
4428 memset(&hwconfig
, 0, sizeof(hwconfig
));
4429 hwconfig
.tx_type
= HWTSTAMP_TX_ON
;
4430 hwconfig
.rx_filter
= HWTSTAMP_FILTER_ALL
;
4432 memset(&ifr
, 0, sizeof(ifr
));
4433 pcap_strlcpy(ifr
.ifr_name
, handle
->opt
.device
, sizeof(ifr
.ifr_name
));
4434 ifr
.ifr_data
= (void *)&hwconfig
;
4436 if (ioctl(handle
->fd
, SIOCSHWTSTAMP
, &ifr
) < 0) {
4441 * Treat this as an error, as the
4442 * user should try to run this
4443 * with the appropriate privileges -
4444 * and, if they can't, shouldn't
4445 * try requesting hardware time stamps.
4447 *status
= PCAP_ERROR_PERM_DENIED
;
4453 * Treat this as a warning, as the
4454 * only way to fix the warning is to
4455 * get an adapter that supports hardware
4456 * time stamps for *all* packets.
4457 * (ERANGE means "we support hardware
4458 * time stamps, but for packets matching
4459 * that particular filter", so it means
4460 * "we don't support hardware time stamps
4461 * for all incoming packets" here.)
4463 * We'll just fall back on the standard
4466 *status
= PCAP_WARNING_TSTAMP_TYPE_NOTSUP
;
4470 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
4471 PCAP_ERRBUF_SIZE
, errno
,
4472 "SIOCSHWTSTAMP failed");
4473 *status
= PCAP_ERROR
;
4478 * Well, that worked. Now specify the type of
4479 * hardware time stamp we want for this
4482 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
) {
4484 * Hardware timestamp, synchronized
4485 * with the system clock.
4487 timesource
= SOF_TIMESTAMPING_SYS_HARDWARE
;
4490 * PCAP_TSTAMP_ADAPTER_UNSYNCED - hardware
4491 * timestamp, not synchronized with the
4494 timesource
= SOF_TIMESTAMPING_RAW_HARDWARE
;
4496 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_TIMESTAMP
,
4497 (void *)×ource
, sizeof(timesource
))) {
4498 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
4499 PCAP_ERRBUF_SIZE
, errno
,
4500 "can't set PACKET_TIMESTAMP");
4501 *status
= PCAP_ERROR
;
4506 #endif /* HAVE_LINUX_NET_TSTAMP_H && PACKET_TIMESTAMP */
4508 /* ask the kernel to create the ring */
4510 req
.tp_block_nr
= req
.tp_frame_nr
/ frames_per_block
;
4512 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
4513 req
.tp_frame_nr
= req
.tp_block_nr
* frames_per_block
;
4515 #ifdef HAVE_TPACKET3
4516 /* timeout value to retire block - use the configured buffering timeout, or default if <0. */
4517 if (handlep
->timeout
> 0) {
4518 /* Use the user specified timeout as the block timeout */
4519 req
.tp_retire_blk_tov
= handlep
->timeout
;
4520 } else if (handlep
->timeout
== 0) {
4522 * In pcap, this means "infinite timeout"; TPACKET_V3
4523 * doesn't support that, so just set it to UINT_MAX
4524 * milliseconds. In the TPACKET_V3 loop, if the
4525 * timeout is 0, and we haven't yet seen any packets,
4526 * and we block and still don't have any packets, we
4527 * keep blocking until we do.
4529 req
.tp_retire_blk_tov
= UINT_MAX
;
4532 * XXX - this is not valid; use 0, meaning "have the
4533 * kernel pick a default", for now.
4535 req
.tp_retire_blk_tov
= 0;
4537 /* private data not used */
4538 req
.tp_sizeof_priv
= 0;
4539 /* Rx ring - feature request bits - none (rxhash will not be filled) */
4540 req
.tp_feature_req_word
= 0;
4543 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
4544 (void *) &req
, sizeof(req
))) {
4545 if ((errno
== ENOMEM
) && (req
.tp_block_nr
> 1)) {
4547 * Memory failure; try to reduce the requested ring
4550 * We used to reduce this by half -- do 5% instead.
4551 * That may result in more iterations and a longer
4552 * startup, but the user will be much happier with
4553 * the resulting buffer size.
4555 if (req
.tp_frame_nr
< 20)
4556 req
.tp_frame_nr
-= 1;
4558 req
.tp_frame_nr
-= req
.tp_frame_nr
/20;
4561 if (errno
== ENOPROTOOPT
) {
4563 * We don't have ring buffer support in this kernel.
4567 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4568 errno
, "can't create rx ring on packet socket");
4569 *status
= PCAP_ERROR
;
4573 /* memory map the rx ring */
4574 handlep
->mmapbuflen
= req
.tp_block_nr
* req
.tp_block_size
;
4575 handlep
->mmapbuf
= mmap(0, handlep
->mmapbuflen
,
4576 PROT_READ
|PROT_WRITE
, MAP_SHARED
, handle
->fd
, 0);
4577 if (handlep
->mmapbuf
== MAP_FAILED
) {
4578 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4579 errno
, "can't mmap rx ring");
4581 /* clear the allocated ring on error*/
4582 destroy_ring(handle
);
4583 *status
= PCAP_ERROR
;
4587 /* allocate a ring for each frame header pointer*/
4588 handle
->cc
= req
.tp_frame_nr
;
4589 handle
->buffer
= malloc(handle
->cc
* sizeof(union thdr
*));
4590 if (!handle
->buffer
) {
4591 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4592 errno
, "can't allocate ring of frame headers");
4594 destroy_ring(handle
);
4595 *status
= PCAP_ERROR
;
4599 /* fill the header ring with proper frame ptr*/
4601 for (i
=0; i
<req
.tp_block_nr
; ++i
) {
4602 u_char
*base
= &handlep
->mmapbuf
[i
*req
.tp_block_size
];
4603 for (j
=0; j
<frames_per_block
; ++j
, ++handle
->offset
) {
4604 RING_GET_CURRENT_FRAME(handle
) = base
;
4605 base
+= req
.tp_frame_size
;
4609 handle
->bufsize
= req
.tp_frame_size
;
4614 /* free all ring related resources*/
4616 destroy_ring(pcap_t
*handle
)
4618 struct pcap_linux
*handlep
= handle
->priv
;
4620 /* tell the kernel to destroy the ring*/
4621 struct tpacket_req req
;
4622 memset(&req
, 0, sizeof(req
));
4623 /* do not test for setsockopt failure, as we can't recover from any error */
4624 (void)setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
4625 (void *) &req
, sizeof(req
));
4627 /* if ring is mapped, unmap it*/
4628 if (handlep
->mmapbuf
) {
4629 /* do not test for mmap failure, as we can't recover from any error */
4630 (void)munmap(handlep
->mmapbuf
, handlep
->mmapbuflen
);
4631 handlep
->mmapbuf
= NULL
;
4636 * Special one-shot callback, used for pcap_next() and pcap_next_ex(),
4637 * for Linux mmapped capture.
4639 * The problem is that pcap_next() and pcap_next_ex() expect the packet
4640 * data handed to the callback to be valid after the callback returns,
4641 * but pcap_read_linux_mmap() has to release that packet as soon as
4642 * the callback returns (otherwise, the kernel thinks there's still
4643 * at least one unprocessed packet available in the ring, so a select()
4644 * will immediately return indicating that there's data to process), so,
4645 * in the callback, we have to make a copy of the packet.
4647 * Yes, this means that, if the capture is using the ring buffer, using
4648 * pcap_next() or pcap_next_ex() requires more copies than using
4649 * pcap_loop() or pcap_dispatch(). If that bothers you, don't use
4650 * pcap_next() or pcap_next_ex().
4653 pcap_oneshot_mmap(u_char
*user
, const struct pcap_pkthdr
*h
,
4654 const u_char
*bytes
)
4656 struct oneshot_userdata
*sp
= (struct oneshot_userdata
*)user
;
4657 pcap_t
*handle
= sp
->pd
;
4658 struct pcap_linux
*handlep
= handle
->priv
;
4661 memcpy(handlep
->oneshot_buffer
, bytes
, h
->caplen
);
4662 *sp
->pkt
= handlep
->oneshot_buffer
;
4666 pcap_cleanup_linux_mmap( pcap_t
*handle
)
4668 struct pcap_linux
*handlep
= handle
->priv
;
4670 destroy_ring(handle
);
4671 if (handlep
->oneshot_buffer
!= NULL
) {
4672 free(handlep
->oneshot_buffer
);
4673 handlep
->oneshot_buffer
= NULL
;
4675 pcap_cleanup_linux(handle
);
4680 pcap_getnonblock_mmap(pcap_t
*handle
)
4682 struct pcap_linux
*handlep
= handle
->priv
;
4684 /* use negative value of timeout to indicate non blocking ops */
4685 return (handlep
->timeout
<0);
4689 pcap_setnonblock_mmap(pcap_t
*handle
, int nonblock
)
4691 struct pcap_linux
*handlep
= handle
->priv
;
4694 * Set the file descriptor to non-blocking mode, as we use
4695 * it for sending packets.
4697 if (pcap_setnonblock_fd(handle
, nonblock
) == -1)
4701 * Map each value to their corresponding negation to
4702 * preserve the timeout value provided with pcap_set_timeout.
4705 if (handlep
->timeout
>= 0) {
4707 * Indicate that we're switching to
4708 * non-blocking mode.
4710 handlep
->timeout
= ~handlep
->timeout
;
4713 if (handlep
->timeout
< 0) {
4714 handlep
->timeout
= ~handlep
->timeout
;
4717 /* Update the timeout to use in poll(). */
4718 set_poll_timeout(handlep
);
4723 * Get the status field of the ring buffer frame at a specified offset.
4726 pcap_get_ring_frame_status(pcap_t
*handle
, int offset
)
4728 struct pcap_linux
*handlep
= handle
->priv
;
4731 h
.raw
= RING_GET_FRAME_AT(handle
, offset
);
4732 switch (handlep
->tp_version
) {
4735 * This is an unsigned long, but only the lower 32
4738 return (u_int
)(h
.h1
->tp_status
);
4742 * This is an unsigned long in the kernel, which is 64-bit,
4743 * but only the lower 32 bits are used.
4745 return (u_int
)(h
.h1_64
->tp_status
);
4747 #ifdef HAVE_TPACKET2
4749 return (h
.h2
->tp_status
);
4752 #ifdef HAVE_TPACKET3
4754 return (h
.h3
->hdr
.bh1
.block_status
);
4758 /* This should not happen. */
4767 * Block waiting for frames to be available.
4769 static int pcap_wait_for_frames_mmap(pcap_t
*handle
)
4771 struct pcap_linux
*handlep
= handle
->priv
;
4774 #ifdef HAVE_SYS_EVENTFD_H
4775 struct pollfd pollinfo
[2];
4776 pollinfo
[1].fd
= handlep
->poll_breakloop_fd
;
4777 pollinfo
[1].events
= POLLIN
;
4779 struct pollfd pollinfo
[1];
4781 pollinfo
[0].fd
= handle
->fd
;
4782 pollinfo
[0].events
= POLLIN
;
4786 * Yes, we do this even in non-blocking mode, as it's
4787 * the only way to get error indications from a
4790 * The timeout is 0 in non-blocking mode, so poll()
4791 * returns immediately.
4794 #ifdef HAVE_SYS_EVENTFD_H
4795 ret
= poll(pollinfo
, 2, handlep
->poll_timeout
);
4797 ret
= poll(pollinfo
, 1, handlep
->poll_timeout
);
4799 if (ret
< 0 && errno
!= EINTR
) {
4800 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
4801 PCAP_ERRBUF_SIZE
, errno
,
4802 "can't poll on packet socket");
4804 } else if (ret
> 0 && pollinfo
[0].revents
&&
4805 (pollinfo
[0].revents
& (POLLHUP
|POLLRDHUP
|POLLERR
|POLLNVAL
))) {
4807 * There's some indication other than
4808 * "you can read on this descriptor" on
4811 if (pollinfo
[0].revents
& (POLLHUP
| POLLRDHUP
)) {
4812 snprintf(handle
->errbuf
,
4814 "Hangup on packet socket");
4817 if (pollinfo
[0].revents
& POLLERR
) {
4819 * A recv() will give us the actual error code.
4821 * XXX - make the socket non-blocking?
4823 if (recv(handle
->fd
, &c
, sizeof c
,
4825 continue; /* what, no error? */
4826 if (errno
== ENETDOWN
) {
4828 * The device on which we're
4829 * capturing went away.
4831 * XXX - we should really return
4832 * PCAP_ERROR_IFACE_NOT_UP, but
4833 * pcap_dispatch() etc. aren't
4834 * defined to return that.
4836 snprintf(handle
->errbuf
,
4838 "The interface went down");
4840 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
4841 PCAP_ERRBUF_SIZE
, errno
,
4842 "Error condition on packet socket");
4846 if (pollinfo
[0].revents
& POLLNVAL
) {
4847 snprintf(handle
->errbuf
,
4849 "Invalid polling request on packet socket");
4854 #ifdef HAVE_SYS_EVENTFD_H
4855 if (pollinfo
[1].revents
& POLLIN
) {
4857 (void)read(handlep
->poll_breakloop_fd
, &value
, sizeof(value
));
4861 /* check for break loop condition on interrupted syscall*/
4862 if (handle
->break_loop
) {
4863 handle
->break_loop
= 0;
4864 return PCAP_ERROR_BREAK
;
4870 /* handle a single memory mapped packet */
4871 static int pcap_handle_packet_mmap(
4873 pcap_handler callback
,
4875 unsigned char *frame
,
4876 unsigned int tp_len
,
4877 unsigned int tp_mac
,
4878 unsigned int tp_snaplen
,
4879 unsigned int tp_sec
,
4880 unsigned int tp_usec
,
4881 int tp_vlan_tci_valid
,
4885 struct pcap_linux
*handlep
= handle
->priv
;
4887 struct sockaddr_ll
*sll
;
4888 struct pcap_pkthdr pcaphdr
;
4889 unsigned int snaplen
= tp_snaplen
;
4890 struct utsname utsname
;
4892 /* perform sanity check on internal offset. */
4893 if (tp_mac
+ tp_snaplen
> handle
->bufsize
) {
4895 * Report some system information as a debugging aid.
4897 if (uname(&utsname
) != -1) {
4898 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4899 "corrupted frame on kernel ring mac "
4900 "offset %u + caplen %u > frame len %d "
4901 "(kernel %.32s version %s, machine %.16s)",
4902 tp_mac
, tp_snaplen
, handle
->bufsize
,
4903 utsname
.release
, utsname
.version
,
4906 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4907 "corrupted frame on kernel ring mac "
4908 "offset %u + caplen %u > frame len %d",
4909 tp_mac
, tp_snaplen
, handle
->bufsize
);
4914 /* run filter on received packet
4915 * If the kernel filtering is enabled we need to run the
4916 * filter until all the frames present into the ring
4917 * at filter creation time are processed.
4918 * In this case, blocks_to_filter_in_userland is used
4919 * as a counter for the packet we need to filter.
4920 * Note: alternatively it could be possible to stop applying
4921 * the filter when the ring became empty, but it can possibly
4922 * happen a lot later... */
4923 bp
= frame
+ tp_mac
;
4925 /* if required build in place the sll header*/
4926 sll
= (void *)(frame
+ TPACKET_ALIGN(handlep
->tp_hdrlen
));
4927 if (handlep
->cooked
) {
4928 if (handle
->linktype
== DLT_LINUX_SLL2
) {
4929 struct sll2_header
*hdrp
;
4932 * The kernel should have left us with enough
4933 * space for an sll header; back up the packet
4934 * data pointer into that space, as that'll be
4935 * the beginning of the packet we pass to the
4941 * Let's make sure that's past the end of
4942 * the tpacket header, i.e. >=
4943 * ((u_char *)thdr + TPACKET_HDRLEN), so we
4944 * don't step on the header when we construct
4947 if (bp
< (u_char
*)frame
+
4948 TPACKET_ALIGN(handlep
->tp_hdrlen
) +
4949 sizeof(struct sockaddr_ll
)) {
4950 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4951 "cooked-mode frame doesn't have room for sll header");
4956 * OK, that worked; construct the sll header.
4958 hdrp
= (struct sll2_header
*)bp
;
4959 hdrp
->sll2_protocol
= sll
->sll_protocol
;
4960 hdrp
->sll2_reserved_mbz
= 0;
4961 hdrp
->sll2_if_index
= htonl(sll
->sll_ifindex
);
4962 hdrp
->sll2_hatype
= htons(sll
->sll_hatype
);
4963 hdrp
->sll2_pkttype
= sll
->sll_pkttype
;
4964 hdrp
->sll2_halen
= sll
->sll_halen
;
4965 memcpy(hdrp
->sll2_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
4967 snaplen
+= sizeof(struct sll2_header
);
4969 struct sll_header
*hdrp
;
4972 * The kernel should have left us with enough
4973 * space for an sll header; back up the packet
4974 * data pointer into that space, as that'll be
4975 * the beginning of the packet we pass to the
4981 * Let's make sure that's past the end of
4982 * the tpacket header, i.e. >=
4983 * ((u_char *)thdr + TPACKET_HDRLEN), so we
4984 * don't step on the header when we construct
4987 if (bp
< (u_char
*)frame
+
4988 TPACKET_ALIGN(handlep
->tp_hdrlen
) +
4989 sizeof(struct sockaddr_ll
)) {
4990 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4991 "cooked-mode frame doesn't have room for sll header");
4996 * OK, that worked; construct the sll header.
4998 hdrp
= (struct sll_header
*)bp
;
4999 hdrp
->sll_pkttype
= htons(sll
->sll_pkttype
);
5000 hdrp
->sll_hatype
= htons(sll
->sll_hatype
);
5001 hdrp
->sll_halen
= htons(sll
->sll_halen
);
5002 memcpy(hdrp
->sll_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
5003 hdrp
->sll_protocol
= sll
->sll_protocol
;
5005 snaplen
+= sizeof(struct sll_header
);
5009 if (handlep
->filter_in_userland
&& handle
->fcode
.bf_insns
) {
5010 struct bpf_aux_data aux_data
;
5012 aux_data
.vlan_tag_present
= tp_vlan_tci_valid
;
5013 aux_data
.vlan_tag
= tp_vlan_tci
& 0x0fff;
5015 if (pcap_filter_with_aux_data(handle
->fcode
.bf_insns
,
5023 if (!linux_check_direction(handle
, sll
))
5026 /* get required packet info from ring header */
5027 pcaphdr
.ts
.tv_sec
= tp_sec
;
5028 pcaphdr
.ts
.tv_usec
= tp_usec
;
5029 pcaphdr
.caplen
= tp_snaplen
;
5030 pcaphdr
.len
= tp_len
;
5032 /* if required build in place the sll header*/
5033 if (handlep
->cooked
) {
5034 /* update packet len */
5035 if (handle
->linktype
== DLT_LINUX_SLL2
) {
5036 pcaphdr
.caplen
+= SLL2_HDR_LEN
;
5037 pcaphdr
.len
+= SLL2_HDR_LEN
;
5039 pcaphdr
.caplen
+= SLL_HDR_LEN
;
5040 pcaphdr
.len
+= SLL_HDR_LEN
;
5044 #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
5045 if (tp_vlan_tci_valid
&&
5046 handlep
->vlan_offset
!= -1 &&
5047 tp_snaplen
>= (unsigned int) handlep
->vlan_offset
)
5049 struct vlan_tag
*tag
;
5052 * Move everything in the header, except the type field,
5053 * down VLAN_TAG_LEN bytes, to allow us to insert the
5054 * VLAN tag between that stuff and the type field.
5057 memmove(bp
, bp
+ VLAN_TAG_LEN
, handlep
->vlan_offset
);
5060 * Now insert the tag.
5062 tag
= (struct vlan_tag
*)(bp
+ handlep
->vlan_offset
);
5063 tag
->vlan_tpid
= htons(tp_vlan_tpid
);
5064 tag
->vlan_tci
= htons(tp_vlan_tci
);
5067 * Add the tag to the packet lengths.
5069 pcaphdr
.caplen
+= VLAN_TAG_LEN
;
5070 pcaphdr
.len
+= VLAN_TAG_LEN
;
5075 * The only way to tell the kernel to cut off the
5076 * packet at a snapshot length is with a filter program;
5077 * if there's no filter program, the kernel won't cut
5080 * Trim the snapshot length to be no longer than the
5081 * specified snapshot length.
5083 if (pcaphdr
.caplen
> (bpf_u_int32
)handle
->snapshot
)
5084 pcaphdr
.caplen
= handle
->snapshot
;
5086 /* pass the packet to the user */
5087 callback(user
, &pcaphdr
, bp
);
5093 pcap_read_linux_mmap_v1(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
5096 struct pcap_linux
*handlep
= handle
->priv
;
5101 /* wait for frames availability.*/
5102 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
5103 if (h
.h1
->tp_status
== TP_STATUS_KERNEL
) {
5105 * The current frame is owned by the kernel; wait for
5106 * a frame to be handed to us.
5108 ret
= pcap_wait_for_frames_mmap(handle
);
5114 /* non-positive values of max_packets are used to require all
5115 * packets currently available in the ring */
5116 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
5118 * Get the current ring buffer frame, and break if
5119 * it's still owned by the kernel.
5121 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
5122 if (h
.h1
->tp_status
== TP_STATUS_KERNEL
)
5125 ret
= pcap_handle_packet_mmap(
5140 handlep
->packets_read
++;
5141 } else if (ret
< 0) {
5146 * Hand this block back to the kernel, and, if we're
5147 * counting blocks that need to be filtered in userland
5148 * after having been filtered by the kernel, count
5149 * the one we've just processed.
5151 h
.h1
->tp_status
= TP_STATUS_KERNEL
;
5152 if (handlep
->blocks_to_filter_in_userland
> 0) {
5153 handlep
->blocks_to_filter_in_userland
--;
5154 if (handlep
->blocks_to_filter_in_userland
== 0) {
5156 * No more blocks need to be filtered
5159 handlep
->filter_in_userland
= 0;
5164 if (++handle
->offset
>= handle
->cc
)
5167 /* check for break loop condition*/
5168 if (handle
->break_loop
) {
5169 handle
->break_loop
= 0;
5170 return PCAP_ERROR_BREAK
;
5177 pcap_read_linux_mmap_v1_64(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
5180 struct pcap_linux
*handlep
= handle
->priv
;
5185 /* wait for frames availability.*/
5186 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
5187 if (h
.h1_64
->tp_status
== TP_STATUS_KERNEL
) {
5189 * The current frame is owned by the kernel; wait for
5190 * a frame to be handed to us.
5192 ret
= pcap_wait_for_frames_mmap(handle
);
5198 /* non-positive values of max_packets are used to require all
5199 * packets currently available in the ring */
5200 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
5202 * Get the current ring buffer frame, and break if
5203 * it's still owned by the kernel.
5205 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
5206 if (h
.h1_64
->tp_status
== TP_STATUS_KERNEL
)
5209 ret
= pcap_handle_packet_mmap(
5216 h
.h1_64
->tp_snaplen
,
5224 handlep
->packets_read
++;
5225 } else if (ret
< 0) {
5230 * Hand this block back to the kernel, and, if we're
5231 * counting blocks that need to be filtered in userland
5232 * after having been filtered by the kernel, count
5233 * the one we've just processed.
5235 h
.h1_64
->tp_status
= TP_STATUS_KERNEL
;
5236 if (handlep
->blocks_to_filter_in_userland
> 0) {
5237 handlep
->blocks_to_filter_in_userland
--;
5238 if (handlep
->blocks_to_filter_in_userland
== 0) {
5240 * No more blocks need to be filtered
5243 handlep
->filter_in_userland
= 0;
5248 if (++handle
->offset
>= handle
->cc
)
5251 /* check for break loop condition*/
5252 if (handle
->break_loop
) {
5253 handle
->break_loop
= 0;
5254 return PCAP_ERROR_BREAK
;
5260 #ifdef HAVE_TPACKET2
5262 pcap_read_linux_mmap_v2(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
5265 struct pcap_linux
*handlep
= handle
->priv
;
5270 /* wait for frames availability.*/
5271 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
5272 if (h
.h2
->tp_status
== TP_STATUS_KERNEL
) {
5274 * The current frame is owned by the kernel; wait for
5275 * a frame to be handed to us.
5277 ret
= pcap_wait_for_frames_mmap(handle
);
5283 /* non-positive values of max_packets are used to require all
5284 * packets currently available in the ring */
5285 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
5287 * Get the current ring buffer frame, and break if
5288 * it's still owned by the kernel.
5290 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
5291 if (h
.h2
->tp_status
== TP_STATUS_KERNEL
)
5294 ret
= pcap_handle_packet_mmap(
5303 handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
? h
.h2
->tp_nsec
: h
.h2
->tp_nsec
/ 1000,
5304 VLAN_VALID(h
.h2
, h
.h2
),
5306 VLAN_TPID(h
.h2
, h
.h2
));
5309 handlep
->packets_read
++;
5310 } else if (ret
< 0) {
5315 * Hand this block back to the kernel, and, if we're
5316 * counting blocks that need to be filtered in userland
5317 * after having been filtered by the kernel, count
5318 * the one we've just processed.
5320 h
.h2
->tp_status
= TP_STATUS_KERNEL
;
5321 if (handlep
->blocks_to_filter_in_userland
> 0) {
5322 handlep
->blocks_to_filter_in_userland
--;
5323 if (handlep
->blocks_to_filter_in_userland
== 0) {
5325 * No more blocks need to be filtered
5328 handlep
->filter_in_userland
= 0;
5333 if (++handle
->offset
>= handle
->cc
)
5336 /* check for break loop condition*/
5337 if (handle
->break_loop
) {
5338 handle
->break_loop
= 0;
5339 return PCAP_ERROR_BREAK
;
5344 #endif /* HAVE_TPACKET2 */
5346 #ifdef HAVE_TPACKET3
5348 pcap_read_linux_mmap_v3(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
5351 struct pcap_linux
*handlep
= handle
->priv
;
5357 if (handlep
->current_packet
== NULL
) {
5358 /* wait for frames availability.*/
5359 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
5360 if (h
.h3
->hdr
.bh1
.block_status
== TP_STATUS_KERNEL
) {
5362 * The current frame is owned by the kernel; wait
5363 * for a frame to be handed to us.
5365 ret
= pcap_wait_for_frames_mmap(handle
);
5371 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
5372 if (h
.h3
->hdr
.bh1
.block_status
== TP_STATUS_KERNEL
) {
5373 if (pkts
== 0 && handlep
->timeout
== 0) {
5374 /* Block until we see a packet. */
5380 /* non-positive values of max_packets are used to require all
5381 * packets currently available in the ring */
5382 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
5383 int packets_to_read
;
5385 if (handlep
->current_packet
== NULL
) {
5386 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
5387 if (h
.h3
->hdr
.bh1
.block_status
== TP_STATUS_KERNEL
)
5390 handlep
->current_packet
= h
.raw
+ h
.h3
->hdr
.bh1
.offset_to_first_pkt
;
5391 handlep
->packets_left
= h
.h3
->hdr
.bh1
.num_pkts
;
5393 packets_to_read
= handlep
->packets_left
;
5395 if (!PACKET_COUNT_IS_UNLIMITED(max_packets
) &&
5396 packets_to_read
> (max_packets
- pkts
)) {
5398 * We've been given a maximum number of packets
5399 * to process, and there are more packets in
5400 * this buffer than that. Only process enough
5401 * of them to get us up to that maximum.
5403 packets_to_read
= max_packets
- pkts
;
5406 while (packets_to_read
-- && !handle
->break_loop
) {
5407 struct tpacket3_hdr
* tp3_hdr
= (struct tpacket3_hdr
*) handlep
->current_packet
;
5408 ret
= pcap_handle_packet_mmap(
5412 handlep
->current_packet
,
5415 tp3_hdr
->tp_snaplen
,
5417 handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
? tp3_hdr
->tp_nsec
: tp3_hdr
->tp_nsec
/ 1000,
5418 VLAN_VALID(tp3_hdr
, &tp3_hdr
->hv1
),
5419 tp3_hdr
->hv1
.tp_vlan_tci
,
5420 VLAN_TPID(tp3_hdr
, &tp3_hdr
->hv1
));
5423 handlep
->packets_read
++;
5424 } else if (ret
< 0) {
5425 handlep
->current_packet
= NULL
;
5428 handlep
->current_packet
+= tp3_hdr
->tp_next_offset
;
5429 handlep
->packets_left
--;
5432 if (handlep
->packets_left
<= 0) {
5434 * Hand this block back to the kernel, and, if
5435 * we're counting blocks that need to be
5436 * filtered in userland after having been
5437 * filtered by the kernel, count the one we've
5440 h
.h3
->hdr
.bh1
.block_status
= TP_STATUS_KERNEL
;
5441 if (handlep
->blocks_to_filter_in_userland
> 0) {
5442 handlep
->blocks_to_filter_in_userland
--;
5443 if (handlep
->blocks_to_filter_in_userland
== 0) {
5445 * No more blocks need to be filtered
5448 handlep
->filter_in_userland
= 0;
5453 if (++handle
->offset
>= handle
->cc
)
5456 handlep
->current_packet
= NULL
;
5459 /* check for break loop condition*/
5460 if (handle
->break_loop
) {
5461 handle
->break_loop
= 0;
5462 return PCAP_ERROR_BREAK
;
5465 if (pkts
== 0 && handlep
->timeout
== 0) {
5466 /* Block until we see a packet. */
5471 #endif /* HAVE_TPACKET3 */
5474 pcap_setfilter_linux_mmap(pcap_t
*handle
, struct bpf_program
*filter
)
5476 struct pcap_linux
*handlep
= handle
->priv
;
5481 * Don't rewrite "ret" instructions; we don't need to, as
5482 * we're not reading packets with recvmsg(), and we don't
5483 * want to, as, by not rewriting them, the kernel can avoid
5484 * copying extra data.
5486 ret
= pcap_setfilter_linux_common(handle
, filter
, 1);
5491 * If we're filtering in userland, there's nothing to do;
5492 * the new filter will be used for the next packet.
5494 if (handlep
->filter_in_userland
)
5498 * We're filtering in the kernel; the packets present in
5499 * all blocks currently in the ring were already filtered
5500 * by the old filter, and so will need to be filtered in
5501 * userland by the new filter.
5503 * Get an upper bound for the number of such blocks; first,
5504 * walk the ring backward and count the free blocks.
5506 offset
= handle
->offset
;
5508 offset
= handle
->cc
- 1;
5509 for (n
=0; n
< handle
->cc
; ++n
) {
5511 offset
= handle
->cc
- 1;
5512 if (pcap_get_ring_frame_status(handle
, offset
) != TP_STATUS_KERNEL
)
5517 * If we found free blocks, decrement the count of free
5518 * blocks by 1, just in case we lost a race with another
5519 * thread of control that was adding a packet while
5520 * we were counting and that had run the filter before
5523 * XXX - could there be more than one block added in
5526 * XXX - is there a way to avoid that race, e.g. somehow
5527 * wait for all packets that passed the old filter to
5528 * be added to the ring?
5534 * Set the count of blocks worth of packets to filter
5535 * in userland to the total number of blocks in the
5536 * ring minus the number of free blocks we found, and
5537 * turn on userland filtering. (The count of blocks
5538 * worth of packets to filter in userland is guaranteed
5539 * not to be zero - n, above, couldn't be set to a
5540 * value > handle->cc, and if it were equal to
5541 * handle->cc, it wouldn't be zero, and thus would
5542 * be decremented to handle->cc - 1.)
5544 handlep
->blocks_to_filter_in_userland
= handle
->cc
- n
;
5545 handlep
->filter_in_userland
= 1;
5548 #endif /* HAVE_PACKET_RING */
5551 * Return the index of the given device name. Fill ebuf and return
5555 iface_get_id(int fd
, const char *device
, char *ebuf
)
5559 memset(&ifr
, 0, sizeof(ifr
));
5560 pcap_strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5562 if (ioctl(fd
, SIOCGIFINDEX
, &ifr
) == -1) {
5563 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
5564 errno
, "SIOCGIFINDEX");
5568 return ifr
.ifr_ifindex
;
5572 * Bind the socket associated with FD to the given device.
5573 * Return 0 on success or a PCAP_ERROR_ value on a hard error.
5576 iface_bind(int fd
, int ifindex
, char *ebuf
, int protocol
)
5578 struct sockaddr_ll sll
;
5580 socklen_t errlen
= sizeof(err
);
5582 memset(&sll
, 0, sizeof(sll
));
5583 sll
.sll_family
= AF_PACKET
;
5584 sll
.sll_ifindex
= ifindex
;
5585 sll
.sll_protocol
= protocol
;
5587 if (bind(fd
, (struct sockaddr
*) &sll
, sizeof(sll
)) == -1) {
5588 if (errno
== ENETDOWN
) {
5590 * Return a "network down" indication, so that
5591 * the application can report that rather than
5592 * saying we had a mysterious failure and
5593 * suggest that they report a problem to the
5594 * libpcap developers.
5596 return PCAP_ERROR_IFACE_NOT_UP
;
5598 if (errno
== ENODEV
)
5599 ret
= PCAP_ERROR_NO_SUCH_DEVICE
;
5602 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
5607 /* Any pending errors, e.g., network is down? */
5609 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
5610 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
5611 errno
, "getsockopt (SO_ERROR)");
5615 if (err
== ENETDOWN
) {
5617 * Return a "network down" indication, so that
5618 * the application can report that rather than
5619 * saying we had a mysterious failure and
5620 * suggest that they report a problem to the
5621 * libpcap developers.
5623 return PCAP_ERROR_IFACE_NOT_UP
;
5624 } else if (err
> 0) {
5625 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
5633 #ifdef IW_MODE_MONITOR
5635 * Check whether the device supports the Wireless Extensions.
5636 * Returns 1 if it does, 0 if it doesn't, PCAP_ERROR_NO_SUCH_DEVICE
5637 * if the device doesn't even exist.
5640 has_wext(int sock_fd
, const char *device
, char *ebuf
)
5645 if (is_bonding_device(sock_fd
, device
))
5646 return 0; /* bonding device, so don't even try */
5648 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5649 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5650 if (ioctl(sock_fd
, SIOCGIWNAME
, &ireq
) >= 0)
5652 if (errno
== ENODEV
)
5653 ret
= PCAP_ERROR_NO_SUCH_DEVICE
;
5656 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
, errno
,
5657 "%s: SIOCGIWNAME", device
);
5662 * Per me si va ne la citta dolente,
5663 * Per me si va ne l'etterno dolore,
5665 * Lasciate ogne speranza, voi ch'intrate.
5667 * XXX - airmon-ng does special stuff with the Orinoco driver and the
5683 * Use the Wireless Extensions, if we have them, to try to turn monitor mode
5684 * on if it's not already on.
5686 * Returns 1 on success, 0 if we don't support the Wireless Extensions
5687 * on this device, or a PCAP_ERROR_ value if we do support them but
5688 * we weren't able to turn monitor mode on.
5691 enter_rfmon_mode_wext(pcap_t
*handle
, int sock_fd
, const char *device
)
5694 * XXX - at least some adapters require non-Wireless Extensions
5695 * mechanisms to turn monitor mode on.
5697 * Atheros cards might require that a separate "monitor virtual access
5698 * point" be created, with later versions of the madwifi driver.
5701 * wlanconfig ath create wlandev {if_name} wlanmode monitor -bssid
5703 * which apparently spits out a line "athN" where "athN" is the
5704 * monitor mode device. To leave monitor mode, it destroys the
5705 * monitor mode device.
5707 * Some Intel Centrino adapters might require private ioctls to get
5708 * radio headers; the ipw2200 and ipw3945 drivers allow you to
5709 * configure a separate "rtapN" interface to capture in monitor
5710 * mode without preventing the adapter from operating normally.
5711 * (airmon-ng doesn't appear to use that, though.)
5713 * It would be Truly Wonderful if mac80211 and nl80211 cleaned this
5714 * up, and if all drivers were converted to mac80211 drivers.
5716 * If interface {if_name} is a mac80211 driver, the file
5717 * /sys/class/net/{if_name}/phy80211 is a symlink to
5718 * /sys/class/ieee80211/{phydev_name}, for some {phydev_name}.
5720 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
5721 * least, has a "wmaster0" device and a "wlan0" device; the
5722 * latter is the one with the IP address. Both show up in
5723 * "tcpdump -D" output. Capturing on the wmaster0 device
5724 * captures with 802.11 headers.
5726 * airmon-ng searches through /sys/class/net for devices named
5727 * monN, starting with mon0; as soon as one *doesn't* exist,
5728 * it chooses that as the monitor device name. If the "iw"
5729 * command exists, it does
5731 * iw dev {if_name} interface add {monif_name} type monitor"
5733 * where {monif_name} is the monitor device. It then (sigh) sleeps
5734 * .1 second, and then configures the device up. Otherwise, if
5735 * /sys/class/ieee80211/{phydev_name}/add_iface is a file, it writes
5736 * {mondev_name}, without a newline, to that file, and again (sigh)
5737 * sleeps .1 second, and then iwconfig's that device into monitor
5738 * mode and configures it up. Otherwise, you can't do monitor mode.
5740 * All these devices are "glued" together by having the
5741 * /sys/class/net/{device_name}/phy80211 links pointing to the same
5742 * place, so, given a wmaster, wlan, or mon device, you can
5743 * find the other devices by looking for devices with
5744 * the same phy80211 link.
5746 * To turn monitor mode off, delete the monitor interface,
5749 * iw dev {monif_name} interface del
5751 * or by sending {monif_name}, with no NL, down
5752 * /sys/class/ieee80211/{phydev_name}/remove_iface
5754 * Note: if you try to create a monitor device named "monN", and
5755 * there's already a "monN" device, it fails, as least with
5756 * the netlink interface (which is what iw uses), with a return
5757 * value of -ENFILE. (Return values are negative errnos.) We
5758 * could probably use that to find an unused device.
5760 struct pcap_linux
*handlep
= handle
->priv
;
5763 struct iw_priv_args
*priv
;
5764 monitor_type montype
;
5773 * Does this device *support* the Wireless Extensions?
5775 err
= has_wext(sock_fd
, device
, handle
->errbuf
);
5777 return err
; /* either it doesn't or the device doesn't even exist */
5779 * Start out assuming we have no private extensions to control
5782 montype
= MONITOR_WEXT
;
5786 * Try to get all the Wireless Extensions private ioctls
5787 * supported by this device.
5789 * First, get the size of the buffer we need, by supplying no
5790 * buffer and a length of 0. If the device supports private
5791 * ioctls, it should return E2BIG, with ireq.u.data.length set
5792 * to the length we need. If it doesn't support them, it should
5793 * return EOPNOTSUPP.
5795 memset(&ireq
, 0, sizeof ireq
);
5796 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5797 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5798 ireq
.u
.data
.pointer
= (void *)args
;
5799 ireq
.u
.data
.length
= 0;
5800 ireq
.u
.data
.flags
= 0;
5801 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) != -1) {
5802 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5803 "%s: SIOCGIWPRIV with a zero-length buffer didn't fail!",
5807 if (errno
!= EOPNOTSUPP
) {
5809 * OK, it's not as if there are no private ioctls.
5811 if (errno
!= E2BIG
) {
5815 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
5816 PCAP_ERRBUF_SIZE
, errno
, "%s: SIOCGIWPRIV", device
);
5821 * OK, try to get the list of private ioctls.
5823 priv
= malloc(ireq
.u
.data
.length
* sizeof (struct iw_priv_args
));
5825 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
5826 PCAP_ERRBUF_SIZE
, errno
, "malloc");
5829 ireq
.u
.data
.pointer
= (void *)priv
;
5830 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) == -1) {
5831 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
5832 PCAP_ERRBUF_SIZE
, errno
, "%s: SIOCGIWPRIV", device
);
5838 * Look for private ioctls to turn monitor mode on or, if
5839 * monitor mode is on, to set the header type.
5841 for (i
= 0; i
< ireq
.u
.data
.length
; i
++) {
5842 if (strcmp(priv
[i
].name
, "monitor_type") == 0) {
5844 * Hostap driver, use this one.
5845 * Set monitor mode first.
5846 * You can set it to 0 to get DLT_IEEE80211,
5847 * 1 to get DLT_PRISM, 2 to get
5848 * DLT_IEEE80211_RADIO_AVS, and, with more
5849 * recent versions of the driver, 3 to get
5850 * DLT_IEEE80211_RADIO.
5852 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5854 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
5856 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
5858 montype
= MONITOR_HOSTAP
;
5862 if (strcmp(priv
[i
].name
, "set_prismhdr") == 0) {
5864 * Prism54 driver, use this one.
5865 * Set monitor mode first.
5866 * You can set it to 2 to get DLT_IEEE80211
5867 * or 3 or get DLT_PRISM.
5869 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5871 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
5873 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
5875 montype
= MONITOR_PRISM54
;
5879 if (strcmp(priv
[i
].name
, "forceprismheader") == 0) {
5881 * RT2570 driver, use this one.
5882 * Do this after turning monitor mode on.
5883 * You can set it to 1 to get DLT_PRISM or 2
5884 * to get DLT_IEEE80211.
5886 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5888 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
5890 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
5892 montype
= MONITOR_RT2570
;
5896 if (strcmp(priv
[i
].name
, "forceprism") == 0) {
5898 * RT73 driver, use this one.
5899 * Do this after turning monitor mode on.
5900 * Its argument is a *string*; you can
5901 * set it to "1" to get DLT_PRISM or "2"
5902 * to get DLT_IEEE80211.
5904 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_CHAR
)
5906 if (priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
)
5908 montype
= MONITOR_RT73
;
5912 if (strcmp(priv
[i
].name
, "prismhdr") == 0) {
5914 * One of the RTL8xxx drivers, use this one.
5915 * It can only be done after monitor mode
5916 * has been turned on. You can set it to 1
5917 * to get DLT_PRISM or 0 to get DLT_IEEE80211.
5919 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5921 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
5923 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
5925 montype
= MONITOR_RTL8XXX
;
5929 if (strcmp(priv
[i
].name
, "rfmontx") == 0) {
5931 * RT2500 or RT61 driver, use this one.
5932 * It has one one-byte parameter; set
5933 * u.data.length to 1 and u.data.pointer to
5934 * point to the parameter.
5935 * It doesn't itself turn monitor mode on.
5936 * You can set it to 1 to allow transmitting
5937 * in monitor mode(?) and get DLT_IEEE80211,
5938 * or set it to 0 to disallow transmitting in
5939 * monitor mode(?) and get DLT_PRISM.
5941 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5943 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 2)
5945 montype
= MONITOR_RT2500
;
5949 if (strcmp(priv
[i
].name
, "monitor") == 0) {
5951 * Either ACX100 or hostap, use this one.
5952 * It turns monitor mode on.
5953 * If it takes two arguments, it's ACX100;
5954 * the first argument is 1 for DLT_PRISM
5955 * or 2 for DLT_IEEE80211, and the second
5956 * argument is the channel on which to
5957 * run. If it takes one argument, it's
5958 * HostAP, and the argument is 2 for
5959 * DLT_IEEE80211 and 3 for DLT_PRISM.
5961 * If we see this, we don't quit, as this
5962 * might be a version of the hostap driver
5963 * that also supports "monitor_type".
5965 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5967 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
5969 switch (priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) {
5972 montype
= MONITOR_PRISM
;
5977 montype
= MONITOR_ACX100
;
5990 * XXX - ipw3945? islism?
5996 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5997 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5998 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) == -1) {
6000 * We probably won't be able to set the mode, either.
6002 return PCAP_ERROR_RFMON_NOTSUP
;
6006 * Is it currently in monitor mode?
6008 if (ireq
.u
.mode
== IW_MODE_MONITOR
) {
6010 * Yes. Just leave things as they are.
6011 * We don't offer multiple link-layer types, as
6012 * changing the link-layer type out from under
6013 * somebody else capturing in monitor mode would
6014 * be considered rude.
6019 * No. We have to put the adapter into rfmon mode.
6023 * If we haven't already done so, arrange to have
6024 * "pcap_close_all()" called when we exit.
6026 if (!pcap_do_addexit(handle
)) {
6028 * "atexit()" failed; don't put the interface
6029 * in rfmon mode, just give up.
6031 return PCAP_ERROR_RFMON_NOTSUP
;
6035 * Save the old mode.
6037 handlep
->oldmode
= ireq
.u
.mode
;
6040 * Put the adapter in rfmon mode. How we do this depends
6041 * on whether we have a special private ioctl or not.
6043 if (montype
== MONITOR_PRISM
) {
6045 * We have the "monitor" private ioctl, but none of
6046 * the other private ioctls. Use this, and select
6049 * If it fails, just fall back on SIOCSIWMODE.
6051 memset(&ireq
, 0, sizeof ireq
);
6052 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6053 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6054 ireq
.u
.data
.length
= 1; /* 1 argument */
6055 args
[0] = 3; /* request Prism header */
6056 memcpy(ireq
.u
.name
, args
, sizeof (int));
6057 if (ioctl(sock_fd
, cmd
, &ireq
) != -1) {
6060 * Note that we have to put the old mode back
6061 * when we close the device.
6063 handlep
->must_do_on_close
|= MUST_CLEAR_RFMON
;
6066 * Add this to the list of pcaps to close
6069 pcap_add_to_pcaps_to_close(handle
);
6075 * Failure. Fall back on SIOCSIWMODE.
6080 * First, take the interface down if it's up; otherwise, we
6083 memset(&ifr
, 0, sizeof(ifr
));
6084 pcap_strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
6085 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
6086 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6087 errno
, "%s: Can't get flags", device
);
6091 if (ifr
.ifr_flags
& IFF_UP
) {
6092 oldflags
= ifr
.ifr_flags
;
6093 ifr
.ifr_flags
&= ~IFF_UP
;
6094 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
6095 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
6096 PCAP_ERRBUF_SIZE
, errno
, "%s: Can't set flags",
6103 * Then turn monitor mode on.
6105 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6106 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6107 ireq
.u
.mode
= IW_MODE_MONITOR
;
6108 if (ioctl(sock_fd
, SIOCSIWMODE
, &ireq
) == -1) {
6110 * Scientist, you've failed.
6111 * Bring the interface back up if we shut it down.
6113 ifr
.ifr_flags
= oldflags
;
6114 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
6115 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
6116 PCAP_ERRBUF_SIZE
, errno
, "%s: Can't set flags",
6120 return PCAP_ERROR_RFMON_NOTSUP
;
6124 * XXX - airmon-ng does "iwconfig {if_name} key off" after setting
6125 * monitor mode and setting the channel, and then does
6130 * Now select the appropriate radio header.
6136 * We don't have any private ioctl to set the header.
6140 case MONITOR_HOSTAP
:
6142 * Try to select the radiotap header.
6144 memset(&ireq
, 0, sizeof ireq
);
6145 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6146 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6147 args
[0] = 3; /* request radiotap header */
6148 memcpy(ireq
.u
.name
, args
, sizeof (int));
6149 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
6150 break; /* success */
6153 * That failed. Try to select the AVS header.
6155 memset(&ireq
, 0, sizeof ireq
);
6156 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6157 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6158 args
[0] = 2; /* request AVS header */
6159 memcpy(ireq
.u
.name
, args
, sizeof (int));
6160 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
6161 break; /* success */
6164 * That failed. Try to select the Prism header.
6166 memset(&ireq
, 0, sizeof ireq
);
6167 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6168 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6169 args
[0] = 1; /* request Prism header */
6170 memcpy(ireq
.u
.name
, args
, sizeof (int));
6171 ioctl(sock_fd
, cmd
, &ireq
);
6176 * The private ioctl failed.
6180 case MONITOR_PRISM54
:
6182 * Select the Prism header.
6184 memset(&ireq
, 0, sizeof ireq
);
6185 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6186 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6187 args
[0] = 3; /* request Prism header */
6188 memcpy(ireq
.u
.name
, args
, sizeof (int));
6189 ioctl(sock_fd
, cmd
, &ireq
);
6192 case MONITOR_ACX100
:
6194 * Get the current channel.
6196 memset(&ireq
, 0, sizeof ireq
);
6197 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6198 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6199 if (ioctl(sock_fd
, SIOCGIWFREQ
, &ireq
) == -1) {
6200 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
6201 PCAP_ERRBUF_SIZE
, errno
, "%s: SIOCGIWFREQ", device
);
6204 channel
= ireq
.u
.freq
.m
;
6207 * Select the Prism header, and set the channel to the
6210 memset(&ireq
, 0, sizeof ireq
);
6211 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6212 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6213 args
[0] = 1; /* request Prism header */
6214 args
[1] = channel
; /* set channel */
6215 memcpy(ireq
.u
.name
, args
, 2*sizeof (int));
6216 ioctl(sock_fd
, cmd
, &ireq
);
6219 case MONITOR_RT2500
:
6221 * Disallow transmission - that turns on the
6224 memset(&ireq
, 0, sizeof ireq
);
6225 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6226 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6227 args
[0] = 0; /* disallow transmitting */
6228 memcpy(ireq
.u
.name
, args
, sizeof (int));
6229 ioctl(sock_fd
, cmd
, &ireq
);
6232 case MONITOR_RT2570
:
6234 * Force the Prism header.
6236 memset(&ireq
, 0, sizeof ireq
);
6237 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6238 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6239 args
[0] = 1; /* request Prism header */
6240 memcpy(ireq
.u
.name
, args
, sizeof (int));
6241 ioctl(sock_fd
, cmd
, &ireq
);
6246 * Force the Prism header.
6248 memset(&ireq
, 0, sizeof ireq
);
6249 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6250 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6251 ireq
.u
.data
.length
= 1; /* 1 argument */
6252 ireq
.u
.data
.pointer
= "1";
6253 ireq
.u
.data
.flags
= 0;
6254 ioctl(sock_fd
, cmd
, &ireq
);
6257 case MONITOR_RTL8XXX
:
6259 * Force the Prism header.
6261 memset(&ireq
, 0, sizeof ireq
);
6262 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6263 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6264 args
[0] = 1; /* request Prism header */
6265 memcpy(ireq
.u
.name
, args
, sizeof (int));
6266 ioctl(sock_fd
, cmd
, &ireq
);
6271 * Now bring the interface back up if we brought it down.
6273 if (oldflags
!= 0) {
6274 ifr
.ifr_flags
= oldflags
;
6275 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
6276 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
6277 PCAP_ERRBUF_SIZE
, errno
, "%s: Can't set flags",
6281 * At least try to restore the old mode on the
6284 if (ioctl(handle
->fd
, SIOCSIWMODE
, &ireq
) == -1) {
6286 * Scientist, you've failed.
6289 "Can't restore interface wireless mode (SIOCSIWMODE failed: %s).\n"
6290 "Please adjust manually.\n",
6298 * Note that we have to put the old mode back when we
6301 handlep
->must_do_on_close
|= MUST_CLEAR_RFMON
;
6304 * Add this to the list of pcaps to close when we exit.
6306 pcap_add_to_pcaps_to_close(handle
);
6310 #endif /* IW_MODE_MONITOR */
6313 * Try various mechanisms to enter monitor mode.
6316 enter_rfmon_mode(pcap_t
*handle
, int sock_fd
, const char *device
)
6318 #if defined(HAVE_LIBNL) || defined(IW_MODE_MONITOR)
6323 ret
= enter_rfmon_mode_mac80211(handle
, sock_fd
, device
);
6325 return ret
; /* error attempting to do so */
6327 return 1; /* success */
6328 #endif /* HAVE_LIBNL */
6330 #ifdef IW_MODE_MONITOR
6331 ret
= enter_rfmon_mode_wext(handle
, sock_fd
, device
);
6333 return ret
; /* error attempting to do so */
6335 return 1; /* success */
6336 #endif /* IW_MODE_MONITOR */
6339 * Either none of the mechanisms we know about work or none
6340 * of those mechanisms are available, so we can't do monitor
6346 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
6348 * Map SOF_TIMESTAMPING_ values to PCAP_TSTAMP_ values.
6350 static const struct {
6351 int soft_timestamping_val
;
6352 int pcap_tstamp_val
;
6353 } sof_ts_type_map
[3] = {
6354 { SOF_TIMESTAMPING_SOFTWARE
, PCAP_TSTAMP_HOST
},
6355 { SOF_TIMESTAMPING_SYS_HARDWARE
, PCAP_TSTAMP_ADAPTER
},
6356 { SOF_TIMESTAMPING_RAW_HARDWARE
, PCAP_TSTAMP_ADAPTER_UNSYNCED
}
6358 #define NUM_SOF_TIMESTAMPING_TYPES (sizeof sof_ts_type_map / sizeof sof_ts_type_map[0])
6361 * Set the list of time stamping types to include all types.
6364 iface_set_all_ts_types(pcap_t
*handle
)
6368 handle
->tstamp_type_count
= NUM_SOF_TIMESTAMPING_TYPES
;
6369 handle
->tstamp_type_list
= malloc(NUM_SOF_TIMESTAMPING_TYPES
* sizeof(u_int
));
6370 for (i
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++)
6371 handle
->tstamp_type_list
[i
] = sof_ts_type_map
[i
].pcap_tstamp_val
;
6374 #ifdef ETHTOOL_GET_TS_INFO
6376 * Get a list of time stamping capabilities.
6379 iface_ethtool_get_ts_info(const char *device
, pcap_t
*handle
, char *ebuf
)
6383 struct ethtool_ts_info info
;
6388 * This doesn't apply to the "any" device; you can't say "turn on
6389 * hardware time stamping for all devices that exist now and arrange
6390 * that it be turned on for any device that appears in the future",
6391 * and not all devices even necessarily *support* hardware time
6392 * stamping, so don't report any time stamp types.
6394 if (strcmp(device
, "any") == 0) {
6395 handle
->tstamp_type_list
= NULL
;
6400 * Create a socket from which to fetch time stamping capabilities.
6402 fd
= socket(PF_UNIX
, SOCK_RAW
, 0);
6404 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
6405 errno
, "socket for SIOCETHTOOL(ETHTOOL_GET_TS_INFO)");
6409 memset(&ifr
, 0, sizeof(ifr
));
6410 pcap_strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
6411 memset(&info
, 0, sizeof(info
));
6412 info
.cmd
= ETHTOOL_GET_TS_INFO
;
6413 ifr
.ifr_data
= (caddr_t
)&info
;
6414 if (ioctl(fd
, SIOCETHTOOL
, &ifr
) == -1) {
6415 int save_errno
= errno
;
6418 switch (save_errno
) {
6423 * OK, this OS version or driver doesn't support
6424 * asking for the time stamping types, so let's
6425 * just return all the possible types.
6427 iface_set_all_ts_types(handle
);
6432 * OK, no such device.
6433 * The user will find that out when they try to
6434 * activate the device; just return an empty
6435 * list of time stamp types.
6437 handle
->tstamp_type_list
= NULL
;
6444 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
6446 "%s: SIOCETHTOOL(ETHTOOL_GET_TS_INFO) ioctl failed",
6454 * Do we support hardware time stamping of *all* packets?
6456 if (!(info
.rx_filters
& (1 << HWTSTAMP_FILTER_ALL
))) {
6458 * No, so don't report any time stamp types.
6460 * XXX - some devices either don't report
6461 * HWTSTAMP_FILTER_ALL when they do support it, or
6462 * report HWTSTAMP_FILTER_ALL but map it to only
6463 * time stamping a few PTP packets. See
6464 * http://marc.info/?l=linux-netdev&m=146318183529571&w=2
6466 handle
->tstamp_type_list
= NULL
;
6471 for (i
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++) {
6472 if (info
.so_timestamping
& sof_ts_type_map
[i
].soft_timestamping_val
)
6475 handle
->tstamp_type_count
= num_ts_types
;
6476 if (num_ts_types
!= 0) {
6477 handle
->tstamp_type_list
= malloc(num_ts_types
* sizeof(u_int
));
6478 for (i
= 0, j
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++) {
6479 if (info
.so_timestamping
& sof_ts_type_map
[i
].soft_timestamping_val
) {
6480 handle
->tstamp_type_list
[j
] = sof_ts_type_map
[i
].pcap_tstamp_val
;
6485 handle
->tstamp_type_list
= NULL
;
6489 #else /* ETHTOOL_GET_TS_INFO */
6491 iface_ethtool_get_ts_info(const char *device
, pcap_t
*handle
, char *ebuf _U_
)
6494 * This doesn't apply to the "any" device; you can't say "turn on
6495 * hardware time stamping for all devices that exist now and arrange
6496 * that it be turned on for any device that appears in the future",
6497 * and not all devices even necessarily *support* hardware time
6498 * stamping, so don't report any time stamp types.
6500 if (strcmp(device
, "any") == 0) {
6501 handle
->tstamp_type_list
= NULL
;
6506 * We don't have an ioctl to use to ask what's supported,
6507 * so say we support everything.
6509 iface_set_all_ts_types(handle
);
6512 #endif /* ETHTOOL_GET_TS_INFO */
6514 #endif /* defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP) */
6516 #ifdef HAVE_PACKET_RING
6518 * Find out if we have any form of fragmentation/reassembly offloading.
6520 * We do so using SIOCETHTOOL checking for various types of offloading;
6521 * if SIOCETHTOOL isn't defined, or we don't have any #defines for any
6522 * of the types of offloading, there's nothing we can do to check, so
6523 * we just say "no, we don't".
6525 * We treat EOPNOTSUPP, EINVAL and, if eperm_ok is true, EPERM as
6526 * indications that the operation isn't supported. We do EPERM
6527 * weirdly because the SIOCETHTOOL code in later kernels 1) doesn't
6528 * support ETHTOOL_GUFO, 2) also doesn't include it in the list
6529 * of ethtool operations that don't require CAP_NET_ADMIN privileges,
6530 * and 3) does the "is this permitted" check before doing the "is
6531 * this even supported" check, so it fails with "this is not permitted"
6532 * rather than "this is not even supported". To work around this
6533 * annoyance, we only treat EPERM as an error for the first feature,
6534 * and assume that they all do the same permission checks, so if the
6535 * first one is allowed all the others are allowed if supported.
6537 #if defined(SIOCETHTOOL) && (defined(ETHTOOL_GTSO) || defined(ETHTOOL_GUFO) || defined(ETHTOOL_GGSO) || defined(ETHTOOL_GFLAGS) || defined(ETHTOOL_GGRO))
6539 iface_ethtool_flag_ioctl(pcap_t
*handle
, int cmd
, const char *cmdname
,
6543 struct ethtool_value eval
;
6545 memset(&ifr
, 0, sizeof(ifr
));
6546 pcap_strlcpy(ifr
.ifr_name
, handle
->opt
.device
, sizeof(ifr
.ifr_name
));
6549 ifr
.ifr_data
= (caddr_t
)&eval
;
6550 if (ioctl(handle
->fd
, SIOCETHTOOL
, &ifr
) == -1) {
6551 if (errno
== EOPNOTSUPP
|| errno
== EINVAL
||
6552 (errno
== EPERM
&& eperm_ok
)) {
6554 * OK, let's just return 0, which, in our
6555 * case, either means "no, what we're asking
6556 * about is not enabled" or "all the flags
6557 * are clear (i.e., nothing is enabled)".
6561 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6562 errno
, "%s: SIOCETHTOOL(%s) ioctl failed",
6563 handle
->opt
.device
, cmdname
);
6570 * XXX - it's annoying that we have to check for offloading at all, but,
6571 * given that we have to, it's still annoying that we have to check for
6572 * particular types of offloading, especially that shiny new types of
6573 * offloading may be added - and, worse, may not be checkable with
6574 * a particular ETHTOOL_ operation; ETHTOOL_GFEATURES would, in
6575 * theory, give those to you, but the actual flags being used are
6576 * opaque (defined in a non-uapi header), and there doesn't seem to
6577 * be any obvious way to ask the kernel what all the offloading flags
6578 * are - at best, you can ask for a set of strings(!) to get *names*
6579 * for various flags. (That whole mechanism appears to have been
6580 * designed for the sole purpose of letting ethtool report flags
6581 * by name and set flags by name, with the names having no semantics
6582 * ethtool understands.)
6585 iface_get_offload(pcap_t
*handle
)
6590 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GTSO
, "ETHTOOL_GTSO", 0);
6594 return 1; /* TCP segmentation offloading on */
6599 * XXX - will this cause large unsegmented packets to be
6600 * handed to PF_PACKET sockets on transmission? If not,
6601 * this need not be checked.
6603 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GGSO
, "ETHTOOL_GGSO", 0);
6607 return 1; /* generic segmentation offloading on */
6610 #ifdef ETHTOOL_GFLAGS
6611 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GFLAGS
, "ETHTOOL_GFLAGS", 0);
6614 if (ret
& ETH_FLAG_LRO
)
6615 return 1; /* large receive offloading on */
6620 * XXX - will this cause large reassembled packets to be
6621 * handed to PF_PACKET sockets on receipt? If not,
6622 * this need not be checked.
6624 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GGRO
, "ETHTOOL_GGRO", 0);
6628 return 1; /* generic (large) receive offloading on */
6633 * Do this one last, as support for it was removed in later
6634 * kernels, and it fails with EPERM on those kernels rather
6635 * than with EOPNOTSUPP (see explanation in comment for
6636 * iface_ethtool_flag_ioctl()).
6638 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GUFO
, "ETHTOOL_GUFO", 1);
6642 return 1; /* UDP fragmentation offloading on */
6647 #else /* SIOCETHTOOL */
6649 iface_get_offload(pcap_t
*handle _U_
)
6652 * XXX - do we need to get this information if we don't
6653 * have the ethtool ioctls? If so, how do we do that?
6657 #endif /* SIOCETHTOOL */
6659 #endif /* HAVE_PACKET_RING */
6661 static struct dsa_proto
{
6663 bpf_u_int32 linktype
;
6666 * None is special and indicates that the interface does not have
6667 * any tagging protocol configured, and is therefore a standard
6668 * Ethernet interface.
6670 { "none", DLT_EN10MB
},
6671 { "brcm", DLT_DSA_TAG_BRCM
},
6672 { "brcm-prepend", DLT_DSA_TAG_BRCM_PREPEND
},
6673 { "dsa", DLT_DSA_TAG_DSA
},
6674 { "edsa", DLT_DSA_TAG_EDSA
},
6678 iface_dsa_get_proto_info(const char *device
, pcap_t
*handle
)
6683 * Make this significantly smaller than PCAP_ERRBUF_SIZE;
6684 * the tag *shouldn't* have some huge long name, and making
6685 * it smaller keeps newer versions of GCC from whining that
6686 * the error message if we don't support the tag could
6687 * overflow the error message buffer.
6693 fd
= asprintf(&pathstr
, "/sys/class/net/%s/dsa/tagging", device
);
6695 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6700 fd
= open(pathstr
, O_RDONLY
);
6703 * This is not fatal, kernel >= 4.20 *might* expose this attribute
6708 r
= read(fd
, buf
, sizeof(buf
) - 1);
6710 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6718 * Buffer should be LF terminated.
6720 if (buf
[r
- 1] == '\n')
6724 for (i
= 0; i
< sizeof(dsa_protos
) / sizeof(dsa_protos
[0]); i
++) {
6725 if (strlen(dsa_protos
[i
].name
) == (size_t)r
&&
6726 strcmp(buf
, dsa_protos
[i
].name
) == 0) {
6727 handle
->linktype
= dsa_protos
[i
].linktype
;
6728 switch (dsa_protos
[i
].linktype
) {
6737 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6738 "unsupported DSA tag: %s", buf
);
6744 * Query the kernel for the MTU of the given interface.
6747 iface_get_mtu(int fd
, const char *device
, char *ebuf
)
6752 return BIGGER_THAN_ALL_MTUS
;
6754 memset(&ifr
, 0, sizeof(ifr
));
6755 pcap_strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
6757 if (ioctl(fd
, SIOCGIFMTU
, &ifr
) == -1) {
6758 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
6759 errno
, "SIOCGIFMTU");
6767 * Get the hardware type of the given interface as ARPHRD_xxx constant.
6770 iface_get_arptype(int fd
, const char *device
, char *ebuf
)
6775 memset(&ifr
, 0, sizeof(ifr
));
6776 pcap_strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
6778 if (ioctl(fd
, SIOCGIFHWADDR
, &ifr
) == -1) {
6779 if (errno
== ENODEV
) {
6783 ret
= PCAP_ERROR_NO_SUCH_DEVICE
;
6786 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
6787 errno
, "SIOCGIFHWADDR");
6791 return ifr
.ifr_hwaddr
.sa_family
;
6794 #ifdef SO_ATTACH_FILTER
6796 fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
, int is_mmapped
)
6798 struct pcap_linux
*handlep
= handle
->priv
;
6801 register struct bpf_insn
*p
;
6806 * Make a copy of the filter, and modify that copy if
6809 prog_size
= sizeof(*handle
->fcode
.bf_insns
) * handle
->fcode
.bf_len
;
6810 len
= handle
->fcode
.bf_len
;
6811 f
= (struct bpf_insn
*)malloc(prog_size
);
6813 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6817 memcpy(f
, handle
->fcode
.bf_insns
, prog_size
);
6819 fcode
->filter
= (struct sock_filter
*) f
;
6821 for (i
= 0; i
< len
; ++i
) {
6824 * What type of instruction is this?
6826 switch (BPF_CLASS(p
->code
)) {
6830 * It's a return instruction; are we capturing
6831 * in memory-mapped mode?
6835 * No; is the snapshot length a constant,
6836 * rather than the contents of the
6839 if (BPF_MODE(p
->code
) == BPF_K
) {
6841 * Yes - if the value to be returned,
6842 * i.e. the snapshot length, is
6843 * anything other than 0, make it
6844 * MAXIMUM_SNAPLEN, so that the packet
6845 * is truncated by "recvfrom()",
6846 * not by the filter.
6848 * XXX - there's nothing we can
6849 * easily do if it's getting the
6850 * value from the accumulator; we'd
6851 * have to insert code to force
6852 * non-zero values to be
6856 p
->k
= MAXIMUM_SNAPLEN
;
6864 * It's a load instruction; is it loading
6867 switch (BPF_MODE(p
->code
)) {
6873 * Yes; are we in cooked mode?
6875 if (handlep
->cooked
) {
6877 * Yes, so we need to fix this
6880 if (fix_offset(handle
, p
) < 0) {
6882 * We failed to do so.
6883 * Return 0, so our caller
6884 * knows to punt to userland.
6894 return 1; /* we succeeded */
6898 fix_offset(pcap_t
*handle
, struct bpf_insn
*p
)
6901 * Existing references to auxiliary data shouldn't be adjusted.
6903 * Note that SKF_AD_OFF is negative, but p->k is unsigned, so
6904 * we use >= and cast SKF_AD_OFF to unsigned.
6906 if (p
->k
>= (bpf_u_int32
)SKF_AD_OFF
)
6908 if (handle
->linktype
== DLT_LINUX_SLL2
) {
6910 * What's the offset?
6912 if (p
->k
>= SLL2_HDR_LEN
) {
6914 * It's within the link-layer payload; that starts
6915 * at an offset of 0, as far as the kernel packet
6916 * filter is concerned, so subtract the length of
6917 * the link-layer header.
6919 p
->k
-= SLL2_HDR_LEN
;
6920 } else if (p
->k
== 0) {
6922 * It's the protocol field; map it to the
6923 * special magic kernel offset for that field.
6925 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
6926 } else if (p
->k
== 10) {
6928 * It's the packet type field; map it to the
6929 * special magic kernel offset for that field.
6931 p
->k
= SKF_AD_OFF
+ SKF_AD_PKTTYPE
;
6932 } else if ((bpf_int32
)(p
->k
) > 0) {
6934 * It's within the header, but it's not one of
6935 * those fields; we can't do that in the kernel,
6936 * so punt to userland.
6942 * What's the offset?
6944 if (p
->k
>= SLL_HDR_LEN
) {
6946 * It's within the link-layer payload; that starts
6947 * at an offset of 0, as far as the kernel packet
6948 * filter is concerned, so subtract the length of
6949 * the link-layer header.
6951 p
->k
-= SLL_HDR_LEN
;
6952 } else if (p
->k
== 0) {
6954 * It's the packet type field; map it to the
6955 * special magic kernel offset for that field.
6957 p
->k
= SKF_AD_OFF
+ SKF_AD_PKTTYPE
;
6958 } else if (p
->k
== 14) {
6960 * It's the protocol field; map it to the
6961 * special magic kernel offset for that field.
6963 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
6964 } else if ((bpf_int32
)(p
->k
) > 0) {
6966 * It's within the header, but it's not one of
6967 * those fields; we can't do that in the kernel,
6968 * so punt to userland.
6977 set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
)
6979 int total_filter_on
= 0;
6985 * The socket filter code doesn't discard all packets queued
6986 * up on the socket when the filter is changed; this means
6987 * that packets that don't match the new filter may show up
6988 * after the new filter is put onto the socket, if those
6989 * packets haven't yet been read.
6991 * This means, for example, that if you do a tcpdump capture
6992 * with a filter, the first few packets in the capture might
6993 * be packets that wouldn't have passed the filter.
6995 * We therefore discard all packets queued up on the socket
6996 * when setting a kernel filter. (This isn't an issue for
6997 * userland filters, as the userland filtering is done after
6998 * packets are queued up.)
7000 * To flush those packets, we put the socket in read-only mode,
7001 * and read packets from the socket until there are no more to
7004 * In order to keep that from being an infinite loop - i.e.,
7005 * to keep more packets from arriving while we're draining
7006 * the queue - we put the "total filter", which is a filter
7007 * that rejects all packets, onto the socket before draining
7010 * This code deliberately ignores any errors, so that you may
7011 * get bogus packets if an error occurs, rather than having
7012 * the filtering done in userland even if it could have been
7013 * done in the kernel.
7015 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
7016 &total_fcode
, sizeof(total_fcode
)) == 0) {
7020 * Note that we've put the total filter onto the socket.
7022 total_filter_on
= 1;
7025 * Save the socket's current mode, and put it in
7026 * non-blocking mode; we drain it by reading packets
7027 * until we get an error (which is normally a
7028 * "nothing more to be read" error).
7030 save_mode
= fcntl(handle
->fd
, F_GETFL
, 0);
7031 if (save_mode
== -1) {
7032 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
7033 PCAP_ERRBUF_SIZE
, errno
,
7034 "can't get FD flags when changing filter");
7037 if (fcntl(handle
->fd
, F_SETFL
, save_mode
| O_NONBLOCK
) < 0) {
7038 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
7039 PCAP_ERRBUF_SIZE
, errno
,
7040 "can't set nonblocking mode when changing filter");
7043 while (recv(handle
->fd
, &drain
, sizeof drain
, MSG_TRUNC
) >= 0)
7046 if (save_errno
!= EAGAIN
) {
7050 * If we can't restore the mode or reset the
7051 * kernel filter, there's nothing we can do.
7053 (void)fcntl(handle
->fd
, F_SETFL
, save_mode
);
7054 (void)reset_kernel_filter(handle
);
7055 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
7056 PCAP_ERRBUF_SIZE
, save_errno
,
7057 "recv failed when changing filter");
7060 if (fcntl(handle
->fd
, F_SETFL
, save_mode
) == -1) {
7061 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
7062 PCAP_ERRBUF_SIZE
, errno
,
7063 "can't restore FD flags when changing filter");
7069 * Now attach the new filter.
7071 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
7072 fcode
, sizeof(*fcode
));
7073 if (ret
== -1 && total_filter_on
) {
7075 * Well, we couldn't set that filter on the socket,
7076 * but we could set the total filter on the socket.
7078 * This could, for example, mean that the filter was
7079 * too big to put into the kernel, so we'll have to
7080 * filter in userland; in any case, we'll be doing
7081 * filtering in userland, so we need to remove the
7082 * total filter so we see packets.
7087 * If this fails, we're really screwed; we have the
7088 * total filter on the socket, and it won't come off.
7089 * Report it as a fatal error.
7091 if (reset_kernel_filter(handle
) == -1) {
7092 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
7093 PCAP_ERRBUF_SIZE
, errno
,
7094 "can't remove kernel total filter");
7095 return -2; /* fatal error */
7104 reset_kernel_filter(pcap_t
*handle
)
7108 * setsockopt() barfs unless it get a dummy parameter.
7109 * valgrind whines unless the value is initialized,
7110 * as it has no idea that setsockopt() ignores its
7115 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_DETACH_FILTER
,
7116 &dummy
, sizeof(dummy
));
7118 * Ignore ENOENT - it means "we don't have a filter", so there
7119 * was no filter to remove, and there's still no filter.
7121 * Also ignore ENONET, as a lot of kernel versions had a
7122 * typo where ENONET, rather than ENOENT, was returned.
7124 if (ret
== -1 && errno
!= ENOENT
&& errno
!= ENONET
)
7131 pcap_set_protocol_linux(pcap_t
*p
, int protocol
)
7133 if (pcap_check_activated(p
))
7134 return (PCAP_ERROR_ACTIVATED
);
7135 p
->opt
.protocol
= protocol
;
7140 * Libpcap version string.
7143 pcap_lib_version(void)
7145 #ifdef HAVE_PACKET_RING
7146 #if defined(HAVE_TPACKET3)
7147 return (PCAP_VERSION_STRING
" (with TPACKET_V3)");
7148 #elif defined(HAVE_TPACKET2)
7149 return (PCAP_VERSION_STRING
" (with TPACKET_V2)");
7151 return (PCAP_VERSION_STRING
" (with TPACKET_V1)");
7154 return (PCAP_VERSION_STRING
" (without TPACKET)");