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
86 #include <sys/socket.h>
87 #include <sys/ioctl.h>
88 #include <sys/utsname.h>
91 #include <linux/if_packet.h>
92 #include <linux/sockios.h>
93 #include <linux/ethtool.h>
94 #include <netinet/in.h>
95 #include <linux/if_ether.h>
97 #include <linux/if_arp.h>
98 #ifndef ARPHRD_IEEE802154
99 // Linux before 2.6.31
100 #define ARPHRD_IEEE802154 804
102 #ifndef ARPHRD_IEEE802154_MONITOR
104 #define ARPHRD_IEEE802154_MONITOR 805
106 #ifndef ARPHRD_NETLINK
108 #define ARPHRD_NETLINK 824
110 #ifndef ARPHRD_6LOWPAN
112 #define ARPHRD_6LOWPAN 825
114 #ifndef ARPHRD_VSOCKMON
116 #define ARPHRD_VSOCKMON 826
120 * ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
121 * is needed, please report it to <daniele@orlandi.com>
123 #define ARPHRD_LAPD 8445
128 #include <sys/eventfd.h>
130 #include "pcap-int.h"
131 #include "pcap-util.h"
132 #include "pcap-snf.h"
133 #include "pcap/sll.h"
134 #include "pcap/vlan.h"
135 #include "pcap/can_socketcan.h"
137 #include "diag-control.h"
140 * We require TPACKET_V2 support.
142 #ifndef TPACKET2_HDRLEN
143 #error "Libpcap will only work if TPACKET_V2 is supported; you must build for a 2.6.27 or later kernel"
146 /* check for memory mapped access availability. We assume every needed
147 * struct is defined if the macro TPACKET_HDRLEN is defined, because it
148 * uses many ring related structs and macros */
149 #ifdef TPACKET3_HDRLEN
150 # define HAVE_TPACKET3
151 #endif /* TPACKET3_HDRLEN */
154 * Not all compilers that are used to compile code to run on Linux have
155 * these builtins. For example, older versions of GCC don't, and at
156 * least some people are doing cross-builds for MIPS with older versions
159 #ifndef HAVE___ATOMIC_LOAD_N
160 #define __atomic_load_n(ptr, memory_model) (*(ptr))
162 #ifndef HAVE___ATOMIC_STORE_N
163 #define __atomic_store_n(ptr, val, memory_model) *(ptr) = (val)
166 #define packet_mmap_acquire(pkt) \
167 (__atomic_load_n(&pkt->tp_status, __ATOMIC_ACQUIRE) != TP_STATUS_KERNEL)
168 #define packet_mmap_release(pkt) \
169 (__atomic_store_n(&pkt->tp_status, TP_STATUS_KERNEL, __ATOMIC_RELEASE))
170 #define packet_mmap_v3_acquire(pkt) \
171 (__atomic_load_n(&pkt->hdr.bh1.block_status, __ATOMIC_ACQUIRE) != TP_STATUS_KERNEL)
172 #define packet_mmap_v3_release(pkt) \
173 (__atomic_store_n(&pkt->hdr.bh1.block_status, TP_STATUS_KERNEL, __ATOMIC_RELEASE))
175 #include <linux/types.h>
176 #include <linux/filter.h>
178 #ifdef HAVE_LINUX_NET_TSTAMP_H
179 #include <linux/net_tstamp.h>
183 * For checking whether a device is a bonding device.
185 #include <linux/if_bonding.h>
191 #include <linux/nl80211.h>
193 #include <netlink/genl/genl.h>
194 #include <netlink/genl/family.h>
195 #include <netlink/genl/ctrl.h>
196 #include <netlink/msg.h>
197 #include <netlink/attr.h>
198 #endif /* HAVE_LIBNL */
200 #ifndef HAVE_SOCKLEN_T
201 typedef int socklen_t
;
204 #define MAX_LINKHEADER_SIZE 256
207 * When capturing on all interfaces we use this as the buffer size.
208 * Should be bigger then all MTUs that occur in real life.
209 * 64kB should be enough for now.
211 #define BIGGER_THAN_ALL_MTUS (64*1024)
214 * Private data for capturing on Linux PF_PACKET sockets.
217 long long sysfs_dropped
; /* packets reported dropped by /sys/class/net/{if_name}/statistics/rx_{missed,fifo}_errors */
218 struct pcap_stat stat
;
220 char *device
; /* device name */
221 int filter_in_userland
; /* must filter in userland */
222 u_int blocks_to_filter_in_userland
;
223 int must_do_on_close
; /* stuff we must do when we close */
224 int timeout
; /* timeout for buffering */
225 int cooked
; /* using SOCK_DGRAM rather than SOCK_RAW */
226 int ifindex
; /* interface index of device we're bound to */
227 int lo_ifindex
; /* interface index of the loopback device */
228 int netdown
; /* we got an ENETDOWN and haven't resolved it */
229 bpf_u_int32 oldmode
; /* mode to restore when turning monitor mode off */
230 char *mondevice
; /* mac80211 monitor device we created */
231 u_char
*mmapbuf
; /* memory-mapped region pointer */
232 size_t mmapbuflen
; /* size of region */
233 int vlan_offset
; /* offset at which to insert vlan tags; if -1, don't insert */
234 u_int tp_version
; /* version of tpacket_hdr for mmaped ring */
235 u_int tp_hdrlen
; /* hdrlen of tpacket_hdr for mmaped ring */
236 u_char
*oneshot_buffer
; /* buffer for copy of packet */
237 int poll_timeout
; /* timeout to use in poll() */
239 unsigned char *current_packet
; /* Current packet within the TPACKET_V3 block. Move to next block if NULL. */
240 int packets_left
; /* Unhandled packets left within the block from previous call to pcap_read_linux_mmap_v3 in case of TPACKET_V3. */
242 int poll_breakloop_fd
; /* fd to an eventfd to break from blocking operations */
246 * Stuff to do when we close.
248 #define MUST_DELETE_MONIF 0x00000001 /* delete monitor-mode interface */
251 * Prototypes for internal functions and methods.
253 static int is_wifi(const char *);
254 static int pcap_activate_linux(pcap_t
*);
255 static int setup_socket(pcap_t
*, int);
256 static int setup_mmapped(pcap_t
*);
257 static int pcap_can_set_rfmon_linux(pcap_t
*);
258 static int pcap_inject_linux(pcap_t
*, const void *, int);
259 static int pcap_stats_linux(pcap_t
*, struct pcap_stat
*);
260 static int pcap_setfilter_linux(pcap_t
*, struct bpf_program
*);
261 static int pcap_setdirection_linux(pcap_t
*, pcap_direction_t
);
262 static int pcap_set_datalink_linux(pcap_t
*, int);
265 struct tpacket2_hdr
*h2
;
267 struct tpacket_block_desc
*h3
;
272 #define RING_GET_FRAME_AT(h, offset) (((u_char **)h->buffer)[(offset)])
273 #define RING_GET_CURRENT_FRAME(h) RING_GET_FRAME_AT(h, h->offset)
275 static void destroy_ring(pcap_t
*handle
);
276 static int create_ring(pcap_t
*handle
);
277 static int prepare_tpacket_socket(pcap_t
*handle
);
278 static int pcap_read_linux_mmap_v2(pcap_t
*, int, pcap_handler
, u_char
*);
280 static int pcap_read_linux_mmap_v3(pcap_t
*, int, pcap_handler
, u_char
*);
282 static int pcap_setnonblock_linux(pcap_t
*p
, int nonblock
);
283 static int pcap_getnonblock_linux(pcap_t
*p
);
284 static void pcapint_oneshot_linux(u_char
*user
, const struct pcap_pkthdr
*h
,
285 const u_char
*bytes
);
288 * In pre-3.0 kernels, the tp_vlan_tci field is set to whatever the
289 * vlan_tci field in the skbuff is. 0 can either mean "not on a VLAN"
290 * or "on VLAN 0". There is no flag set in the tp_status field to
291 * distinguish between them.
293 * In 3.0 and later kernels, if there's a VLAN tag present, the tp_vlan_tci
294 * field is set to the VLAN tag, and the TP_STATUS_VLAN_VALID flag is set
295 * in the tp_status field, otherwise the tp_vlan_tci field is set to 0 and
296 * the TP_STATUS_VLAN_VALID flag isn't set in the tp_status field.
298 * With a pre-3.0 kernel, we cannot distinguish between packets with no
299 * VLAN tag and packets on VLAN 0, so we will mishandle some packets, and
300 * there's nothing we can do about that.
302 * So, on those systems, which never set the TP_STATUS_VLAN_VALID flag, we
303 * continue the behavior of earlier libpcaps, wherein we treated packets
304 * with a VLAN tag of 0 as being packets without a VLAN tag rather than packets
305 * on VLAN 0. We do this by treating packets with a tp_vlan_tci of 0 and
306 * with the TP_STATUS_VLAN_VALID flag not set in tp_status as not having
307 * VLAN tags. This does the right thing on 3.0 and later kernels, and
308 * continues the old unfixably-imperfect behavior on pre-3.0 kernels.
310 * If TP_STATUS_VLAN_VALID isn't defined, we test it as the 0x10 bit; it
311 * has that value in 3.0 and later kernels.
313 #ifdef TP_STATUS_VLAN_VALID
314 #define VLAN_VALID(hdr, hv) ((hv)->tp_vlan_tci != 0 || ((hdr)->tp_status & TP_STATUS_VLAN_VALID))
317 * This is being compiled on a system that lacks TP_STATUS_VLAN_VALID,
318 * so we test with the value it has in the 3.0 and later kernels, so
319 * we can test it if we're running on a system that has it. (If we're
320 * running on a system that doesn't have it, it won't be set in the
321 * tp_status field, so the tests of it will always fail; that means
322 * we behave the way we did before we introduced this macro.)
324 #define VLAN_VALID(hdr, hv) ((hv)->tp_vlan_tci != 0 || ((hdr)->tp_status & 0x10))
327 #ifdef TP_STATUS_VLAN_TPID_VALID
328 # define VLAN_TPID(hdr, hv) (((hv)->tp_vlan_tpid || ((hdr)->tp_status & TP_STATUS_VLAN_TPID_VALID)) ? (hv)->tp_vlan_tpid : ETH_P_8021Q)
330 # define VLAN_TPID(hdr, hv) ETH_P_8021Q
334 * Required select timeout if we're polling for an "interface disappeared"
335 * indication - 1 millisecond.
337 static const struct timeval netdown_timeout
= {
338 0, 1000 /* 1000 microseconds = 1 millisecond */
342 * Wrap some ioctl calls
344 static int iface_get_id(int fd
, const char *device
, char *ebuf
);
345 static int iface_get_mtu(int fd
, const char *device
, char *ebuf
);
346 static int iface_get_arptype(int fd
, const char *device
, char *ebuf
);
347 static int iface_bind(int fd
, int ifindex
, char *ebuf
, int protocol
);
348 static int enter_rfmon_mode(pcap_t
*handle
, int sock_fd
,
350 static int iface_get_ts_types(const char *device
, pcap_t
*handle
,
352 static int iface_get_offload(pcap_t
*handle
);
354 static int fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
);
355 static int fix_offset(pcap_t
*handle
, struct bpf_insn
*p
);
356 static int set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
);
357 static int reset_kernel_filter(pcap_t
*handle
);
359 static struct sock_filter total_insn
360 = BPF_STMT(BPF_RET
| BPF_K
, 0);
361 static struct sock_fprog total_fcode
362 = { 1, &total_insn
};
364 static int iface_dsa_get_proto_info(const char *device
, pcap_t
*handle
);
367 pcapint_create_interface(const char *device
, char *ebuf
)
371 handle
= PCAP_CREATE_COMMON(ebuf
, struct pcap_linux
);
375 handle
->activate_op
= pcap_activate_linux
;
376 handle
->can_set_rfmon_op
= pcap_can_set_rfmon_linux
;
379 * See what time stamp types we support.
381 if (iface_get_ts_types(device
, handle
, ebuf
) == -1) {
387 * We claim that we support microsecond and nanosecond time
390 * XXX - with adapter-supplied time stamps, can we choose
391 * microsecond or nanosecond time stamps on arbitrary
394 handle
->tstamp_precision_list
= malloc(2 * sizeof(u_int
));
395 if (handle
->tstamp_precision_list
== NULL
) {
396 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
401 handle
->tstamp_precision_list
[0] = PCAP_TSTAMP_PRECISION_MICRO
;
402 handle
->tstamp_precision_list
[1] = PCAP_TSTAMP_PRECISION_NANO
;
403 handle
->tstamp_precision_count
= 2;
406 * Start out with the breakloop handle not open; we don't
407 * need it until we're activated and ready to capture.
409 struct pcap_linux
*handlep
= handle
->priv
;
410 handlep
->poll_breakloop_fd
= -1;
417 * If interface {if_name} is a mac80211 driver, the file
418 * /sys/class/net/{if_name}/phy80211 is a symlink to
419 * /sys/class/ieee80211/{phydev_name}, for some {phydev_name}.
421 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
422 * least, has a "wmaster0" device and a "wlan0" device; the
423 * latter is the one with the IP address. Both show up in
424 * "tcpdump -D" output. Capturing on the wmaster0 device
425 * captures with 802.11 headers.
427 * airmon-ng searches through /sys/class/net for devices named
428 * monN, starting with mon0; as soon as one *doesn't* exist,
429 * it chooses that as the monitor device name. If the "iw"
430 * command exists, it does
432 * iw dev {if_name} interface add {monif_name} type monitor
434 * where {monif_name} is the monitor device. It then (sigh) sleeps
435 * .1 second, and then configures the device up. Otherwise, if
436 * /sys/class/ieee80211/{phydev_name}/add_iface is a file, it writes
437 * {mondev_name}, without a newline, to that file, and again (sigh)
438 * sleeps .1 second, and then iwconfig's that device into monitor
439 * mode and configures it up. Otherwise, you can't do monitor mode.
441 * All these devices are "glued" together by having the
442 * /sys/class/net/{if_name}/phy80211 links pointing to the same
443 * place, so, given a wmaster, wlan, or mon device, you can
444 * find the other devices by looking for devices with
445 * the same phy80211 link.
447 * To turn monitor mode off, delete the monitor interface,
450 * iw dev {monif_name} interface del
452 * or by sending {monif_name}, with no NL, down
453 * /sys/class/ieee80211/{phydev_name}/remove_iface
455 * Note: if you try to create a monitor device named "monN", and
456 * there's already a "monN" device, it fails, as least with
457 * the netlink interface (which is what iw uses), with a return
458 * value of -ENFILE. (Return values are negative errnos.) We
459 * could probably use that to find an unused device.
461 * Yes, you can have multiple monitor devices for a given
466 * Is this a mac80211 device? If so, fill in the physical device path and
467 * return 1; if not, return 0. On an error, fill in handle->errbuf and
471 get_mac80211_phydev(pcap_t
*handle
, const char *device
, char *phydev_path
,
472 size_t phydev_max_pathlen
)
478 * Generate the path string for the symlink to the physical device.
480 if (asprintf(&pathstr
, "/sys/class/net/%s/phy80211", device
) == -1) {
481 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
482 "%s: Can't generate path name string for /sys/class/net device",
486 bytes_read
= readlink(pathstr
, phydev_path
, phydev_max_pathlen
);
487 if (bytes_read
== -1) {
488 if (errno
== ENOENT
) {
490 * This either means that the directory
491 * /sys/class/net/{device} exists but doesn't
492 * have anything named "phy80211" in it,
493 * in which case it's not a mac80211 device,
494 * or that the directory doesn't exist,
495 * in which case the device doesn't exist.
497 * Directly check whether the directory
503 if (asprintf(&pathstr
, "/sys/class/net/%s", device
) == -1) {
504 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
505 "%s: Can't generate path name string for /sys/class/net device",
509 if (stat(pathstr
, &statb
) == -1) {
510 if (errno
== ENOENT
) {
514 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
515 "%s: %s doesn't exist",
518 return PCAP_ERROR_NO_SUCH_DEVICE
;
520 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
521 "%s: Can't stat %s: %s",
522 device
, pathstr
, strerror(errno
));
528 * Path to the directory that would contain
529 * "phy80211" exists, but "phy80211" doesn't
530 * exist; that means it's not a mac80211
536 if (errno
== EINVAL
) {
538 * Exists, but it's not a symlink; assume that
539 * means it's not a mac80211 device.
544 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
545 errno
, "%s: Can't readlink %s", device
, pathstr
);
550 phydev_path
[bytes_read
] = '\0';
554 struct nl80211_state
{
555 struct nl_sock
*nl_sock
;
556 struct nl_cache
*nl_cache
;
557 struct genl_family
*nl80211
;
561 nl80211_init(pcap_t
*handle
, struct nl80211_state
*state
, const char *device
)
565 state
->nl_sock
= nl_socket_alloc();
566 if (!state
->nl_sock
) {
567 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
568 "%s: failed to allocate netlink handle", device
);
572 if (genl_connect(state
->nl_sock
)) {
573 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
574 "%s: failed to connect to generic netlink", device
);
575 goto out_handle_destroy
;
578 err
= genl_ctrl_alloc_cache(state
->nl_sock
, &state
->nl_cache
);
580 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
581 "%s: failed to allocate generic netlink cache: %s",
582 device
, nl_geterror(-err
));
583 goto out_handle_destroy
;
586 state
->nl80211
= genl_ctrl_search_by_name(state
->nl_cache
, "nl80211");
587 if (!state
->nl80211
) {
588 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
589 "%s: nl80211 not found", device
);
596 nl_cache_free(state
->nl_cache
);
598 nl_socket_free(state
->nl_sock
);
603 nl80211_cleanup(struct nl80211_state
*state
)
605 genl_family_put(state
->nl80211
);
606 nl_cache_free(state
->nl_cache
);
607 nl_socket_free(state
->nl_sock
);
611 del_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
612 const char *device
, const char *mondevice
);
615 if_type_cb(struct nl_msg
*msg
, void* arg
)
617 struct nlmsghdr
* ret_hdr
= nlmsg_hdr(msg
);
618 struct nlattr
*tb_msg
[NL80211_ATTR_MAX
+ 1];
619 int *type
= (int*)arg
;
621 struct genlmsghdr
*gnlh
= (struct genlmsghdr
*) nlmsg_data(ret_hdr
);
623 nla_parse(tb_msg
, NL80211_ATTR_MAX
, genlmsg_attrdata(gnlh
, 0),
624 genlmsg_attrlen(gnlh
, 0), NULL
);
626 if (!tb_msg
[NL80211_ATTR_IFTYPE
]) {
630 *type
= nla_get_u32(tb_msg
[NL80211_ATTR_IFTYPE
]);
635 get_if_type(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
636 const char *device
, int *type
)
642 ifindex
= iface_get_id(sock_fd
, device
, handle
->errbuf
);
646 struct nl_cb
*cb
= nl_cb_alloc(NL_CB_DEFAULT
);
647 nl_cb_set(cb
, NL_CB_VALID
, NL_CB_CUSTOM
, if_type_cb
, (void*)type
);
651 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
652 "%s: failed to allocate netlink msg", device
);
656 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
657 0, NL80211_CMD_GET_INTERFACE
, 0);
658 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
660 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
662 if (err
== -NLE_FAILURE
) {
664 * Device not available; our caller should just
665 * keep trying. (libnl 2.x maps ENFILE to
666 * NLE_FAILURE; it can also map other errors
667 * to that, but there's not much we can do
674 * Real failure, not just "that device is not
677 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
678 "%s: nl_send_auto_complete failed getting interface type: %s",
679 device
, nl_geterror(-err
));
685 nl_recvmsgs(state
->nl_sock
, cb
);
695 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
696 "%s: nl_put failed getting interface type",
703 add_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
704 const char *device
, const char *mondevice
)
706 struct pcap_linux
*handlep
= handle
->priv
;
711 ifindex
= iface_get_id(sock_fd
, device
, handle
->errbuf
);
717 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
718 "%s: failed to allocate netlink msg", device
);
722 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
723 0, NL80211_CMD_NEW_INTERFACE
, 0);
724 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
726 NLA_PUT_STRING(msg
, NL80211_ATTR_IFNAME
, mondevice
);
728 NLA_PUT_U32(msg
, NL80211_ATTR_IFTYPE
, NL80211_IFTYPE_MONITOR
);
730 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
732 if (err
== -NLE_FAILURE
) {
734 * Device not available; our caller should just
735 * keep trying. (libnl 2.x maps ENFILE to
736 * NLE_FAILURE; it can also map other errors
737 * to that, but there's not much we can do
744 * Real failure, not just "that device is not
747 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
748 "%s: nl_send_auto_complete failed adding %s interface: %s",
749 device
, mondevice
, nl_geterror(-err
));
754 err
= nl_wait_for_ack(state
->nl_sock
);
756 if (err
== -NLE_FAILURE
) {
758 * Device not available; our caller should just
759 * keep trying. (libnl 2.x maps ENFILE to
760 * NLE_FAILURE; it can also map other errors
761 * to that, but there's not much we can do
768 * Real failure, not just "that device is not
771 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
772 "%s: nl_wait_for_ack failed adding %s interface: %s",
773 device
, mondevice
, nl_geterror(-err
));
785 * Try to remember the monitor device.
787 handlep
->mondevice
= strdup(mondevice
);
788 if (handlep
->mondevice
== NULL
) {
789 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
792 * Get rid of the monitor device.
794 del_mon_if(handle
, sock_fd
, state
, device
, mondevice
);
800 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
801 "%s: nl_put failed adding %s interface",
808 del_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
809 const char *device
, const char *mondevice
)
815 ifindex
= iface_get_id(sock_fd
, mondevice
, handle
->errbuf
);
821 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
822 "%s: failed to allocate netlink msg", device
);
826 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
827 0, NL80211_CMD_DEL_INTERFACE
, 0);
828 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
830 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
832 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
833 "%s: nl_send_auto_complete failed deleting %s interface: %s",
834 device
, mondevice
, nl_geterror(-err
));
838 err
= nl_wait_for_ack(state
->nl_sock
);
840 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
841 "%s: nl_wait_for_ack failed deleting %s interface: %s",
842 device
, mondevice
, nl_geterror(-err
));
854 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
855 "%s: nl_put failed deleting %s interface",
860 #endif /* HAVE_LIBNL */
862 static int pcap_protocol(pcap_t
*handle
)
866 protocol
= handle
->opt
.protocol
;
868 protocol
= ETH_P_ALL
;
870 return htons(protocol
);
874 pcap_can_set_rfmon_linux(pcap_t
*handle
)
877 char phydev_path
[PATH_MAX
+1];
881 if (strcmp(handle
->opt
.device
, "any") == 0) {
883 * Monitor mode makes no sense on the "any" device.
890 * Bleah. There doesn't seem to be a way to ask a mac80211
891 * device, through libnl, whether it supports monitor mode;
892 * we'll just check whether the device appears to be a
893 * mac80211 device and, if so, assume the device supports
896 ret
= get_mac80211_phydev(handle
, handle
->opt
.device
, phydev_path
,
899 return ret
; /* error */
901 return 1; /* mac80211 device */
908 * Grabs the number of missed packets by the interface from
909 * /sys/class/net/{if_name}/statistics/rx_{missed,fifo}_errors.
911 * Compared to /proc/net/dev this avoids counting software drops,
912 * but may be unimplemented and just return 0.
913 * The author has found no straightforward way to check for support.
916 linux_get_stat(const char * if_name
, const char * stat
) {
919 char buffer
[PATH_MAX
];
921 snprintf(buffer
, sizeof(buffer
), "/sys/class/net/%s/statistics/%s", if_name
, stat
);
922 fd
= open(buffer
, O_RDONLY
);
926 bytes_read
= read(fd
, buffer
, sizeof(buffer
) - 1);
928 if (bytes_read
== -1)
930 buffer
[bytes_read
] = '\0';
932 return strtoll(buffer
, NULL
, 10);
936 linux_if_drops(const char * if_name
)
938 long long int missed
= linux_get_stat(if_name
, "rx_missed_errors");
939 long long int fifo
= linux_get_stat(if_name
, "rx_fifo_errors");
940 return missed
+ fifo
;
945 * Monitor mode is kind of interesting because we have to reset the
946 * interface before exiting. The problem can't really be solved without
947 * some daemon taking care of managing usage counts. If we put the
948 * interface into monitor mode, we set a flag indicating that we must
949 * take it out of that mode when the interface is closed, and, when
950 * closing the interface, if that flag is set we take it out of monitor
954 static void pcap_cleanup_linux( pcap_t
*handle
)
956 struct pcap_linux
*handlep
= handle
->priv
;
958 struct nl80211_state nlstate
;
960 #endif /* HAVE_LIBNL */
962 if (handlep
->must_do_on_close
!= 0) {
964 * There's something we have to do when closing this
968 if (handlep
->must_do_on_close
& MUST_DELETE_MONIF
) {
969 ret
= nl80211_init(handle
, &nlstate
, handlep
->device
);
971 ret
= del_mon_if(handle
, handle
->fd
, &nlstate
,
972 handlep
->device
, handlep
->mondevice
);
973 nl80211_cleanup(&nlstate
);
977 "Can't delete monitor interface %s (%s).\n"
978 "Please delete manually.\n",
979 handlep
->mondevice
, handle
->errbuf
);
982 #endif /* HAVE_LIBNL */
985 * Take this pcap out of the list of pcaps for which we
986 * have to take the interface out of some mode.
988 pcapint_remove_from_pcaps_to_close(handle
);
991 if (handle
->fd
!= -1) {
993 * Destroy the ring buffer (assuming we've set it up),
994 * and unmap it if it's mapped.
996 destroy_ring(handle
);
999 if (handlep
->oneshot_buffer
!= NULL
) {
1000 munmap(handlep
->oneshot_buffer
, handle
->snapshot
);
1001 handlep
->oneshot_buffer
= NULL
;
1004 if (handlep
->mondevice
!= NULL
) {
1005 free(handlep
->mondevice
);
1006 handlep
->mondevice
= NULL
;
1008 if (handlep
->device
!= NULL
) {
1009 free(handlep
->device
);
1010 handlep
->device
= NULL
;
1013 if (handlep
->poll_breakloop_fd
!= -1) {
1014 close(handlep
->poll_breakloop_fd
);
1015 handlep
->poll_breakloop_fd
= -1;
1017 pcapint_cleanup_live_common(handle
);
1020 #ifdef HAVE_TPACKET3
1022 * Some versions of TPACKET_V3 have annoying bugs/misfeatures
1023 * around which we have to work. Determine if we have those
1025 * 3.19 is the first release with a fixed version of
1026 * TPACKET_V3. We treat anything before that as
1027 * not having a fixed version; that may really mean
1028 * it has *no* version.
1030 static int has_broken_tpacket_v3(void)
1032 struct utsname utsname
;
1033 const char *release
;
1035 int matches
, verlen
;
1037 /* No version information, assume broken. */
1038 if (uname(&utsname
) == -1)
1040 release
= utsname
.release
;
1042 /* A malformed version, ditto. */
1043 matches
= sscanf(release
, "%ld.%ld%n", &major
, &minor
, &verlen
);
1046 if (release
[verlen
] != '.' && release
[verlen
] != '\0')
1049 /* OK, a fixed version. */
1050 if (major
> 3 || (major
== 3 && minor
>= 19))
1059 * Set the timeout to be used in poll() with memory-mapped packet capture.
1062 set_poll_timeout(struct pcap_linux
*handlep
)
1064 #ifdef HAVE_TPACKET3
1065 int broken_tpacket_v3
= has_broken_tpacket_v3();
1067 if (handlep
->timeout
== 0) {
1068 #ifdef HAVE_TPACKET3
1070 * XXX - due to a set of (mis)features in the TPACKET_V3
1071 * kernel code prior to the 3.19 kernel, blocking forever
1072 * with a TPACKET_V3 socket can, if few packets are
1073 * arriving and passing the socket filter, cause most
1074 * packets to be dropped. See libpcap issue #335 for the
1075 * full painful story.
1077 * The workaround is to have poll() time out very quickly,
1078 * so we grab the frames handed to us, and return them to
1081 if (handlep
->tp_version
== TPACKET_V3
&& broken_tpacket_v3
)
1082 handlep
->poll_timeout
= 1; /* don't block for very long */
1085 handlep
->poll_timeout
= -1; /* block forever */
1086 } else if (handlep
->timeout
> 0) {
1087 #ifdef HAVE_TPACKET3
1089 * For TPACKET_V3, the timeout is handled by the kernel,
1090 * so block forever; that way, we don't get extra timeouts.
1091 * Don't do that if we have a broken TPACKET_V3, though.
1093 if (handlep
->tp_version
== TPACKET_V3
&& !broken_tpacket_v3
)
1094 handlep
->poll_timeout
= -1; /* block forever, let TPACKET_V3 wake us up */
1097 handlep
->poll_timeout
= handlep
->timeout
; /* block for that amount of time */
1100 * Non-blocking mode; we call poll() to pick up error
1101 * indications, but we don't want it to wait for
1104 handlep
->poll_timeout
= 0;
1108 static void pcap_breakloop_linux(pcap_t
*handle
)
1110 pcapint_breakloop_common(handle
);
1111 struct pcap_linux
*handlep
= handle
->priv
;
1115 if (handlep
->poll_breakloop_fd
!= -1) {
1117 * XXX - pcap_breakloop() doesn't have a return value,
1118 * so we can't indicate an error.
1120 DIAG_OFF_WARN_UNUSED_RESULT
1121 (void)write(handlep
->poll_breakloop_fd
, &value
, sizeof(value
));
1122 DIAG_ON_WARN_UNUSED_RESULT
1127 * Set the offset at which to insert VLAN tags.
1128 * That should be the offset of the type field.
1131 set_vlan_offset(pcap_t
*handle
)
1133 struct pcap_linux
*handlep
= handle
->priv
;
1135 switch (handle
->linktype
) {
1139 * The type field is after the destination and source
1142 handlep
->vlan_offset
= 2 * ETH_ALEN
;
1147 * The type field is in the last 2 bytes of the
1148 * DLT_LINUX_SLL header.
1150 handlep
->vlan_offset
= SLL_HDR_LEN
- 2;
1154 handlep
->vlan_offset
= -1; /* unknown */
1160 pcap_activate_linux(pcap_t
*handle
)
1162 struct pcap_linux
*handlep
= handle
->priv
;
1169 device
= handle
->opt
.device
;
1172 * Start out assuming no warnings.
1177 * Make sure the name we were handed will fit into the ioctls we
1178 * might perform on the device; if not, return a "No such device"
1179 * indication, as the Linux kernel shouldn't support creating
1180 * a device whose name won't fit into those ioctls.
1182 * "Will fit" means "will fit, complete with a null terminator",
1183 * so if the length, which does *not* include the null terminator,
1184 * is greater than *or equal to* the size of the field into which
1185 * we'll be copying it, that won't fit.
1187 if (strlen(device
) >= sizeof(ifr
.ifr_name
)) {
1189 * There's nothing more to say, so clear the error
1192 handle
->errbuf
[0] = '\0';
1193 status
= PCAP_ERROR_NO_SUCH_DEVICE
;
1198 * Turn a negative snapshot value (invalid), a snapshot value of
1199 * 0 (unspecified), or a value bigger than the normal maximum
1200 * value, into the maximum allowed value.
1202 * If some application really *needs* a bigger snapshot
1203 * length, we should just increase MAXIMUM_SNAPLEN.
1205 if (handle
->snapshot
<= 0 || handle
->snapshot
> MAXIMUM_SNAPLEN
)
1206 handle
->snapshot
= MAXIMUM_SNAPLEN
;
1208 handlep
->device
= strdup(device
);
1209 if (handlep
->device
== NULL
) {
1210 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1212 status
= PCAP_ERROR
;
1217 * The "any" device is a special device which causes us not
1218 * to bind to a particular device and thus to look at all
1221 is_any_device
= (strcmp(device
, "any") == 0);
1222 if (is_any_device
) {
1223 if (handle
->opt
.promisc
) {
1224 handle
->opt
.promisc
= 0;
1225 /* Just a warning. */
1226 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1227 "Promiscuous mode not supported on the \"any\" device");
1228 status
= PCAP_WARNING_PROMISC_NOTSUP
;
1232 /* copy timeout value */
1233 handlep
->timeout
= handle
->opt
.timeout
;
1236 * If we're in promiscuous mode, then we probably want
1237 * to see when the interface drops packets too, so get an
1238 * initial count from
1239 * /sys/class/net/{if_name}/statistics/rx_{missed,fifo}_errors
1241 if (handle
->opt
.promisc
)
1242 handlep
->sysfs_dropped
= linux_if_drops(handlep
->device
);
1245 * If the "any" device is specified, try to open a SOCK_DGRAM.
1246 * Otherwise, open a SOCK_RAW.
1248 ret
= setup_socket(handle
, is_any_device
);
1251 * Fatal error; the return value is the error code,
1252 * and handle->errbuf has been set to an appropriate
1260 * We got a warning; return that, as handle->errbuf
1261 * might have been overwritten by this warning.
1267 * Success (possibly with a warning).
1269 * First, try to allocate an event FD for breakloop, if
1270 * we're not going to start in non-blocking mode.
1272 if (!handle
->opt
.nonblock
) {
1273 handlep
->poll_breakloop_fd
= eventfd(0, EFD_NONBLOCK
);
1274 if (handlep
->poll_breakloop_fd
== -1) {
1278 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
1279 PCAP_ERRBUF_SIZE
, errno
, "could not open eventfd");
1280 status
= PCAP_ERROR
;
1287 * Try to set up memory-mapped access.
1289 ret
= setup_mmapped(handle
);
1292 * We failed to set up to use it, or the
1293 * kernel supports it, but we failed to
1294 * enable it. The return value is the
1295 * error status to return and, if it's
1296 * PCAP_ERROR, handle->errbuf contains
1297 * the error message.
1304 * We got a warning; return that, as handle->errbuf
1305 * might have been overwritten by this warning.
1311 * We succeeded. status has been set to the status to return,
1312 * which might be 0, or might be a PCAP_WARNING_ value.
1315 * Now that we have activated the mmap ring, we can
1316 * set the correct protocol.
1318 if ((ret
= iface_bind(handle
->fd
, handlep
->ifindex
,
1319 handle
->errbuf
, pcap_protocol(handle
))) != 0) {
1324 handle
->inject_op
= pcap_inject_linux
;
1325 handle
->setfilter_op
= pcap_setfilter_linux
;
1326 handle
->setdirection_op
= pcap_setdirection_linux
;
1327 handle
->set_datalink_op
= pcap_set_datalink_linux
;
1328 handle
->setnonblock_op
= pcap_setnonblock_linux
;
1329 handle
->getnonblock_op
= pcap_getnonblock_linux
;
1330 handle
->cleanup_op
= pcap_cleanup_linux
;
1331 handle
->stats_op
= pcap_stats_linux
;
1332 handle
->breakloop_op
= pcap_breakloop_linux
;
1334 switch (handlep
->tp_version
) {
1337 handle
->read_op
= pcap_read_linux_mmap_v2
;
1339 #ifdef HAVE_TPACKET3
1341 handle
->read_op
= pcap_read_linux_mmap_v3
;
1345 handle
->oneshot_callback
= pcapint_oneshot_linux
;
1346 handle
->selectable_fd
= handle
->fd
;
1351 pcap_cleanup_linux(handle
);
1356 pcap_set_datalink_linux(pcap_t
*handle
, int dlt
)
1358 handle
->linktype
= dlt
;
1361 * Update the offset at which to insert VLAN tags for the
1362 * new link-layer type.
1364 set_vlan_offset(handle
);
1370 * linux_check_direction()
1372 * Do checks based on packet direction.
1375 linux_check_direction(const pcap_t
*handle
, const struct sockaddr_ll
*sll
)
1377 struct pcap_linux
*handlep
= handle
->priv
;
1379 if (sll
->sll_pkttype
== PACKET_OUTGOING
) {
1382 * If this is from the loopback device, reject it;
1383 * we'll see the packet as an incoming packet as well,
1384 * and we don't want to see it twice.
1386 if (sll
->sll_ifindex
== handlep
->lo_ifindex
)
1390 * If this is an outgoing CAN or CAN FD frame, and
1391 * the user doesn't only want outgoing packets,
1392 * reject it; CAN devices and drivers, and the CAN
1393 * stack, always arrange to loop back transmitted
1394 * packets, so they also appear as incoming packets.
1395 * We don't want duplicate packets, and we can't
1396 * easily distinguish packets looped back by the CAN
1397 * layer than those received by the CAN layer, so we
1398 * eliminate this packet instead.
1400 * We check whether this is a CAN or CAN FD frame
1401 * by checking whether the device's hardware type
1404 if (sll
->sll_hatype
== ARPHRD_CAN
&&
1405 handle
->direction
!= PCAP_D_OUT
)
1409 * If the user only wants incoming packets, reject it.
1411 if (handle
->direction
== PCAP_D_IN
)
1416 * If the user only wants outgoing packets, reject it.
1418 if (handle
->direction
== PCAP_D_OUT
)
1425 * Check whether the device to which the pcap_t is bound still exists.
1426 * We do so by asking what address the socket is bound to, and checking
1427 * whether the ifindex in the address is -1, meaning "that device is gone",
1428 * or some other value, meaning "that device still exists".
1431 device_still_exists(pcap_t
*handle
)
1433 struct pcap_linux
*handlep
= handle
->priv
;
1434 struct sockaddr_ll addr
;
1438 * If handlep->ifindex is -1, the socket isn't bound, meaning
1439 * we're capturing on the "any" device; that device never
1440 * disappears. (It should also never be configured down, so
1441 * we shouldn't even get here, but let's make sure.)
1443 if (handlep
->ifindex
== -1)
1444 return (1); /* it's still here */
1447 * OK, now try to get the address for the socket.
1449 addr_len
= sizeof (addr
);
1450 if (getsockname(handle
->fd
, (struct sockaddr
*) &addr
, &addr_len
) == -1) {
1452 * Error - report an error and return -1.
1454 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1455 errno
, "getsockname failed");
1458 if (addr
.sll_ifindex
== -1) {
1460 * This means the device went away.
1466 * The device presumably just went down.
1472 pcap_inject_linux(pcap_t
*handle
, const void *buf
, int size
)
1474 struct pcap_linux
*handlep
= handle
->priv
;
1477 if (handlep
->ifindex
== -1) {
1479 * We don't support sending on the "any" device.
1481 pcapint_strlcpy(handle
->errbuf
,
1482 "Sending packets isn't supported on the \"any\" device",
1487 if (handlep
->cooked
) {
1489 * We don't support sending on cooked-mode sockets.
1491 * XXX - how do you send on a bound cooked-mode
1493 * Is a "sendto()" required there?
1495 pcapint_strlcpy(handle
->errbuf
,
1496 "Sending packets isn't supported in cooked mode",
1501 ret
= (int)send(handle
->fd
, buf
, size
, 0);
1503 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1511 * Get the statistics for the given packet capture handle.
1514 pcap_stats_linux(pcap_t
*handle
, struct pcap_stat
*stats
)
1516 struct pcap_linux
*handlep
= handle
->priv
;
1517 #ifdef HAVE_TPACKET3
1519 * For sockets using TPACKET_V2, the extra stuff at the end
1520 * of a struct tpacket_stats_v3 will not be filled in, and
1521 * we don't look at it so this is OK even for those sockets.
1522 * In addition, the PF_PACKET socket code in the kernel only
1523 * uses the length parameter to compute how much data to
1524 * copy out and to indicate how much data was copied out, so
1525 * it's OK to base it on the size of a struct tpacket_stats.
1527 * XXX - it's probably OK, in fact, to just use a
1528 * struct tpacket_stats for V3 sockets, as we don't
1529 * care about the tp_freeze_q_cnt stat.
1531 struct tpacket_stats_v3 kstats
;
1532 #else /* HAVE_TPACKET3 */
1533 struct tpacket_stats kstats
;
1534 #endif /* HAVE_TPACKET3 */
1535 socklen_t len
= sizeof (struct tpacket_stats
);
1537 long long if_dropped
= 0;
1540 * To fill in ps_ifdrop, we parse
1541 * /sys/class/net/{if_name}/statistics/rx_{missed,fifo}_errors
1544 if (handle
->opt
.promisc
)
1547 * XXX - is there any reason to do this by remembering
1548 * the last counts value, subtracting it from the
1549 * current counts value, and adding that to stat.ps_ifdrop,
1550 * maintaining stat.ps_ifdrop as a count, rather than just
1551 * saving the *initial* counts value and setting
1552 * stat.ps_ifdrop to the difference between the current
1553 * value and the initial value?
1555 * One reason might be to handle the count wrapping
1556 * around, on platforms where the count is 32 bits
1557 * and where you might get more than 2^32 dropped
1558 * packets; is there any other reason?
1560 * (We maintain the count as a long long int so that,
1561 * if the kernel maintains the counts as 64-bit even
1562 * on 32-bit platforms, we can handle the real count.
1564 * Unfortunately, we can't report 64-bit counts; we
1565 * need a better API for reporting statistics, such as
1566 * one that reports them in a style similar to the
1567 * pcapng Interface Statistics Block, so that 1) the
1568 * counts are 64-bit, 2) it's easier to add new statistics
1569 * without breaking the ABI, and 3) it's easier to
1570 * indicate to a caller that wants one particular
1571 * statistic that it's not available by just not supplying
1574 if_dropped
= handlep
->sysfs_dropped
;
1575 handlep
->sysfs_dropped
= linux_if_drops(handlep
->device
);
1576 handlep
->stat
.ps_ifdrop
+= (u_int
)(handlep
->sysfs_dropped
- if_dropped
);
1580 * Try to get the packet counts from the kernel.
1582 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_STATISTICS
,
1583 &kstats
, &len
) > -1) {
1585 * "ps_recv" counts only packets that *passed* the
1586 * filter, not packets that didn't pass the filter.
1587 * This includes packets later dropped because we
1588 * ran out of buffer space.
1590 * "ps_drop" counts packets dropped because we ran
1591 * out of buffer space. It doesn't count packets
1592 * dropped by the interface driver. It counts only
1593 * packets that passed the filter.
1595 * See above for ps_ifdrop.
1597 * Both statistics include packets not yet read from
1598 * the kernel by libpcap, and thus not yet seen by
1601 * In "linux/net/packet/af_packet.c", at least in 2.6.27
1602 * through 5.6 kernels, "tp_packets" is incremented for
1603 * every packet that passes the packet filter *and* is
1604 * successfully copied to the ring buffer; "tp_drops" is
1605 * incremented for every packet dropped because there's
1606 * not enough free space in the ring buffer.
1608 * When the statistics are returned for a PACKET_STATISTICS
1609 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
1610 * so that "tp_packets" counts all packets handed to
1611 * the PF_PACKET socket, including packets dropped because
1612 * there wasn't room on the socket buffer - but not
1613 * including packets that didn't pass the filter.
1615 * In the BSD BPF, the count of received packets is
1616 * incremented for every packet handed to BPF, regardless
1617 * of whether it passed the filter.
1619 * We can't make "pcap_stats()" work the same on both
1620 * platforms, but the best approximation is to return
1621 * "tp_packets" as the count of packets and "tp_drops"
1622 * as the count of drops.
1624 * Keep a running total because each call to
1625 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
1626 * resets the counters to zero.
1628 handlep
->stat
.ps_recv
+= kstats
.tp_packets
;
1629 handlep
->stat
.ps_drop
+= kstats
.tp_drops
;
1630 *stats
= handlep
->stat
;
1634 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
, errno
,
1635 "failed to get statistics from socket");
1640 * A PF_PACKET socket can be bound to any network interface.
1643 can_be_bound(const char *name _U_
)
1649 * Get a socket to use with various interface ioctls.
1652 get_if_ioctl_socket(void)
1657 * This is a bit ugly.
1659 * There isn't a socket type that's guaranteed to work.
1661 * AF_NETLINK will work *if* you have Netlink configured into the
1662 * kernel (can it be configured out if you have any networking
1663 * support at all?) *and* if you're running a sufficiently recent
1664 * kernel, but not all the kernels we support are sufficiently
1665 * recent - that feature was introduced in Linux 4.6.
1667 * AF_UNIX will work *if* you have UNIX-domain sockets configured
1668 * into the kernel and *if* you're not on a system that doesn't
1669 * allow them - some SELinux systems don't allow you create them.
1670 * Most systems probably have them configured in, but not all systems
1671 * have them configured in and allow them to be created.
1673 * AF_INET will work *if* you have IPv4 configured into the kernel,
1674 * but, apparently, some systems have network adapters but have
1675 * kernels without IPv4 support.
1677 * AF_INET6 will work *if* you have IPv6 configured into the
1678 * kernel, but if you don't have AF_INET, you might not have
1679 * AF_INET6, either (that is, independently on its own grounds).
1681 * AF_PACKET would work, except that some of these calls should
1682 * work even if you *don't* have capture permission (you should be
1683 * able to enumerate interfaces and get information about them
1684 * without capture permission; you shouldn't get a failure until
1685 * you try pcap_activate()). (If you don't allow programs to
1686 * get as much information as possible about interfaces if you
1687 * don't have permission to capture, you run the risk of users
1688 * asking "why isn't it showing XXX" - or, worse, if you don't
1689 * show interfaces *at all* if you don't have permission to
1690 * capture on them, "why do no interfaces show up?" - when the
1691 * real problem is a permissions problem. Error reports of that
1692 * type require a lot more back-and-forth to debug, as evidenced
1693 * by many Wireshark bugs/mailing list questions/Q&A questions.)
1697 * we first try an AF_NETLINK socket, where "try" includes
1698 * "try to do a device ioctl on it", as, in the future, once
1699 * pre-4.6 kernels are sufficiently rare, that will probably
1700 * be the mechanism most likely to work;
1702 * if that fails, we try an AF_UNIX socket, as that's less
1703 * likely to be configured out on a networking-capable system
1706 * if that fails, we try an AF_INET6 socket;
1708 * if that fails, we try an AF_INET socket.
1710 fd
= socket(AF_NETLINK
, SOCK_RAW
, NETLINK_GENERIC
);
1713 * OK, let's make sure we can do an SIOCGIFNAME
1718 memset(&ifr
, 0, sizeof(ifr
));
1719 if (ioctl(fd
, SIOCGIFNAME
, &ifr
) == 0 ||
1720 errno
!= EOPNOTSUPP
) {
1722 * It succeeded, or failed for some reason
1723 * other than "netlink sockets don't support
1724 * device ioctls". Go with the AF_NETLINK
1731 * OK, that didn't work, so it's as bad as "netlink
1732 * sockets aren't available". Close the socket and
1739 * Now try an AF_UNIX socket.
1741 fd
= socket(AF_UNIX
, SOCK_RAW
, 0);
1750 * Now try an AF_INET6 socket.
1752 fd
= socket(AF_INET6
, SOCK_DGRAM
, 0);
1758 * Now try an AF_INET socket.
1760 * XXX - if that fails, is there anything else we should try?
1761 * AF_CAN, for embedded systems in vehicles, in case they're
1762 * built without Internet protocol support? Any other socket
1763 * types popular in non-Internet embedded systems?
1765 return (socket(AF_INET
, SOCK_DGRAM
, 0));
1769 * Get additional flags for a device, using SIOCETHTOOL.
1772 get_if_flags(const char *name
, bpf_u_int32
*flags
, char *errbuf
)
1776 unsigned int arptype
= ARPHRD_VOID
;
1778 struct ethtool_value info
;
1780 if (*flags
& PCAP_IF_LOOPBACK
) {
1782 * Loopback devices aren't wireless, and "connected"/
1783 * "disconnected" doesn't apply to them.
1785 *flags
|= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
1789 sock
= get_if_ioctl_socket();
1791 pcapint_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
, errno
,
1792 "Can't create socket to get ethtool information for %s",
1798 * OK, what type of network is this?
1799 * In particular, is it wired or wireless?
1801 if (is_wifi(name
)) {
1803 * Wi-Fi, hence wireless.
1805 *flags
|= PCAP_IF_WIRELESS
;
1808 * OK, what does /sys/class/net/{if_name}/type contain?
1809 * (We don't use that for Wi-Fi, as it'll report
1810 * "Ethernet", i.e. ARPHRD_ETHER, for non-monitor-
1815 if (asprintf(&pathstr
, "/sys/class/net/%s/type", name
) == -1) {
1816 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1817 "%s: Can't generate path name string for /sys/class/net device",
1822 fh
= fopen(pathstr
, "r");
1824 if (fscanf(fh
, "%u", &arptype
) == 1) {
1826 * OK, we got an ARPHRD_ type; what is it?
1830 case ARPHRD_LOOPBACK
:
1832 * These are types to which
1833 * "connected" and "disconnected"
1834 * don't apply, so don't bother
1837 * XXX - add other types?
1845 case ARPHRD_IEEE80211
:
1846 case ARPHRD_IEEE80211_PRISM
:
1847 case ARPHRD_IEEE80211_RADIOTAP
:
1848 case ARPHRD_IEEE802154
:
1849 case ARPHRD_IEEE802154_MONITOR
:
1850 case ARPHRD_6LOWPAN
:
1852 * Various wireless types.
1854 *flags
|= PCAP_IF_WIRELESS
;
1863 #ifdef ETHTOOL_GLINK
1864 memset(&ifr
, 0, sizeof(ifr
));
1865 pcapint_strlcpy(ifr
.ifr_name
, name
, sizeof(ifr
.ifr_name
));
1866 info
.cmd
= ETHTOOL_GLINK
;
1868 * XXX - while Valgrind handles SIOCETHTOOL and knows that
1869 * the ETHTOOL_GLINK command sets the .data member of the
1870 * structure, Memory Sanitizer doesn't yet do so:
1872 * https://bugs.llvm.org/show_bug.cgi?id=45814
1874 * For now, we zero it out to squelch warnings; if the bug
1875 * in question is fixed, we can remove this.
1878 ifr
.ifr_data
= (caddr_t
)&info
;
1879 if (ioctl(sock
, SIOCETHTOOL
, &ifr
) == -1) {
1880 int save_errno
= errno
;
1882 switch (save_errno
) {
1887 * OK, this OS version or driver doesn't support
1888 * asking for this information.
1889 * XXX - distinguish between "this doesn't
1890 * support ethtool at all because it's not
1891 * that type of device" vs. "this doesn't
1892 * support ethtool even though it's that
1893 * type of device", and return "unknown".
1895 *flags
|= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
1901 * OK, no such device.
1902 * The user will find that out when they try to
1903 * activate the device; just say "OK" and
1904 * don't set anything.
1913 pcapint_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
1915 "%s: SIOCETHTOOL(ETHTOOL_GLINK) ioctl failed",
1929 *flags
|= PCAP_IF_CONNECTION_STATUS_CONNECTED
;
1932 * It's disconnected.
1934 *flags
|= PCAP_IF_CONNECTION_STATUS_DISCONNECTED
;
1941 // For "down" SNF devices the SNF API makes the flags more relevant.
1942 if (arptype
== ARPHRD_ETHER
&&
1943 ! (*flags
& PCAP_IF_UP
) &&
1944 snf_get_if_flags(name
, flags
, errbuf
) < 0)
1946 #endif // HAVE_SNF_API
1952 pcapint_platform_finddevs(pcap_if_list_t
*devlistp
, char *errbuf
)
1955 * Get the list of regular interfaces first.
1957 if (pcapint_findalldevs_interfaces(devlistp
, errbuf
, can_be_bound
,
1958 get_if_flags
) == -1)
1959 return (-1); /* failure */
1962 * Add the "any" device.
1964 if (pcapint_add_any_dev(devlistp
, errbuf
) == NULL
)
1971 * Set direction flag: Which packets do we accept on a forwarding
1972 * single device? IN, OUT or both?
1975 pcap_setdirection_linux(pcap_t
*handle
, pcap_direction_t d
)
1978 * It's guaranteed, at this point, that d is a valid
1981 handle
->direction
= d
;
1986 is_wifi(const char *device
)
1992 * See if there's a sysfs wireless directory for it.
1993 * If so, it's a wireless interface.
1995 if (asprintf(&pathstr
, "/sys/class/net/%s/wireless", device
) == -1) {
1997 * Just give up here.
2001 if (stat(pathstr
, &statb
) == 0) {
2011 * Linux uses the ARP hardware type to identify the type of an
2012 * interface. pcap uses the DLT_xxx constants for this. This
2013 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
2014 * constant, as arguments, and sets "handle->linktype" to the
2015 * appropriate DLT_XXX constant and sets "handle->offset" to
2016 * the appropriate value (to make "handle->offset" plus link-layer
2017 * header length be a multiple of 4, so that the link-layer payload
2018 * will be aligned on a 4-byte boundary when capturing packets).
2019 * (If the offset isn't set here, it'll be 0; add code as appropriate
2020 * for cases where it shouldn't be 0.)
2022 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
2023 * in cooked mode; otherwise, we can't use cooked mode, so we have
2024 * to pick some type that works in raw mode, or fail.
2026 * Sets the link type to -1 if unable to map the type.
2028 * Returns 0 on success or a PCAP_ERROR_ value on error.
2030 static int map_arphrd_to_dlt(pcap_t
*handle
, int arptype
,
2031 const char *device
, int cooked_ok
)
2033 static const char cdma_rmnet
[] = "cdma_rmnet";
2039 * For various annoying reasons having to do with DHCP
2040 * software, some versions of Android give the mobile-
2041 * phone-network interface an ARPHRD_ value of
2042 * ARPHRD_ETHER, even though the packets supplied by
2043 * that interface have no link-layer header, and begin
2044 * with an IP header, so that the ARPHRD_ value should
2047 * Detect those devices by checking the device name, and
2048 * use DLT_RAW for them.
2050 if (strncmp(device
, cdma_rmnet
, sizeof cdma_rmnet
- 1) == 0) {
2051 handle
->linktype
= DLT_RAW
;
2056 * Is this a real Ethernet device? If so, give it a
2057 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
2058 * that an application can let you choose it, in case you're
2059 * capturing DOCSIS traffic that a Cisco Cable Modem
2060 * Termination System is putting out onto an Ethernet (it
2061 * doesn't put an Ethernet header onto the wire, it puts raw
2062 * DOCSIS frames out on the wire inside the low-level
2063 * Ethernet framing).
2065 * XXX - are there any other sorts of "fake Ethernet" that
2066 * have ARPHRD_ETHER but that shouldn't offer DLT_DOCSIS as
2067 * a Cisco CMTS won't put traffic onto it or get traffic
2068 * bridged onto it? ISDN is handled in "setup_socket()",
2069 * as we fall back on cooked mode there, and we use
2070 * is_wifi() to check for 802.11 devices; are there any
2073 if (!is_wifi(device
)) {
2077 * This is not a Wi-Fi device but it could be
2078 * a DSA master/management network device.
2080 ret
= iface_dsa_get_proto_info(device
, handle
);
2086 * This is a DSA master/management network
2087 * device linktype is already set by
2088 * iface_dsa_get_proto_info() set an
2089 * appropriate offset here.
2096 * It's not a Wi-Fi device; offer DOCSIS.
2098 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
2099 if (handle
->dlt_list
== NULL
) {
2100 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
2101 PCAP_ERRBUF_SIZE
, errno
, "malloc");
2102 return (PCAP_ERROR
);
2104 handle
->dlt_list
[0] = DLT_EN10MB
;
2105 handle
->dlt_list
[1] = DLT_DOCSIS
;
2106 handle
->dlt_count
= 2;
2110 case ARPHRD_METRICOM
:
2111 case ARPHRD_LOOPBACK
:
2112 handle
->linktype
= DLT_EN10MB
;
2117 handle
->linktype
= DLT_EN3MB
;
2121 handle
->linktype
= DLT_AX25_KISS
;
2125 handle
->linktype
= DLT_PRONET
;
2129 handle
->linktype
= DLT_CHAOS
;
2133 handle
->linktype
= DLT_CAN_SOCKETCAN
;
2136 case ARPHRD_IEEE802_TR
:
2137 case ARPHRD_IEEE802
:
2138 handle
->linktype
= DLT_IEEE802
;
2143 handle
->linktype
= DLT_ARCNET_LINUX
;
2147 handle
->linktype
= DLT_FDDI
;
2153 * The Classical IP implementation in ATM for Linux
2154 * supports both what RFC 1483 calls "LLC Encapsulation",
2155 * in which each packet has an LLC header, possibly
2156 * with a SNAP header as well, prepended to it, and
2157 * what RFC 1483 calls "VC Based Multiplexing", in which
2158 * different virtual circuits carry different network
2159 * layer protocols, and no header is prepended to packets.
2161 * They both have an ARPHRD_ type of ARPHRD_ATM, so
2162 * you can't use the ARPHRD_ type to find out whether
2163 * captured packets will have an LLC header, and,
2164 * while there's a socket ioctl to *set* the encapsulation
2165 * type, there's no ioctl to *get* the encapsulation type.
2169 * programs that dissect Linux Classical IP frames
2170 * would have to check for an LLC header and,
2171 * depending on whether they see one or not, dissect
2172 * the frame as LLC-encapsulated or as raw IP (I
2173 * don't know whether there's any traffic other than
2174 * IP that would show up on the socket, or whether
2175 * there's any support for IPv6 in the Linux
2176 * Classical IP code);
2178 * filter expressions would have to compile into
2179 * code that checks for an LLC header and does
2182 * Both of those are a nuisance - and, at least on systems
2183 * that support PF_PACKET sockets, we don't have to put
2184 * up with those nuisances; instead, we can just capture
2185 * in cooked mode. That's what we'll do, if we can.
2186 * Otherwise, we'll just fail.
2189 handle
->linktype
= DLT_LINUX_SLL
;
2191 handle
->linktype
= -1;
2194 case ARPHRD_IEEE80211
:
2195 handle
->linktype
= DLT_IEEE802_11
;
2198 case ARPHRD_IEEE80211_PRISM
:
2199 handle
->linktype
= DLT_PRISM_HEADER
;
2202 case ARPHRD_IEEE80211_RADIOTAP
:
2203 handle
->linktype
= DLT_IEEE802_11_RADIO
;
2208 * Some PPP code in the kernel supplies no link-layer
2209 * header whatsoever to PF_PACKET sockets; other PPP
2210 * code supplies PPP link-layer headers ("syncppp.c");
2211 * some PPP code might supply random link-layer
2212 * headers (PPP over ISDN - there's code in Ethereal,
2213 * for example, to cope with PPP-over-ISDN captures
2214 * with which the Ethereal developers have had to cope,
2215 * heuristically trying to determine which of the
2216 * oddball link-layer headers particular packets have).
2218 * As such, we just punt, and run all PPP interfaces
2219 * in cooked mode, if we can; otherwise, we just treat
2220 * it as DLT_RAW, for now - if somebody needs to capture,
2221 * on a 2.0[.x] kernel, on PPP devices that supply a
2222 * link-layer header, they'll have to add code here to
2223 * map to the appropriate DLT_ type (possibly adding a
2224 * new DLT_ type, if necessary).
2227 handle
->linktype
= DLT_LINUX_SLL
;
2230 * XXX - handle ISDN types here? We can't fall
2231 * back on cooked sockets, so we'd have to
2232 * figure out from the device name what type of
2233 * link-layer encapsulation it's using, and map
2234 * that to an appropriate DLT_ value, meaning
2235 * we'd map "isdnN" devices to DLT_RAW (they
2236 * supply raw IP packets with no link-layer
2237 * header) and "isdY" devices to a new DLT_I4L_IP
2238 * type that has only an Ethernet packet type as
2239 * a link-layer header.
2241 * But sometimes we seem to get random crap
2242 * in the link-layer header when capturing on
2245 handle
->linktype
= DLT_RAW
;
2250 handle
->linktype
= DLT_C_HDLC
;
2253 /* Not sure if this is correct for all tunnels, but it
2262 case ARPHRD_RAWHDLC
:
2265 * XXX - should some of those be mapped to DLT_LINUX_SLL
2266 * instead? Should we just map all of them to DLT_LINUX_SLL?
2268 handle
->linktype
= DLT_RAW
;
2272 handle
->linktype
= DLT_FRELAY
;
2275 case ARPHRD_LOCALTLK
:
2276 handle
->linktype
= DLT_LTALK
;
2281 * RFC 4338 defines an encapsulation for IP and ARP
2282 * packets that's compatible with the RFC 2625
2283 * encapsulation, but that uses a different ARP
2284 * hardware type and hardware addresses. That
2285 * ARP hardware type is 18; Linux doesn't define
2286 * any ARPHRD_ value as 18, but if it ever officially
2287 * supports RFC 4338-style IP-over-FC, it should define
2290 * For now, we map it to DLT_IP_OVER_FC, in the hopes
2291 * that this will encourage its use in the future,
2292 * should Linux ever officially support RFC 4338-style
2295 handle
->linktype
= DLT_IP_OVER_FC
;
2301 case ARPHRD_FCFABRIC
:
2303 * Back in 2002, Donald Lee at Cray wanted a DLT_ for
2306 * https://www.mail-archive.com/tcpdump-workers@sandelman.ottawa.on.ca/msg01043.html
2308 * and one was assigned.
2310 * In a later private discussion (spun off from a message
2311 * on the ethereal-users list) on how to get that DLT_
2312 * value in libpcap on Linux, I ended up deciding that
2313 * the best thing to do would be to have him tweak the
2314 * driver to set the ARPHRD_ value to some ARPHRD_FCxx
2315 * type, and map all those types to DLT_IP_OVER_FC:
2317 * I've checked into the libpcap and tcpdump CVS tree
2318 * support for DLT_IP_OVER_FC. In order to use that,
2319 * you'd have to modify your modified driver to return
2320 * one of the ARPHRD_FCxxx types, in "fcLINUXfcp.c" -
2321 * change it to set "dev->type" to ARPHRD_FCFABRIC, for
2322 * example (the exact value doesn't matter, it can be
2323 * any of ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL, or
2326 * 11 years later, Christian Svensson wanted to map
2327 * various ARPHRD_ values to DLT_FC_2 and
2328 * DLT_FC_2_WITH_FRAME_DELIMS for raw Fibre Channel
2331 * https://github.com/mcr/libpcap/pull/29
2333 * There doesn't seem to be any network drivers that uses
2334 * any of the ARPHRD_FC* values for IP-over-FC, and
2335 * it's not exactly clear what the "Dummy types for non
2336 * ARP hardware" are supposed to mean (link-layer
2337 * header type? Physical network type?), so it's
2338 * not exactly clear why the ARPHRD_FC* types exist
2339 * in the first place.
2341 * For now, we map them to DLT_FC_2, and provide an
2342 * option of DLT_FC_2_WITH_FRAME_DELIMS, as well as
2343 * DLT_IP_OVER_FC just in case there's some old
2344 * driver out there that uses one of those types for
2345 * IP-over-FC on which somebody wants to capture
2348 handle
->linktype
= DLT_FC_2
;
2349 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 3);
2350 if (handle
->dlt_list
== NULL
) {
2351 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
2352 PCAP_ERRBUF_SIZE
, errno
, "malloc");
2353 return (PCAP_ERROR
);
2355 handle
->dlt_list
[0] = DLT_FC_2
;
2356 handle
->dlt_list
[1] = DLT_FC_2_WITH_FRAME_DELIMS
;
2357 handle
->dlt_list
[2] = DLT_IP_OVER_FC
;
2358 handle
->dlt_count
= 3;
2362 /* Don't expect IP packet out of this interfaces... */
2363 handle
->linktype
= DLT_LINUX_IRDA
;
2364 /* We need to save packet direction for IrDA decoding,
2365 * so let's use "Linux-cooked" mode. Jean II
2367 * XXX - this is handled in setup_socket(). */
2368 /* handlep->cooked = 1; */
2372 /* Don't expect IP packet out of this interfaces... */
2373 handle
->linktype
= DLT_LINUX_LAPD
;
2378 * No link-layer header; packets are just IP
2379 * packets, so use DLT_RAW.
2381 handle
->linktype
= DLT_RAW
;
2384 case ARPHRD_IEEE802154
:
2385 handle
->linktype
= DLT_IEEE802_15_4_NOFCS
;
2388 case ARPHRD_NETLINK
:
2389 handle
->linktype
= DLT_NETLINK
;
2391 * We need to use cooked mode, so that in sll_protocol we
2392 * pick up the netlink protocol type such as NETLINK_ROUTE,
2393 * NETLINK_GENERIC, NETLINK_FIB_LOOKUP, etc.
2395 * XXX - this is handled in setup_socket().
2397 /* handlep->cooked = 1; */
2400 case ARPHRD_VSOCKMON
:
2401 handle
->linktype
= DLT_VSOCK
;
2405 handle
->linktype
= -1;
2412 * Try to set up a PF_PACKET socket.
2413 * Returns 0 or a PCAP_WARNING_ value on success and a PCAP_ERROR_ value
2417 setup_socket(pcap_t
*handle
, int is_any_device
)
2419 struct pcap_linux
*handlep
= handle
->priv
;
2420 const char *device
= handle
->opt
.device
;
2422 int sock_fd
, arptype
;
2425 struct packet_mreq mr
;
2426 #if defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT)
2428 socklen_t len
= sizeof(bpf_extensions
);
2432 * Open a socket with protocol family packet. If cooked is true,
2433 * we open a SOCK_DGRAM socket for the cooked interface, otherwise
2434 * we open a SOCK_RAW socket for the raw interface.
2436 * The protocol is set to 0. This means we will receive no
2437 * packets until we "bind" the socket with a non-zero
2438 * protocol. This allows us to setup the ring buffers without
2439 * dropping any packets.
2441 sock_fd
= is_any_device
?
2442 socket(PF_PACKET
, SOCK_DGRAM
, 0) :
2443 socket(PF_PACKET
, SOCK_RAW
, 0);
2445 if (sock_fd
== -1) {
2446 if (errno
== EPERM
|| errno
== EACCES
) {
2448 * You don't have permission to open the
2451 status
= PCAP_ERROR_PERM_DENIED
;
2452 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2453 "Attempt to create packet socket failed - CAP_NET_RAW may be required");
2454 } else if (errno
== EAFNOSUPPORT
) {
2456 * PF_PACKET sockets not supported.
2457 * Perhaps we're running on the WSL1 module
2458 * in the Windows NT kernel rather than on
2459 * a real Linux kernel.
2461 status
= PCAP_ERROR_CAPTURE_NOTSUP
;
2462 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2463 "PF_PACKET sockets not supported - is this WSL1?");
2468 status
= PCAP_ERROR
;
2470 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2476 * Get the interface index of the loopback device.
2477 * If the attempt fails, don't fail, just set the
2478 * "handlep->lo_ifindex" to -1.
2480 * XXX - can there be more than one device that loops
2481 * packets back, i.e. devices other than "lo"? If so,
2482 * we'd need to find them all, and have an array of
2483 * indices for them, and check all of them in
2484 * "pcap_read_packet()".
2486 handlep
->lo_ifindex
= iface_get_id(sock_fd
, "lo", handle
->errbuf
);
2489 * Default value for offset to align link-layer payload
2490 * on a 4-byte boundary.
2495 * What kind of frames do we have to deal with? Fall back
2496 * to cooked mode if we have an unknown interface type
2497 * or a type we know doesn't work well in raw mode.
2499 if (!is_any_device
) {
2500 /* Assume for now we don't need cooked mode. */
2501 handlep
->cooked
= 0;
2503 if (handle
->opt
.rfmon
) {
2505 * We were asked to turn on monitor mode.
2506 * Do so before we get the link-layer type,
2507 * because entering monitor mode could change
2508 * the link-layer type.
2510 err
= enter_rfmon_mode(handle
, sock_fd
, device
);
2518 * Nothing worked for turning monitor mode
2523 return PCAP_ERROR_RFMON_NOTSUP
;
2527 * Either monitor mode has been turned on for
2528 * the device, or we've been given a different
2529 * device to open for monitor mode. If we've
2530 * been given a different device, use it.
2532 if (handlep
->mondevice
!= NULL
)
2533 device
= handlep
->mondevice
;
2535 arptype
= iface_get_arptype(sock_fd
, device
, handle
->errbuf
);
2540 status
= map_arphrd_to_dlt(handle
, arptype
, device
, 1);
2545 if (handle
->linktype
== -1 ||
2546 handle
->linktype
== DLT_LINUX_SLL
||
2547 handle
->linktype
== DLT_LINUX_IRDA
||
2548 handle
->linktype
== DLT_LINUX_LAPD
||
2549 handle
->linktype
== DLT_NETLINK
||
2550 (handle
->linktype
== DLT_EN10MB
&&
2551 (strncmp("isdn", device
, 4) == 0 ||
2552 strncmp("isdY", device
, 4) == 0))) {
2554 * Unknown interface type (-1), or a
2555 * device we explicitly chose to run
2556 * in cooked mode (e.g., PPP devices),
2557 * or an ISDN device (whose link-layer
2558 * type we can only determine by using
2559 * APIs that may be different on different
2560 * kernels) - reopen in cooked mode.
2562 * If the type is unknown, return a warning;
2563 * map_arphrd_to_dlt() has already set the
2566 if (close(sock_fd
) == -1) {
2567 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
2568 PCAP_ERRBUF_SIZE
, errno
, "close");
2571 sock_fd
= socket(PF_PACKET
, SOCK_DGRAM
, 0);
2574 * Fatal error. We treat this as
2575 * a generic error; we already know
2576 * that we were able to open a
2577 * PF_PACKET/SOCK_RAW socket, so
2578 * any failure is a "this shouldn't
2581 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
2582 PCAP_ERRBUF_SIZE
, errno
, "socket");
2585 handlep
->cooked
= 1;
2588 * Get rid of any link-layer type list
2589 * we allocated - this only supports cooked
2592 if (handle
->dlt_list
!= NULL
) {
2593 free(handle
->dlt_list
);
2594 handle
->dlt_list
= NULL
;
2595 handle
->dlt_count
= 0;
2598 if (handle
->linktype
== -1) {
2600 * Warn that we're falling back on
2601 * cooked mode; we may want to
2602 * update "map_arphrd_to_dlt()"
2603 * to handle the new type.
2605 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2607 "supported by libpcap - "
2608 "falling back to cooked "
2611 status
= PCAP_WARNING
;
2615 * IrDA capture is not a real "cooked" capture,
2616 * it's IrLAP frames, not IP packets. The
2617 * same applies to LAPD capture.
2619 if (handle
->linktype
!= DLT_LINUX_IRDA
&&
2620 handle
->linktype
!= DLT_LINUX_LAPD
&&
2621 handle
->linktype
!= DLT_NETLINK
)
2622 handle
->linktype
= DLT_LINUX_SLL
;
2625 handlep
->ifindex
= iface_get_id(sock_fd
, device
,
2627 if (handlep
->ifindex
== -1) {
2632 if ((err
= iface_bind(sock_fd
, handlep
->ifindex
,
2633 handle
->errbuf
, 0)) != 0) {
2641 if (handle
->opt
.rfmon
) {
2643 * It doesn't support monitor mode.
2646 return PCAP_ERROR_RFMON_NOTSUP
;
2650 * It uses cooked mode.
2651 * Support both DLT_LINUX_SLL and DLT_LINUX_SLL2.
2653 handlep
->cooked
= 1;
2654 handle
->linktype
= DLT_LINUX_SLL
;
2655 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
2656 if (handle
->dlt_list
== NULL
) {
2657 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
2658 PCAP_ERRBUF_SIZE
, errno
, "malloc");
2659 return (PCAP_ERROR
);
2661 handle
->dlt_list
[0] = DLT_LINUX_SLL
;
2662 handle
->dlt_list
[1] = DLT_LINUX_SLL2
;
2663 handle
->dlt_count
= 2;
2666 * We're not bound to a device.
2667 * For now, we're using this as an indication
2668 * that we can't transmit; stop doing that only
2669 * if we figure out how to transmit in cooked
2672 handlep
->ifindex
= -1;
2676 * Select promiscuous mode on if "promisc" is set.
2678 * Do not turn allmulti mode on if we don't select
2679 * promiscuous mode - on some devices (e.g., Orinoco
2680 * wireless interfaces), allmulti mode isn't supported
2681 * and the driver implements it by turning promiscuous
2682 * mode on, and that screws up the operation of the
2683 * card as a normal networking interface, and on no
2684 * other platform I know of does starting a non-
2685 * promiscuous capture affect which multicast packets
2686 * are received by the interface.
2690 * Hmm, how can we set promiscuous mode on all interfaces?
2691 * I am not sure if that is possible at all. For now, we
2692 * silently ignore attempts to turn promiscuous mode on
2693 * for the "any" device (so you don't have to explicitly
2694 * disable it in programs such as tcpdump).
2697 if (!is_any_device
&& handle
->opt
.promisc
) {
2698 memset(&mr
, 0, sizeof(mr
));
2699 mr
.mr_ifindex
= handlep
->ifindex
;
2700 mr
.mr_type
= PACKET_MR_PROMISC
;
2701 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_ADD_MEMBERSHIP
,
2702 &mr
, sizeof(mr
)) == -1) {
2703 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
2704 PCAP_ERRBUF_SIZE
, errno
, "setsockopt (PACKET_ADD_MEMBERSHIP)");
2711 * Enable auxiliary data and reserve room for reconstructing
2714 * XXX - is enabling auxiliary data necessary, now that we
2715 * only support memory-mapped capture? The kernel's memory-mapped
2716 * capture code doesn't seem to check whether auxiliary data
2717 * is enabled, it seems to provide it whether it is or not.
2720 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_AUXDATA
, &val
,
2721 sizeof(val
)) == -1 && errno
!= ENOPROTOOPT
) {
2722 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2723 errno
, "setsockopt (PACKET_AUXDATA)");
2727 handle
->offset
+= VLAN_TAG_LEN
;
2730 * If we're in cooked mode, make the snapshot length
2731 * large enough to hold a "cooked mode" header plus
2732 * 1 byte of packet data (so we don't pass a byte
2733 * count of 0 to "recvfrom()").
2734 * XXX - we don't know whether this will be DLT_LINUX_SLL
2735 * or DLT_LINUX_SLL2, so make sure it's big enough for
2736 * a DLT_LINUX_SLL2 "cooked mode" header; a snapshot length
2737 * that small is silly anyway.
2739 if (handlep
->cooked
) {
2740 if (handle
->snapshot
< SLL2_HDR_LEN
+ 1)
2741 handle
->snapshot
= SLL2_HDR_LEN
+ 1;
2743 handle
->bufsize
= handle
->snapshot
;
2746 * Set the offset at which to insert VLAN tags.
2748 set_vlan_offset(handle
);
2750 if (handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
) {
2751 int nsec_tstamps
= 1;
2753 if (setsockopt(sock_fd
, SOL_SOCKET
, SO_TIMESTAMPNS
, &nsec_tstamps
, sizeof(nsec_tstamps
)) < 0) {
2754 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "setsockopt: unable to set SO_TIMESTAMPNS");
2761 * We've succeeded. Save the socket FD in the pcap structure.
2763 handle
->fd
= sock_fd
;
2765 #ifdef SO_BPF_EXTENSIONS
2767 * Can we generate special code for VLAN checks?
2768 * (XXX - what if we need the special code but it's not supported
2769 * by the OS? Is that possible?)
2771 if (getsockopt(sock_fd
, SOL_SOCKET
, SO_BPF_EXTENSIONS
,
2772 &bpf_extensions
, &len
) == 0) {
2774 * This is a live capture with some BPF extensions support,
2775 * so indicate that at least the auxiliary data items from
2776 * Linux 2.6.27 are available (this concerns SKF_AD_PKTTYPE
2777 * and SKF_AD_IFINDEX in the first place).
2779 handle
->bpf_codegen_flags
|= BPF_SPECIAL_BASIC_HANDLING
;
2780 #ifdef SKF_AD_VLAN_TAG_PRESENT
2781 if (bpf_extensions
>= SKF_AD_VLAN_TAG_PRESENT
) {
2783 * Yes, we can. Request that we do so.
2785 handle
->bpf_codegen_flags
|= BPF_SPECIAL_VLAN_HANDLING
;
2787 #endif // SKF_AD_VLAN_TAG_PRESENT
2789 #endif // SO_BPF_EXTENSIONS
2795 * Attempt to setup memory-mapped access.
2797 * On success, returns 0 if there are no warnings or a PCAP_WARNING_ code
2798 * if there is a warning.
2800 * On error, returns the appropriate error code; if that is PCAP_ERROR,
2801 * sets handle->errbuf to the appropriate message.
2804 setup_mmapped(pcap_t
*handle
)
2806 struct pcap_linux
*handlep
= handle
->priv
;
2807 int flags
= MAP_ANONYMOUS
| MAP_PRIVATE
;
2811 * Attempt to allocate a buffer to hold the contents of one
2812 * packet, for use by the oneshot callback.
2815 if (pcapint_mmap_32bit
) flags
|= MAP_32BIT
;
2817 handlep
->oneshot_buffer
= mmap(0, handle
->snapshot
, PROT_READ
| PROT_WRITE
, flags
, -1, 0);
2818 if (handlep
->oneshot_buffer
== MAP_FAILED
) {
2819 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2820 errno
, "can't allocate oneshot buffer");
2824 if (handle
->opt
.buffer_size
== 0) {
2825 /* by default request 2M for the ring buffer */
2826 handle
->opt
.buffer_size
= 2*1024*1024;
2828 status
= prepare_tpacket_socket(handle
);
2830 munmap(handlep
->oneshot_buffer
, handle
->snapshot
);
2831 handlep
->oneshot_buffer
= NULL
;
2834 status
= create_ring(handle
);
2837 * Error attempting to enable memory-mapped capture;
2838 * fail. The return value is the status to return.
2840 munmap(handlep
->oneshot_buffer
, handle
->snapshot
);
2841 handlep
->oneshot_buffer
= NULL
;
2846 * Success. status has been set either to 0 if there are no
2847 * warnings or to a PCAP_WARNING_ value if there is a warning.
2849 * handle->offset is used to get the current position into the rx ring.
2850 * handle->cc is used to store the ring size.
2854 * Set the timeout to use in poll() before returning.
2856 set_poll_timeout(handlep
);
2862 * Attempt to set the socket to the specified version of the memory-mapped
2865 * Return 0 if we succeed; return 1 if we fail because that version isn't
2866 * supported; return -1 on any other error, and set handle->errbuf.
2869 init_tpacket(pcap_t
*handle
, int version
, const char *version_str
)
2871 struct pcap_linux
*handlep
= handle
->priv
;
2873 socklen_t len
= sizeof(val
);
2876 * Probe whether kernel supports the specified TPACKET version;
2877 * this also gets the length of the header for that version.
2879 * This socket option was introduced in 2.6.27, which was
2880 * also the first release with TPACKET_V2 support.
2882 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_HDRLEN
, &val
, &len
) < 0) {
2883 if (errno
== EINVAL
) {
2885 * EINVAL means this specific version of TPACKET
2886 * is not supported. Tell the caller they can try
2887 * with a different one; if they've run out of
2888 * others to try, let them set the error message
2895 * All other errors are fatal.
2897 if (errno
== ENOPROTOOPT
) {
2899 * PACKET_HDRLEN isn't supported, which means
2900 * that memory-mapped capture isn't supported.
2901 * Indicate that in the message.
2903 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2904 "Kernel doesn't support memory-mapped capture; a 2.6.27 or later 2.x kernel is required, with CONFIG_PACKET_MMAP specified for 2.x kernels");
2907 * Some unexpected error.
2909 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2910 errno
, "can't get %s header len on packet socket",
2915 handlep
->tp_hdrlen
= val
;
2918 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_VERSION
, &val
,
2920 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2921 errno
, "can't activate %s on packet socket", version_str
);
2924 handlep
->tp_version
= version
;
2930 * Attempt to set the socket to version 3 of the memory-mapped header and,
2931 * if that fails because version 3 isn't supported, attempt to fall
2932 * back to version 2. If version 2 isn't supported, just fail.
2934 * Return 0 if we succeed and -1 on any other error, and set handle->errbuf.
2937 prepare_tpacket_socket(pcap_t
*handle
)
2941 #ifdef HAVE_TPACKET3
2943 * Try setting the version to TPACKET_V3.
2945 * The only mode in which buffering is done on PF_PACKET
2946 * sockets, so that packets might not be delivered
2947 * immediately, is TPACKET_V3 mode.
2949 * The buffering cannot be disabled in that mode, so
2950 * if the user has requested immediate mode, we don't
2953 if (!handle
->opt
.immediate
) {
2954 ret
= init_tpacket(handle
, TPACKET_V3
, "TPACKET_V3");
2963 * We failed for some reason other than "the
2964 * kernel doesn't support TPACKET_V3".
2970 * This means it returned 1, which means "the kernel
2971 * doesn't support TPACKET_V3"; try TPACKET_V2.
2974 #endif /* HAVE_TPACKET3 */
2977 * Try setting the version to TPACKET_V2.
2979 ret
= init_tpacket(handle
, TPACKET_V2
, "TPACKET_V2");
2989 * OK, the kernel supports memory-mapped capture, but
2990 * not TPACKET_V2. Set the error message appropriately.
2992 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2993 "Kernel doesn't support TPACKET_V2; a 2.6.27 or later kernel is required");
3002 #define MAX(a,b) ((a)>(b)?(a):(b))
3005 * Attempt to set up memory-mapped access.
3007 * On success, returns 0 if there are no warnings or to a PCAP_WARNING_ code
3008 * if there is a warning.
3010 * On error, returns the appropriate error code; if that is PCAP_ERROR,
3011 * sets handle->errbuf to the appropriate message.
3014 create_ring(pcap_t
*handle
)
3016 struct pcap_linux
*handlep
= handle
->priv
;
3017 unsigned i
, j
, frames_per_block
;
3018 int flags
= MAP_SHARED
;
3019 #ifdef HAVE_TPACKET3
3021 * For sockets using TPACKET_V2, the extra stuff at the end of a
3022 * struct tpacket_req3 will be ignored, so this is OK even for
3025 struct tpacket_req3 req
;
3027 struct tpacket_req req
;
3030 unsigned int sk_type
, tp_reserve
, maclen
, tp_hdrlen
, netoff
, macoff
;
3031 unsigned int frame_size
;
3035 * Start out assuming no warnings.
3040 * Reserve space for VLAN tag reconstruction.
3042 tp_reserve
= VLAN_TAG_LEN
;
3045 * If we're capturing in cooked mode, reserve space for
3046 * a DLT_LINUX_SLL2 header; we don't know yet whether
3047 * we'll be using DLT_LINUX_SLL or DLT_LINUX_SLL2, as
3048 * that can be changed on an open device, so we reserve
3049 * space for the larger of the two.
3051 * XXX - we assume that the kernel is still adding
3052 * 16 bytes of extra space, so we subtract 16 from
3053 * SLL2_HDR_LEN to get the additional space needed.
3054 * (Are they doing that for DLT_LINUX_SLL, the link-
3055 * layer header for which is 16 bytes?)
3057 * XXX - should we use TPACKET_ALIGN(SLL2_HDR_LEN - 16)?
3059 if (handlep
->cooked
)
3060 tp_reserve
+= SLL2_HDR_LEN
- 16;
3063 * Try to request that amount of reserve space.
3064 * This must be done before creating the ring buffer.
3066 len
= sizeof(tp_reserve
);
3067 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
,
3068 &tp_reserve
, len
) < 0) {
3069 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
3070 PCAP_ERRBUF_SIZE
, errno
,
3071 "setsockopt (PACKET_RESERVE)");
3075 switch (handlep
->tp_version
) {
3078 /* Note that with large snapshot length (say 256K, which is
3079 * the default for recent versions of tcpdump, Wireshark,
3080 * TShark, dumpcap or 64K, the value that "-s 0" has given for
3081 * a long time with tcpdump), if we use the snapshot
3082 * length to calculate the frame length, only a few frames
3083 * will be available in the ring even with pretty
3084 * large ring size (and a lot of memory will be unused).
3086 * Ideally, we should choose a frame length based on the
3087 * minimum of the specified snapshot length and the maximum
3088 * packet size. That's not as easy as it sounds; consider,
3089 * for example, an 802.11 interface in monitor mode, where
3090 * the frame would include a radiotap header, where the
3091 * maximum radiotap header length is device-dependent.
3093 * So, for now, we just do this for Ethernet devices, where
3094 * there's no metadata header, and the link-layer header is
3095 * fixed length. We can get the maximum packet size by
3096 * adding 18, the Ethernet header length plus the CRC length
3097 * (just in case we happen to get the CRC in the packet), to
3098 * the MTU of the interface; we fetch the MTU in the hopes
3099 * that it reflects support for jumbo frames. (Even if the
3100 * interface is just being used for passive snooping, the
3101 * driver might set the size of buffers in the receive ring
3102 * based on the MTU, so that the MTU limits the maximum size
3103 * of packets that we can receive.)
3105 * If segmentation/fragmentation or receive offload are
3106 * enabled, we can get reassembled/aggregated packets larger
3107 * than MTU, but bounded to 65535 plus the Ethernet overhead,
3108 * due to kernel and protocol constraints */
3109 frame_size
= handle
->snapshot
;
3110 if (handle
->linktype
== DLT_EN10MB
) {
3111 unsigned int max_frame_len
;
3115 mtu
= iface_get_mtu(handle
->fd
, handle
->opt
.device
,
3119 offload
= iface_get_offload(handle
);
3123 max_frame_len
= MAX(mtu
, 65535);
3125 max_frame_len
= mtu
;
3126 max_frame_len
+= 18;
3128 if (frame_size
> max_frame_len
)
3129 frame_size
= max_frame_len
;
3132 /* NOTE: calculus matching those in tpacket_rcv()
3133 * in linux-2.6/net/packet/af_packet.c
3135 len
= sizeof(sk_type
);
3136 if (getsockopt(handle
->fd
, SOL_SOCKET
, SO_TYPE
, &sk_type
,
3138 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
3139 PCAP_ERRBUF_SIZE
, errno
, "getsockopt (SO_TYPE)");
3142 maclen
= (sk_type
== SOCK_DGRAM
) ? 0 : MAX_LINKHEADER_SIZE
;
3143 /* XXX: in the kernel maclen is calculated from
3144 * LL_ALLOCATED_SPACE(dev) and vnet_hdr.hdr_len
3145 * in: packet_snd() in linux-2.6/net/packet/af_packet.c
3146 * then packet_alloc_skb() in linux-2.6/net/packet/af_packet.c
3147 * then sock_alloc_send_pskb() in linux-2.6/net/core/sock.c
3148 * but I see no way to get those sizes in userspace,
3149 * like for instance with an ifreq ioctl();
3150 * the best thing I've found so far is MAX_HEADER in
3151 * the kernel part of linux-2.6/include/linux/netdevice.h
3152 * which goes up to 128+48=176; since pcap-linux.c
3153 * defines a MAX_LINKHEADER_SIZE of 256 which is
3154 * greater than that, let's use it.. maybe is it even
3155 * large enough to directly replace macoff..
3157 tp_hdrlen
= TPACKET_ALIGN(handlep
->tp_hdrlen
) + sizeof(struct sockaddr_ll
) ;
3158 netoff
= TPACKET_ALIGN(tp_hdrlen
+ (maclen
< 16 ? 16 : maclen
)) + tp_reserve
;
3159 /* NOTE: AFAICS tp_reserve may break the TPACKET_ALIGN
3160 * of netoff, which contradicts
3161 * linux-2.6/Documentation/networking/packet_mmap.txt
3163 * "- Gap, chosen so that packet data (Start+tp_net)
3164 * aligns to TPACKET_ALIGNMENT=16"
3166 /* NOTE: in linux-2.6/include/linux/skbuff.h:
3167 * "CPUs often take a performance hit
3168 * when accessing unaligned memory locations"
3170 macoff
= netoff
- maclen
;
3171 req
.tp_frame_size
= TPACKET_ALIGN(macoff
+ frame_size
);
3173 * Round the buffer size up to a multiple of the
3174 * frame size (rather than rounding down, which
3175 * would give a buffer smaller than our caller asked
3176 * for, and possibly give zero frames if the requested
3177 * buffer size is too small for one frame).
3179 req
.tp_frame_nr
= (handle
->opt
.buffer_size
+ req
.tp_frame_size
- 1)/req
.tp_frame_size
;
3182 #ifdef HAVE_TPACKET3
3184 /* The "frames" for this are actually buffers that
3185 * contain multiple variable-sized frames.
3187 * We pick a "frame" size of MAXIMUM_SNAPLEN to leave
3188 * enough room for at least one reasonably-sized packet
3189 * in the "frame". */
3190 req
.tp_frame_size
= MAXIMUM_SNAPLEN
;
3192 * Round the buffer size up to a multiple of the
3193 * "frame" size (rather than rounding down, which
3194 * would give a buffer smaller than our caller asked
3195 * for, and possibly give zero "frames" if the requested
3196 * buffer size is too small for one "frame").
3198 req
.tp_frame_nr
= (handle
->opt
.buffer_size
+ req
.tp_frame_size
- 1)/req
.tp_frame_size
;
3202 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3203 "Internal error: unknown TPACKET_ value %u",
3204 handlep
->tp_version
);
3208 /* compute the minimum block size that will handle this frame.
3209 * The block has to be page size aligned.
3210 * The max block size allowed by the kernel is arch-dependent and
3211 * it's not explicitly checked here. */
3212 req
.tp_block_size
= getpagesize();
3213 while (req
.tp_block_size
< req
.tp_frame_size
)
3214 req
.tp_block_size
<<= 1;
3216 frames_per_block
= req
.tp_block_size
/req
.tp_frame_size
;
3219 * PACKET_TIMESTAMP was added after linux/net_tstamp.h was,
3220 * so we check for PACKET_TIMESTAMP. We check for
3221 * linux/net_tstamp.h just in case a system somehow has
3222 * PACKET_TIMESTAMP but not linux/net_tstamp.h; that might
3225 * SIOCSHWTSTAMP was introduced in the patch that introduced
3226 * linux/net_tstamp.h, so we don't bother checking whether
3227 * SIOCSHWTSTAMP is defined (if your Linux system has
3228 * linux/net_tstamp.h but doesn't define SIOCSHWTSTAMP, your
3229 * Linux system is badly broken).
3231 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
3233 * If we were told to do so, ask the kernel and the driver
3234 * to use hardware timestamps.
3236 * Hardware timestamps are only supported with mmapped
3239 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
||
3240 handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER_UNSYNCED
) {
3241 struct hwtstamp_config hwconfig
;
3246 * Ask for hardware time stamps on all packets,
3247 * including transmitted packets.
3249 memset(&hwconfig
, 0, sizeof(hwconfig
));
3250 hwconfig
.tx_type
= HWTSTAMP_TX_ON
;
3251 hwconfig
.rx_filter
= HWTSTAMP_FILTER_ALL
;
3253 memset(&ifr
, 0, sizeof(ifr
));
3254 pcapint_strlcpy(ifr
.ifr_name
, handle
->opt
.device
, sizeof(ifr
.ifr_name
));
3255 ifr
.ifr_data
= (void *)&hwconfig
;
3258 * This may require CAP_NET_ADMIN.
3260 if (ioctl(handle
->fd
, SIOCSHWTSTAMP
, &ifr
) < 0) {
3265 * Treat this as an error, as the
3266 * user should try to run this
3267 * with the appropriate privileges -
3268 * and, if they can't, shouldn't
3269 * try requesting hardware time stamps.
3271 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3272 "Attempt to set hardware timestamp failed - CAP_NET_ADMIN may be required");
3273 return PCAP_ERROR_PERM_DENIED
;
3278 * Treat this as a warning, as the
3279 * only way to fix the warning is to
3280 * get an adapter that supports hardware
3281 * time stamps for *all* packets.
3282 * (ERANGE means "we support hardware
3283 * time stamps, but for packets matching
3284 * that particular filter", so it means
3285 * "we don't support hardware time stamps
3286 * for all incoming packets" here.)
3288 * We'll just fall back on the standard
3291 status
= PCAP_WARNING_TSTAMP_TYPE_NOTSUP
;
3295 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
3296 PCAP_ERRBUF_SIZE
, errno
,
3297 "SIOCSHWTSTAMP failed");
3302 * Well, that worked. Now specify the type of
3303 * hardware time stamp we want for this
3306 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
) {
3308 * Hardware timestamp, synchronized
3309 * with the system clock.
3311 timesource
= SOF_TIMESTAMPING_SYS_HARDWARE
;
3314 * PCAP_TSTAMP_ADAPTER_UNSYNCED - hardware
3315 * timestamp, not synchronized with the
3318 timesource
= SOF_TIMESTAMPING_RAW_HARDWARE
;
3320 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_TIMESTAMP
,
3321 (void *)×ource
, sizeof(timesource
))) {
3322 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
3323 PCAP_ERRBUF_SIZE
, errno
,
3324 "can't set PACKET_TIMESTAMP");
3329 #endif /* HAVE_LINUX_NET_TSTAMP_H && PACKET_TIMESTAMP */
3331 /* ask the kernel to create the ring */
3333 req
.tp_block_nr
= req
.tp_frame_nr
/ frames_per_block
;
3335 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
3336 req
.tp_frame_nr
= req
.tp_block_nr
* frames_per_block
;
3338 #ifdef HAVE_TPACKET3
3339 /* timeout value to retire block - use the configured buffering timeout, or default if <0. */
3340 if (handlep
->timeout
> 0) {
3341 /* Use the user specified timeout as the block timeout */
3342 req
.tp_retire_blk_tov
= handlep
->timeout
;
3343 } else if (handlep
->timeout
== 0) {
3345 * In pcap, this means "infinite timeout"; TPACKET_V3
3346 * doesn't support that, so just set it to UINT_MAX
3347 * milliseconds. In the TPACKET_V3 loop, if the
3348 * timeout is 0, and we haven't yet seen any packets,
3349 * and we block and still don't have any packets, we
3350 * keep blocking until we do.
3352 req
.tp_retire_blk_tov
= UINT_MAX
;
3355 * XXX - this is not valid; use 0, meaning "have the
3356 * kernel pick a default", for now.
3358 req
.tp_retire_blk_tov
= 0;
3360 /* private data not used */
3361 req
.tp_sizeof_priv
= 0;
3362 /* Rx ring - feature request bits - none (rxhash will not be filled) */
3363 req
.tp_feature_req_word
= 0;
3366 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
3367 (void *) &req
, sizeof(req
))) {
3368 if ((errno
== ENOMEM
) && (req
.tp_block_nr
> 1)) {
3370 * Memory failure; try to reduce the requested ring
3373 * We used to reduce this by half -- do 5% instead.
3374 * That may result in more iterations and a longer
3375 * startup, but the user will be much happier with
3376 * the resulting buffer size.
3378 if (req
.tp_frame_nr
< 20)
3379 req
.tp_frame_nr
-= 1;
3381 req
.tp_frame_nr
-= req
.tp_frame_nr
/20;
3384 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3385 errno
, "can't create rx ring on packet socket");
3389 /* memory map the rx ring */
3390 handlep
->mmapbuflen
= req
.tp_block_nr
* req
.tp_block_size
;
3392 if (pcapint_mmap_32bit
) flags
|= MAP_32BIT
;
3394 handlep
->mmapbuf
= mmap(0, handlep
->mmapbuflen
, PROT_READ
| PROT_WRITE
, flags
, handle
->fd
, 0);
3395 if (handlep
->mmapbuf
== MAP_FAILED
) {
3396 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3397 errno
, "can't mmap rx ring");
3399 /* clear the allocated ring on error*/
3400 destroy_ring(handle
);
3404 /* allocate a ring for each frame header pointer*/
3405 handle
->cc
= req
.tp_frame_nr
;
3406 handle
->buffer
= malloc(handle
->cc
* sizeof(union thdr
*));
3407 if (!handle
->buffer
) {
3408 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3409 errno
, "can't allocate ring of frame headers");
3411 destroy_ring(handle
);
3415 /* fill the header ring with proper frame ptr*/
3417 for (i
=0; i
<req
.tp_block_nr
; ++i
) {
3418 u_char
*base
= &handlep
->mmapbuf
[i
*req
.tp_block_size
];
3419 for (j
=0; j
<frames_per_block
; ++j
, ++handle
->offset
) {
3420 RING_GET_CURRENT_FRAME(handle
) = base
;
3421 base
+= req
.tp_frame_size
;
3425 handle
->bufsize
= req
.tp_frame_size
;
3430 /* free all ring related resources*/
3432 destroy_ring(pcap_t
*handle
)
3434 struct pcap_linux
*handlep
= handle
->priv
;
3437 * Tell the kernel to destroy the ring.
3438 * We don't check for setsockopt failure, as 1) we can't recover
3439 * from an error and 2) we might not yet have set it up in the
3442 struct tpacket_req req
;
3443 memset(&req
, 0, sizeof(req
));
3444 (void)setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
3445 (void *) &req
, sizeof(req
));
3447 /* if ring is mapped, unmap it*/
3448 if (handlep
->mmapbuf
) {
3449 /* do not test for mmap failure, as we can't recover from any error */
3450 (void)munmap(handlep
->mmapbuf
, handlep
->mmapbuflen
);
3451 handlep
->mmapbuf
= NULL
;
3456 * Special one-shot callback, used for pcap_next() and pcap_next_ex(),
3457 * for Linux mmapped capture.
3459 * The problem is that pcap_next() and pcap_next_ex() expect the packet
3460 * data handed to the callback to be valid after the callback returns,
3461 * but pcap_read_linux_mmap() has to release that packet as soon as
3462 * the callback returns (otherwise, the kernel thinks there's still
3463 * at least one unprocessed packet available in the ring, so a select()
3464 * will immediately return indicating that there's data to process), so,
3465 * in the callback, we have to make a copy of the packet.
3467 * Yes, this means that, if the capture is using the ring buffer, using
3468 * pcap_next() or pcap_next_ex() requires more copies than using
3469 * pcap_loop() or pcap_dispatch(). If that bothers you, don't use
3470 * pcap_next() or pcap_next_ex().
3473 pcapint_oneshot_linux(u_char
*user
, const struct pcap_pkthdr
*h
,
3474 const u_char
*bytes
)
3476 struct oneshot_userdata
*sp
= (struct oneshot_userdata
*)user
;
3477 pcap_t
*handle
= sp
->pd
;
3478 struct pcap_linux
*handlep
= handle
->priv
;
3481 memcpy(handlep
->oneshot_buffer
, bytes
, h
->caplen
);
3482 *sp
->pkt
= handlep
->oneshot_buffer
;
3486 pcap_getnonblock_linux(pcap_t
*handle
)
3488 struct pcap_linux
*handlep
= handle
->priv
;
3490 /* use negative value of timeout to indicate non blocking ops */
3491 return (handlep
->timeout
<0);
3495 pcap_setnonblock_linux(pcap_t
*handle
, int nonblock
)
3497 struct pcap_linux
*handlep
= handle
->priv
;
3500 * Set the file descriptor to the requested mode, as we use
3501 * it for sending packets.
3503 if (pcapint_setnonblock_fd(handle
, nonblock
) == -1)
3507 * Map each value to their corresponding negation to
3508 * preserve the timeout value provided with pcap_set_timeout.
3512 * We're setting the mode to non-blocking mode.
3514 if (handlep
->timeout
>= 0) {
3516 * Indicate that we're switching to
3517 * non-blocking mode.
3519 handlep
->timeout
= ~handlep
->timeout
;
3521 if (handlep
->poll_breakloop_fd
!= -1) {
3522 /* Close the eventfd; we do not need it in nonblock mode. */
3523 close(handlep
->poll_breakloop_fd
);
3524 handlep
->poll_breakloop_fd
= -1;
3528 * We're setting the mode to blocking mode.
3530 if (handlep
->poll_breakloop_fd
== -1) {
3531 /* If we did not have an eventfd, open one now that we are blocking. */
3532 if ( ( handlep
->poll_breakloop_fd
= eventfd(0, EFD_NONBLOCK
) ) == -1 ) {
3533 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
3534 PCAP_ERRBUF_SIZE
, errno
,
3535 "could not open eventfd");
3539 if (handlep
->timeout
< 0) {
3540 handlep
->timeout
= ~handlep
->timeout
;
3543 /* Update the timeout to use in poll(). */
3544 set_poll_timeout(handlep
);
3549 * Get the status field of the ring buffer frame at a specified offset.
3552 pcap_get_ring_frame_status(pcap_t
*handle
, u_int offset
)
3554 struct pcap_linux
*handlep
= handle
->priv
;
3557 h
.raw
= RING_GET_FRAME_AT(handle
, offset
);
3558 switch (handlep
->tp_version
) {
3560 return __atomic_load_n(&h
.h2
->tp_status
, __ATOMIC_ACQUIRE
);
3562 #ifdef HAVE_TPACKET3
3564 return __atomic_load_n(&h
.h3
->hdr
.bh1
.block_status
, __ATOMIC_ACQUIRE
);
3568 /* This should not happen. */
3573 * Block waiting for frames to be available.
3575 static int pcap_wait_for_frames_mmap(pcap_t
*handle
)
3577 struct pcap_linux
*handlep
= handle
->priv
;
3581 struct pollfd pollinfo
[2];
3583 pollinfo
[0].fd
= handle
->fd
;
3584 pollinfo
[0].events
= POLLIN
;
3585 if ( handlep
->poll_breakloop_fd
== -1 ) {
3587 pollinfo
[1].revents
= 0;
3589 * We set pollinfo[1].revents to zero, even though
3590 * numpollinfo = 1 meaning that poll() doesn't see
3591 * pollinfo[1], so that we do not have to add a
3592 * conditional of numpollinfo > 1 below when we
3593 * test pollinfo[1].revents.
3596 pollinfo
[1].fd
= handlep
->poll_breakloop_fd
;
3597 pollinfo
[1].events
= POLLIN
;
3602 * Keep polling until we either get some packets to read, see
3603 * that we got told to break out of the loop, get a fatal error,
3604 * or discover that the device went away.
3606 * In non-blocking mode, we must still do one poll() to catch
3607 * any pending error indications, but the poll() has a timeout
3608 * of 0, so that it doesn't block, and we quit after that one
3611 * If we've seen an ENETDOWN, it might be the first indication
3612 * that the device went away, or it might just be that it was
3613 * configured down. Unfortunately, there's no guarantee that
3614 * the device has actually been removed as an interface, because:
3616 * 1) if, as appears to be the case at least some of the time,
3617 * the PF_PACKET socket code first gets a NETDEV_DOWN indication
3618 * for the device and then gets a NETDEV_UNREGISTER indication
3619 * for it, the first indication will cause a wakeup with ENETDOWN
3620 * but won't set the packet socket's field for the interface index
3621 * to -1, and the second indication won't cause a wakeup (because
3622 * the first indication also caused the protocol hook to be
3623 * unregistered) but will set the packet socket's field for the
3624 * interface index to -1;
3626 * 2) even if just a NETDEV_UNREGISTER indication is registered,
3627 * the packet socket's field for the interface index only gets
3628 * set to -1 after the wakeup, so there's a small but non-zero
3629 * risk that a thread blocked waiting for the wakeup will get
3630 * to the "fetch the socket name" code before the interface index
3631 * gets set to -1, so it'll get the old interface index.
3633 * Therefore, if we got an ENETDOWN and haven't seen a packet
3634 * since then, we assume that we might be waiting for the interface
3635 * to disappear, and poll with a timeout to try again in a short
3636 * period of time. If we *do* see a packet, the interface has
3637 * come back up again, and is *definitely* still there, so we
3638 * don't need to poll.
3642 * Yes, we do this even in non-blocking mode, as it's
3643 * the only way to get error indications from a
3646 * The timeout is 0 in non-blocking mode, so poll()
3647 * returns immediately.
3649 timeout
= handlep
->poll_timeout
;
3652 * If we got an ENETDOWN and haven't gotten an indication
3653 * that the device has gone away or that the device is up,
3654 * we don't yet know for certain whether the device has
3655 * gone away or not, do a poll() with a 1-millisecond timeout,
3656 * as we have to poll indefinitely for "device went away"
3657 * indications until we either get one or see that the
3660 if (handlep
->netdown
) {
3664 ret
= poll(pollinfo
, numpollinfo
, timeout
);
3667 * Error. If it's not EINTR, report it.
3669 if (errno
!= EINTR
) {
3670 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
3671 PCAP_ERRBUF_SIZE
, errno
,
3672 "can't poll on packet socket");
3677 * It's EINTR; if we were told to break out of
3680 if (handle
->break_loop
) {
3681 handle
->break_loop
= 0;
3682 return PCAP_ERROR_BREAK
;
3684 } else if (ret
> 0) {
3686 * OK, some descriptor is ready.
3687 * Check the socket descriptor first.
3689 * As I read the Linux man page, pollinfo[0].revents
3690 * will either be POLLIN, POLLERR, POLLHUP, or POLLNVAL.
3692 if (pollinfo
[0].revents
== POLLIN
) {
3694 * OK, we may have packets to
3699 if (pollinfo
[0].revents
!= 0) {
3701 * There's some indication other than
3702 * "you can read on this descriptor" on
3705 if (pollinfo
[0].revents
& POLLNVAL
) {
3706 snprintf(handle
->errbuf
,
3708 "Invalid polling request on packet socket");
3711 if (pollinfo
[0].revents
& (POLLHUP
| POLLRDHUP
)) {
3712 snprintf(handle
->errbuf
,
3714 "Hangup on packet socket");
3717 if (pollinfo
[0].revents
& POLLERR
) {
3724 errlen
= sizeof(err
);
3725 if (getsockopt(handle
->fd
, SOL_SOCKET
,
3726 SO_ERROR
, &err
, &errlen
) == -1) {
3728 * The call *itself* returned
3729 * an error; make *that*
3736 * OK, we have the error.
3738 if (err
== ENETDOWN
) {
3740 * The device on which we're
3741 * capturing went away or the
3742 * interface was taken down.
3744 * We don't know for certain
3745 * which happened, and the
3746 * next poll() may indicate
3747 * that there are packets
3748 * to be read, so just set
3749 * a flag to get us to do
3750 * checks later, and set
3751 * the required select
3752 * timeout to 1 millisecond
3753 * so that event loops that
3754 * check our socket descriptor
3755 * also time out so that
3756 * they can call us and we
3757 * can do the checks.
3759 handlep
->netdown
= 1;
3760 handle
->required_select_timeout
= &netdown_timeout
;
3761 } else if (err
== 0) {
3763 * This shouldn't happen, so
3764 * report a special indication
3767 snprintf(handle
->errbuf
,
3769 "Error condition on packet socket: Reported error was 0");
3772 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
3775 "Error condition on packet socket");
3781 * Now check the event device.
3783 if (pollinfo
[1].revents
& POLLIN
) {
3788 * This should never fail, but, just
3791 nread
= read(handlep
->poll_breakloop_fd
, &value
,
3794 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
3797 "Error reading from event FD");
3802 * According to the Linux read(2) man
3803 * page, read() will transfer at most
3804 * 2^31-1 bytes, so the return value is
3805 * either -1 or a value between 0
3806 * and 2^31-1, so it's non-negative.
3808 * Cast it to size_t to squelch
3809 * warnings from the compiler; add this
3810 * comment to squelch warnings from
3811 * humans reading the code. :-)
3813 * Don't treat an EOF as an error, but
3814 * *do* treat a short read as an error;
3815 * that "shouldn't happen", but....
3818 (size_t)nread
< sizeof(value
)) {
3819 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3820 "Short read from event FD: expected %zu, got %zd",
3821 sizeof(value
), nread
);
3826 * This event gets signaled by a
3827 * pcap_breakloop() call; if we were told
3828 * to break out of the loop, do so.
3830 if (handle
->break_loop
) {
3831 handle
->break_loop
= 0;
3832 return PCAP_ERROR_BREAK
;
3840 * 1) we got neither an error from poll() nor any
3841 * readable descriptors, in which case there
3842 * are no packets waiting to read
3846 * 2) We got readable descriptors but the PF_PACKET
3847 * socket wasn't one of them, in which case there
3848 * are no packets waiting to read
3850 * so, if we got an ENETDOWN, we've drained whatever
3851 * packets were available to read at the point of the
3854 * So, if we got an ENETDOWN and haven't gotten an indication
3855 * that the device has gone away or that the device is up,
3856 * we don't yet know for certain whether the device has
3857 * gone away or not, check whether the device exists and is
3860 if (handlep
->netdown
) {
3861 if (!device_still_exists(handle
)) {
3863 * The device doesn't exist any more;
3866 * XXX - we should really return an
3867 * appropriate error for that, but
3868 * pcap_dispatch() etc. aren't documented
3869 * as having error returns other than
3870 * PCAP_ERROR or PCAP_ERROR_BREAK.
3872 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3873 "The interface disappeared");
3878 * The device still exists; try to see if it's up.
3880 memset(&ifr
, 0, sizeof(ifr
));
3881 pcapint_strlcpy(ifr
.ifr_name
, handlep
->device
,
3882 sizeof(ifr
.ifr_name
));
3883 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
3884 if (errno
== ENXIO
|| errno
== ENODEV
) {
3886 * OK, *now* it's gone.
3888 * XXX - see above comment.
3890 snprintf(handle
->errbuf
,
3892 "The interface disappeared");
3895 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
3896 PCAP_ERRBUF_SIZE
, errno
,
3897 "%s: Can't get flags",
3902 if (ifr
.ifr_flags
& IFF_UP
) {
3904 * It's up, so it definitely still exists.
3905 * Cancel the ENETDOWN indication - we
3906 * presumably got it due to the interface
3907 * going down rather than the device going
3908 * away - and revert to "no required select
3911 handlep
->netdown
= 0;
3912 handle
->required_select_timeout
= NULL
;
3917 * If we're in non-blocking mode, just quit now, rather
3918 * than spinning in a loop doing poll()s that immediately
3919 * time out if there's no indication on any descriptor.
3921 if (handlep
->poll_timeout
== 0)
3927 /* handle a single memory mapped packet */
3928 static int pcap_handle_packet_mmap(
3930 pcap_handler callback
,
3932 unsigned char *frame
,
3933 unsigned int tp_len
,
3934 unsigned int tp_mac
,
3935 unsigned int tp_snaplen
,
3936 unsigned int tp_sec
,
3937 unsigned int tp_usec
,
3938 int tp_vlan_tci_valid
,
3942 struct pcap_linux
*handlep
= handle
->priv
;
3944 struct sockaddr_ll
*sll
;
3945 struct pcap_pkthdr pcaphdr
;
3946 unsigned int snaplen
= tp_snaplen
;
3947 struct utsname utsname
;
3949 /* perform sanity check on internal offset. */
3950 if (tp_mac
+ tp_snaplen
> handle
->bufsize
) {
3952 * Report some system information as a debugging aid.
3954 if (uname(&utsname
) != -1) {
3955 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3956 "corrupted frame on kernel ring mac "
3957 "offset %u + caplen %u > frame len %d "
3958 "(kernel %.32s version %s, machine %.16s)",
3959 tp_mac
, tp_snaplen
, handle
->bufsize
,
3960 utsname
.release
, utsname
.version
,
3963 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3964 "corrupted frame on kernel ring mac "
3965 "offset %u + caplen %u > frame len %d",
3966 tp_mac
, tp_snaplen
, handle
->bufsize
);
3971 /* run filter on received packet
3972 * If the kernel filtering is enabled we need to run the
3973 * filter until all the frames present into the ring
3974 * at filter creation time are processed.
3975 * In this case, blocks_to_filter_in_userland is used
3976 * as a counter for the packet we need to filter.
3977 * Note: alternatively it could be possible to stop applying
3978 * the filter when the ring became empty, but it can possibly
3979 * happen a lot later... */
3980 bp
= frame
+ tp_mac
;
3982 /* if required build in place the sll header*/
3983 sll
= (void *)(frame
+ TPACKET_ALIGN(handlep
->tp_hdrlen
));
3984 if (handlep
->cooked
) {
3985 if (handle
->linktype
== DLT_LINUX_SLL2
) {
3986 struct sll2_header
*hdrp
;
3989 * The kernel should have left us with enough
3990 * space for an sll header; back up the packet
3991 * data pointer into that space, as that'll be
3992 * the beginning of the packet we pass to the
3998 * Let's make sure that's past the end of
3999 * the tpacket header, i.e. >=
4000 * ((u_char *)thdr + TPACKET_HDRLEN), so we
4001 * don't step on the header when we construct
4004 if (bp
< (u_char
*)frame
+
4005 TPACKET_ALIGN(handlep
->tp_hdrlen
) +
4006 sizeof(struct sockaddr_ll
)) {
4007 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4008 "cooked-mode frame doesn't have room for sll header");
4013 * OK, that worked; construct the sll header.
4015 hdrp
= (struct sll2_header
*)bp
;
4016 hdrp
->sll2_protocol
= sll
->sll_protocol
;
4017 hdrp
->sll2_reserved_mbz
= 0;
4018 hdrp
->sll2_if_index
= htonl(sll
->sll_ifindex
);
4019 hdrp
->sll2_hatype
= htons(sll
->sll_hatype
);
4020 hdrp
->sll2_pkttype
= sll
->sll_pkttype
;
4021 hdrp
->sll2_halen
= sll
->sll_halen
;
4022 memcpy(hdrp
->sll2_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
4024 snaplen
+= sizeof(struct sll2_header
);
4026 struct sll_header
*hdrp
;
4029 * The kernel should have left us with enough
4030 * space for an sll header; back up the packet
4031 * data pointer into that space, as that'll be
4032 * the beginning of the packet we pass to the
4038 * Let's make sure that's past the end of
4039 * the tpacket header, i.e. >=
4040 * ((u_char *)thdr + TPACKET_HDRLEN), so we
4041 * don't step on the header when we construct
4044 if (bp
< (u_char
*)frame
+
4045 TPACKET_ALIGN(handlep
->tp_hdrlen
) +
4046 sizeof(struct sockaddr_ll
)) {
4047 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4048 "cooked-mode frame doesn't have room for sll header");
4053 * OK, that worked; construct the sll header.
4055 hdrp
= (struct sll_header
*)bp
;
4056 hdrp
->sll_pkttype
= htons(sll
->sll_pkttype
);
4057 hdrp
->sll_hatype
= htons(sll
->sll_hatype
);
4058 hdrp
->sll_halen
= htons(sll
->sll_halen
);
4059 memcpy(hdrp
->sll_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
4060 hdrp
->sll_protocol
= sll
->sll_protocol
;
4062 snaplen
+= sizeof(struct sll_header
);
4066 * If this is a packet from a CAN device, so that
4067 * sll->sll_hatype is ARPHRD_CAN, then, as we're
4068 * not capturing in cooked mode, its link-layer
4069 * type is DLT_CAN_SOCKETCAN. Fix up the header
4070 * provided by the code below us to match what
4071 * DLT_CAN_SOCKETCAN is expected to provide.
4073 if (sll
->sll_hatype
== ARPHRD_CAN
) {
4074 pcap_can_socketcan_hdr
*canhdr
= (pcap_can_socketcan_hdr
*)bp
;
4075 pcap_can_socketcan_xl_hdr
*canxl_hdr
= (pcap_can_socketcan_xl_hdr
*)bp
;
4076 uint16_t protocol
= ntohs(sll
->sll_protocol
);
4079 * Check the protocol field from the sll header.
4080 * If it's one of the known CAN protocol types,
4081 * make sure the appropriate flags are set, so
4082 * that a program can tell what type of frame
4085 * These operations should not have any effect
4086 * when reading proper CAN frames from Linux
4087 * CAN interfaces. Enforcing these bit values
4088 * ensures proper DLT_CAN_SOCKETCAN data even
4089 * with malformed PF_PACKET content.
4091 * The two flags are:
4093 * CANFD_FDF, which is in the fd_flags field
4094 * of the CAN CC/CAN FD header;
4096 * CANXL_XLF, which is in the flags field
4097 * of the CAN XL header, which overlaps
4098 * the payload_length field of the CAN CC/
4099 * CAN FD header. Setting CANXL_XLF in the
4100 * payload_length of CAN CC/FD frames would
4101 * intentionally break the payload length.
4105 case LINUX_SLL_P_CAN
:
4107 * CAN CC frame (aka Classical CAN, CAN 2.0B)
4109 * Zero out the CAN FD and CAN XL flags
4110 * so that this frame will be identified
4111 * as a CAN CC frame.
4113 canxl_hdr
->flags
&= ~CANXL_XLF
;
4114 canhdr
->fd_flags
&= ~CANFD_FDF
;
4117 case LINUX_SLL_P_CANFD
:
4121 * Set CANFD_FDF in the fd_flags field,
4122 * and clear the CANXL_XLF bit in the
4123 * CAN XL flags field, so that this frame
4124 * will be identified as a CAN FD frame.
4126 * The CANFD_FDF bit is not reliably
4127 * set by the Linux kernel. But setting
4128 * that bit for CAN FD is recommended.
4130 canxl_hdr
->flags
&= ~CANXL_XLF
;
4131 canhdr
->fd_flags
|= CANFD_FDF
;
4134 case LINUX_SLL_P_CANXL
:
4138 * Set CANXL_XLF bit in the CAN XL flags
4139 * field, so that this frame will appear
4140 * to be a CAN XL frame.
4142 canxl_hdr
->flags
|= CANXL_XLF
;
4147 * Put multi-byte header fields in a byte-order
4148 *-independent format.
4150 if (canxl_hdr
->flags
& CANXL_XLF
) {
4152 * This is a CAN XL frame.
4154 * DLT_CAN_SOCKETCAN is specified as having
4155 * the Priority ID/VCID field in big--
4156 * endian byte order, and the payload length
4157 * and Acceptance Field in little-endian byte
4158 * order. but capturing on a CAN device
4159 * provides them in host byte order.
4160 * Convert them to the appropriate byte
4163 * The reason we put the first field
4164 * into big-endian byte order is that
4165 * older libpcap code, ignorant of
4166 * CAN XL, treated it as the CAN ID
4167 * field and put it into big-endian
4168 * byte order, and we don't want to
4169 * break code that understands CAN XL
4170 * headers, and treats that field as
4173 * The other fields are put in little-
4174 * endian byte order is that older
4175 * libpcap code, ignorant of CAN XL,
4176 * left those fields alone, and the
4177 * processors on which the CAN XL
4178 * frames were captured are likely
4179 * to be little-endian processors.
4182 #if __BYTE_ORDER == __LITTLE_ENDIAN
4184 * We're capturing on a little-endian
4185 * machine, so we put the priority/VCID
4186 * field into big-endian byte order, and
4187 * leave the payload length and acceptance
4188 * field in little-endian byte order.
4190 /* Byte-swap priority/VCID. */
4191 canxl_hdr
->priority_vcid
= SWAPLONG(canxl_hdr
->priority_vcid
);
4192 #elif __BYTE_ORDER == __BIG_ENDIAN
4194 * We're capturing on a big-endian
4195 * machine, so we want to leave the
4196 * priority/VCID field alone, and byte-swap
4197 * the payload length and acceptance
4198 * fields to little-endian.
4200 /* Byte-swap the payload length */
4201 canxl_hdr
->payload_length
= SWAPSHORT(canxl_hdr
->payload_length
);
4204 * Byte-swap the acceptance field.
4206 * XXX - is it just a 4-octet string,
4207 * not in any byte order?
4209 canxl_hdr
->acceptance_field
= SWAPLONG(canxl_hdr
->acceptance_field
);
4211 #error "Unknown byte order"
4215 * CAN CC or CAN FD frame.
4217 * DLT_CAN_SOCKETCAN is specified as having
4218 * the CAN ID and flags in network byte
4219 * order, but capturing on a CAN device
4220 * provides it in host byte order. Convert
4221 * it to network byte order.
4223 canhdr
->can_id
= htonl(canhdr
->can_id
);
4228 if (handlep
->filter_in_userland
&& handle
->fcode
.bf_insns
) {
4229 struct pcap_bpf_aux_data aux_data
;
4231 aux_data
.vlan_tag_present
= tp_vlan_tci_valid
;
4232 aux_data
.vlan_tag
= tp_vlan_tci
& 0x0fff;
4234 if (pcapint_filter_with_aux_data(handle
->fcode
.bf_insns
,
4242 if (!linux_check_direction(handle
, sll
))
4246 * Get required packet info from ring header.
4248 * The seconds part of the time stamp is a 32-bit
4249 * unsigned integer; this will have a problem in 2106,
4252 * ts.tv_sec is a time_t, which is signed, and which
4253 * may be 32-bit or 64-bit. Pass it through; if we
4254 * have a 32-bit signed time_t, in which values >
4255 * 2^31-1 won't fit, then:
4257 * Writing the packet to a file will pass the bits
4258 * through. If the program reading the file can
4259 * handle 32-bit unsigned time stamps, including
4260 * any conversion to local time or UTC, it will
4261 * properly handle the time stamps.
4263 * Reporting the packet time stamp may give
4264 * an error or a pre-1970 time stamp on platforms
4265 * with signed 32-bit time stamps, but that
4266 * will happen even if it's captured on a
4267 * platform with a 64-bit time_t.
4269 pcaphdr
.ts
.tv_sec
= tp_sec
;
4270 pcaphdr
.ts
.tv_usec
= tp_usec
;
4271 pcaphdr
.caplen
= tp_snaplen
;
4272 pcaphdr
.len
= tp_len
;
4274 /* if required build in place the sll header*/
4275 if (handlep
->cooked
) {
4276 /* update packet len */
4277 if (handle
->linktype
== DLT_LINUX_SLL2
) {
4278 pcaphdr
.caplen
+= SLL2_HDR_LEN
;
4279 pcaphdr
.len
+= SLL2_HDR_LEN
;
4281 pcaphdr
.caplen
+= SLL_HDR_LEN
;
4282 pcaphdr
.len
+= SLL_HDR_LEN
;
4286 if (tp_vlan_tci_valid
&&
4287 handlep
->vlan_offset
!= -1 &&
4288 tp_snaplen
>= (unsigned int) handlep
->vlan_offset
)
4290 struct vlan_tag
*tag
;
4293 * Move everything in the header, except the type field,
4294 * down VLAN_TAG_LEN bytes, to allow us to insert the
4295 * VLAN tag between that stuff and the type field.
4298 memmove(bp
, bp
+ VLAN_TAG_LEN
, handlep
->vlan_offset
);
4301 * Now insert the tag.
4303 tag
= (struct vlan_tag
*)(bp
+ handlep
->vlan_offset
);
4304 tag
->vlan_tpid
= htons(tp_vlan_tpid
);
4305 tag
->vlan_tci
= htons(tp_vlan_tci
);
4308 * Add the tag to the packet lengths.
4310 pcaphdr
.caplen
+= VLAN_TAG_LEN
;
4311 pcaphdr
.len
+= VLAN_TAG_LEN
;
4315 * The only way to tell the kernel to cut off the
4316 * packet at a snapshot length is with a filter program;
4317 * if there's no filter program, the kernel won't cut
4320 * Trim the snapshot length to be no longer than the
4321 * specified snapshot length.
4323 * XXX - an alternative is to put a filter, consisting
4324 * of a "ret <snaplen>" instruction, on the socket
4325 * in the activate routine, so that the truncation is
4326 * done in the kernel even if nobody specified a filter;
4327 * that means that less buffer space is consumed in
4328 * the memory-mapped buffer.
4330 if (pcaphdr
.caplen
> (bpf_u_int32
)handle
->snapshot
)
4331 pcaphdr
.caplen
= handle
->snapshot
;
4333 /* pass the packet to the user */
4334 callback(user
, &pcaphdr
, bp
);
4340 pcap_read_linux_mmap_v2(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
4343 struct pcap_linux
*handlep
= handle
->priv
;
4348 /* wait for frames availability.*/
4349 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4350 if (!packet_mmap_acquire(h
.h2
)) {
4352 * The current frame is owned by the kernel; wait for
4353 * a frame to be handed to us.
4355 ret
= pcap_wait_for_frames_mmap(handle
);
4362 * This can conceivably process more than INT_MAX packets,
4363 * which would overflow the packet count, causing it either
4364 * to look like a negative number, and thus cause us to
4365 * return a value that looks like an error, or overflow
4366 * back into positive territory, and thus cause us to
4367 * return a too-low count.
4369 * Therefore, if the packet count is unlimited, we clip
4370 * it at INT_MAX; this routine is not expected to
4371 * process packets indefinitely, so that's not an issue.
4373 if (PACKET_COUNT_IS_UNLIMITED(max_packets
))
4374 max_packets
= INT_MAX
;
4376 while (pkts
< max_packets
) {
4378 * Get the current ring buffer frame, and break if
4379 * it's still owned by the kernel.
4381 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4382 if (!packet_mmap_acquire(h
.h2
))
4385 ret
= pcap_handle_packet_mmap(
4394 handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
? h
.h2
->tp_nsec
: h
.h2
->tp_nsec
/ 1000,
4395 VLAN_VALID(h
.h2
, h
.h2
),
4397 VLAN_TPID(h
.h2
, h
.h2
));
4400 } else if (ret
< 0) {
4405 * Hand this block back to the kernel, and, if we're
4406 * counting blocks that need to be filtered in userland
4407 * after having been filtered by the kernel, count
4408 * the one we've just processed.
4410 packet_mmap_release(h
.h2
);
4411 if (handlep
->blocks_to_filter_in_userland
!= 0) {
4412 handlep
->blocks_to_filter_in_userland
--;
4413 if (handlep
->blocks_to_filter_in_userland
== 0) {
4415 * No more blocks need to be filtered
4418 handlep
->filter_in_userland
= 0;
4423 if (++handle
->offset
>= handle
->cc
)
4426 /* check for break loop condition*/
4427 if (handle
->break_loop
) {
4428 handle
->break_loop
= 0;
4429 return PCAP_ERROR_BREAK
;
4435 #ifdef HAVE_TPACKET3
4437 pcap_read_linux_mmap_v3(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
4440 struct pcap_linux
*handlep
= handle
->priv
;
4446 if (handlep
->current_packet
== NULL
) {
4447 /* wait for frames availability.*/
4448 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4449 if (!packet_mmap_v3_acquire(h
.h3
)) {
4451 * The current frame is owned by the kernel; wait
4452 * for a frame to be handed to us.
4454 ret
= pcap_wait_for_frames_mmap(handle
);
4460 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4461 if (!packet_mmap_v3_acquire(h
.h3
)) {
4462 if (pkts
== 0 && handlep
->timeout
== 0) {
4463 /* Block until we see a packet. */
4470 * This can conceivably process more than INT_MAX packets,
4471 * which would overflow the packet count, causing it either
4472 * to look like a negative number, and thus cause us to
4473 * return a value that looks like an error, or overflow
4474 * back into positive territory, and thus cause us to
4475 * return a too-low count.
4477 * Therefore, if the packet count is unlimited, we clip
4478 * it at INT_MAX; this routine is not expected to
4479 * process packets indefinitely, so that's not an issue.
4481 if (PACKET_COUNT_IS_UNLIMITED(max_packets
))
4482 max_packets
= INT_MAX
;
4484 while (pkts
< max_packets
) {
4485 int packets_to_read
;
4487 if (handlep
->current_packet
== NULL
) {
4488 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4489 if (!packet_mmap_v3_acquire(h
.h3
))
4492 handlep
->current_packet
= h
.raw
+ h
.h3
->hdr
.bh1
.offset_to_first_pkt
;
4493 handlep
->packets_left
= h
.h3
->hdr
.bh1
.num_pkts
;
4495 packets_to_read
= handlep
->packets_left
;
4497 if (packets_to_read
> (max_packets
- pkts
)) {
4499 * There are more packets in the buffer than
4500 * the number of packets we have left to
4501 * process to get up to the maximum number
4502 * of packets to process. Only process enough
4503 * of them to get us up to that maximum.
4505 packets_to_read
= max_packets
- pkts
;
4508 while (packets_to_read
-- && !handle
->break_loop
) {
4509 struct tpacket3_hdr
* tp3_hdr
= (struct tpacket3_hdr
*) handlep
->current_packet
;
4510 ret
= pcap_handle_packet_mmap(
4514 handlep
->current_packet
,
4517 tp3_hdr
->tp_snaplen
,
4519 handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
? tp3_hdr
->tp_nsec
: tp3_hdr
->tp_nsec
/ 1000,
4520 VLAN_VALID(tp3_hdr
, &tp3_hdr
->hv1
),
4521 tp3_hdr
->hv1
.tp_vlan_tci
,
4522 VLAN_TPID(tp3_hdr
, &tp3_hdr
->hv1
));
4525 } else if (ret
< 0) {
4526 handlep
->current_packet
= NULL
;
4529 handlep
->current_packet
+= tp3_hdr
->tp_next_offset
;
4530 handlep
->packets_left
--;
4533 if (handlep
->packets_left
<= 0) {
4535 * Hand this block back to the kernel, and, if
4536 * we're counting blocks that need to be
4537 * filtered in userland after having been
4538 * filtered by the kernel, count the one we've
4541 packet_mmap_v3_release(h
.h3
);
4542 if (handlep
->blocks_to_filter_in_userland
!= 0) {
4543 handlep
->blocks_to_filter_in_userland
--;
4544 if (handlep
->blocks_to_filter_in_userland
== 0) {
4546 * No more blocks need to be filtered
4549 handlep
->filter_in_userland
= 0;
4554 if (++handle
->offset
>= handle
->cc
)
4557 handlep
->current_packet
= NULL
;
4560 /* check for break loop condition*/
4561 if (handle
->break_loop
) {
4562 handle
->break_loop
= 0;
4563 return PCAP_ERROR_BREAK
;
4566 if (pkts
== 0 && handlep
->timeout
== 0) {
4567 /* Block until we see a packet. */
4572 #endif /* HAVE_TPACKET3 */
4575 * Attach the given BPF code to the packet capture device.
4578 pcap_setfilter_linux(pcap_t
*handle
, struct bpf_program
*filter
)
4580 struct pcap_linux
*handlep
;
4581 struct sock_fprog fcode
;
4582 int can_filter_in_kernel
;
4589 pcapint_strlcpy(handle
->errbuf
, "setfilter: No filter specified",
4594 handlep
= handle
->priv
;
4596 /* Make our private copy of the filter */
4598 if (pcapint_install_bpf_program(handle
, filter
) < 0)
4599 /* pcapint_install_bpf_program() filled in errbuf */
4603 * Run user level packet filter by default. Will be overridden if
4604 * installing a kernel filter succeeds.
4606 handlep
->filter_in_userland
= 1;
4608 /* Install kernel level filter if possible */
4610 if (handle
->fcode
.bf_len
> USHRT_MAX
) {
4612 * fcode.len is an unsigned short for current kernel.
4613 * I have yet to see BPF-Code with that much
4614 * instructions but still it is possible. So for the
4615 * sake of correctness I added this check.
4617 fprintf(stderr
, "Warning: Filter too complex for kernel\n");
4619 fcode
.filter
= NULL
;
4620 can_filter_in_kernel
= 0;
4623 * Oh joy, the Linux kernel uses struct sock_fprog instead
4624 * of struct bpf_program and of course the length field is
4625 * of different size. Pointed out by Sebastian
4627 * Oh, and we also need to fix it up so that all "ret"
4628 * instructions with non-zero operands have MAXIMUM_SNAPLEN
4629 * as the operand if we're not capturing in memory-mapped
4630 * mode, and so that, if we're in cooked mode, all memory-
4631 * reference instructions use special magic offsets in
4632 * references to the link-layer header and assume that the
4633 * link-layer payload begins at 0; "fix_program()" will do
4636 switch (fix_program(handle
, &fcode
)) {
4641 * Fatal error; just quit.
4642 * (The "default" case shouldn't happen; we
4643 * return -1 for that reason.)
4649 * The program performed checks that we can't make
4650 * work in the kernel.
4652 can_filter_in_kernel
= 0;
4657 * We have a filter that'll work in the kernel.
4659 can_filter_in_kernel
= 1;
4665 * NOTE: at this point, we've set both the "len" and "filter"
4666 * fields of "fcode". As of the 2.6.32.4 kernel, at least,
4667 * those are the only members of the "sock_fprog" structure,
4668 * so we initialize every member of that structure.
4670 * If there is anything in "fcode" that is not initialized,
4671 * it is either a field added in a later kernel, or it's
4674 * If a new field is added, this code needs to be updated
4675 * to set it correctly.
4677 * If there are no other fields, then:
4679 * if the Linux kernel looks at the padding, it's
4682 * if the Linux kernel doesn't look at the padding,
4683 * then if some tool complains that we're passing
4684 * uninitialized data to the kernel, then the tool
4685 * is buggy and needs to understand that it's just
4688 if (can_filter_in_kernel
) {
4689 if ((err
= set_kernel_filter(handle
, &fcode
)) == 0)
4692 * Installation succeeded - using kernel filter,
4693 * so userland filtering not needed.
4695 handlep
->filter_in_userland
= 0;
4697 else if (err
== -1) /* Non-fatal error */
4700 * Print a warning if we weren't able to install
4701 * the filter for a reason other than "this kernel
4702 * isn't configured to support socket filters.
4704 if (errno
== ENOMEM
) {
4706 * Either a kernel memory allocation
4707 * failure occurred, or there's too
4708 * much "other/option memory" allocated
4709 * for this socket. Suggest that they
4710 * increase the "other/option memory"
4714 "Warning: Couldn't allocate kernel memory for filter: try increasing net.core.optmem_max with sysctl\n");
4715 } else if (errno
!= ENOPROTOOPT
&& errno
!= EOPNOTSUPP
) {
4717 "Warning: Kernel filter failed: %s\n",
4718 pcap_strerror(errno
));
4724 * If we're not using the kernel filter, get rid of any kernel
4725 * filter that might've been there before, e.g. because the
4726 * previous filter could work in the kernel, or because some other
4727 * code attached a filter to the socket by some means other than
4728 * calling "pcap_setfilter()". Otherwise, the kernel filter may
4729 * filter out packets that would pass the new userland filter.
4731 if (handlep
->filter_in_userland
) {
4732 if (reset_kernel_filter(handle
) == -1) {
4733 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
4734 PCAP_ERRBUF_SIZE
, errno
,
4735 "can't remove kernel filter");
4736 err
= -2; /* fatal error */
4741 * Free up the copy of the filter that was made by "fix_program()".
4743 if (fcode
.filter
!= NULL
)
4751 * If we're filtering in userland, there's nothing to do;
4752 * the new filter will be used for the next packet.
4754 if (handlep
->filter_in_userland
)
4758 * We're filtering in the kernel; the packets present in
4759 * all blocks currently in the ring were already filtered
4760 * by the old filter, and so will need to be filtered in
4761 * userland by the new filter.
4763 * Get an upper bound for the number of such blocks; first,
4764 * walk the ring backward and count the free blocks.
4766 offset
= handle
->offset
;
4768 offset
= handle
->cc
;
4770 for (n
=0; n
< handle
->cc
; ++n
) {
4772 offset
= handle
->cc
;
4774 if (pcap_get_ring_frame_status(handle
, offset
) != TP_STATUS_KERNEL
)
4779 * If we found free blocks, decrement the count of free
4780 * blocks by 1, just in case we lost a race with another
4781 * thread of control that was adding a packet while
4782 * we were counting and that had run the filter before
4785 * XXX - could there be more than one block added in
4788 * XXX - is there a way to avoid that race, e.g. somehow
4789 * wait for all packets that passed the old filter to
4790 * be added to the ring?
4796 * Set the count of blocks worth of packets to filter
4797 * in userland to the total number of blocks in the
4798 * ring minus the number of free blocks we found, and
4799 * turn on userland filtering. (The count of blocks
4800 * worth of packets to filter in userland is guaranteed
4801 * not to be zero - n, above, couldn't be set to a
4802 * value > handle->cc, and if it were equal to
4803 * handle->cc, it wouldn't be zero, and thus would
4804 * be decremented to handle->cc - 1.)
4806 handlep
->blocks_to_filter_in_userland
= handle
->cc
- n
;
4807 handlep
->filter_in_userland
= 1;
4813 * Return the index of the given device name. Fill ebuf and return
4817 iface_get_id(int fd
, const char *device
, char *ebuf
)
4821 memset(&ifr
, 0, sizeof(ifr
));
4822 pcapint_strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4824 if (ioctl(fd
, SIOCGIFINDEX
, &ifr
) == -1) {
4825 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
4826 errno
, "SIOCGIFINDEX");
4830 return ifr
.ifr_ifindex
;
4834 * Bind the socket associated with FD to the given device.
4835 * Return 0 on success or a PCAP_ERROR_ value on a hard error.
4838 iface_bind(int fd
, int ifindex
, char *ebuf
, int protocol
)
4840 struct sockaddr_ll sll
;
4842 socklen_t errlen
= sizeof(err
);
4844 memset(&sll
, 0, sizeof(sll
));
4845 sll
.sll_family
= AF_PACKET
;
4846 sll
.sll_ifindex
= ifindex
< 0 ? 0 : ifindex
;
4847 sll
.sll_protocol
= protocol
;
4849 if (bind(fd
, (struct sockaddr
*) &sll
, sizeof(sll
)) == -1) {
4850 if (errno
== ENETDOWN
) {
4852 * Return a "network down" indication, so that
4853 * the application can report that rather than
4854 * saying we had a mysterious failure and
4855 * suggest that they report a problem to the
4856 * libpcap developers.
4858 return PCAP_ERROR_IFACE_NOT_UP
;
4860 if (errno
== ENODEV
) {
4862 * There's nothing more to say, so clear the
4866 ret
= PCAP_ERROR_NO_SUCH_DEVICE
;
4869 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
4875 /* Any pending errors, e.g., network is down? */
4877 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
4878 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
4879 errno
, "getsockopt (SO_ERROR)");
4883 if (err
== ENETDOWN
) {
4885 * Return a "network down" indication, so that
4886 * the application can report that rather than
4887 * saying we had a mysterious failure and
4888 * suggest that they report a problem to the
4889 * libpcap developers.
4891 return PCAP_ERROR_IFACE_NOT_UP
;
4892 } else if (err
> 0) {
4893 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
4902 * Try to enter monitor mode.
4903 * If we have libnl, try to create a new monitor-mode device and
4904 * capture on that; otherwise, just say "not supported".
4908 enter_rfmon_mode(pcap_t
*handle
, int sock_fd
, const char *device
)
4910 struct pcap_linux
*handlep
= handle
->priv
;
4912 char phydev_path
[PATH_MAX
+1];
4913 struct nl80211_state nlstate
;
4918 * Is this a mac80211 device?
4920 ret
= get_mac80211_phydev(handle
, device
, phydev_path
, PATH_MAX
);
4922 return ret
; /* error */
4924 return 0; /* no error, but not mac80211 device */
4926 ret
= nl80211_init(handle
, &nlstate
, device
);
4931 * Is this already a monN device?
4932 * If so, we're done.
4935 ret
= get_if_type(handle
, sock_fd
, &nlstate
, device
, &type
);
4938 * < 0 is a Hard failure. Just return ret; handle->errbuf
4939 * has already been set.
4941 * 0 is "device not available"; the caller should retry later.
4943 nl80211_cleanup(&nlstate
);
4946 if (type
== NL80211_IFTYPE_MONITOR
) {
4948 * OK, it's already a monitor mode device; just use it.
4949 * There's no point in creating another monitor device
4950 * that will have to be cleaned up.
4952 nl80211_cleanup(&nlstate
);
4957 * OK, it's apparently a mac80211 device but not a monitor device.
4958 * Try to find an unused monN device for it.
4960 for (n
= 0; n
< UINT_MAX
; n
++) {
4964 char mondevice
[3+10+1]; /* mon{UINT_MAX}\0 */
4966 snprintf(mondevice
, sizeof mondevice
, "mon%u", n
);
4967 ret
= add_mon_if(handle
, sock_fd
, &nlstate
, device
, mondevice
);
4970 * Success. We don't clean up the libnl state
4971 * yet, as we'll be using it later.
4977 * Hard failure. Just return ret; handle->errbuf
4978 * has already been set.
4980 nl80211_cleanup(&nlstate
);
4985 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4986 "%s: No free monN interfaces", device
);
4987 nl80211_cleanup(&nlstate
);
4994 * Sleep for .1 seconds.
4997 delay
.tv_nsec
= 500000000;
4998 nanosleep(&delay
, NULL
);
5002 * If we haven't already done so, arrange to have
5003 * "pcap_close_all()" called when we exit.
5005 if (!pcapint_do_addexit(handle
)) {
5007 * "atexit()" failed; don't put the interface
5008 * in rfmon mode, just give up.
5009 * handle->errbuf has already been filled.
5011 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
5012 handlep
->mondevice
);
5013 nl80211_cleanup(&nlstate
);
5018 * Now configure the monitor interface up.
5020 memset(&ifr
, 0, sizeof(ifr
));
5021 pcapint_strlcpy(ifr
.ifr_name
, handlep
->mondevice
, sizeof(ifr
.ifr_name
));
5022 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
5023 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5024 errno
, "%s: Can't get flags for %s", device
,
5025 handlep
->mondevice
);
5026 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
5027 handlep
->mondevice
);
5028 nl80211_cleanup(&nlstate
);
5031 ifr
.ifr_flags
|= IFF_UP
|IFF_RUNNING
;
5032 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
5033 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5034 errno
, "%s: Can't set flags for %s", device
,
5035 handlep
->mondevice
);
5036 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
5037 handlep
->mondevice
);
5038 nl80211_cleanup(&nlstate
);
5043 * Success. Clean up the libnl state.
5045 nl80211_cleanup(&nlstate
);
5048 * Note that we have to delete the monitor device when we close
5051 handlep
->must_do_on_close
|= MUST_DELETE_MONIF
;
5054 * Add this to the list of pcaps to close when we exit.
5056 pcapint_add_to_pcaps_to_close(handle
);
5060 #else /* HAVE_LIBNL */
5062 enter_rfmon_mode(pcap_t
*handle _U_
, int sock_fd _U_
, const char *device _U_
)
5065 * We don't have libnl, so we can't do monitor mode.
5069 #endif /* HAVE_LIBNL */
5071 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
5073 * Map SOF_TIMESTAMPING_ values to PCAP_TSTAMP_ values.
5075 static const struct {
5076 int soft_timestamping_val
;
5077 int pcap_tstamp_val
;
5078 } sof_ts_type_map
[3] = {
5079 { SOF_TIMESTAMPING_SOFTWARE
, PCAP_TSTAMP_HOST
},
5080 { SOF_TIMESTAMPING_SYS_HARDWARE
, PCAP_TSTAMP_ADAPTER
},
5081 { SOF_TIMESTAMPING_RAW_HARDWARE
, PCAP_TSTAMP_ADAPTER_UNSYNCED
}
5083 #define NUM_SOF_TIMESTAMPING_TYPES (sizeof sof_ts_type_map / sizeof sof_ts_type_map[0])
5086 * Set the list of time stamping types to include all types.
5089 iface_set_all_ts_types(pcap_t
*handle
, char *ebuf
)
5093 handle
->tstamp_type_list
= malloc(NUM_SOF_TIMESTAMPING_TYPES
* sizeof(u_int
));
5094 if (handle
->tstamp_type_list
== NULL
) {
5095 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
5099 for (i
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++)
5100 handle
->tstamp_type_list
[i
] = sof_ts_type_map
[i
].pcap_tstamp_val
;
5101 handle
->tstamp_type_count
= NUM_SOF_TIMESTAMPING_TYPES
;
5106 * Get a list of time stamp types.
5108 #ifdef ETHTOOL_GET_TS_INFO
5110 iface_get_ts_types(const char *device
, pcap_t
*handle
, char *ebuf
)
5114 struct ethtool_ts_info info
;
5119 * This doesn't apply to the "any" device; you can't say "turn on
5120 * hardware time stamping for all devices that exist now and arrange
5121 * that it be turned on for any device that appears in the future",
5122 * and not all devices even necessarily *support* hardware time
5123 * stamping, so don't report any time stamp types.
5125 if (strcmp(device
, "any") == 0) {
5126 handle
->tstamp_type_list
= NULL
;
5131 * Create a socket from which to fetch time stamping capabilities.
5133 fd
= get_if_ioctl_socket();
5135 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
5136 errno
, "socket for SIOCETHTOOL(ETHTOOL_GET_TS_INFO)");
5140 memset(&ifr
, 0, sizeof(ifr
));
5141 pcapint_strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5142 memset(&info
, 0, sizeof(info
));
5143 info
.cmd
= ETHTOOL_GET_TS_INFO
;
5144 ifr
.ifr_data
= (caddr_t
)&info
;
5145 if (ioctl(fd
, SIOCETHTOOL
, &ifr
) == -1) {
5146 int save_errno
= errno
;
5149 switch (save_errno
) {
5154 * OK, this OS version or driver doesn't support
5155 * asking for the time stamping types, so let's
5156 * just return all the possible types.
5158 if (iface_set_all_ts_types(handle
, ebuf
) == -1)
5164 * OK, no such device.
5165 * The user will find that out when they try to
5166 * activate the device; just return an empty
5167 * list of time stamp types.
5169 handle
->tstamp_type_list
= NULL
;
5176 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
5178 "%s: SIOCETHTOOL(ETHTOOL_GET_TS_INFO) ioctl failed",
5186 * Do we support hardware time stamping of *all* packets?
5188 if (!(info
.rx_filters
& (1 << HWTSTAMP_FILTER_ALL
))) {
5190 * No, so don't report any time stamp types.
5192 * XXX - some devices either don't report
5193 * HWTSTAMP_FILTER_ALL when they do support it, or
5194 * report HWTSTAMP_FILTER_ALL but map it to only
5195 * time stamping a few PTP packets. See
5196 * http://marc.info/?l=linux-netdev&m=146318183529571&w=2
5198 * Maybe that got fixed later.
5200 handle
->tstamp_type_list
= NULL
;
5205 for (i
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++) {
5206 if (info
.so_timestamping
& sof_ts_type_map
[i
].soft_timestamping_val
)
5209 if (num_ts_types
!= 0) {
5210 handle
->tstamp_type_list
= malloc(num_ts_types
* sizeof(u_int
));
5211 if (handle
->tstamp_type_list
== NULL
) {
5212 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
5216 for (i
= 0, j
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++) {
5217 if (info
.so_timestamping
& sof_ts_type_map
[i
].soft_timestamping_val
) {
5218 handle
->tstamp_type_list
[j
] = sof_ts_type_map
[i
].pcap_tstamp_val
;
5222 handle
->tstamp_type_count
= num_ts_types
;
5224 handle
->tstamp_type_list
= NULL
;
5228 #else /* ETHTOOL_GET_TS_INFO */
5230 iface_get_ts_types(const char *device
, pcap_t
*handle
, char *ebuf
)
5233 * This doesn't apply to the "any" device; you can't say "turn on
5234 * hardware time stamping for all devices that exist now and arrange
5235 * that it be turned on for any device that appears in the future",
5236 * and not all devices even necessarily *support* hardware time
5237 * stamping, so don't report any time stamp types.
5239 if (strcmp(device
, "any") == 0) {
5240 handle
->tstamp_type_list
= NULL
;
5245 * We don't have an ioctl to use to ask what's supported,
5246 * so say we support everything.
5248 if (iface_set_all_ts_types(handle
, ebuf
) == -1)
5252 #endif /* ETHTOOL_GET_TS_INFO */
5253 #else /* defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP) */
5255 iface_get_ts_types(const char *device _U_
, pcap_t
*p _U_
, char *ebuf _U_
)
5258 * Nothing to fetch, so it always "succeeds".
5262 #endif /* defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP) */
5265 * Find out if we have any form of fragmentation/reassembly offloading.
5267 * We do so using SIOCETHTOOL checking for various types of offloading;
5268 * if SIOCETHTOOL isn't defined, or we don't have any #defines for any
5269 * of the types of offloading, there's nothing we can do to check, so
5270 * we just say "no, we don't".
5272 * We treat EOPNOTSUPP, EINVAL and, if eperm_ok is true, EPERM as
5273 * indications that the operation isn't supported. We do EPERM
5274 * weirdly because the SIOCETHTOOL code in later kernels 1) doesn't
5275 * support ETHTOOL_GUFO, 2) also doesn't include it in the list
5276 * of ethtool operations that don't require CAP_NET_ADMIN privileges,
5277 * and 3) does the "is this permitted" check before doing the "is
5278 * this even supported" check, so it fails with "this is not permitted"
5279 * rather than "this is not even supported". To work around this
5280 * annoyance, we only treat EPERM as an error for the first feature,
5281 * and assume that they all do the same permission checks, so if the
5282 * first one is allowed all the others are allowed if supported.
5284 #if defined(SIOCETHTOOL) && (defined(ETHTOOL_GTSO) || defined(ETHTOOL_GUFO) || defined(ETHTOOL_GGSO) || defined(ETHTOOL_GFLAGS) || defined(ETHTOOL_GGRO))
5286 iface_ethtool_flag_ioctl(pcap_t
*handle
, int cmd
, const char *cmdname
,
5290 struct ethtool_value eval
;
5292 memset(&ifr
, 0, sizeof(ifr
));
5293 pcapint_strlcpy(ifr
.ifr_name
, handle
->opt
.device
, sizeof(ifr
.ifr_name
));
5296 ifr
.ifr_data
= (caddr_t
)&eval
;
5297 if (ioctl(handle
->fd
, SIOCETHTOOL
, &ifr
) == -1) {
5298 if (errno
== EOPNOTSUPP
|| errno
== EINVAL
||
5299 (errno
== EPERM
&& eperm_ok
)) {
5301 * OK, let's just return 0, which, in our
5302 * case, either means "no, what we're asking
5303 * about is not enabled" or "all the flags
5304 * are clear (i.e., nothing is enabled)".
5308 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5309 errno
, "%s: SIOCETHTOOL(%s) ioctl failed",
5310 handle
->opt
.device
, cmdname
);
5317 * XXX - it's annoying that we have to check for offloading at all, but,
5318 * given that we have to, it's still annoying that we have to check for
5319 * particular types of offloading, especially that shiny new types of
5320 * offloading may be added - and, worse, may not be checkable with
5321 * a particular ETHTOOL_ operation; ETHTOOL_GFEATURES would, in
5322 * theory, give those to you, but the actual flags being used are
5323 * opaque (defined in a non-uapi header), and there doesn't seem to
5324 * be any obvious way to ask the kernel what all the offloading flags
5325 * are - at best, you can ask for a set of strings(!) to get *names*
5326 * for various flags. (That whole mechanism appears to have been
5327 * designed for the sole purpose of letting ethtool report flags
5328 * by name and set flags by name, with the names having no semantics
5329 * ethtool understands.)
5332 iface_get_offload(pcap_t
*handle
)
5337 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GTSO
, "ETHTOOL_GTSO", 0);
5341 return 1; /* TCP segmentation offloading on */
5346 * XXX - will this cause large unsegmented packets to be
5347 * handed to PF_PACKET sockets on transmission? If not,
5348 * this need not be checked.
5350 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GGSO
, "ETHTOOL_GGSO", 0);
5354 return 1; /* generic segmentation offloading on */
5357 #ifdef ETHTOOL_GFLAGS
5358 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GFLAGS
, "ETHTOOL_GFLAGS", 0);
5361 if (ret
& ETH_FLAG_LRO
)
5362 return 1; /* large receive offloading on */
5367 * XXX - will this cause large reassembled packets to be
5368 * handed to PF_PACKET sockets on receipt? If not,
5369 * this need not be checked.
5371 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GGRO
, "ETHTOOL_GGRO", 0);
5375 return 1; /* generic (large) receive offloading on */
5380 * Do this one last, as support for it was removed in later
5381 * kernels, and it fails with EPERM on those kernels rather
5382 * than with EOPNOTSUPP (see explanation in comment for
5383 * iface_ethtool_flag_ioctl()).
5385 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GUFO
, "ETHTOOL_GUFO", 1);
5389 return 1; /* UDP fragmentation offloading on */
5394 #else /* SIOCETHTOOL */
5396 iface_get_offload(pcap_t
*handle _U_
)
5399 * XXX - do we need to get this information if we don't
5400 * have the ethtool ioctls? If so, how do we do that?
5404 #endif /* SIOCETHTOOL */
5406 static struct dsa_proto
{
5408 bpf_u_int32 linktype
;
5411 * None is special and indicates that the interface does not have
5412 * any tagging protocol configured, and is therefore a standard
5413 * Ethernet interface.
5415 { "none", DLT_EN10MB
},
5416 { "brcm", DLT_DSA_TAG_BRCM
},
5417 { "brcm-prepend", DLT_DSA_TAG_BRCM_PREPEND
},
5418 { "dsa", DLT_DSA_TAG_DSA
},
5419 { "edsa", DLT_DSA_TAG_EDSA
},
5420 { "rtl4a", DLT_EN10MB
},
5421 { "rtl8_4", DLT_EN10MB
},
5422 { "rtl8_4t", DLT_EN10MB
},
5426 iface_dsa_get_proto_info(const char *device
, pcap_t
*handle
)
5431 * Make this significantly smaller than PCAP_ERRBUF_SIZE;
5432 * the tag *shouldn't* have some huge long name, and making
5433 * it smaller keeps newer versions of GCC from whining that
5434 * the error message if we don't support the tag could
5435 * overflow the error message buffer.
5441 fd
= asprintf(&pathstr
, "/sys/class/net/%s/dsa/tagging", device
);
5443 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5448 fd
= open(pathstr
, O_RDONLY
);
5451 * This is not fatal, kernel >= 4.20 *might* expose this attribute
5456 r
= read(fd
, buf
, sizeof(buf
) - 1);
5458 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5466 * Buffer should be LF terminated.
5468 if (buf
[r
- 1] == '\n')
5472 for (i
= 0; i
< sizeof(dsa_protos
) / sizeof(dsa_protos
[0]); i
++) {
5473 if (strlen(dsa_protos
[i
].name
) == (size_t)r
&&
5474 strcmp(buf
, dsa_protos
[i
].name
) == 0) {
5475 handle
->linktype
= dsa_protos
[i
].linktype
;
5476 switch (dsa_protos
[i
].linktype
) {
5485 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5486 "unsupported DSA tag: %s", buf
);
5492 * Query the kernel for the MTU of the given interface.
5495 iface_get_mtu(int fd
, const char *device
, char *ebuf
)
5500 return BIGGER_THAN_ALL_MTUS
;
5502 memset(&ifr
, 0, sizeof(ifr
));
5503 pcapint_strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5505 if (ioctl(fd
, SIOCGIFMTU
, &ifr
) == -1) {
5506 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
5507 errno
, "SIOCGIFMTU");
5515 * Get the hardware type of the given interface as ARPHRD_xxx constant.
5518 iface_get_arptype(int fd
, const char *device
, char *ebuf
)
5523 memset(&ifr
, 0, sizeof(ifr
));
5524 pcapint_strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5526 if (ioctl(fd
, SIOCGIFHWADDR
, &ifr
) == -1) {
5527 if (errno
== ENODEV
) {
5531 * There's nothing more to say, so clear
5532 * the error message.
5534 ret
= PCAP_ERROR_NO_SUCH_DEVICE
;
5538 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
5539 errno
, "SIOCGIFHWADDR");
5544 return ifr
.ifr_hwaddr
.sa_family
;
5548 fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
)
5550 struct pcap_linux
*handlep
= handle
->priv
;
5553 register struct bpf_insn
*p
;
5558 * Make a copy of the filter, and modify that copy if
5561 prog_size
= sizeof(*handle
->fcode
.bf_insns
) * handle
->fcode
.bf_len
;
5562 len
= handle
->fcode
.bf_len
;
5563 f
= (struct bpf_insn
*)malloc(prog_size
);
5565 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5569 memcpy(f
, handle
->fcode
.bf_insns
, prog_size
);
5571 fcode
->filter
= (struct sock_filter
*) f
;
5573 for (i
= 0; i
< len
; ++i
) {
5576 * What type of instruction is this?
5578 switch (BPF_CLASS(p
->code
)) {
5583 * It's a load instruction; is it loading
5586 switch (BPF_MODE(p
->code
)) {
5592 * Yes; are we in cooked mode?
5594 if (handlep
->cooked
) {
5596 * Yes, so we need to fix this
5599 if (fix_offset(handle
, p
) < 0) {
5601 * We failed to do so.
5602 * Return 0, so our caller
5603 * knows to punt to userland.
5613 return 1; /* we succeeded */
5617 fix_offset(pcap_t
*handle
, struct bpf_insn
*p
)
5620 * Existing references to auxiliary data shouldn't be adjusted.
5622 * Note that SKF_AD_OFF is negative, but p->k is unsigned, so
5623 * we use >= and cast SKF_AD_OFF to unsigned.
5625 if (p
->k
>= (bpf_u_int32
)SKF_AD_OFF
)
5627 if (handle
->linktype
== DLT_LINUX_SLL2
) {
5629 * What's the offset?
5631 if (p
->k
>= SLL2_HDR_LEN
) {
5633 * It's within the link-layer payload; that starts
5634 * at an offset of 0, as far as the kernel packet
5635 * filter is concerned, so subtract the length of
5636 * the link-layer header.
5638 p
->k
-= SLL2_HDR_LEN
;
5639 } else if (p
->k
== 0) {
5641 * It's the protocol field; map it to the
5642 * special magic kernel offset for that field.
5644 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
5645 } else if (p
->k
== 4) {
5647 * It's the ifindex field; map it to the
5648 * special magic kernel offset for that field.
5650 p
->k
= SKF_AD_OFF
+ SKF_AD_IFINDEX
;
5651 } else if (p
->k
== 10) {
5653 * It's the packet type field; map it to the
5654 * special magic kernel offset for that field.
5656 p
->k
= SKF_AD_OFF
+ SKF_AD_PKTTYPE
;
5657 } else if ((bpf_int32
)(p
->k
) > 0) {
5659 * It's within the header, but it's not one of
5660 * those fields; we can't do that in the kernel,
5661 * so punt to userland.
5667 * What's the offset?
5669 if (p
->k
>= SLL_HDR_LEN
) {
5671 * It's within the link-layer payload; that starts
5672 * at an offset of 0, as far as the kernel packet
5673 * filter is concerned, so subtract the length of
5674 * the link-layer header.
5676 p
->k
-= SLL_HDR_LEN
;
5677 } else if (p
->k
== 0) {
5679 * It's the packet type field; map it to the
5680 * special magic kernel offset for that field.
5682 p
->k
= SKF_AD_OFF
+ SKF_AD_PKTTYPE
;
5683 } else if (p
->k
== 14) {
5685 * It's the protocol field; map it to the
5686 * special magic kernel offset for that field.
5688 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
5689 } else if ((bpf_int32
)(p
->k
) > 0) {
5691 * It's within the header, but it's not one of
5692 * those fields; we can't do that in the kernel,
5693 * so punt to userland.
5702 set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
)
5704 int total_filter_on
= 0;
5710 * The socket filter code doesn't discard all packets queued
5711 * up on the socket when the filter is changed; this means
5712 * that packets that don't match the new filter may show up
5713 * after the new filter is put onto the socket, if those
5714 * packets haven't yet been read.
5716 * This means, for example, that if you do a tcpdump capture
5717 * with a filter, the first few packets in the capture might
5718 * be packets that wouldn't have passed the filter.
5720 * We therefore discard all packets queued up on the socket
5721 * when setting a kernel filter. (This isn't an issue for
5722 * userland filters, as the userland filtering is done after
5723 * packets are queued up.)
5725 * To flush those packets, we put the socket in read-only mode,
5726 * and read packets from the socket until there are no more to
5729 * In order to keep that from being an infinite loop - i.e.,
5730 * to keep more packets from arriving while we're draining
5731 * the queue - we put the "total filter", which is a filter
5732 * that rejects all packets, onto the socket before draining
5735 * This code deliberately ignores any errors, so that you may
5736 * get bogus packets if an error occurs, rather than having
5737 * the filtering done in userland even if it could have been
5738 * done in the kernel.
5740 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
5741 &total_fcode
, sizeof(total_fcode
)) == 0) {
5745 * Note that we've put the total filter onto the socket.
5747 total_filter_on
= 1;
5750 * Save the socket's current mode, and put it in
5751 * non-blocking mode; we drain it by reading packets
5752 * until we get an error (which is normally a
5753 * "nothing more to be read" error).
5755 save_mode
= fcntl(handle
->fd
, F_GETFL
, 0);
5756 if (save_mode
== -1) {
5757 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
5758 PCAP_ERRBUF_SIZE
, errno
,
5759 "can't get FD flags when changing filter");
5762 if (fcntl(handle
->fd
, F_SETFL
, save_mode
| O_NONBLOCK
) < 0) {
5763 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
5764 PCAP_ERRBUF_SIZE
, errno
,
5765 "can't set nonblocking mode when changing filter");
5768 while (recv(handle
->fd
, &drain
, sizeof drain
, MSG_TRUNC
) >= 0)
5771 if (save_errno
!= EAGAIN
) {
5775 * If we can't restore the mode or reset the
5776 * kernel filter, there's nothing we can do.
5778 (void)fcntl(handle
->fd
, F_SETFL
, save_mode
);
5779 (void)reset_kernel_filter(handle
);
5780 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
5781 PCAP_ERRBUF_SIZE
, save_errno
,
5782 "recv failed when changing filter");
5785 if (fcntl(handle
->fd
, F_SETFL
, save_mode
) == -1) {
5786 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
5787 PCAP_ERRBUF_SIZE
, errno
,
5788 "can't restore FD flags when changing filter");
5794 * Now attach the new filter.
5796 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
5797 fcode
, sizeof(*fcode
));
5798 if (ret
== -1 && total_filter_on
) {
5800 * Well, we couldn't set that filter on the socket,
5801 * but we could set the total filter on the socket.
5803 * This could, for example, mean that the filter was
5804 * too big to put into the kernel, so we'll have to
5805 * filter in userland; in any case, we'll be doing
5806 * filtering in userland, so we need to remove the
5807 * total filter so we see packets.
5812 * If this fails, we're really screwed; we have the
5813 * total filter on the socket, and it won't come off.
5814 * Report it as a fatal error.
5816 if (reset_kernel_filter(handle
) == -1) {
5817 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
5818 PCAP_ERRBUF_SIZE
, errno
,
5819 "can't remove kernel total filter");
5820 return -2; /* fatal error */
5829 reset_kernel_filter(pcap_t
*handle
)
5833 * setsockopt() barfs unless it get a dummy parameter.
5834 * valgrind whines unless the value is initialized,
5835 * as it has no idea that setsockopt() ignores its
5840 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_DETACH_FILTER
,
5841 &dummy
, sizeof(dummy
));
5843 * Ignore ENOENT - it means "we don't have a filter", so there
5844 * was no filter to remove, and there's still no filter.
5846 * Also ignore ENONET, as a lot of kernel versions had a
5847 * typo where ENONET, rather than ENOENT, was returned.
5849 if (ret
== -1 && errno
!= ENOENT
&& errno
!= ENONET
)
5855 pcap_set_protocol_linux(pcap_t
*p
, int protocol
)
5857 if (pcapint_check_activated(p
))
5858 return (PCAP_ERROR_ACTIVATED
);
5859 p
->opt
.protocol
= protocol
;
5864 * Libpcap version string.
5867 pcap_lib_version(void)
5869 return (PCAP_VERSION_STRING
5870 #if defined(HAVE_TPACKET3) && defined(PCAP_SUPPORT_NETMAP)
5871 " (with TPACKET_V3 and netmap)"
5872 #elif defined(HAVE_TPACKET3)
5873 " (with TPACKET_V3)"
5874 #elif defined(PCAP_SUPPORT_NETMAP)
5875 " (with TPACKET_V2 and netmap)"
5877 " (with TPACKET_V2)"